const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-BlWsMnVB.js","assets/useLeadSiteSearchSuggestions-DwB87_Kt.js","assets/CityPagesModule-CHDW78rn.js","assets/ListingCarouselModule-D0OERMYC.js","assets/imageOptimization-Csrlnz8M.js","assets/LeadSiteLuxuryHome-RM_sMFXO.js","assets/LeadSiteLandRanchHome-Cae7QDsl.js","assets/LeadSiteSearch-DHUN_sPZ.js","assets/LeadSiteListingCardImage-DnTDbfNn.js","assets/LeadSiteMap-rt1EMTPL.js","assets/LeadSiteLuxurySearch-YoFqLRzL.js","assets/LeadSiteListingDetail-CU7xIBbl.js","assets/ListingVideoTour-CraO6dwE.js","assets/useListingVideos-fQj9sR_N.js","assets/LeadSiteLuxuryListingDetail-C9N50Ua6.js","assets/LeadSiteCityPage-BLS3CJTU.js","assets/LeadSiteSubdivisionPage-CupSLk0R.js","assets/LeadSiteFocusPage-BrTDiI1y.js","assets/PublicLiveEvent-BzzkvBRw.js","assets/useLiveEngagement-C2cUHlAr.js","assets/LiveEventConsole-CEFM4N-_.js","assets/PostcardManager-YbpswS6o.js","assets/usePostcardZones-DMfWJ1W6.js","assets/DirectMail-Dt6kxK7f.js","assets/LeadSiteEditor-5BStUxC6.js","assets/ImageUrlField-BoMTSib4.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-CvNm7oAB.js","assets/MLSListingDetail-Y0BLWDK1.js","assets/EmailCampaignComposer-TC9MeOxg.js","assets/EditorModeSelector-CNDBLsWM.js","assets/SharedCampaignTemplates-Bt1JD_Yf.js","assets/TemplateEditorDialog-gJXb5SQY.js","assets/AgentTemplates-vt9CEXUC.js","assets/TheLocalMoveHome-B-7WXCIT.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-B95w5RPY.js"])))=>i.map(i=>d[i]); var sKt=Object.defineProperty;var jet=s=>{throw TypeError(s)};var nKt=(s,t,n)=>t in s?sKt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var Ar=(s,t,n)=>nKt(s,typeof t!="symbol"?t+"":t,n),w6e=(s,t,n)=>t.has(s)||jet("Cannot "+n);var me=(s,t,n)=>(w6e(s,t,"read from private field"),n?n.call(s):t.get(s)),rs=(s,t,n)=>t.has(s)?jet("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),Ot=(s,t,n,r)=>(w6e(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),Kt=(s,t,n)=>(w6e(s,t,"access private method"),n);var Ig=(s,t,n,r)=>({set _(a){Ot(s,t,a,n)},get _(){return me(s,t,r)}});function rKt(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 aKt="modulepreload",iKt=function(s){return"/"+s},Net={},Mi=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=Promise.allSettled(n.map(c=>{if(c=iKt(c),c in Net)return;Net[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":aKt,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((m,p)=>{h.addEventListener("load",m),h.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return a.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return t().catch(i)})};var Xf=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function sd(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function oKt(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 r1t={exports:{}},u4e={},a1t={exports:{}},Hc={};/** * @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 KQ=Symbol.for("react.element"),lKt=Symbol.for("react.portal"),cKt=Symbol.for("react.fragment"),dKt=Symbol.for("react.strict_mode"),uKt=Symbol.for("react.profiler"),hKt=Symbol.for("react.provider"),mKt=Symbol.for("react.context"),pKt=Symbol.for("react.forward_ref"),fKt=Symbol.for("react.suspense"),xKt=Symbol.for("react.memo"),gKt=Symbol.for("react.lazy"),ket=Symbol.iterator;function yKt(s){return s===null||typeof s!="object"?null:(s=ket&&s[ket]||s["@@iterator"],typeof s=="function"?s:null)}var i1t={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},o1t=Object.assign,l1t={};function AU(s,t,n){this.props=s,this.context=t,this.refs=l1t,this.updater=n||i1t}AU.prototype.isReactComponent={};AU.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")};AU.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function c1t(){}c1t.prototype=AU.prototype;function p$e(s,t,n){this.props=s,this.context=t,this.refs=l1t,this.updater=n||i1t}var f$e=p$e.prototype=new c1t;f$e.constructor=p$e;o1t(f$e,AU.prototype);f$e.isPureReactComponent=!0;var Cet=Array.isArray,d1t=Object.prototype.hasOwnProperty,x$e={current:null},u1t={key:!0,ref:!0,__self:!0,__source:!0};function h1t(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)d1t.call(t,r)&&!u1t.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,de=le[ie];if(0>>1;iea(xe,oe))fea(Se,xe)?(le[ie]=Se,le[fe]=oe,ie=fe):(le[ie]=xe,le[je]=oe,ie=je);else if(fea(Se,oe))le[ie]=Se,le[fe]=oe,ie=fe;else break e}}return ue}function a(le,ue){var oe=le.sortIndex-ue.sortIndex;return oe!==0?oe:le.id-ue.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;s.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();s.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,m=3,p=!1,x=!1,y=!1,g=typeof setTimeout=="function"?setTimeout:null,b=typeof clearTimeout=="function"?clearTimeout:null,v=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function k(le){for(var ue=n(d);ue!==null;){if(ue.callback===null)r(d);else if(ue.startTime<=le)r(d),ue.sortIndex=ue.expirationTime,t(c,ue);else break;ue=n(d)}}function C(le){if(y=!1,k(le),!x)if(n(c)!==null)x=!0,ee(T);else{var ue=n(d);ue!==null&&J(C,ue.startTime-le)}}function T(le,ue){x=!1,y&&(y=!1,b(L),L=-1),p=!0;var oe=m;try{for(k(ue),h=n(c);h!==null&&(!(h.expirationTime>ue)||le&&!$());){var ie=h.callback;if(typeof ie=="function"){h.callback=null,m=h.priorityLevel;var de=ie(h.expirationTime<=ue);ue=s.unstable_now(),typeof de=="function"?h.callback=de:h===n(c)&&r(c),k(ue)}else r(c);h=n(c)}if(h!==null)var we=!0;else{var je=n(d);je!==null&&J(C,je.startTime-ue),we=!1}return we}finally{h=null,m=oe,p=!1}}var M=!1,P=null,L=-1,I=5,O=-1;function $(){return!(s.unstable_now()-Ole||125ie?(le.sortIndex=oe,t(d,le),n(c)===null&&le===n(d)&&(y?(b(L),L=-1):y=!0,J(C,oe-ie))):(le.sortIndex=de,t(c,le),x||p||(x=!0,ee(T))),le},s.unstable_shouldYield=$,s.unstable_wrapCallback=function(le){var ue=m;return function(){var oe=m;m=ue;try{return le.apply(this,arguments)}finally{m=oe}}}})(g1t);x1t.exports=g1t;var xW=x1t.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 TKt=j,tw=xW;function Pa(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"),nRe=Object.prototype.hasOwnProperty,EKt=/^[: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]*$/,Tet={},Eet={};function MKt(s){return nRe.call(Eet,s)?!0:nRe.call(Tet,s)?!1:EKt.test(s)?Eet[s]=!0:(Tet[s]=!0,!1)}function LKt(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 PKt(s,t,n,r){if(t===null||typeof t>"u"||LKt(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 g1(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 dy={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){dy[s]=new g1(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];dy[t]=new g1(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){dy[s]=new g1(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){dy[s]=new g1(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){dy[s]=new g1(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){dy[s]=new g1(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){dy[s]=new g1(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){dy[s]=new g1(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){dy[s]=new g1(s,5,!1,s.toLowerCase(),null,!1,!1)});var v$e=/[\-:]([a-z])/g;function b$e(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(v$e,b$e);dy[t]=new g1(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(v$e,b$e);dy[t]=new g1(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(v$e,b$e);dy[t]=new g1(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){dy[s]=new g1(s,1,!1,s.toLowerCase(),null,!1,!1)});dy.xlinkHref=new g1("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){dy[s]=new g1(s,1,!1,s.toLowerCase(),null,!0,!0)});function _$e(s,t,n,r){var a=dy.hasOwnProperty(t)?dy[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{k6e=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?jG(s):""}function IKt(s){switch(s.tag){case 5:return jG(s.type);case 16:return jG("Lazy");case 13:return jG("Suspense");case 19:return jG("SuspenseList");case 0:case 2:case 15:return s=S6e(s.type,!1),s;case 11:return s=S6e(s.type.render,!1),s;case 1:return s=S6e(s.type,!0),s;default:return""}}function oRe(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 Y7:return"Fragment";case K7:return"Portal";case rRe:return"Profiler";case w$e:return"StrictMode";case aRe:return"Suspense";case iRe:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case b1t:return(s.displayName||"Context")+".Consumer";case v1t:return(s._context.displayName||"Context")+".Provider";case j$e:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case N$e:return t=s.displayName||null,t!==null?t:oRe(s.type)||"Memo";case iA:t=s._payload,s=s._init;try{return oRe(s(t))}catch{}}return null}function RKt(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 oRe(t);case 8:return t===w$e?"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 wE(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function w1t(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function DKt(s){var t=w1t(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 Vte(s){s._valueTracker||(s._valueTracker=DKt(s))}function j1t(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=w1t(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function z2e(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 lRe(s,t){var n=t.checked;return Up({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function Let(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=wE(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 N1t(s,t){t=t.checked,t!=null&&_$e(s,"checked",t,!1)}function cRe(s,t){N1t(s,t);var n=wE(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")?dRe(s,t.type,n):t.hasOwnProperty("defaultValue")&&dRe(s,t.type,wE(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function Pet(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 dRe(s,t,n){(t!=="number"||z2e(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var NG=Array.isArray;function A9(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Hte.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function jY(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var gW={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},OKt=["Webkit","ms","Moz","O"];Object.keys(gW).forEach(function(s){OKt.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),gW[t]=gW[s]})});function A1t(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||gW.hasOwnProperty(s)&&gW[s]?(""+t).trim():t+"px"}function T1t(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=A1t(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var FKt=Up({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 mRe(s,t){if(t){if(FKt[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Pa(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Pa(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Pa(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Pa(62))}}function pRe(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 fRe=null;function k$e(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var xRe=null,T9=null,E9=null;function Det(s){if(s=XQ(s)){if(typeof xRe!="function")throw Error(Pa(280));var t=s.stateNode;t&&(t=x4e(t),xRe(s.stateNode,s.type,t))}}function E1t(s){T9?E9?E9.push(s):E9=[s]:T9=s}function M1t(){if(T9){var s=T9,t=E9;if(E9=T9=null,Det(s),t)for(s=0;s>>=0,s===0?32:31-(YKt(s)/ZKt|0)|0}var Gte=64,Wte=4194304;function kG(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 q2e(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=kG(o):(i&=l,i!==0&&(r=kG(i)))}else l=n&~a,l!==0?r=kG(l):i!==0&&(r=kG(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 YQ(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-dN(t),s[t]=n}function eYt(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=vW),Het=" ",Get=!1;function X1t(s,t){switch(s){case"keyup":return AYt.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Q1t(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var Z7=!1;function EYt(s,t){switch(s){case"compositionend":return Q1t(t);case"keypress":return t.which!==32?null:(Get=!0,Het);case"textInput":return s=t.data,s===Het&&Get?null:s;default:return null}}function MYt(s,t){if(Z7)return s==="compositionend"||!P$e&&X1t(s,t)?(s=Y1t(),nae=E$e=gT=null,Z7=!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=Zet(n)}}function sbt(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?sbt(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function nbt(){for(var s=window,t=z2e();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=z2e(s.document)}return t}function I$e(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 BYt(s){var t=nbt(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&sbt(n.ownerDocument.documentElement,n)){if(r!==null&&I$e(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=Xet(n,i);var l=Xet(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,X7=null,wRe=null,_W=null,jRe=!1;function Qet(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;jRe||X7==null||X7!==z2e(r)||(r=X7,"selectionStart"in r&&I$e(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}),_W&&TY(_W,r)||(_W=r,r=G2e(wRe,"onSelect"),0e9||(s.current=TRe[e9],TRe[e9]=null,e9--)}function $h(s,t){e9++,TRe[e9]=s.current,s.current=t}var jE={},ev=KE(jE),hb=KE(!1),yD=jE;function i$(s,t){var n=s.type.contextTypes;if(!n)return jE;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 mb(s){return s=s.childContextTypes,s!=null}function K2e(){fm(hb),fm(ev)}function att(s,t,n){if(ev.current!==jE)throw Error(Pa(168));$h(ev,t),$h(hb,n)}function hbt(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(Pa(108,RKt(s)||"Unknown",a));return Up({},n,r)}function Y2e(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||jE,yD=ev.current,$h(ev,s),$h(hb,hb.current),!0}function itt(s,t,n){var r=s.stateNode;if(!r)throw Error(Pa(169));n?(s=hbt(s,t,yD),r.__reactInternalMemoizedMergedChildContext=s,fm(hb),fm(ev),$h(ev,s)):fm(hb),$h(hb,n)}var w4=null,g4e=!1,B6e=!1;function mbt(s){w4===null?w4=[s]:w4.push(s)}function QYt(s){g4e=!0,mbt(s)}function YE(){if(!B6e&&w4!==null){B6e=!0;var s=0,t=Yu;try{var n=w4;for(Yu=1;s>=l,a-=l,n3=1<<32-dN(t)+a|n<L?(I=P,P=null):I=P.sibling;var O=m(b,P,k[L],C);if(O===null){P===null&&(P=I);break}s&&P&&O.alternate===null&&t(b,P),v=i(O,v,L),M===null?T=O:M.sibling=O,M=O,P=I}if(L===k.length)return n(b,P),Vm&&wM(b,L),T;if(P===null){for(;LL?(I=P,P=null):I=P.sibling;var $=m(b,P,O.value,C);if($===null){P===null&&(P=I);break}s&&P&&$.alternate===null&&t(b,P),v=i($,v,L),M===null?T=$:M.sibling=$,M=$,P=I}if(O.done)return n(b,P),Vm&&wM(b,L),T;if(P===null){for(;!O.done;L++,O=k.next())O=h(b,O.value,C),O!==null&&(v=i(O,v,L),M===null?T=O:M.sibling=O,M=O);return Vm&&wM(b,L),T}for(P=r(b,P);!O.done;L++,O=k.next())O=p(P,b,L,O.value,C),O!==null&&(s&&O.alternate!==null&&P.delete(O.key===null?L:O.key),v=i(O,v,L),M===null?T=O:M.sibling=O,M=O);return s&&P.forEach(function(q){return t(b,q)}),Vm&&wM(b,L),T}function g(b,v,k,C){if(typeof k=="object"&&k!==null&&k.type===Y7&&k.key===null&&(k=k.props.children),typeof k=="object"&&k!==null){switch(k.$$typeof){case qte:e:{for(var T=k.key,M=v;M!==null;){if(M.key===T){if(T=k.type,T===Y7){if(M.tag===7){n(b,M.sibling),v=a(M,k.props.children),v.return=b,b=v;break e}}else if(M.elementType===T||typeof T=="object"&&T!==null&&T.$$typeof===iA&&ctt(T)===M.type){n(b,M.sibling),v=a(M,k.props),v.ref=aH(b,M,k),v.return=b,b=v;break e}n(b,M);break}else t(b,M);M=M.sibling}k.type===Y7?(v=AR(k.props.children,b.mode,C,k.key),v.return=b,b=v):(C=uae(k.type,k.key,k.props,null,b.mode,C),C.ref=aH(b,v,k),C.return=b,b=C)}return l(b);case K7:e:{for(M=k.key;v!==null;){if(v.key===M)if(v.tag===4&&v.stateNode.containerInfo===k.containerInfo&&v.stateNode.implementation===k.implementation){n(b,v.sibling),v=a(v,k.children||[]),v.return=b,b=v;break e}else{n(b,v);break}else t(b,v);v=v.sibling}v=K6e(k,b.mode,C),v.return=b,b=v}return l(b);case iA:return M=k._init,g(b,v,M(k._payload),C)}if(NG(k))return x(b,v,k,C);if(eH(k))return y(b,v,k,C);ese(b,k)}return typeof k=="string"&&k!==""||typeof k=="number"?(k=""+k,v!==null&&v.tag===6?(n(b,v.sibling),v=a(v,k),v.return=b,b=v):(n(b,v),v=W6e(k,b.mode,C),v.return=b,b=v),l(b)):n(b,v)}return g}var l$=gbt(!0),ybt=gbt(!1),Q2e=KE(null),J2e=null,n9=null,F$e=null;function z$e(){F$e=n9=J2e=null}function B$e(s){var t=Q2e.current;fm(Q2e),s._currentValue=t}function LRe(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 L9(s,t){J2e=s,F$e=n9=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(ab=!0),s.firstContext=null)}function Dj(s){var t=s._currentValue;if(F$e!==s)if(s={context:s,memoizedValue:t,next:null},n9===null){if(J2e===null)throw Error(Pa(308));n9=s,J2e.dependencies={lanes:0,firstContext:s}}else n9=n9.next=s;return t}var QI=null;function $$e(s){QI===null?QI=[s]:QI.push(s)}function vbt(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,$$e(t)):(n.next=a.next,a.next=n),t.interleaved=n,R3(s,r)}function R3(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 oA=!1;function U$e(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function bbt(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 m3(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function RT(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,Dd&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,R3(s,n)}return a=r.interleaved,a===null?(t.next=t,$$e(r)):(t.next=a.next,a.next=t),r.interleaved=t,R3(s,n)}function aae(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,C$e(s,n)}}function dtt(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 eNe(s,t,n,r){var a=s.updateQueue;oA=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var u=s.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(i!==null){var h=a.baseState;l=0,u=d=c=null,o=i;do{var m=o.lane,p=o.eventTime;if((r&m)===m){u!==null&&(u=u.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var x=s,y=o;switch(m=t,p=n,y.tag){case 1:if(x=y.payload,typeof x=="function"){h=x.call(p,h,m);break e}h=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=y.payload,m=typeof x=="function"?x.call(p,h,m):x,m==null)break e;h=Up({},h,m);break e;case 2:oA=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,m=a.effects,m===null?a.effects=[o]:m.push(o))}else p={eventTime:p,lane:m,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=p,c=h):u=u.next=p,l|=m;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;m=o,o=m.next,m.next=null,a.lastBaseUpdate=m,a.shared.pending=null}}while(!0);if(u===null&&(c=h),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=u,t=a.shared.interleaved,t!==null){a=t;do l|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);_D|=l,s.lanes=l,s.memoizedState=h}}function utt(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=U6e.transition;U6e.transition={};try{s(!1),t()}finally{Yu=n,U6e.transition=r}}function Obt(){return Oj().memoizedState}function sZt(s,t,n){var r=OT(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Fbt(s))zbt(t,n);else if(n=vbt(s,t,n,r),n!==null){var a=t1();uN(n,s,r,a),Bbt(n,t,r)}}function nZt(s,t,n){var r=OT(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Fbt(s))zbt(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,kN(o,l)){var c=t.interleaved;c===null?(a.next=a,$$e(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=vbt(s,t,a,r),n!==null&&(a=t1(),uN(n,s,r,a),Bbt(n,t,r))}}function Fbt(s){var t=s.alternate;return s===Dp||t!==null&&t===Dp}function zbt(s,t){wW=sNe=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function Bbt(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,C$e(s,n)}}var nNe={readContext:Dj,useCallback:Cy,useContext:Cy,useEffect:Cy,useImperativeHandle:Cy,useInsertionEffect:Cy,useLayoutEffect:Cy,useMemo:Cy,useReducer:Cy,useRef:Cy,useState:Cy,useDebugValue:Cy,useDeferredValue:Cy,useTransition:Cy,useMutableSource:Cy,useSyncExternalStore:Cy,useId:Cy,unstable_isNewReconciler:!1},rZt={readContext:Dj,useCallback:function(s,t){return Ik().memoizedState=[s,t===void 0?null:t],s},useContext:Dj,useEffect:mtt,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,oae(4194308,4,Lbt.bind(null,t,s),n)},useLayoutEffect:function(s,t){return oae(4194308,4,s,t)},useInsertionEffect:function(s,t){return oae(4,2,s,t)},useMemo:function(s,t){var n=Ik();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=Ik();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=sZt.bind(null,Dp,s),[r.memoizedState,s]},useRef:function(s){var t=Ik();return s={current:s},t.memoizedState=s},useState:htt,useDebugValue:Z$e,useDeferredValue:function(s){return Ik().memoizedState=s},useTransition:function(){var s=htt(!1),t=s[0];return s=tZt.bind(null,s[1]),Ik().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=Dp,a=Ik();if(Vm){if(n===void 0)throw Error(Pa(407));n=n()}else{if(n=t(),e0===null)throw Error(Pa(349));bD&30||Nbt(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,mtt(Sbt.bind(null,r,i,s),[s]),r.flags|=2048,OY(9,kbt.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=Ik(),t=e0.identifierPrefix;if(Vm){var n=r3,r=n3;n=(r&~(1<<32-dN(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=RY++,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[m5]=t,s[LY]=r,Zbt(s,t,!1,!1),t.stateNode=s;e:{switch(l=pRe(n,r),n){case"dialog":om("cancel",s),om("close",s),a=r;break;case"iframe":case"object":case"embed":om("load",s),a=r;break;case"video":case"audio":for(a=0;au$&&(t.flags|=128,r=!0,iH(i,!1),t.lanes=4194304)}else{if(!r)if(s=tNe(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),iH(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Vm)return Ay(t),null}else 2*Vf()-i.renderingStartTime>u$&&n!==1073741824&&(t.flags|=128,r=!0,iH(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=Vf(),t.sibling=null,n=Ap.current,$h(Ap,r?n&1|2:n&1),t):(Ay(t),null);case 22:case 23:return sUe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?A_&1073741824&&(Ay(t),t.subtreeFlags&6&&(t.flags|=8192)):Ay(t),null;case 24:return null;case 25:return null}throw Error(Pa(156,t.tag))}function hZt(s,t){switch(D$e(t),t.tag){case 1:return mb(t.type)&&K2e(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return c$(),fm(hb),fm(ev),H$e(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return V$e(t),null;case 13:if(fm(Ap),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(Pa(340));o$()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return fm(Ap),null;case 4:return c$(),null;case 10:return B$e(t.type._context),null;case 22:case 23:return sUe(),null;case 24:return null;default:return null}}var sse=!1,Vy=!1,mZt=typeof WeakSet=="function"?WeakSet:Set,Wi=null;function r9(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){uf(s,t,r)}else n.current=null}function $Re(s,t,n){try{n()}catch(r){uf(s,t,r)}}var Ntt=!1;function pZt(s,t){if(NRe=V2e,s=nbt(),I$e(s)){if("selectionStart"in s)var n={start:s.selectionStart,end:s.selectionEnd};else e:{n=(n=s.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,d=0,u=0,h=s,m=null;t:for(;;){for(var p;h!==n||a!==0&&h.nodeType!==3||(o=l+a),h!==i||r!==0&&h.nodeType!==3||(c=l+r),h.nodeType===3&&(l+=h.nodeValue.length),(p=h.firstChild)!==null;)m=h,h=p;for(;;){if(h===s)break t;if(m===n&&++d===a&&(o=l),m===i&&++u===r&&(c=l),(p=h.nextSibling)!==null)break;h=m,m=h.parentNode}h=p}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(kRe={focusedElem:s,selectionRange:n},V2e=!1,Wi=t;Wi!==null;)if(t=Wi,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,Wi=s;else for(;Wi!==null;){t=Wi;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var y=x.memoizedProps,g=x.memoizedState,b=t.stateNode,v=b.getSnapshotBeforeUpdate(t.elementType===t.type?y:M2(t.type,y),g);b.__reactInternalSnapshotBeforeUpdate=v}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(Pa(163))}}catch(C){uf(t,t.return,C)}if(s=t.sibling,s!==null){s.return=t.return,Wi=s;break}Wi=t.return}return x=Ntt,Ntt=!1,x}function jW(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&&$Re(t,n,i)}a=a.next}while(a!==r)}}function b4e(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 URe(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 Jbt(s){var t=s.alternate;t!==null&&(s.alternate=null,Jbt(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[m5],delete t[LY],delete t[ARe],delete t[ZYt],delete t[XYt])),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 e_t(s){return s.tag===5||s.tag===3||s.tag===4}function ktt(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||e_t(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 qRe(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=W2e));else if(r!==4&&(s=s.child,s!==null))for(qRe(s,t,n),s=s.sibling;s!==null;)qRe(s,t,n),s=s.sibling}function VRe(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(VRe(s,t,n),s=s.sibling;s!==null;)VRe(s,t,n),s=s.sibling}var $0=null,K2=!1;function CC(s,t,n){for(n=n.child;n!==null;)t_t(s,t,n),n=n.sibling}function t_t(s,t,n){if(T5&&typeof T5.onCommitFiberUnmount=="function")try{T5.onCommitFiberUnmount(h4e,n)}catch{}switch(n.tag){case 5:Vy||r9(n,t);case 6:var r=$0,a=K2;$0=null,CC(s,t,n),$0=r,K2=a,$0!==null&&(K2?(s=$0,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):$0.removeChild(n.stateNode));break;case 18:$0!==null&&(K2?(s=$0,n=n.stateNode,s.nodeType===8?z6e(s.parentNode,n):s.nodeType===1&&z6e(s,n),CY(s)):z6e($0,n.stateNode));break;case 4:r=$0,a=K2,$0=n.stateNode.containerInfo,K2=!0,CC(s,t,n),$0=r,K2=a;break;case 0:case 11:case 14:case 15:if(!Vy&&(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)&&$Re(n,t,l),a=a.next}while(a!==r)}CC(s,t,n);break;case 1:if(!Vy&&(r9(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){uf(n,t,o)}CC(s,t,n);break;case 21:CC(s,t,n);break;case 22:n.mode&1?(Vy=(r=Vy)||n.memoizedState!==null,CC(s,t,n),Vy=r):CC(s,t,n);break;default:CC(s,t,n)}}function Stt(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new mZt),t.forEach(function(r){var a=jZt.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function b2(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=Vf()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*xZt(r/1960))-r,10s?16:s,yT===null)var r=!1;else{if(s=yT,yT=null,iNe=0,Dd&6)throw Error(Pa(331));var a=Dd;for(Dd|=4,Wi=s.current;Wi!==null;){var i=Wi,l=i.child;if(Wi.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cVf()-eUe?CR(s,0):J$e|=n),pb(s,t)}function c_t(s,t){t===0&&(s.mode&1?(t=Wte,Wte<<=1,!(Wte&130023424)&&(Wte=4194304)):t=1);var n=t1();s=R3(s,t),s!==null&&(YQ(s,t,n),pb(s,n))}function wZt(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),c_t(s,n)}function jZt(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(Pa(314))}r!==null&&r.delete(t),c_t(s,n)}var d_t;d_t=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||hb.current)ab=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return ab=!1,dZt(s,t,n);ab=!!(s.flags&131072)}else ab=!1,Vm&&t.flags&1048576&&pbt(t,X2e,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;lae(s,t),s=t.pendingProps;var a=i$(t,ev.current);L9(t,n),a=W$e(null,t,r,s,a,n);var i=K$e();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,mb(r)?(i=!0,Y2e(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,U$e(t),a.updater=v4e,t.stateNode=a,a._reactInternals=t,IRe(t,r,s,n),t=ORe(null,t,r,!0,i,n)):(t.tag=0,Vm&&i&&R$e(t),zv(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(lae(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=kZt(r),s=M2(r,s),a){case 0:t=DRe(null,t,r,s,n);break e;case 1:t=_tt(null,t,r,s,n);break e;case 11:t=vtt(null,t,r,s,n);break e;case 14:t=btt(null,t,r,M2(r.type,s),n);break e}throw Error(Pa(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:M2(r,a),DRe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:M2(r,a),_tt(s,t,r,a,n);case 3:e:{if(Wbt(t),s===null)throw Error(Pa(387));r=t.pendingProps,i=t.memoizedState,a=i.element,bbt(s,t),eNe(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=d$(Error(Pa(423)),t),t=wtt(s,t,r,n,a);break e}else if(r!==a){a=d$(Error(Pa(424)),t),t=wtt(s,t,r,n,a);break e}else for(F_=IT(t.stateNode.containerInfo.firstChild),$_=t,Vm=!0,eN=null,n=ybt(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(o$(),r===a){t=D3(s,t,n);break e}zv(s,t,r,n)}t=t.child}return t;case 5:return _bt(t),s===null&&MRe(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,SRe(r,a)?l=null:i!==null&&SRe(r,i)&&(t.flags|=32),Gbt(s,t),zv(s,t,l,n),t.child;case 6:return s===null&&MRe(t),null;case 13:return Kbt(s,t,n);case 4:return q$e(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=l$(t,null,r,n):zv(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:M2(r,a),vtt(s,t,r,a,n);case 7:return zv(s,t,t.pendingProps,n),t.child;case 8:return zv(s,t,t.pendingProps.children,n),t.child;case 12:return zv(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,$h(Q2e,r._currentValue),r._currentValue=l,i!==null)if(kN(i.value,l)){if(i.children===a.children&&!hb.current){t=D3(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=m3(-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),LRe(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(Pa(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),LRe(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}zv(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,L9(t,n),a=Dj(a),r=r(a),t.flags|=1,zv(s,t,r,n),t.child;case 14:return r=t.type,a=M2(r,t.pendingProps),a=M2(r.type,a),btt(s,t,r,a,n);case 15:return Vbt(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:M2(r,a),lae(s,t),t.tag=1,mb(r)?(s=!0,Y2e(t)):s=!1,L9(t,n),$bt(t,r,a),IRe(t,r,a,n),ORe(null,t,r,!0,s,n);case 19:return Ybt(s,t,n);case 22:return Hbt(s,t,n)}throw Error(Pa(156,t.tag))};function u_t(s,t){return F1t(s,t)}function NZt(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 xj(s,t,n,r){return new NZt(s,t,n,r)}function rUe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function kZt(s){if(typeof s=="function")return rUe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===j$e)return 11;if(s===N$e)return 14}return 2}function FT(s,t){var n=s.alternate;return n===null?(n=xj(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 uae(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")rUe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case Y7:return AR(n.children,a,i,t);case w$e:l=8,a|=8;break;case rRe:return s=xj(12,n,t,a|2),s.elementType=rRe,s.lanes=i,s;case aRe:return s=xj(13,n,t,a),s.elementType=aRe,s.lanes=i,s;case iRe:return s=xj(19,n,t,a),s.elementType=iRe,s.lanes=i,s;case _1t:return w4e(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case v1t:l=10;break e;case b1t:l=9;break e;case j$e:l=11;break e;case N$e:l=14;break e;case iA:l=16,r=null;break e}throw Error(Pa(130,s==null?s:typeof s,""))}return t=xj(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function AR(s,t,n,r){return s=xj(7,s,r,t),s.lanes=n,s}function w4e(s,t,n,r){return s=xj(22,s,r,t),s.elementType=_1t,s.lanes=n,s.stateNode={isHidden:!1},s}function W6e(s,t,n){return s=xj(6,s,null,t),s.lanes=n,s}function K6e(s,t,n){return t=xj(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function SZt(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=A6e(0),this.expirationTimes=A6e(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=A6e(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function aUe(s,t,n,r,a,i,l,o,c){return s=new SZt(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=xj(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},U$e(i),s}function CZt(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(f_t)}catch(s){console.error(s)}}f_t(),f1t.exports=iw;var Hv=f1t.exports;const cUe=sd(Hv);var x_t,Itt=Hv;x_t=Itt.createRoot,Itt.hydrateRoot;const g_t=["traceysellspalmbeach.com"],y_t=s=>s.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function LZt(s){return g_t.includes(y_t(s))}function PZt(s){const t=y_t(s);return g_t.includes(t)?t:null}const IZt=1,RZt=1e6;let Y6e=0;function DZt(){return Y6e=(Y6e+1)%Number.MAX_SAFE_INTEGER,Y6e.toString()}const Z6e=new Map,Rtt=s=>{if(Z6e.has(s))return;const t=setTimeout(()=>{Z6e.delete(s),SW({type:"REMOVE_TOAST",toastId:s})},RZt);Z6e.set(s,t)},OZt=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,IZt)};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?Rtt(n):s.toasts.forEach(r=>{Rtt(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)}}},hae=[];let mae={toasts:[]};function SW(s){mae=OZt(mae,s),hae.forEach(t=>{t(mae)})}function ba({...s}){const t=DZt(),n=a=>SW({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>SW({type:"DISMISS_TOAST",toastId:t});return SW({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||r()}}}),{id:t,dismiss:r,update:n}}function pi(){const[s,t]=j.useState(mae);return j.useEffect(()=>(hae.push(t),()=>{const n=hae.indexOf(t);n>-1&&hae.splice(n,1)}),[s]),{...s,toast:ba,dismiss:n=>SW({type:"DISMISS_TOAST",toastId:n})}}function ua(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 Dtt(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function O3(...s){return t=>{let n=!1;const r=s.map(a=>{const i=Dtt(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{children:l,...o}=i,c=j.useMemo(()=>o,Object.values(o));return e.jsx(n.Provider,{value:c,children:l})};r.displayName=s+"Provider";function a(i){const l=j.useContext(n);if(l)return l;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${s}\``)}return[r,a]}function Zm(s,t=[]){let n=[];function r(i,l){const o=j.createContext(l),c=n.length;n=[...n,l];const d=h=>{var b;const{scope:m,children:p,...x}=h,y=((b=m==null?void 0:m[s])==null?void 0:b[c])||o,g=j.useMemo(()=>x,Object.values(x));return e.jsx(y.Provider,{value:g,children:p})};d.displayName=i+"Provider";function u(h,m){var y;const p=((y=m==null?void 0:m[s])==null?void 0:y[c])||o,x=j.useContext(p);if(x)return x;if(l!==void 0)return l;throw new Error(`\`${h}\` must be used within \`${i}\``)}return[d,u]}const a=()=>{const i=n.map(l=>j.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return j.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[r,zZt(a,...t)]}function zZt(...s){const t=s[0];if(s.length===1)return t;const n=()=>{const r=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const l=r.reduce((o,{useScope:c,scopeName:d})=>{const h=c(i)[`__scope${d}`];return{...o,...h}},{});return j.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return n.scopeName=t.scopeName,n}function NE(s){const t=BZt(s),n=j.forwardRef((r,a)=>{const{children:i,...l}=r,o=j.Children.toArray(i),c=o.find($Zt);if(c){const d=c.props.children,u=o.map(h=>h===c?j.Children.count(d)>1?j.Children.only(null):j.isValidElement(d)?d.props.children:null:h);return e.jsx(t,{...l,ref:a,children:j.isValidElement(d)?j.cloneElement(d,void 0,u):null})}return e.jsx(t,{...l,ref:a,children:i})});return n.displayName=`${s}.Slot`,n}var dUe=NE("Slot");function BZt(s){const t=j.forwardRef((n,r)=>{const{children:a,...i}=n;if(j.isValidElement(a)){const l=qZt(a),o=UZt(i,a.props);return a.type!==j.Fragment&&(o.ref=r?O3(r,l):l),j.cloneElement(a,o)}return j.Children.count(a)>1?j.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var v_t=Symbol("radix.slottable");function b_t(s){const t=({children:n})=>e.jsx(e.Fragment,{children:n});return t.displayName=`${s}.Slottable`,t.__radixId=v_t,t}function $Zt(s){return j.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===v_t}function UZt(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 qZt(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 MU(s){const t=s+"CollectionProvider",[n,r]=Zm(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=y=>{const{scope:g,children:b}=y,v=Lt.useRef(null),k=Lt.useRef(new Map).current;return e.jsx(a,{scope:g,itemMap:k,collectionRef:v,children:b})};l.displayName=t;const o=s+"CollectionSlot",c=NE(o),d=Lt.forwardRef((y,g)=>{const{scope:b,children:v}=y,k=i(o,b),C=ko(g,k.collectionRef);return e.jsx(c,{ref:C,children:v})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",m=NE(u),p=Lt.forwardRef((y,g)=>{const{scope:b,children:v,...k}=y,C=Lt.useRef(null),T=ko(g,C),M=i(u,b);return Lt.useEffect(()=>(M.itemMap.set(C,{ref:C,...k}),()=>void M.itemMap.delete(C))),e.jsx(m,{[h]:"",ref:T,children:v})});p.displayName=u;function x(y){const g=i(s+"CollectionConsumer",y);return Lt.useCallback(()=>{const v=g.collectionRef.current;if(!v)return[];const k=Array.from(v.querySelectorAll(`[${h}]`));return Array.from(g.itemMap.values()).sort((M,P)=>k.indexOf(M.ref.current)-k.indexOf(P.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:l,Slot:d,ItemSlot:p},x,r]}var VZt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ua=VZt.reduce((s,t)=>{const n=NE(`Primitive.${t}`),r=j.forwardRef((a,i)=>{const{asChild:l,...o}=a,c=l?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(c,{...o,ref:i})});return r.displayName=`Primitive.${t}`,{...s,[t]:r}},{});function uUe(s,t){s&&Hv.flushSync(()=>s.dispatchEvent(t))}function gf(s){const t=j.useRef(s);return j.useEffect(()=>{t.current=s}),j.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function HZt(s,t=globalThis==null?void 0:globalThis.document){const n=gf(s);j.useEffect(()=>{const r=a=>{a.key==="Escape"&&n(a)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var GZt="DismissableLayer",YRe="dismissableLayer.update",WZt="dismissableLayer.pointerDownOutside",KZt="dismissableLayer.focusOutside",Ott,__t=j.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),ZE=j.forwardRef((s,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=j.useContext(__t),[u,h]=j.useState(null),m=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,p]=j.useState({}),x=ko(t,P=>h(P)),y=Array.from(d.layers),[g]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),b=y.indexOf(g),v=u?y.indexOf(u):-1,k=d.layersWithOutsidePointerEventsDisabled.size>0,C=v>=b,T=ZZt(P=>{const L=P.target,I=[...d.branches].some(O=>O.contains(L));!C||I||(a==null||a(P),l==null||l(P),P.defaultPrevented||o==null||o())},m),M=XZt(P=>{const L=P.target;[...d.branches].some(O=>O.contains(L))||(i==null||i(P),l==null||l(P),P.defaultPrevented||o==null||o())},m);return HZt(P=>{v===d.layers.size-1&&(r==null||r(P),!P.defaultPrevented&&o&&(P.preventDefault(),o()))},m),j.useEffect(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(Ott=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),Ftt(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=Ott)}},[u,m,n,d]),j.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),Ftt())},[u,d]),j.useEffect(()=>{const P=()=>p({});return document.addEventListener(YRe,P),()=>document.removeEventListener(YRe,P)},[]),e.jsx(Ua.div,{...c,ref:x,style:{pointerEvents:k?C?"auto":"none":void 0,...s.style},onFocusCapture:ua(s.onFocusCapture,M.onFocusCapture),onBlurCapture:ua(s.onBlurCapture,M.onBlurCapture),onPointerDownCapture:ua(s.onPointerDownCapture,T.onPointerDownCapture)})});ZE.displayName=GZt;var YZt="DismissableLayerBranch",w_t=j.forwardRef((s,t)=>{const n=j.useContext(__t),r=j.useRef(null),a=ko(t,r);return j.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),e.jsx(Ua.div,{...s,ref:a})});w_t.displayName=YZt;function ZZt(s,t=globalThis==null?void 0:globalThis.document){const n=gf(s),r=j.useRef(!1),a=j.useRef(()=>{});return j.useEffect(()=>{const i=o=>{if(o.target&&!r.current){let c=function(){j_t(WZt,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 XZt(s,t=globalThis==null?void 0:globalThis.document){const n=gf(s),r=j.useRef(!1);return j.useEffect(()=>{const a=i=>{i.target&&!r.current&&j_t(KZt,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 Ftt(){const s=new CustomEvent(YRe);document.dispatchEvent(s)}function j_t(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?uUe(a,i):a.dispatchEvent(i)}var QZt=ZE,JZt=w_t,Nf=globalThis!=null&&globalThis.document?j.useLayoutEffect:()=>{},eXt="Portal",LU=j.forwardRef((s,t)=>{var o;const{container:n,...r}=s,[a,i]=j.useState(!1);Nf(()=>i(!0),[]);const l=n||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?cUe.createPortal(e.jsx(Ua.div,{...r,ref:t}),l):null});LU.displayName=eXt;function tXt(s,t){return j.useReducer((n,r)=>t[n][r]??n,s)}var ax=s=>{const{present:t,children:n}=s,r=sXt(t),a=typeof n=="function"?n({present:r.isPresent}):j.Children.only(n),i=ko(r.ref,nXt(a));return typeof n=="function"||r.isPresent?j.cloneElement(a,{ref:i}):null};ax.displayName="Presence";function sXt(s){const[t,n]=j.useState(),r=j.useRef(null),a=j.useRef(s),i=j.useRef("none"),l=s?"mounted":"unmounted",[o,c]=tXt(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return j.useEffect(()=>{const d=ase(r.current);i.current=o==="mounted"?d:"none"},[o]),Nf(()=>{const d=r.current,u=a.current;if(u!==s){const m=i.current,p=ase(d);s?c("MOUNT"):p==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(u&&m!==p?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,c]),Nf(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,h=p=>{const y=ase(r.current).includes(p.animationName);if(p.target===t&&y&&(c("ANIMATION_END"),!a.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},m=p=>{p.target===t&&(i.current=ase(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:j.useCallback(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function ase(s){return(s==null?void 0:s.animationName)||"none"}function nXt(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 rXt=y$e[" useInsertionEffect ".trim().toString()]||Nf;function Mx({prop:s,defaultProp:t,onChange:n=()=>{},caller:r}){const[a,i,l]=aXt({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a;{const u=j.useRef(s!==void 0);j.useEffect(()=>{const h=u.current;h!==o&&console.warn(`${r} is changing from ${h?"controlled":"uncontrolled"} to ${o?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=o},[o,r])}const d=j.useCallback(u=>{var h;if(o){const m=iXt(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 aXt({defaultProp:s,onChange:t}){const[n,r]=j.useState(s),a=j.useRef(n),i=j.useRef(t);return rXt(()=>{i.current=t},[t]),j.useEffect(()=>{var l;a.current!==n&&((l=i.current)==null||l.call(i,n),a.current=n)},[n,a]),[n,r,i]}function iXt(s){return typeof s=="function"}var N_t=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"}),oXt="VisuallyHidden",C4e=j.forwardRef((s,t)=>e.jsx(Ua.span,{...s,ref:t,style:{...N_t,...s.style}}));C4e.displayName=oXt;var lXt=C4e,hUe="ToastProvider",[mUe,cXt,dXt]=MU("Toast"),[k_t,Gzn]=Zm("Toast",[dXt]),[uXt,A4e]=k_t(hUe),S_t=s=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:a="right",swipeThreshold:i=50,children:l}=s,[o,c]=j.useState(null),[d,u]=j.useState(0),h=j.useRef(!1),m=j.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${hUe}\`. Expected non-empty \`string\`.`),e.jsx(mUe.Provider,{scope:t,children:e.jsx(uXt,{scope:t,label:n,duration:r,swipeDirection:a,swipeThreshold:i,toastCount:d,viewport:o,onViewportChange:c,onToastAdd:j.useCallback(()=>u(p=>p+1),[]),onToastRemove:j.useCallback(()=>u(p=>p-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:m,children:l})})};S_t.displayName=hUe;var C_t="ToastViewport",hXt=["F8"],ZRe="toast.viewportPause",XRe="toast.viewportResume",A_t=j.forwardRef((s,t)=>{const{__scopeToast:n,hotkey:r=hXt,label:a="Notifications ({hotkey})",...i}=s,l=A4e(C_t,n),o=cXt(n),c=j.useRef(null),d=j.useRef(null),u=j.useRef(null),h=j.useRef(null),m=ko(t,h,l.onViewportChange),p=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=l.toastCount>0;j.useEffect(()=>{const g=b=>{var k;r.length!==0&&r.every(C=>b[C]||b.code===C)&&((k=h.current)==null||k.focus())};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[r]),j.useEffect(()=>{const g=c.current,b=h.current;if(x&&g&&b){const v=()=>{if(!l.isClosePausedRef.current){const M=new CustomEvent(ZRe);b.dispatchEvent(M),l.isClosePausedRef.current=!0}},k=()=>{if(l.isClosePausedRef.current){const M=new CustomEvent(XRe);b.dispatchEvent(M),l.isClosePausedRef.current=!1}},C=M=>{!g.contains(M.relatedTarget)&&k()},T=()=>{g.contains(document.activeElement)||k()};return g.addEventListener("focusin",v),g.addEventListener("focusout",C),g.addEventListener("pointermove",v),g.addEventListener("pointerleave",T),window.addEventListener("blur",v),window.addEventListener("focus",k),()=>{g.removeEventListener("focusin",v),g.removeEventListener("focusout",C),g.removeEventListener("pointermove",v),g.removeEventListener("pointerleave",T),window.removeEventListener("blur",v),window.removeEventListener("focus",k)}}},[x,l.isClosePausedRef]);const y=j.useCallback(({tabbingDirection:g})=>{const v=o().map(k=>{const C=k.ref.current,T=[C,...kXt(C)];return g==="forwards"?T:T.reverse()});return(g==="forwards"?v.reverse():v).flat()},[o]);return j.useEffect(()=>{const g=h.current;if(g){const b=v=>{var T,M,P;const k=v.altKey||v.ctrlKey||v.metaKey;if(v.key==="Tab"&&!k){const L=document.activeElement,I=v.shiftKey;if(v.target===g&&I){(T=d.current)==null||T.focus();return}const q=y({tabbingDirection:I?"backwards":"forwards"}),W=q.findIndex(G=>G===L);X6e(q.slice(W+1))?v.preventDefault():I?(M=d.current)==null||M.focus():(P=u.current)==null||P.focus()}};return g.addEventListener("keydown",b),()=>g.removeEventListener("keydown",b)}},[o,y]),e.jsxs(JZt,{ref:c,role:"region","aria-label":a.replace("{hotkey}",p),tabIndex:-1,style:{pointerEvents:x?void 0:"none"},children:[x&&e.jsx(QRe,{ref:d,onFocusFromOutsideViewport:()=>{const g=y({tabbingDirection:"forwards"});X6e(g)}}),e.jsx(mUe.Slot,{scope:n,children:e.jsx(Ua.ol,{tabIndex:-1,...i,ref:m})}),x&&e.jsx(QRe,{ref:u,onFocusFromOutsideViewport:()=>{const g=y({tabbingDirection:"backwards"});X6e(g)}})]})});A_t.displayName=C_t;var T_t="ToastFocusProxy",QRe=j.forwardRef((s,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...a}=s,i=A4e(T_t,n);return e.jsx(C4e,{"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()}})});QRe.displayName=T_t;var JQ="Toast",mXt="toast.swipeStart",pXt="toast.swipeMove",fXt="toast.swipeCancel",xXt="toast.swipeEnd",E_t=j.forwardRef((s,t)=>{const{forceMount:n,open:r,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=Mx({prop:r,defaultProp:a??!0,onChange:i,caller:JQ});return e.jsx(ax,{present:n||o,children:e.jsx(vXt,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:gf(s.onPause),onResume:gf(s.onResume),onSwipeStart:ua(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ua(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:ua(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:ua(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)})})})});E_t.displayName=JQ;var[gXt,yXt]=k_t(JQ,{onClose(){}}),vXt=j.forwardRef((s,t)=>{const{__scopeToast:n,type:r="foreground",duration:a,open:i,onClose:l,onEscapeKeyDown:o,onPause:c,onResume:d,onSwipeStart:u,onSwipeMove:h,onSwipeCancel:m,onSwipeEnd:p,...x}=s,y=A4e(JQ,n),[g,b]=j.useState(null),v=ko(t,G=>b(G)),k=j.useRef(null),C=j.useRef(null),T=a||y.duration,M=j.useRef(0),P=j.useRef(T),L=j.useRef(0),{onToastAdd:I,onToastRemove:O}=y,$=gf(()=>{var K;(g==null?void 0:g.contains(document.activeElement))&&((K=y.viewport)==null||K.focus()),l()}),q=j.useCallback(G=>{!G||G===1/0||(window.clearTimeout(L.current),M.current=new Date().getTime(),L.current=window.setTimeout($,G))},[$]);j.useEffect(()=>{const G=y.viewport;if(G){const K=()=>{q(P.current),d==null||d()},ee=()=>{const J=new Date().getTime()-M.current;P.current=P.current-J,window.clearTimeout(L.current),c==null||c()};return G.addEventListener(ZRe,ee),G.addEventListener(XRe,K),()=>{G.removeEventListener(ZRe,ee),G.removeEventListener(XRe,K)}}},[y.viewport,T,c,d,q]),j.useEffect(()=>{i&&!y.isClosePausedRef.current&&q(T)},[i,T,y.isClosePausedRef,q]),j.useEffect(()=>(I(),()=>O()),[I,O]);const W=j.useMemo(()=>g?O_t(g):null,[g]);return y.viewport?e.jsxs(e.Fragment,{children:[W&&e.jsx(bXt,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:W}),e.jsx(gXt,{scope:n,onClose:$,children:Hv.createPortal(e.jsx(mUe.ItemSlot,{scope:n,children:e.jsx(QZt,{asChild:!0,onEscapeKeyDown:ua(o,()=>{y.isFocusedToastEscapeKeyDownRef.current||$(),y.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(Ua.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":y.swipeDirection,...x,ref:v,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:ua(s.onKeyDown,G=>{G.key==="Escape"&&(o==null||o(G.nativeEvent),G.nativeEvent.defaultPrevented||(y.isFocusedToastEscapeKeyDownRef.current=!0,$()))}),onPointerDown:ua(s.onPointerDown,G=>{G.button===0&&(k.current={x:G.clientX,y:G.clientY})}),onPointerMove:ua(s.onPointerMove,G=>{if(!k.current)return;const K=G.clientX-k.current.x,ee=G.clientY-k.current.y,J=!!C.current,le=["left","right"].includes(y.swipeDirection),ue=["left","up"].includes(y.swipeDirection)?Math.min:Math.max,oe=le?ue(0,K):0,ie=le?0:ue(0,ee),de=G.pointerType==="touch"?10:2,we={x:oe,y:ie},je={originalEvent:G,delta:we};J?(C.current=we,ise(pXt,h,je,{discrete:!1})):ztt(we,y.swipeDirection,de)?(C.current=we,ise(mXt,u,je,{discrete:!1}),G.target.setPointerCapture(G.pointerId)):(Math.abs(K)>de||Math.abs(ee)>de)&&(k.current=null)}),onPointerUp:ua(s.onPointerUp,G=>{const K=C.current,ee=G.target;if(ee.hasPointerCapture(G.pointerId)&&ee.releasePointerCapture(G.pointerId),C.current=null,k.current=null,K){const J=G.currentTarget,le={originalEvent:G,delta:K};ztt(K,y.swipeDirection,y.swipeThreshold)?ise(xXt,p,le,{discrete:!0}):ise(fXt,m,le,{discrete:!0}),J.addEventListener("click",ue=>ue.preventDefault(),{once:!0})}})})})}),y.viewport)})]}):null}),bXt=s=>{const{__scopeToast:t,children:n,...r}=s,a=A4e(JQ,t),[i,l]=j.useState(!1),[o,c]=j.useState(!1);return jXt(()=>l(!0)),j.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(LU,{asChild:!0,children:e.jsx(C4e,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},_Xt="ToastTitle",M_t=j.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(Ua.div,{...r,ref:t})});M_t.displayName=_Xt;var wXt="ToastDescription",L_t=j.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(Ua.div,{...r,ref:t})});L_t.displayName=wXt;var P_t="ToastAction",I_t=j.forwardRef((s,t)=>{const{altText:n,...r}=s;return n.trim()?e.jsx(D_t,{altText:n,asChild:!0,children:e.jsx(pUe,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${P_t}\`. Expected non-empty \`string\`.`),null)});I_t.displayName=P_t;var R_t="ToastClose",pUe=j.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s,a=yXt(R_t,n);return e.jsx(D_t,{asChild:!0,children:e.jsx(Ua.button,{type:"button",...r,ref:t,onClick:ua(s.onClick,a.onClose)})})});pUe.displayName=R_t;var D_t=j.forwardRef((s,t)=>{const{__scopeToast:n,altText:r,...a}=s;return e.jsx(Ua.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...a,ref:t})});function O_t(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),NXt(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(...O_t(r))}}),t}function ise(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?uUe(a,i):a.dispatchEvent(i)}var ztt=(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 jXt(s=()=>{}){const t=gf(s);Nf(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function NXt(s){return s.nodeType===s.ELEMENT_NODE}function kXt(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 X6e(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var SXt=S_t,F_t=A_t,z_t=E_t,B_t=M_t,$_t=L_t,U_t=I_t,q_t=pUe;function V_t(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,$tt=Il,hO=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return $tt(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=Btt(u)||Btt(h);return a[d][m]}),o=n&&Object.entries(n).reduce((d,u)=>{let[h,m]=u;return m===void 0||(d[h]=m),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,u)=>{let{class:h,className:m,...p}=u;return Object.entries(p).every(x=>{let[y,g]=x;return Array.isArray(g)?g.includes({...i,...o}[y]):{...i,...o}[y]===g})?[...d,h,m]:d},[]);return $tt(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 CXt=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),H_t=(...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 AXt={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 G_t=j.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>j.createElement("svg",{ref:c,...AXt,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:H_t("lucide",a),...o},[...l.map(([d,u])=>j.createElement(d,u)),...Array.isArray(i)?i:[i]]));/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ce=(s,t)=>{const n=j.forwardRef(({className:r,...a},i)=>j.createElement(G_t,{ref:i,iconNode:t,className:H_t(`lucide-${CXt(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 pae=ce("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 fae=ce("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 xae=ce("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 gae=ce("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 vf=ce("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 yae=ce("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 vae=ce("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 NM=ce("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 kM=ce("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 bae=ce("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 SM=ce("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 _ae=ce("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 wae=ce("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 jae=ce("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 Nae=ce("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 kae=ce("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 TR=ce("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 Sae=ce("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 Cae=ce("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 Aae=ce("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 Tae=ce("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 Eae=ce("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 Mae=ce("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 Lae=ce("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 Pae=ce("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 Iae=ce("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 Rae=ce("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 Dae=ce("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 ER=ce("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 MR=ce("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 Oae=ce("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 Fae=ce("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 zae=ce("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 Bae=ce("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 $ae=ce("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 Uae=ce("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 qae=ce("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 Vae=ce("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 Hae=ce("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 Gae=ce("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 Wae=ce("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 Kae=ce("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 Yae=ce("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 Zae=ce("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 Xae=ce("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 Qae=ce("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 Jae=ce("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 eie=ce("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 tie=ce("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 sie=ce("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 nie=ce("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 rie=ce("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 aie=ce("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 zT=ce("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 iie=ce("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 gm=ce("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 oie=ce("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 lie=ce("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 cie=ce("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 die=ce("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 uie=ce("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 hie=ce("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 mie=ce("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 pie=ce("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 fie=ce("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 xie=ce("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 gie=ce("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 CM=ce("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 yie=ce("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 vie=ce("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 bie=ce("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 CW=ce("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 _ie=ce("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 wie=ce("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 jie=ce("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 AM=ce("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 TM=ce("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 tx=ce("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 Nie=ce("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 AW=ce("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 kie=ce("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 _a=ce("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 Sie=ce("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 M5=ce("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 Cie=ce("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 Xa=ce("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 Aie=ce("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 Tie=ce("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 EM=ce("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 _x=ce("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 Eie=ce("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 Mie=ce("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 Lie=ce("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 MM=ce("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=ce("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 Pie=ce("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 Iie=ce("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 LM=ce("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 Gm=ce("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 Rie=ce("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 Die=ce("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 Oie=ce("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 Fie=ce("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 zie=ce("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 Bie=ce("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 cu=ce("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 $ie=ce("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 PM=ce("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 Uie=ce("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 qie=ce("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 Vie=ce("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 Hie=ce("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 IM=ce("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 Gie=ce("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 Wie=ce("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 Kie=ce("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 Yie=ce("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 Zie=ce("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 Xie=ce("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 Qie=ce("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 Jie=ce("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 eoe=ce("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 toe=ce("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 soe=ce("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 noe=ce("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 roe=ce("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 aoe=ce("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 ioe=ce("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 R9=ce("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 ooe=ce("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 loe=ce("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 coe=ce("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 doe=ce("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 uoe=ce("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 t0=ce("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 hoe=ce("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 moe=ce("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 poe=ce("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 foe=ce("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 xoe=ce("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 goe=ce("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 TW=ce("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 yoe=ce("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 voe=ce("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 p3=ce("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 boe=ce("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 U_=ce("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 _oe=ce("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 woe=ce("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 joe=ce("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 Noe=ce("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 koe=ce("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 Soe=ce("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 L5=ce("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 Coe=ce("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 f3=ce("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 Nx=ce("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 RM=ce("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 DM=ce("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 Aoe=ce("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 Toe=ce("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 Eoe=ce("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 Moe=ce("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 Loe=ce("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 Poe=ce("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 Ioe=ce("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 Roe=ce("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 Doe=ce("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 Ooe=ce("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 Foe=ce("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 zoe=ce("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 Boe=ce("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 $oe=ce("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 Uoe=ce("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 qoe=ce("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 BT=ce("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 Voe=ce("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 Hoe=ce("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 Goe=ce("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 Woe=ce("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 Koe=ce("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 Yoe=ce("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 Zoe=ce("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 OM=ce("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 Xoe=ce("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 Qoe=ce("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 Joe=ce("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 ele=ce("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 tle=ce("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 sle=ce("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 nle=ce("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 rle=ce("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 ale=ce("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 ile=ce("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 Op=ce("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 ole=ce("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 lle=ce("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 cle=ce("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 dle=ce("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 ule=ce("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 hle=ce("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 mle=ce("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 ple=ce("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 fle=ce("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 xle=ce("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 $T=ce("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 gle=ce("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 s1=ce("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 yle=ce("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 vle=ce("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 ble=ce("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 UT=ce("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 EW=ce("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 _le=ce("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 FM=ce("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 wle=ce("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 jle=ce("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 Nle=ce("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 MW=ce("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 kle=ce("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 Sle=ce("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 Cle=ce("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 Ale=ce("BriefcaseMedical",[["path",{d:"M12 11v4",key:"a6ujw6"}],["path",{d:"M14 13h-4",key:"1pl8zg"}],["path",{d:"M16 6V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2",key:"1ksdt3"}],["path",{d:"M18 6v14",key:"1mu4gy"}],["path",{d:"M6 6v14",key:"1s15cj"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kx=ce("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 Tle=ce("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 Ele=ce("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 Mle=ce("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 Lle=ce("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 Ple=ce("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 Ni=ce("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LR=ce("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 Ile=ce("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 Rle=ce("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 Dle=ce("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 Ole=ce("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 Fle=ce("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 Wm=ce("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 P5=ce("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 zle=ce("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 Ble=ce("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 $le=ce("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 Ule=ce("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 n1=ce("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 ym=ce("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 qle=ce("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 Vc=ce("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 Vle=ce("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 hN=ce("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 Hle=ce("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 Gle=ce("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 D9=ce("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 Wle=ce("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 Wy=ce("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 Kle=ce("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 Yle=ce("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 Zle=ce("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 Xle=ce("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 LW=ce("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 ra=ce("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 Qle=ce("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 s0=ce("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 Jle=ce("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 ece=ce("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 tce=ce("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 sce=ce("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 nce=ce("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 zM=ce("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 rce=ce("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 ace=ce("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 ice=ce("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 oce=ce("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 lce=ce("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 cce=ce("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 dce=ce("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 uce=ce("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 hce=ce("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 mce=ce("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 pce=ce("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 fce=ce("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 xce=ce("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 BM=ce("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 $M=ce("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 gce=ce("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 yce=ce("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 vce=ce("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 UM=ce("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 qM=ce("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=ce("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 bce=ce("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 HM=ce("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 _ce=ce("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 ol=ce("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 wce=ce("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 GM=ce("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 jce=ce("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 Nce=ce("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=ce("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 KM=ce("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 kce=ce("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 YM=ce("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 ZM=ce("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 XM=ce("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 Sce=ce("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 PR=ce("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 da=ce("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 Cce=ce("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 Ace=ce("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 Po=ce("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 Tce=ce("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 Ece=ce("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 Cc=ce("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=ce("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 Qy=ce("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 Mce=ce("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 Lce=ce("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 Pce=ce("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 Ice=ce("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 Rce=ce("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 Dce=ce("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 Oce=ce("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 fb=ce("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 Fce=ce("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 IR=ce("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 zce=ce("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 Bce=ce("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 $ce=ce("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 po=ce("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 QM=ce("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 JM=ce("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 eL=ce("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 tL=ce("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 sL=ce("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 nL=ce("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 rL=ce("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 aL=ce("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 To=ce("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 Rr=ce("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iL=ce("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 oL=ce("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 lL=ce("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 cL=ce("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 Uce=ce("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 dL=ce("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 qce=ce("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 Vce=ce("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 Hce=ce("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 Gce=ce("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 Wce=ce("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 Kce=ce("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 Yce=ce("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 uL=ce("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 c5=ce("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 hL=ce("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 Zce=ce("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 mL=ce("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 pL=ce("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 fL=ce("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 xL=ce("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 vh=ce("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 gL=ce("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 yL=ce("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 vL=ce("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 Xce=ce("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 bL=ce("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 _L=ce("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 wL=ce("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rd=ce("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 Sx=ce("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 Qce=ce("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 Jce=ce("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 O9=ce("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 x3=ce("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 ede=ce("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 r1=ce("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 tde=ce("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 sde=ce("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 jL=ce("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 NL=ce("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 nde=ce("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 rde=ce("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 ade=ce("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 ide=ce("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 ode=ce("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 lde=ce("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 cde=ce("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 dde=ce("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 ude=ce("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 PW=ce("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 hde=ce("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 mde=ce("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 pde=ce("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 fde=ce("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 xde=ce("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 gde=ce("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 yde=ce("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 vde=ce("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 bde=ce("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 Vr=ce("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 _de=ce("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 wde=ce("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 kL=ce("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 jde=ce("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 Nde=ce("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 kde=ce("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 Sde=ce("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 Cde=ce("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 Ade=ce("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 Tde=ce("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 Ede=ce("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 Mde=ce("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 Lde=ce("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 Pde=ce("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 Ide=ce("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 SL=ce("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 Rde=ce("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 Dde=ce("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 a3=ce("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 Ode=ce("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 j4=ce("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 qT=ce("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 Fde=ce("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 zde=ce("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 xb=ce("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 Bde=ce("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 IW=ce("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 CL=ce("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 lA=ce("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 $de=ce("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 Ude=ce("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 qde=ce("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 RR=ce("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 Vde=ce("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 Hde=ce("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 Gde=ce("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 Wde=ce("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 Kde=ce("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 AL=ce("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 DR=ce("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 Yde=ce("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 Zde=ce("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 Xde=ce("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 Qde=ce("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 Jde=ce("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 eue=ce("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 tue=ce("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 sue=ce("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 nue=ce("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 ja=ce("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 rue=ce("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 aue=ce("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 iue=ce("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 oue=ce("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 lue=ce("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 cue=ce("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 due=ce("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 uue=ce("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 hue=ce("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 mue=ce("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 pue=ce("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 fue=ce("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 ty=ce("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 xue=ce("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 gue=ce("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 yue=ce("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 vue=ce("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 sy=ce("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 bue=ce("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 _ue=ce("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 wue=ce("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 jue=ce("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 Nue=ce("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 kue=ce("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 Sue=ce("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 RW=ce("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 Cue=ce("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 Aue=ce("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 Tue=ce("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 Eue=ce("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 TL=ce("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 Mue=ce("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 Lue=ce("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 Pue=ce("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 Iue=ce("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 Rue=ce("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 Due=ce("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 Oue=ce("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 Fue=ce("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 zue=ce("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 Bue=ce("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 $ue=ce("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 Uue=ce("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 que=ce("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 Vue=ce("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 Hue=ce("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 Gue=ce("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 Wue=ce("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 Kue=ce("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 Yue=ce("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 Od=ce("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 Zue=ce("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 Xue=ce("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 wj=ce("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 Que=ce("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 ii=ce("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 Jue=ce("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 ehe=ce("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 the=ce("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 she=ce("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 nhe=ce("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 mN=ce("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 rhe=ce("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 ahe=ce("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 ihe=ce("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 ohe=ce("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 lhe=ce("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 che=ce("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 EL=ce("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 dhe=ce("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 uhe=ce("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 hhe=ce("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 F9=ce("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 W0=ce("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 Hy=ce("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 mhe=ce("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 phe=ce("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 fhe=ce("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 xhe=ce("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 ghe=ce("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 yhe=ce("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 vhe=ce("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=ce("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 bhe=ce("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 n0=ce("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 ma=ce("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 sx=ce("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 _he=ce("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 whe=ce("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 jhe=ce("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 Nhe=ce("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 khe=ce("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 She=ce("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 Che=ce("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 Ahe=ce("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 The=ce("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 Ehe=ce("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 ML=ce("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 Mhe=ce("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 Lhe=ce("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 Phe=ce("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 LL=ce("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 PL=ce("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 IL=ce("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 RL=ce("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 Ihe=ce("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 DW=ce("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 Rhe=ce("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 Dhe=ce("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 Ohe=ce("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 DL=ce("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 Fhe=ce("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 zhe=ce("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 jj=ce("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 Bhe=ce("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 g3=ce("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 $he=ce("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 Uhe=ce("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 qhe=ce("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 Vhe=ce("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 Hhe=ce("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 Ghe=ce("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 Whe=ce("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 Khe=ce("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 Yhe=ce("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 Zhe=ce("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 Xhe=ce("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 cA=ce("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 OL=ce("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 Qhe=ce("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 Jhe=ce("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 eme=ce("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 tme=ce("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 sme=ce("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 nme=ce("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 rme=ce("FileSliders",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M10 11v2",key:"1s651w"}],["path",{d:"M8 17h8",key:"wh5c61"}],["path",{d:"M14 16v2",key:"12fp5e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pN=ce("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 OW=ce("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 ame=ce("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 ime=ce("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 $r=ce("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 ome=ce("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 lme=ce("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 cme=ce("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 dme=ce("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 ume=ce("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 FW=ce("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 hme=ce("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 mme=ce("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 pme=ce("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 fme=ce("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 xme=ce("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 z9=ce("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 gme=ce("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 wh=ce("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 yme=ce("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 Nj=ce("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 vme=ce("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 bme=ce("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 _me=ce("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 wme=ce("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 jme=ce("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 Nme=ce("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 kme=ce("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 Sme=ce("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 y3=ce("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 Cme=ce("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 Fd=ce("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 Ame=ce("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 Tme=ce("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 Eme=ce("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 VT=ce("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 Mme=ce("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 Lme=ce("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 zW=ce("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 Pme=ce("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 Ime=ce("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 oN=ce("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 Rme=ce("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 Dme=ce("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 Ome=ce("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 Fme=ce("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 zme=ce("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 Bme=ce("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 $me=ce("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 Ume=ce("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 qme=ce("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 FL=ce("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 Vme=ce("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 Hme=ce("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 Gme=ce("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 Wme=ce("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 Kme=ce("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 Yme=ce("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 Zme=ce("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 Xme=ce("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 Qme=ce("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 Jme=ce("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 epe=ce("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 ny=ce("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 tpe=ce("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 zL=ce("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 spe=ce("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 npe=ce("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 rpe=ce("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 ape=ce("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 ipe=ce("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 ope=ce("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 lpe=ce("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 cpe=ce("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 dpe=ce("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 upe=ce("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 hpe=ce("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 mpe=ce("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 ppe=ce("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 fpe=ce("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 xpe=ce("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 gpe=ce("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 ype=ce("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 vpe=ce("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 bpe=ce("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 _pe=ce("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 wpe=ce("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 jpe=ce("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 Npe=ce("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 kpe=ce("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 Spe=ce("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 Cpe=ce("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 Ape=ce("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 Tpe=ce("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 Epe=ce("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 OR=ce("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 zo=ce("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 Mpe=ce("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 Lpe=ce("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 BL=ce("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 Ppe=ce("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 Ipe=ce("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 Rpe=ce("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 Dpe=ce("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 Ope=ce("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 Fpe=ce("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 zpe=ce("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 Bpe=ce("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 $pe=ce("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 Upe=ce("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 qpe=ce("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 Vpe=ce("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 Hpe=ce("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 Gpe=ce("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 Wpe=ce("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 Kpe=ce("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 Ype=ce("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 Ql=ce("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 Zpe=ce("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 Xpe=ce("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 Uh=ce("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 Qpe=ce("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 Jpe=ce("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 $L=ce("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 efe=ce("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 UL=ce("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 k_=ce("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 tfe=ce("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 Fp=ce("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 sfe=ce("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 nfe=ce("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 rfe=ce("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 afe=ce("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 BW=ce("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 ife=ce("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 FR=ce("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 tN=ce("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 ofe=ce("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 lfe=ce("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 $W=ce("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 fN=ce("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 cfe=ce("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 dfe=ce("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 UW=ce("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 ufe=ce("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 HT=ce("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 hfe=ce("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 mfe=ce("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 B9=ce("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 $9=ce("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 qW=ce("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 pfe=ce("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 ffe=ce("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 xfe=ce("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 gfe=ce("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 yfe=ce("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 vfe=ce("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 bfe=ce("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 _fe=ce("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 zR=ce("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 wfe=ce("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 jfe=ce("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 mo=ce("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 Nfe=ce("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 kfe=ce("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 Sfe=ce("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 GT=ce("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 Cfe=ce("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 Afe=ce("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 Tfe=ce("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 Efe=ce("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 Mfe=ce("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 Lfe=ce("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 Pfe=ce("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 ia=ce("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 qL=ce("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=ce("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 Ife=ce("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 Rfe=ce("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 Dfe=ce("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 Ofe=ce("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 Ffe=ce("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 a1=ce("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 zfe=ce("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 Bfe=ce("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 ac=ce("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 $fe=ce("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 Ufe=ce("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 WT=ce("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 HL=ce("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 GL=ce("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 qfe=ce("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 Vfe=ce("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 I5=ce("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 Hfe=ce("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 vm=ce("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 KT=ce("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 Gfe=ce("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 Wfe=ce("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 Kfe=ce("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 Yfe=ce("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 v3=ce("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 b3=ce("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 Zfe=ce("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 gb=ce("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 Xfe=ce("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 Qfe=ce("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 Jfe=ce("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 exe=ce("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 txe=ce("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 sxe=ce("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 nxe=ce("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 rxe=ce("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 axe=ce("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 ixe=ce("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 VW=ce("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 oxe=ce("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 lxe=ce("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=ce("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 cxe=ce("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 dxe=ce("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 uxe=ce("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 hxe=ce("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 mxe=ce("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 pxe=ce("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 U9=ce("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 BR=ce("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 r0=ce("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 fxe=ce("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 xxe=ce("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 gxe=ce("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 q_=ce("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 yxe=ce("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 vxe=ce("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 bxe=ce("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 _xe=ce("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 wxe=ce("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 i1=ce("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 q9=ce("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 jxe=ce("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 Nxe=ce("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 xN=ce("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 kxe=ce("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 Rc=ce("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vc=ce("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 ry=ce("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 Sxe=ce("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 zp=ce("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 Cxe=ce("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 Axe=ce("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 HW=ce("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 Txe=ce("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 Exe=ce("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 kj=ce("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 Mxe=ce("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 Lxe=ce("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 Pxe=ce("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 Ixe=ce("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 Rxe=ce("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 Dxe=ce("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 Oxe=ce("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 ug=ce("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 Wt=ce("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 Fxe=ce("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 zxe=ce("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 Bxe=ce("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 $xe=ce("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 V9=ce("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 KL=ce("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 Uxe=ce("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 YL=ce("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 du=ce("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 $R=ce("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 UR=ce("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 qxe=ce("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 Vxe=ce("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 Hxe=ce("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 Gxe=ce("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 H9=ce("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 Wxe=ce("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 G9=ce("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 GW=ce("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 Kxe=ce("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 Yxe=ce("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 Zxe=ce("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 W9=ce("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 on=ce("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 Xxe=ce("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 Qxe=ce("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 Jxe=ce("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 ege=ce("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 tge=ce("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 sge=ce("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 nge=ce("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 rge=ce("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 age=ce("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 ige=ce("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 oge=ce("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 lge=ce("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 oi=ce("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 cge=ce("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 qR=ce("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 dge=ce("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 WW=ce("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 VR=ce("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 _3=ce("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 uge=ce("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 jh=ce("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 hge=ce("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 mge=ce("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 YT=ce("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 pge=ce("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 fge=ce("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 xge=ce("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 K9=ce("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 gge=ce("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 yge=ce("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 vge=ce("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 Y9=ce("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 bge=ce("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 _ge=ce("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 wge=ce("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 Yd=ce("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 jge=ce("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 Nge=ce("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 kge=ce("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 Sge=ce("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 Z9=ce("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 Cge=ce("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 KW=ce("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 Age=ce("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 v5=ce("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 w3=ce("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 Tge=ce("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 Ege=ce("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 Mge=ce("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 Lge=ce("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 Pge=ce("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 ro=ce("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 X9=ce("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 Ige=ce("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 ZL=ce("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 Sj=ce("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 Rge=ce("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 Dge=ce("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 Oge=ce("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 Fge=ce("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 zge=ce("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 Bge=ce("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 $ge=ce("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 Uge=ce("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 gN=ce("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 qge=ce("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 Vge=ce("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 Hge=ce("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 Gge=ce("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 Wge=ce("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 Kge=ce("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 Q9=ce("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 Yge=ce("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 Zge=ce("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 Xge=ce("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 HR=ce("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 Qge=ce("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 Cj=ce("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 Jge=ce("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 e0e=ce("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 t0e=ce("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 s0e=ce("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 n0e=ce("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 r0e=ce("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 a0e=ce("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 lu=ce("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 ag=ce("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 i0e=ce("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 XL=ce("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 o0e=ce("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 l0e=ce("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 c0e=ce("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 d0e=ce("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 u0e=ce("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 h0e=ce("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 m0e=ce("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 p0e=ce("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 f0e=ce("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 x0e=ce("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 g0e=ce("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 y0e=ce("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 YW=ce("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 v0e=ce("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 b0e=ce("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 _0e=ce("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=ce("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 w0e=ce("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 j0e=ce("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 N0e=ce("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 ZW=ce("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 k0e=ce("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 V_=ce("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 S0e=ce("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 C0e=ce("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 A0e=ce("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 T0e=ce("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 E0e=ce("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 M0e=ce("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 L0e=ce("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 P0e=ce("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 I0e=ce("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 d5=ce("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 R0e=ce("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 QL=ce("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 JL=ce("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 D0e=ce("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 O0e=ce("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 F0e=ce("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 z0e=ce("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 B0e=ce("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 $0e=ce("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 U0e=ce("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 q0e=ce("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 V0e=ce("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 XW=ce("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 H0e=ce("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 G0e=ce("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 Eu=ce("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 W0e=ce("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 K0e=ce("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 eP=ce("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 Y0e=ce("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 Ac=ce("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 Z0e=ce("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 tP=ce("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 X0e=ce("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 Q0e=ce("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 sP=ce("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 nP=ce("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 rP=ce("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 aP=ce("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 J0e=ce("PanelRightClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iP=ce("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 eye=ce("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 tye=ce("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 sye=ce("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 oP=ce("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 nye=ce("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 rye=ce("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 aye=ce("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 iye=ce("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 N4=ce("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 ZT=ce("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 oye=ce("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 lye=ce("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 bf=ce("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 ay=ce("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 cye=ce("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 dye=ce("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 sN=ce("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 uye=ce("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 XT=ce("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 oj=ce("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 ez=ce("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 hye=ce("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 mye=ce("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 Za=ce("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 pye=ce("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 QT=ce("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 fye=ce("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 xye=ce("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 QW=ce("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 gye=ce("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 yye=ce("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 vye=ce("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 bye=ce("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 _ye=ce("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 pa=ce("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 wye=ce("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 jye=ce("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 Nye=ce("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 kye=ce("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 Sye=ce("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 Cye=ce("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 Aye=ce("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 Tye=ce("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 Eye=ce("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 Mye=ce("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 Lye=ce("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 JW=ce("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 JT=ce("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 Pye=ce("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 Iye=ce("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 Rye=ce("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 Dye=ce("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 eK=ce("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 fd=ce("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 Oye=ce("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 lP=ce("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 R5=ce("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 Js=ce("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 Fye=ce("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 zye=ce("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 Bye=ce("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 $ye=ce("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 Uye=ce("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 qye=ce("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 Vye=ce("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 Hye=ce("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 Gye=ce("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 tK=ce("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 yb=ce("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 Wye=ce("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 GR=ce("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 Kye=ce("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 Yye=ce("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 Zye=ce("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 Xye=ce("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 hg=ce("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 yN=ce("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 Qye=ce("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 tz=ce("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 Jye=ce("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 eve=ce("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 tve=ce("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 sve=ce("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 iy=ce("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 nve=ce("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 rve=ce("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 ave=ce("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 ive=ce("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 ove=ce("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 lve=ce("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 cve=ce("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 dve=ce("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 uve=ce("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 hve=ce("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 mve=ce("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 pve=ce("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 fve=ce("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 xve=ce("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 cP=ce("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 gve=ce("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 yve=ce("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 vve=ce("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 bve=ce("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 _ve=ce("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 eE=ce("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 wve=ce("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 sz=ce("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 jve=ce("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 Ki=ce("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 Nve=ce("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 kve=ce("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 Sve=ce("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 Cve=ce("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 Ave=ce("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 nz=ce("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 Tve=ce("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 Eve=ce("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 Mve=ce("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 sK=ce("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 Lve=ce("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 Pve=ce("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 oy=ce("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 Ive=ce("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 Rve=ce("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 dP=ce("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 Dve=ce("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 bm=ce("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 Ove=ce("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 WR=ce("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 Fve=ce("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 rz=ce("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 zve=ce("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 uP=ce("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 hP=ce("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 Bve=ce("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 $ve=ce("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 j3=ce("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 Uve=ce("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 qve=ce("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 Vve=ce("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 Hve=ce("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 Gve=ce("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 Wve=ce("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 Kve=ce("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 Yve=ce("SaveOff",[["path",{d:"M13 13H8a1 1 0 0 0-1 1v7",key:"h8g396"}],["path",{d:"M14 8h1",key:"1lfen6"}],["path",{d:"M17 21v-4",key:"1yknxs"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20.41 20.41A2 2 0 0 1 19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 .59-1.41",key:"1t4vdl"}],["path",{d:"M29.5 11.5s5 5 4 5",key:"zzn4i6"}],["path",{d:"M9 3h6.2a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V15",key:"24cby9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jo=ce("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 mP=ce("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 az=ce("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 Zve=ce("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 Xve=ce("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 Qve=ce("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 Jve=ce("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 e1e=ce("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 t1e=ce("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 s1e=ce("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 n1e=ce("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 r1e=ce("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 a1e=ce("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 i1e=ce("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 o1e=ce("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 l1e=ce("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 c1e=ce("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 nK=ce("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 d1e=ce("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 u1e=ce("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 h1e=ce("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 m1e=ce("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 rK=ce("SearchX",[["path",{d:"m13.5 8.5-5 5",key:"1cs55j"}],["path",{d:"m8.5 8.5 5 5",key:"a8mexj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fr=ce("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 p1e=ce("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 pP=ce("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 f1e=ce("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 Dr=ce("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 x1e=ce("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 g1e=ce("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 y1e=ce("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 v1e=ce("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 b1e=ce("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 _1e=ce("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 tE=ce("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 ic=ce("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 w1e=ce("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 zd=ce("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 aK=ce("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 j1e=ce("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 N1e=ce("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 iz=ce("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 k1e=ce("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 a0=ce("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 S1e=ce("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 C1e=ce("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 A1e=ce("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 KR=ce("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 T1e=ce("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 E1e=ce("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 fP=ce("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 _f=ce("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 M1e=ce("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 L1e=ce("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 P1e=ce("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 D5=ce("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 I1e=ce("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 ib=ce("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 R1e=ce("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 D1e=ce("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 O1e=ce("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 F1e=ce("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 YR=ce("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 z1e=ce("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 B1e=ce("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 $1e=ce("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 U1e=ce("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 q1e=ce("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 V1e=ce("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 H1e=ce("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 G1e=ce("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 W1e=ce("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 K1e=ce("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 Y1e=ce("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 iK=ce("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 Z1e=ce("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 X1e=ce("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 Q1e=ce("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 J1e=ce("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 sE=ce("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 xP=ce("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 ebe=ce("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 tbe=ce("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 Jy=ce("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 sbe=ce("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 nbe=ce("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 rbe=ce("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 gj=ce("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 abe=ce("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 ibe=ce("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 obe=ce("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 lbe=ce("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 N3=ce("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 yn=ce("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 cbe=ce("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 dbe=ce("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 ube=ce("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 hbe=ce("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 mbe=ce("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 pbe=ce("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 fbe=ce("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 nE=ce("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 gP=ce("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 yP=ce("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 vP=ce("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 bP=ce("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 _P=ce("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 wP=ce("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 jP=ce("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 NP=ce("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 kP=ce("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 SP=ce("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 CP=ce("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 AP=ce("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 TP=ce("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 EP=ce("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 MP=ce("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 Tk=ce("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 k4=ce("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 LP=ce("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 PP=ce("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 IP=ce("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 RP=ce("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 DP=ce("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 OP=ce("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 xbe=ce("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 gbe=ce("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 FP=ce("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 zP=ce("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 BP=ce("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 $P=ce("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 UP=ce("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 qP=ce("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=ce("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 HP=ce("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 GP=ce("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=ce("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 KP=ce("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 YP=ce("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 ZP=ce("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 XP=ce("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 QP=ce("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 kp=ce("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 JP=ce("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 eI=ce("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 tI=ce("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 sI=ce("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 nI=ce("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 rI=ce("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 ybe=ce("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 aI=ce("SquareScissors",[["rect",{width:"20",height:"20",x:"2",y:"2",rx:"2",key:"1btzen"}],["circle",{cx:"8",cy:"8",r:"2",key:"14cg06"}],["path",{d:"M9.414 9.414 12 12",key:"qz4lzr"}],["path",{d:"M14.8 14.8 18 18",key:"11flf1"}],["circle",{cx:"8",cy:"16",r:"2",key:"1acxsx"}],["path",{d:"m18 6-8.586 8.586",key:"11kzk1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iI=ce("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 oI=ce("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 lI=ce("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 cI=ce("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 vbe=ce("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 bbe=ce("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 dI=ce("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 uI=ce("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 hI=ce("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 mI=ce("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 H_=ce("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 _be=ce("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 wbe=ce("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 jbe=ce("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 Nbe=ce("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 kbe=ce("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=ce("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 Sbe=ce("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 Cbe=ce("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 Abe=ce("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 Tbe=ce("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 oK=ce("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 lK=ce("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 Ebe=ce("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 Mbe=ce("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 cK=ce("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 Lbe=ce("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 Pbe=ce("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 Ibe=ce("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 Rbe=ce("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 Dbe=ce("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 Aj=ce("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 Obe=ce("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 Fbe=ce("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 zbe=ce("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 Bbe=ce("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 $be=ce("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 Ube=ce("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 qbe=ce("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 Vbe=ce("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 Hbe=ce("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 oz=ce("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 Gbe=ce("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 Wbe=ce("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 Kbe=ce("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 Ybe=ce("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 Zbe=ce("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 Xbe=ce("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 lz=ce("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 Qbe=ce("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 cz=ce("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 Jbe=ce("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 wf=ce("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 dK=ce("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 e_e=ce("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 t_e=ce("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 s_e=ce("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 n_e=ce("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 r_e=ce("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 a_e=ce("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 uu=ce("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 i_e=ce("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 o_e=ce("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 l_e=ce("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 c_e=ce("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 pI=ce("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 d_e=ce("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 u_e=ce("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 h_e=ce("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 m_e=ce("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 p_e=ce("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 f_e=ce("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 fI=ce("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 x_e=ce("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 g_e=ce("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 y_e=ce("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 v_e=ce("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 uK=ce("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 hK=ce("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 mg=ce("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 b_e=ce("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 __e=ce("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 w_e=ce("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 j_e=ce("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 N_e=ce("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 k_e=ce("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 mK=ce("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 S_e=ce("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 C_e=ce("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 A_e=ce("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 T_e=ce("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 E_e=ce("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 M_e=ce("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 L_e=ce("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 P_e=ce("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 I_e=ce("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 R_e=ce("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 D_e=ce("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 O_e=ce("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 F_e=ce("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 z_e=ce("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 B_e=ce("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 $_e=ce("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 U_e=ce("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 q_e=ce("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 V_e=ce("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 xI=ce("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 Rn=ce("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 H_e=ce("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 G_e=ce("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 gI=ce("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 rE=ce("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 W_e=ce("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 K_e=ce("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 vN=ce("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 Y_e=ce("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 kl=ce("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 hd=ce("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 Z_e=ce("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 X_e=ce("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 ll=ce("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 pK=ce("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 Q_e=ce("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 J_e=ce("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 yI=ce("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 ewe=ce("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 twe=ce("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 swe=ce("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 nwe=ce("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 rwe=ce("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 awe=ce("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 iwe=ce("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 dz=ce("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 fK=ce("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 owe=ce("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 aE=ce("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 lwe=ce("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 cwe=ce("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 dwe=ce("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 vI=ce("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 uwe=ce("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 ZR=ce("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 xK=ce("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 Ja=ce("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 hwe=ce("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 bN=ce("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 gK=ce("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 uz=ce("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 mwe=ce("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 Sl=ce("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 bI=ce("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 _I=ce("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 wI=ce("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 pwe=ce("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 jI=ce("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 fwe=ce("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 NI=ce("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 kI=ce("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 xwe=ce("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 gwe=ce("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 Eo=ce("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 qv=ce("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bn=ce("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 SI=ce("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 CI=ce("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 ywe=ce("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 hz=ce("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 vwe=ce("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 bwe=ce("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 _we=ce("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 wwe=ce("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 jwe=ce("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 Nwe=ce("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 Zr=ce("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 kwe=ce("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 Swe=ce("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 Cwe=ce("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 Awe=ce("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 Twe=ce("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 yK=ce("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 Ewe=ce("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 vK=ce("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 Mwe=ce("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 Lwe=ce("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 Pwe=ce("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 AI=ce("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 mz=ce("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 Iwe=ce("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 um=ce("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 Rwe=ce("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 Dwe=ce("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 Owe=ce("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 Fwe=ce("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 zwe=ce("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 Bwe=ce("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 $we=ce("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 Uwe=ce("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 qwe=ce("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 Vwe=ce("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 Hwe=ce("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 Gwe=ce("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 Wwe=ce("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 Kwe=ce("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 Ywe=ce("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 Zwe=ce("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 Xwe=ce("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 Qwe=ce("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 Jwe=ce("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 eje=ce("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 tje=ce("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 bK=ce("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 _K=ce("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 sje=ce("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 nje=ce("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 O5=ce("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 dr=ce("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 rje=ce("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 aje=ce("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 jf=ce("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 iE=ce("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 pz=ce("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 TXt=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:pae,AArrowUp:fae,ALargeSmall:xae,Accessibility:gae,Activity:vf,AirVent:yae,Airplay:vae,AlarmClock:_ae,AlarmClockCheck:NM,AlarmClockMinus:kM,AlarmClockOff:bae,AlarmClockPlus:SM,AlarmSmoke:wae,Album:jae,AlignCenter:TR,AlignCenterHorizontal:Nae,AlignCenterVertical:kae,AlignEndHorizontal:Sae,AlignEndVertical:Cae,AlignHorizontalDistributeCenter:Aae,AlignHorizontalDistributeEnd:Tae,AlignHorizontalDistributeStart:Eae,AlignHorizontalJustifyCenter:Mae,AlignHorizontalJustifyEnd:Lae,AlignHorizontalJustifyStart:Pae,AlignHorizontalSpaceAround:Iae,AlignHorizontalSpaceBetween:Rae,AlignJustify:Dae,AlignLeft:ER,AlignRight:MR,AlignStartHorizontal:Oae,AlignStartVertical:Fae,AlignVerticalDistributeCenter:zae,AlignVerticalDistributeEnd:Bae,AlignVerticalDistributeStart:$ae,AlignVerticalJustifyCenter:Uae,AlignVerticalJustifyEnd:qae,AlignVerticalJustifyStart:Vae,AlignVerticalSpaceAround:Hae,AlignVerticalSpaceBetween:Gae,Ambulance:Wae,Ampersand:Kae,Ampersands:Yae,Amphora:Zae,Anchor:Xae,Angry:Qae,Annoyed:Jae,Antenna:eie,Anvil:tie,Aperture:sie,AppWindow:rie,AppWindowMac:nie,Apple:aie,Archive:gm,ArchiveRestore:zT,ArchiveX:iie,Armchair:oie,ArrowBigDown:cie,ArrowBigDownDash:lie,ArrowBigLeft:uie,ArrowBigLeftDash:die,ArrowBigRight:mie,ArrowBigRightDash:hie,ArrowBigUp:fie,ArrowBigUpDash:pie,ArrowDown:tx,ArrowDown01:xie,ArrowDown10:gie,ArrowDownAZ:CM,ArrowDownFromLine:yie,ArrowDownLeft:vie,ArrowDownNarrowWide:bie,ArrowDownRight:CW,ArrowDownToDot:_ie,ArrowDownToLine:wie,ArrowDownUp:jie,ArrowDownWideNarrow:AM,ArrowDownZA:TM,ArrowLeft:_a,ArrowLeftFromLine:Nie,ArrowLeftRight:AW,ArrowLeftToLine:kie,ArrowRight:Xa,ArrowRightFromLine:Sie,ArrowRightLeft:M5,ArrowRightToLine:Cie,ArrowUp:Gm,ArrowUp01:Aie,ArrowUp10:Tie,ArrowUpAZ:EM,ArrowUpDown:_x,ArrowUpFromDot:Eie,ArrowUpFromLine:Mie,ArrowUpLeft:Lie,ArrowUpNarrowWide:MM,ArrowUpRight:I9,ArrowUpToLine:Pie,ArrowUpWideNarrow:Iie,ArrowUpZA:LM,ArrowsUpFromLine:Rie,Asterisk:Die,AtSign:Oie,Atom:Fie,AudioLines:zie,AudioWaveform:Bie,Award:cu,Axe:$ie,Axis3d:PM,Baby:Uie,Backpack:qie,Badge:aoe,BadgeAlert:Vie,BadgeCent:Hie,BadgeCheck:IM,BadgeDollarSign:Gie,BadgeEuro:Wie,BadgeHelp:Kie,BadgeIndianRupee:Yie,BadgeInfo:Zie,BadgeJapaneseYen:Xie,BadgeMinus:Qie,BadgePercent:Jie,BadgePlus:eoe,BadgePoundSterling:toe,BadgeRussianRuble:soe,BadgeSwissFranc:noe,BadgeX:roe,BaggageClaim:ioe,Ban:R9,Banana:ooe,Bandage:loe,Banknote:coe,Barcode:doe,Baseline:uoe,Bath:t0,Battery:goe,BatteryCharging:hoe,BatteryFull:moe,BatteryLow:poe,BatteryMedium:foe,BatteryWarning:xoe,Beaker:TW,Bean:voe,BeanOff:yoe,Bed:U_,BedDouble:p3,BedSingle:boe,Beef:_oe,Beer:joe,BeerOff:woe,Bell:Nx,BellDot:Noe,BellElectric:koe,BellMinus:Soe,BellOff:L5,BellPlus:Coe,BellRing:f3,BetweenHorizontalEnd:RM,BetweenHorizontalStart:DM,BetweenVerticalEnd:Aoe,BetweenVerticalStart:Toe,BicepsFlexed:Eoe,Bike:Moe,Binary:Loe,Binoculars:Poe,Biohazard:Ioe,Bird:Roe,Bitcoin:Doe,Blend:Ooe,Blinds:Foe,Blocks:zoe,Bluetooth:qoe,BluetoothConnected:Boe,BluetoothOff:$oe,BluetoothSearching:Uoe,Bold:BT,Bolt:Voe,Bomb:Hoe,Bone:Goe,Book:ple,BookA:Woe,BookAudio:Koe,BookCheck:Yoe,BookCopy:Zoe,BookDashed:OM,BookDown:Xoe,BookHeadphones:Qoe,BookHeart:Joe,BookImage:ele,BookKey:tle,BookLock:sle,BookMarked:nle,BookMinus:rle,BookOpen:Op,BookOpenCheck:ale,BookOpenText:ile,BookPlus:ole,BookText:lle,BookType:cle,BookUp:ule,BookUp2:dle,BookUser:hle,BookX:mle,Bookmark:s1,BookmarkCheck:fle,BookmarkMinus:xle,BookmarkPlus:$T,BookmarkX:gle,BoomBox:yle,Bot:UT,BotMessageSquare:vle,BotOff:ble,Box:EW,Boxes:_le,Braces:FM,Brackets:wle,Brain:MW,BrainCircuit:jle,BrainCog:Nle,BrickWall:kle,Briefcase:kx,BriefcaseBusiness:Sle,BriefcaseConveyorBelt:Cle,BriefcaseMedical:Ale,BringToFront:Tle,Brush:Ele,Bug:Ple,BugOff:Mle,BugPlay:Lle,Building:LR,Building2:Ni,Bus:Rle,BusFront:Ile,Cable:Ole,CableCar:Dle,Cake:Wm,CakeSlice:Fle,Calculator:P5,Calendar:ra,Calendar1:zle,CalendarArrowDown:Ble,CalendarArrowUp:$le,CalendarCheck:n1,CalendarCheck2:Ule,CalendarClock:ym,CalendarCog:qle,CalendarDays:Vc,CalendarFold:Vle,CalendarHeart:hN,CalendarMinus:Gle,CalendarMinus2:Hle,CalendarOff:D9,CalendarPlus:Wy,CalendarPlus2:Wle,CalendarRange:Kle,CalendarSearch:Yle,CalendarSync:Zle,CalendarX:LW,CalendarX2:Xle,Camera:s0,CameraOff:Qle,Candy:tce,CandyCane:Jle,CandyOff:ece,Cannabis:sce,Captions:zM,CaptionsOff:nce,Car:ice,CarFront:rce,CarTaxiFront:ace,Caravan:oce,Carrot:lce,CaseLower:cce,CaseSensitive:dce,CaseUpper:uce,CassetteTape:hce,Cast:mce,Castle:pce,Cat:fce,Cctv:xce,ChartArea:BM,ChartBar:UM,ChartBarBig:$M,ChartBarDecreasing:gce,ChartBarIncreasing:yce,ChartBarStacked:vce,ChartCandlestick:qM,ChartColumn:ol,ChartColumnBig:VM,ChartColumnDecreasing:bce,ChartColumnIncreasing:HM,ChartColumnStacked:_ce,ChartGantt:wce,ChartLine:GM,ChartNetwork:jce,ChartNoAxesColumn:KM,ChartNoAxesColumnDecreasing:Nce,ChartNoAxesColumnIncreasing:WM,ChartNoAxesCombined:kce,ChartNoAxesGantt:YM,ChartPie:ZM,ChartScatter:XM,ChartSpline:Sce,Check:da,CheckCheck:PR,ChefHat:Cce,Cherry:Ace,ChevronDown:Po,ChevronFirst:Tce,ChevronLast:Ece,ChevronLeft:Cc,ChevronRight:Qa,ChevronUp:Qy,ChevronsDown:Lce,ChevronsDownUp:Mce,ChevronsLeft:Rce,ChevronsLeftRight:Ice,ChevronsLeftRightEllipsis:Pce,ChevronsRight:Oce,ChevronsRightLeft:Dce,ChevronsUp:Fce,ChevronsUpDown:fb,Chrome:IR,Church:zce,Cigarette:$ce,CigaretteOff:Bce,Circle:Sx,CircleAlert:po,CircleArrowDown:QM,CircleArrowLeft:JM,CircleArrowOutDownLeft:eL,CircleArrowOutDownRight:tL,CircleArrowOutUpLeft:sL,CircleArrowOutUpRight:nL,CircleArrowRight:rL,CircleArrowUp:aL,CircleCheck:Rr,CircleCheckBig:To,CircleChevronDown:iL,CircleChevronLeft:oL,CircleChevronRight:lL,CircleChevronUp:cL,CircleDashed:Uce,CircleDivide:dL,CircleDollarSign:qce,CircleDot:Hce,CircleDotDashed:Vce,CircleEllipsis:Gce,CircleEqual:Wce,CircleFadingArrowUp:Kce,CircleFadingPlus:Yce,CircleGauge:uL,CircleHelp:c5,CircleMinus:hL,CircleOff:Zce,CircleParking:pL,CircleParkingOff:mL,CirclePause:fL,CirclePercent:xL,CirclePlay:vh,CirclePlus:gL,CirclePower:yL,CircleSlash:Xce,CircleSlash2:vL,CircleStop:bL,CircleUser:wL,CircleUserRound:_L,CircleX:Rd,CircuitBoard:Qce,Citrus:Jce,Clapperboard:O9,Clipboard:ide,ClipboardCheck:x3,ClipboardCopy:ede,ClipboardList:r1,ClipboardMinus:tde,ClipboardPaste:sde,ClipboardPen:NL,ClipboardPenLine:jL,ClipboardPlus:nde,ClipboardType:rde,ClipboardX:ade,Clock:Vr,Clock1:ode,Clock10:lde,Clock11:cde,Clock12:dde,Clock2:ude,Clock3:PW,Clock4:hde,Clock5:mde,Clock6:pde,Clock7:fde,Clock8:xde,Clock9:gde,ClockAlert:yde,ClockArrowDown:vde,ClockArrowUp:bde,Cloud:Rde,CloudAlert:_de,CloudCog:wde,CloudDownload:kL,CloudDrizzle:jde,CloudFog:Nde,CloudHail:kde,CloudLightning:Sde,CloudMoon:Ade,CloudMoonRain:Cde,CloudOff:Tde,CloudRain:Mde,CloudRainWind:Ede,CloudSnow:Lde,CloudSun:Ide,CloudSunRain:Pde,CloudUpload:SL,Cloudy:Dde,Clover:a3,Club:Ode,Code:qT,CodeXml:j4,Codepen:Fde,Codesandbox:zde,Coffee:xb,Cog:Bde,Coins:IW,Columns2:CL,Columns3:lA,Columns4:$de,Combine:Ude,Command:qde,Compass:RR,Component:Vde,Computer:Hde,ConciergeBell:Gde,Cone:Wde,Construction:Kde,Contact:DR,ContactRound:AL,Container:Yde,Contrast:Zde,Cookie:Xde,CookingPot:Qde,Copy:ja,CopyCheck:Jde,CopyMinus:eue,CopyPlus:tue,CopySlash:sue,CopyX:nue,Copyleft:rue,Copyright:aue,CornerDownLeft:iue,CornerDownRight:oue,CornerLeftDown:lue,CornerLeftUp:cue,CornerRightDown:due,CornerRightUp:uue,CornerUpLeft:hue,CornerUpRight:mue,Cpu:pue,CreativeCommons:fue,CreditCard:ty,Croissant:xue,Crop:gue,Cross:yue,Crosshair:vue,Crown:sy,Cuboid:bue,CupSoda:_ue,Currency:wue,Cylinder:jue,Dam:Nue,Database:RW,DatabaseBackup:kue,DatabaseZap:Sue,Delete:Cue,Dessert:Aue,Diameter:Tue,Diamond:Lue,DiamondMinus:Eue,DiamondPercent:TL,DiamondPlus:Mue,Dice1:Pue,Dice2:Iue,Dice3:Rue,Dice4:Due,Dice5:Oue,Dice6:Fue,Dices:zue,Diff:Bue,Disc:Vue,Disc2:$ue,Disc3:Uue,DiscAlbum:que,Divide:Hue,Dna:Wue,DnaOff:Gue,Dock:Kue,Dog:Yue,DollarSign:Od,Donut:Zue,DoorClosed:Xue,DoorOpen:wj,Dot:Que,Download:ii,DraftingCompass:Jue,Drama:ehe,Dribbble:the,Drill:she,Droplet:nhe,Droplets:mN,Drum:rhe,Drumstick:ahe,Dumbbell:ihe,Ear:lhe,EarOff:ohe,Earth:EL,EarthLock:che,Eclipse:dhe,Egg:F9,EggFried:uhe,EggOff:hhe,Ellipsis:Hy,EllipsisVertical:W0,Equal:fhe,EqualApproximately:mhe,EqualNot:phe,Eraser:xhe,EthernetPort:ghe,Euro:yhe,Expand:vhe,ExternalLink:Tr,Eye:ma,EyeClosed:bhe,EyeOff:n0,Facebook:sx,Factory:_he,Fan:whe,FastForward:jhe,Feather:Nhe,Fence:khe,FerrisWheel:She,Figma:Che,File:z9,FileArchive:Ahe,FileAudio:Ehe,FileAudio2:The,FileAxis3d:ML,FileBadge:Lhe,FileBadge2:Mhe,FileBox:Phe,FileChartColumn:PL,FileChartColumnIncreasing:LL,FileChartLine:IL,FileChartPie:RL,FileCheck:DW,FileCheck2:Ihe,FileClock:Rhe,FileCode:Ohe,FileCode2:Dhe,FileCog:DL,FileDiff:Fhe,FileDigit:zhe,FileDown:jj,FileHeart:Bhe,FileImage:g3,FileInput:$he,FileJson:qhe,FileJson2:Uhe,FileKey:Hhe,FileKey2:Vhe,FileLock:Whe,FileLock2:Ghe,FileMinus:Yhe,FileMinus2:Khe,FileMusic:Zhe,FileOutput:Xhe,FilePen:OL,FilePenLine:cA,FilePlus:Jhe,FilePlus2:Qhe,FileQuestion:eme,FileScan:tme,FileSearch:nme,FileSearch2:sme,FileSliders:rme,FileSpreadsheet:pN,FileStack:OW,FileSymlink:ame,FileTerminal:ime,FileText:$r,FileType:lme,FileType2:ome,FileUp:cme,FileUser:dme,FileVideo:FW,FileVideo2:ume,FileVolume:mme,FileVolume2:hme,FileWarning:pme,FileX:xme,FileX2:fme,Files:gme,Film:wh,Filter:Nj,FilterX:yme,Fingerprint:vme,FireExtinguisher:bme,Fish:jme,FishOff:_me,FishSymbol:wme,Flag:y3,FlagOff:Nme,FlagTriangleLeft:kme,FlagTriangleRight:Sme,Flame:Fd,FlameKindling:Cme,Flashlight:Tme,FlashlightOff:Ame,FlaskConical:VT,FlaskConicalOff:Eme,FlaskRound:Mme,FlipHorizontal:zW,FlipHorizontal2:Lme,FlipVertical:Ime,FlipVertical2:Pme,Flower:Rme,Flower2:oN,Focus:Dme,FoldHorizontal:Ome,FoldVertical:Fme,Folder:upe,FolderArchive:zme,FolderCheck:Bme,FolderClock:$me,FolderClosed:Ume,FolderCode:qme,FolderCog:FL,FolderDot:Vme,FolderDown:Hme,FolderGit:Wme,FolderGit2:Gme,FolderHeart:Kme,FolderInput:Yme,FolderKanban:Zme,FolderKey:Xme,FolderLock:Qme,FolderMinus:Jme,FolderOpen:ny,FolderOpenDot:epe,FolderOutput:tpe,FolderPen:zL,FolderPlus:spe,FolderRoot:npe,FolderSearch:ape,FolderSearch2:rpe,FolderSymlink:ipe,FolderSync:ope,FolderTree:lpe,FolderUp:cpe,FolderX:dpe,Folders:hpe,Footprints:mpe,Forklift:ppe,Forward:fpe,Frame:xpe,Framer:gpe,Frown:ype,Fuel:vpe,Fullscreen:bpe,GalleryHorizontal:wpe,GalleryHorizontalEnd:_pe,GalleryThumbnails:jpe,GalleryVertical:kpe,GalleryVerticalEnd:Npe,Gamepad:Cpe,Gamepad2:Spe,Gauge:Ape,Gavel:Tpe,Gem:Epe,Ghost:OR,Gift:zo,GitBranch:Lpe,GitBranchPlus:Mpe,GitCommitHorizontal:BL,GitCommitVertical:Ppe,GitCompare:Rpe,GitCompareArrows:Ipe,GitFork:Dpe,GitGraph:Ope,GitMerge:Fpe,GitPullRequest:Vpe,GitPullRequestArrow:zpe,GitPullRequestClosed:Bpe,GitPullRequestCreate:Upe,GitPullRequestCreateArrow:$pe,GitPullRequestDraft:qpe,Github:Hpe,Gitlab:Gpe,GlassWater:Wpe,Glasses:Kpe,Globe:Ql,GlobeLock:Ype,Goal:Zpe,Grab:Xpe,GraduationCap:Uh,Grape:Qpe,Grid2x2:UL,Grid2x2Check:Jpe,Grid2x2Plus:$L,Grid2x2X:efe,Grid3x3:k_,Grip:sfe,GripHorizontal:tfe,GripVertical:Fp,Group:nfe,Guitar:rfe,Ham:afe,Hammer:BW,Hand:$W,HandCoins:ife,HandHeart:FR,HandHelping:tN,HandMetal:ofe,HandPlatter:lfe,Handshake:fN,HardDrive:UW,HardDriveDownload:cfe,HardDriveUpload:dfe,HardHat:ufe,Hash:HT,Haze:hfe,HdmiPort:mfe,Heading:gfe,Heading1:B9,Heading2:$9,Heading3:qW,Heading4:pfe,Heading5:ffe,Heading6:xfe,HeadphoneOff:yfe,Headphones:vfe,Headset:bfe,Heart:mo,HeartCrack:_fe,HeartHandshake:zR,HeartOff:wfe,HeartPulse:jfe,Heater:Nfe,Hexagon:kfe,Highlighter:Sfe,History:GT,Hop:Afe,HopOff:Cfe,Hospital:Tfe,Hotel:Efe,Hourglass:Mfe,House:ia,HousePlug:Lfe,HousePlus:Pfe,IceCreamBowl:qL,IceCreamCone:VL,IdCard:Ife,Image:ac,ImageDown:Rfe,ImageMinus:Dfe,ImageOff:Ofe,ImagePlay:Ffe,ImagePlus:a1,ImageUp:zfe,ImageUpscale:Bfe,Images:$fe,Import:Ufe,Inbox:WT,IndentDecrease:HL,IndentIncrease:GL,IndianRupee:qfe,Infinity:Vfe,Info:I5,InspectionPanel:Hfe,Instagram:vm,Italic:KT,IterationCcw:Gfe,IterationCw:Wfe,JapaneseYen:Kfe,Joystick:Yfe,Kanban:v3,Key:gb,KeyRound:b3,KeySquare:Zfe,Keyboard:Jfe,KeyboardMusic:Xfe,KeyboardOff:Qfe,Lamp:axe,LampCeiling:exe,LampDesk:txe,LampFloor:sxe,LampWallDown:nxe,LampWallUp:rxe,LandPlot:ixe,Landmark:VW,Languages:oxe,Laptop:cxe,LaptopMinimal:WL,LaptopMinimalCheck:lxe,Lasso:uxe,LassoSelect:dxe,Laugh:hxe,Layers:U9,Layers2:mxe,Layers3:pxe,LayoutDashboard:BR,LayoutGrid:r0,LayoutList:fxe,LayoutPanelLeft:xxe,LayoutPanelTop:gxe,LayoutTemplate:q_,Leaf:yxe,LeafyGreen:vxe,Lectern:bxe,LetterText:_xe,Library:i1,LibraryBig:wxe,LifeBuoy:q9,Ligature:jxe,Lightbulb:xN,LightbulbOff:Nxe,Link:vc,Link2:Rc,Link2Off:kxe,Linkedin:ry,List:ug,ListCheck:Sxe,ListChecks:zp,ListCollapse:Cxe,ListEnd:Axe,ListFilter:HW,ListMinus:Txe,ListMusic:Exe,ListOrdered:kj,ListPlus:Mxe,ListRestart:Lxe,ListStart:Pxe,ListTodo:Ixe,ListTree:Rxe,ListVideo:Dxe,ListX:Oxe,Loader:zxe,LoaderCircle:Wt,LoaderPinwheel:Fxe,Locate:V9,LocateFixed:Bxe,LocateOff:$xe,Lock:du,LockKeyhole:Uxe,LockKeyholeOpen:KL,LockOpen:YL,LogIn:$R,LogOut:UR,Logs:qxe,Lollipop:Vxe,Luggage:Hxe,Magnet:Gxe,Mail:on,MailCheck:H9,MailMinus:Wxe,MailOpen:G9,MailPlus:GW,MailQuestion:Kxe,MailSearch:Yxe,MailWarning:Zxe,MailX:W9,Mailbox:Xxe,Mails:Qxe,Map:qR,MapPin:oi,MapPinCheck:ege,MapPinCheckInside:Jxe,MapPinHouse:tge,MapPinMinus:nge,MapPinMinusInside:sge,MapPinOff:rge,MapPinPlus:ige,MapPinPlusInside:age,MapPinX:lge,MapPinXInside:oge,MapPinned:cge,Martini:dge,Maximize:VR,Maximize2:WW,Medal:_3,Megaphone:jh,MegaphoneOff:uge,Meh:hge,MemoryStick:mge,Menu:YT,Merge:pge,MessageCircle:Yd,MessageCircleCode:fge,MessageCircleDashed:xge,MessageCircleHeart:K9,MessageCircleMore:gge,MessageCircleOff:yge,MessageCirclePlus:vge,MessageCircleQuestion:Y9,MessageCircleReply:bge,MessageCircleWarning:_ge,MessageCircleX:wge,MessageSquare:ro,MessageSquareCode:jge,MessageSquareDashed:Nge,MessageSquareDiff:kge,MessageSquareDot:Sge,MessageSquareHeart:Z9,MessageSquareLock:Cge,MessageSquareMore:KW,MessageSquareOff:Age,MessageSquarePlus:v5,MessageSquareQuote:w3,MessageSquareReply:Tge,MessageSquareShare:Ege,MessageSquareText:Mge,MessageSquareWarning:Lge,MessageSquareX:Pge,MessagesSquare:X9,Mic:Sj,MicOff:Ige,MicVocal:ZL,Microchip:Rge,Microscope:Dge,Microwave:Oge,Milestone:Fge,Milk:Bge,MilkOff:zge,Minimize:Uge,Minimize2:$ge,Minus:gN,Monitor:Cj,MonitorCheck:qge,MonitorCog:Vge,MonitorDot:Hge,MonitorDown:Gge,MonitorOff:Wge,MonitorPause:Kge,MonitorPlay:Q9,MonitorSmartphone:Yge,MonitorSpeaker:Zge,MonitorStop:Xge,MonitorUp:HR,MonitorX:Qge,Moon:e0e,MoonStar:Jge,Mountain:s0e,MountainSnow:t0e,Mouse:i0e,MouseOff:n0e,MousePointer:ag,MousePointer2:r0e,MousePointerBan:a0e,MousePointerClick:lu,Move:YW,Move3d:XL,MoveDiagonal:l0e,MoveDiagonal2:o0e,MoveDown:u0e,MoveDownLeft:c0e,MoveDownRight:d0e,MoveHorizontal:h0e,MoveLeft:m0e,MoveRight:p0e,MoveUp:g0e,MoveUpLeft:f0e,MoveUpRight:x0e,MoveVertical:y0e,Music:J9,Music2:v0e,Music3:b0e,Music4:_0e,Navigation:ZW,Navigation2:j0e,Navigation2Off:w0e,NavigationOff:N0e,Network:k0e,Newspaper:V_,Nfc:S0e,Notebook:E0e,NotebookPen:C0e,NotebookTabs:A0e,NotebookText:T0e,NotepadText:L0e,NotepadTextDashed:M0e,Nut:I0e,NutOff:P0e,Octagon:D0e,OctagonAlert:d5,OctagonMinus:R0e,OctagonPause:QL,OctagonX:JL,Omega:O0e,Option:F0e,Orbit:z0e,Origami:B0e,Package:Eu,Package2:$0e,PackageCheck:U0e,PackageMinus:q0e,PackageOpen:V0e,PackagePlus:XW,PackageSearch:H0e,PackageX:G0e,PaintBucket:W0e,PaintRoller:K0e,Paintbrush:Y0e,PaintbrushVertical:eP,Palette:Ac,PanelBottom:Q0e,PanelBottomClose:Z0e,PanelBottomDashed:tP,PanelBottomOpen:X0e,PanelLeft:aP,PanelLeftClose:sP,PanelLeftDashed:nP,PanelLeftOpen:rP,PanelRight:tye,PanelRightClose:J0e,PanelRightDashed:iP,PanelRightOpen:eye,PanelTop:rye,PanelTopClose:sye,PanelTopDashed:oP,PanelTopOpen:nye,PanelsLeftBottom:aye,PanelsRightBottom:iye,PanelsTopLeft:N4,Paperclip:ZT,Parentheses:oye,ParkingMeter:lye,PartyPopper:bf,Pause:ay,PawPrint:cye,PcCase:dye,Pen:oj,PenLine:sN,PenOff:uye,PenTool:XT,Pencil:Za,PencilLine:ez,PencilOff:hye,PencilRuler:mye,Pentagon:pye,Percent:QT,PersonStanding:fye,PhilippinePeso:xye,Phone:pa,PhoneCall:QW,PhoneForwarded:gye,PhoneIncoming:yye,PhoneMissed:vye,PhoneOff:bye,PhoneOutgoing:_ye,Pi:wye,Piano:jye,Pickaxe:Nye,PictureInPicture:Sye,PictureInPicture2:kye,PiggyBank:Cye,Pilcrow:Eye,PilcrowLeft:Aye,PilcrowRight:Tye,Pill:Lye,PillBottle:Mye,Pin:JT,PinOff:JW,Pipette:Pye,Pizza:Iye,Plane:eK,PlaneLanding:Rye,PlaneTakeoff:Dye,Play:fd,Plug:R5,Plug2:Oye,PlugZap:lP,Plus:Js,Pocket:zye,PocketKnife:Fye,Podcast:Bye,Pointer:Uye,PointerOff:$ye,Popcorn:qye,Popsicle:Vye,PoundSterling:Hye,Power:tK,PowerOff:Gye,Presentation:yb,Printer:GR,PrinterCheck:Wye,Projector:Kye,Proportions:Yye,Puzzle:Zye,Pyramid:Xye,QrCode:hg,Quote:yN,Rabbit:Qye,Radar:tz,Radiation:Jye,Radical:eve,Radio:iy,RadioReceiver:tve,RadioTower:sve,Radius:nve,RailSymbol:rve,Rainbow:ave,Rat:ive,Ratio:ove,Receipt:xve,ReceiptCent:lve,ReceiptEuro:cve,ReceiptIndianRupee:dve,ReceiptJapaneseYen:uve,ReceiptPoundSterling:hve,ReceiptRussianRuble:mve,ReceiptSwissFranc:pve,ReceiptText:fve,RectangleEllipsis:cP,RectangleHorizontal:gve,RectangleVertical:yve,Recycle:vve,Redo:eE,Redo2:bve,RedoDot:_ve,RefreshCcw:sz,RefreshCcwDot:wve,RefreshCw:Ki,RefreshCwOff:jve,Refrigerator:Nve,Regex:kve,RemoveFormatting:Sve,Repeat:nz,Repeat1:Cve,Repeat2:Ave,Replace:Eve,ReplaceAll:Tve,Reply:sK,ReplyAll:Mve,Rewind:Lve,Ribbon:Pve,Rocket:oy,RockingChair:Ive,RollerCoaster:Rve,Rotate3d:dP,RotateCcw:bm,RotateCcwSquare:Dve,RotateCw:WR,RotateCwSquare:Ove,Route:rz,RouteOff:Fve,Router:zve,Rows2:uP,Rows3:hP,Rows4:Bve,Rss:$ve,Ruler:j3,RussianRuble:Uve,Sailboat:qve,Salad:Vve,Sandwich:Hve,Satellite:Wve,SatelliteDish:Gve,Save:Jo,SaveAll:Kve,SaveOff:Yve,Scale:az,Scale3d:mP,Scaling:Zve,Scan:r1e,ScanBarcode:Xve,ScanEye:Qve,ScanFace:Jve,ScanLine:e1e,ScanQrCode:t1e,ScanSearch:s1e,ScanText:n1e,School:a1e,Scissors:o1e,ScissorsLineDashed:i1e,ScreenShare:c1e,ScreenShareOff:l1e,Scroll:d1e,ScrollText:nK,Search:Fr,SearchCheck:u1e,SearchCode:h1e,SearchSlash:m1e,SearchX:rK,Section:p1e,Send:Dr,SendHorizontal:pP,SendToBack:f1e,SeparatorHorizontal:x1e,SeparatorVertical:g1e,Server:_1e,ServerCog:y1e,ServerCrash:v1e,ServerOff:b1e,Settings:ic,Settings2:tE,Shapes:w1e,Share:aK,Share2:zd,Sheet:j1e,Shell:N1e,Shield:_f,ShieldAlert:iz,ShieldBan:k1e,ShieldCheck:a0,ShieldEllipsis:S1e,ShieldHalf:C1e,ShieldMinus:A1e,ShieldOff:KR,ShieldPlus:T1e,ShieldQuestion:E1e,ShieldX:fP,Ship:L1e,ShipWheel:M1e,Shirt:P1e,ShoppingBag:D5,ShoppingBasket:I1e,ShoppingCart:ib,Shovel:R1e,ShowerHead:D1e,Shrink:O1e,Shrub:F1e,Shuffle:YR,Sigma:z1e,Signal:V1e,SignalHigh:B1e,SignalLow:$1e,SignalMedium:U1e,SignalZero:q1e,Signature:H1e,Signpost:W1e,SignpostBig:G1e,Siren:K1e,SkipBack:Y1e,SkipForward:iK,Skull:Z1e,Slack:X1e,Slash:Q1e,Slice:J1e,SlidersHorizontal:sE,SlidersVertical:xP,Smartphone:Jy,SmartphoneCharging:ebe,SmartphoneNfc:tbe,Smile:nbe,SmilePlus:sbe,Snail:rbe,Snowflake:gj,Sofa:abe,Soup:ibe,Space:obe,Spade:lbe,Sparkle:N3,Sparkles:yn,Speaker:cbe,Speech:dbe,SpellCheck:hbe,SpellCheck2:ube,Spline:mbe,Split:pbe,SprayCan:fbe,Sprout:nE,Square:H_,SquareActivity:gP,SquareArrowDown:bP,SquareArrowDownLeft:yP,SquareArrowDownRight:vP,SquareArrowLeft:_P,SquareArrowOutDownLeft:wP,SquareArrowOutDownRight:jP,SquareArrowOutUpLeft:NP,SquareArrowOutUpRight:kP,SquareArrowRight:SP,SquareArrowUp:TP,SquareArrowUpLeft:CP,SquareArrowUpRight:AP,SquareAsterisk:EP,SquareBottomDashedScissors:MP,SquareChartGantt:Tk,SquareCheck:LP,SquareCheckBig:k4,SquareChevronDown:PP,SquareChevronLeft:IP,SquareChevronRight:RP,SquareChevronUp:DP,SquareCode:OP,SquareDashed:BP,SquareDashedBottom:gbe,SquareDashedBottomCode:xbe,SquareDashedKanban:FP,SquareDashedMousePointer:zP,SquareDivide:$P,SquareDot:UP,SquareEqual:qP,SquareFunction:VP,SquareKanban:HP,SquareLibrary:GP,SquareM:WP,SquareMenu:KP,SquareMinus:YP,SquareMousePointer:ZP,SquareParking:QP,SquareParkingOff:XP,SquarePen:kp,SquarePercent:JP,SquarePi:eI,SquarePilcrow:tI,SquarePlay:sI,SquarePlus:nI,SquarePower:rI,SquareRadical:ybe,SquareScissors:aI,SquareSigma:iI,SquareSlash:oI,SquareSplitHorizontal:lI,SquareSplitVertical:cI,SquareSquare:vbe,SquareStack:bbe,SquareTerminal:dI,SquareUser:hI,SquareUserRound:uI,SquareX:mI,Squircle:_be,Squirrel:wbe,Stamp:jbe,Star:Wa,StarHalf:Nbe,StarOff:kbe,StepBack:Sbe,StepForward:Cbe,Stethoscope:Abe,Sticker:Tbe,StickyNote:oK,Store:lK,StretchHorizontal:Ebe,StretchVertical:Mbe,Strikethrough:cK,Subscript:Lbe,Sun:Aj,SunDim:Pbe,SunMedium:Ibe,SunMoon:Rbe,SunSnow:Dbe,Sunrise:Obe,Sunset:Fbe,Superscript:zbe,SwatchBook:Bbe,SwissFranc:$be,SwitchCamera:Ube,Sword:qbe,Swords:Vbe,Syringe:Hbe,Table:lz,Table2:oz,TableCellsMerge:Gbe,TableCellsSplit:Wbe,TableColumnsSplit:Kbe,TableOfContents:Ybe,TableProperties:Zbe,TableRowsSplit:Xbe,Tablet:cz,TabletSmartphone:Qbe,Tablets:Jbe,Tag:wf,Tags:dK,Tally1:e_e,Tally2:t_e,Tally3:s_e,Tally4:n_e,Tally5:r_e,Tangent:a_e,Target:uu,Telescope:i_e,Tent:l_e,TentTree:o_e,Terminal:c_e,TestTube:d_e,TestTubeDiagonal:pI,TestTubes:u_e,Text:x_e,TextCursor:m_e,TextCursorInput:h_e,TextQuote:p_e,TextSearch:f_e,TextSelect:fI,Theater:g_e,Thermometer:uK,ThermometerSnowflake:y_e,ThermometerSun:v_e,ThumbsDown:hK,ThumbsUp:mg,Ticket:mK,TicketCheck:b_e,TicketMinus:__e,TicketPercent:w_e,TicketPlus:j_e,TicketSlash:N_e,TicketX:k_e,Tickets:C_e,TicketsPlane:S_e,Timer:E_e,TimerOff:A_e,TimerReset:T_e,ToggleLeft:M_e,ToggleRight:L_e,Toilet:P_e,Tornado:I_e,Torus:R_e,Touchpad:O_e,TouchpadOff:D_e,TowerControl:F_e,ToyBrick:z_e,Tractor:B_e,TrafficCone:$_e,TrainFront:q_e,TrainFrontTunnel:U_e,TrainTrack:V_e,TramFront:xI,Trash:H_e,Trash2:Rn,TreeDeciduous:G_e,TreePalm:gI,TreePine:rE,Trees:W_e,Trello:K_e,TrendingDown:vN,TrendingUp:kl,TrendingUpDown:Y_e,Triangle:X_e,TriangleAlert:hd,TriangleRight:Z_e,Trophy:ll,Truck:pK,Turtle:Q_e,Tv:ewe,TvMinimal:yI,TvMinimalPlay:J_e,Twitch:twe,Twitter:swe,Type:rwe,TypeOutline:nwe,Umbrella:iwe,UmbrellaOff:awe,Underline:dz,Undo:aE,Undo2:fK,UndoDot:owe,UnfoldHorizontal:lwe,UnfoldVertical:cwe,Ungroup:dwe,University:vI,Unlink:ZR,Unlink2:uwe,Unplug:xK,Upload:Ja,Usb:hwe,User:Eo,UserCheck:bN,UserCog:gK,UserMinus:uz,UserPen:mwe,UserPlus:Sl,UserRound:kI,UserRoundCheck:bI,UserRoundCog:_I,UserRoundMinus:wI,UserRoundPen:pwe,UserRoundPlus:jI,UserRoundSearch:fwe,UserRoundX:NI,UserSearch:xwe,UserX:gwe,Users:Bn,UsersRound:qv,Utensils:CI,UtensilsCrossed:SI,UtilityPole:ywe,Variable:hz,Vault:vwe,Vegan:bwe,VenetianMask:_we,Vibrate:jwe,VibrateOff:wwe,Video:Zr,VideoOff:Nwe,Videotape:kwe,View:Swe,Voicemail:Cwe,Volleyball:Awe,Volume:Mwe,Volume1:Twe,Volume2:yK,VolumeOff:Ewe,VolumeX:vK,Vote:Lwe,Wallet:mz,WalletCards:Pwe,WalletMinimal:AI,Wallpaper:Iwe,Wand:Rwe,WandSparkles:um,Warehouse:Dwe,WashingMachine:Owe,Watch:Fwe,Waves:zwe,Waypoints:Bwe,Webcam:$we,Webhook:qwe,WebhookOff:Uwe,Weight:Vwe,Wheat:Gwe,WheatOff:Hwe,WholeWord:Wwe,Wifi:Qwe,WifiHigh:Kwe,WifiLow:Ywe,WifiOff:Zwe,WifiZero:Xwe,Wind:eje,WindArrowDown:Jwe,Wine:bK,WineOff:tje,Workflow:_K,Worm:sje,WrapText:nje,Wrench:O5,X:dr,Youtube:rje,Zap:jf,ZapOff:aje,ZoomIn:iE,ZoomOut:pz},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 T4e=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:pae,AArrowDownIcon:pae,AArrowUp:fae,AArrowUpIcon:fae,ALargeSmall:xae,ALargeSmallIcon:xae,Accessibility:gae,AccessibilityIcon:gae,Activity:vf,ActivityIcon:vf,ActivitySquare:gP,ActivitySquareIcon:gP,AirVent:yae,AirVentIcon:yae,Airplay:vae,AirplayIcon:vae,AlarmCheck:NM,AlarmCheckIcon:NM,AlarmClock:_ae,AlarmClockCheck:NM,AlarmClockCheckIcon:NM,AlarmClockIcon:_ae,AlarmClockMinus:kM,AlarmClockMinusIcon:kM,AlarmClockOff:bae,AlarmClockOffIcon:bae,AlarmClockPlus:SM,AlarmClockPlusIcon:SM,AlarmMinus:kM,AlarmMinusIcon:kM,AlarmPlus:SM,AlarmPlusIcon:SM,AlarmSmoke:wae,AlarmSmokeIcon:wae,Album:jae,AlbumIcon:jae,AlertCircle:po,AlertCircleIcon:po,AlertOctagon:d5,AlertOctagonIcon:d5,AlertTriangle:hd,AlertTriangleIcon:hd,AlignCenter:TR,AlignCenterHorizontal:Nae,AlignCenterHorizontalIcon:Nae,AlignCenterIcon:TR,AlignCenterVertical:kae,AlignCenterVerticalIcon:kae,AlignEndHorizontal:Sae,AlignEndHorizontalIcon:Sae,AlignEndVertical:Cae,AlignEndVerticalIcon:Cae,AlignHorizontalDistributeCenter:Aae,AlignHorizontalDistributeCenterIcon:Aae,AlignHorizontalDistributeEnd:Tae,AlignHorizontalDistributeEndIcon:Tae,AlignHorizontalDistributeStart:Eae,AlignHorizontalDistributeStartIcon:Eae,AlignHorizontalJustifyCenter:Mae,AlignHorizontalJustifyCenterIcon:Mae,AlignHorizontalJustifyEnd:Lae,AlignHorizontalJustifyEndIcon:Lae,AlignHorizontalJustifyStart:Pae,AlignHorizontalJustifyStartIcon:Pae,AlignHorizontalSpaceAround:Iae,AlignHorizontalSpaceAroundIcon:Iae,AlignHorizontalSpaceBetween:Rae,AlignHorizontalSpaceBetweenIcon:Rae,AlignJustify:Dae,AlignJustifyIcon:Dae,AlignLeft:ER,AlignLeftIcon:ER,AlignRight:MR,AlignRightIcon:MR,AlignStartHorizontal:Oae,AlignStartHorizontalIcon:Oae,AlignStartVertical:Fae,AlignStartVerticalIcon:Fae,AlignVerticalDistributeCenter:zae,AlignVerticalDistributeCenterIcon:zae,AlignVerticalDistributeEnd:Bae,AlignVerticalDistributeEndIcon:Bae,AlignVerticalDistributeStart:$ae,AlignVerticalDistributeStartIcon:$ae,AlignVerticalJustifyCenter:Uae,AlignVerticalJustifyCenterIcon:Uae,AlignVerticalJustifyEnd:qae,AlignVerticalJustifyEndIcon:qae,AlignVerticalJustifyStart:Vae,AlignVerticalJustifyStartIcon:Vae,AlignVerticalSpaceAround:Hae,AlignVerticalSpaceAroundIcon:Hae,AlignVerticalSpaceBetween:Gae,AlignVerticalSpaceBetweenIcon:Gae,Ambulance:Wae,AmbulanceIcon:Wae,Ampersand:Kae,AmpersandIcon:Kae,Ampersands:Yae,AmpersandsIcon:Yae,Amphora:Zae,AmphoraIcon:Zae,Anchor:Xae,AnchorIcon:Xae,Angry:Qae,AngryIcon:Qae,Annoyed:Jae,AnnoyedIcon:Jae,Antenna:eie,AntennaIcon:eie,Anvil:tie,AnvilIcon:tie,Aperture:sie,ApertureIcon:sie,AppWindow:rie,AppWindowIcon:rie,AppWindowMac:nie,AppWindowMacIcon:nie,Apple:aie,AppleIcon:aie,Archive:gm,ArchiveIcon:gm,ArchiveRestore:zT,ArchiveRestoreIcon:zT,ArchiveX:iie,ArchiveXIcon:iie,AreaChart:BM,AreaChartIcon:BM,Armchair:oie,ArmchairIcon:oie,ArrowBigDown:cie,ArrowBigDownDash:lie,ArrowBigDownDashIcon:lie,ArrowBigDownIcon:cie,ArrowBigLeft:uie,ArrowBigLeftDash:die,ArrowBigLeftDashIcon:die,ArrowBigLeftIcon:uie,ArrowBigRight:mie,ArrowBigRightDash:hie,ArrowBigRightDashIcon:hie,ArrowBigRightIcon:mie,ArrowBigUp:fie,ArrowBigUpDash:pie,ArrowBigUpDashIcon:pie,ArrowBigUpIcon:fie,ArrowDown:tx,ArrowDown01:xie,ArrowDown01Icon:xie,ArrowDown10:gie,ArrowDown10Icon:gie,ArrowDownAZ:CM,ArrowDownAZIcon:CM,ArrowDownAz:CM,ArrowDownAzIcon:CM,ArrowDownCircle:QM,ArrowDownCircleIcon:QM,ArrowDownFromLine:yie,ArrowDownFromLineIcon:yie,ArrowDownIcon:tx,ArrowDownLeft:vie,ArrowDownLeftFromCircle:eL,ArrowDownLeftFromCircleIcon:eL,ArrowDownLeftFromSquare:wP,ArrowDownLeftFromSquareIcon:wP,ArrowDownLeftIcon:vie,ArrowDownLeftSquare:yP,ArrowDownLeftSquareIcon:yP,ArrowDownNarrowWide:bie,ArrowDownNarrowWideIcon:bie,ArrowDownRight:CW,ArrowDownRightFromCircle:tL,ArrowDownRightFromCircleIcon:tL,ArrowDownRightFromSquare:jP,ArrowDownRightFromSquareIcon:jP,ArrowDownRightIcon:CW,ArrowDownRightSquare:vP,ArrowDownRightSquareIcon:vP,ArrowDownSquare:bP,ArrowDownSquareIcon:bP,ArrowDownToDot:_ie,ArrowDownToDotIcon:_ie,ArrowDownToLine:wie,ArrowDownToLineIcon:wie,ArrowDownUp:jie,ArrowDownUpIcon:jie,ArrowDownWideNarrow:AM,ArrowDownWideNarrowIcon:AM,ArrowDownZA:TM,ArrowDownZAIcon:TM,ArrowDownZa:TM,ArrowDownZaIcon:TM,ArrowLeft:_a,ArrowLeftCircle:JM,ArrowLeftCircleIcon:JM,ArrowLeftFromLine:Nie,ArrowLeftFromLineIcon:Nie,ArrowLeftIcon:_a,ArrowLeftRight:AW,ArrowLeftRightIcon:AW,ArrowLeftSquare:_P,ArrowLeftSquareIcon:_P,ArrowLeftToLine:kie,ArrowLeftToLineIcon:kie,ArrowRight:Xa,ArrowRightCircle:rL,ArrowRightCircleIcon:rL,ArrowRightFromLine:Sie,ArrowRightFromLineIcon:Sie,ArrowRightIcon:Xa,ArrowRightLeft:M5,ArrowRightLeftIcon:M5,ArrowRightSquare:SP,ArrowRightSquareIcon:SP,ArrowRightToLine:Cie,ArrowRightToLineIcon:Cie,ArrowUp:Gm,ArrowUp01:Aie,ArrowUp01Icon:Aie,ArrowUp10:Tie,ArrowUp10Icon:Tie,ArrowUpAZ:EM,ArrowUpAZIcon:EM,ArrowUpAz:EM,ArrowUpAzIcon:EM,ArrowUpCircle:aL,ArrowUpCircleIcon:aL,ArrowUpDown:_x,ArrowUpDownIcon:_x,ArrowUpFromDot:Eie,ArrowUpFromDotIcon:Eie,ArrowUpFromLine:Mie,ArrowUpFromLineIcon:Mie,ArrowUpIcon:Gm,ArrowUpLeft:Lie,ArrowUpLeftFromCircle:sL,ArrowUpLeftFromCircleIcon:sL,ArrowUpLeftFromSquare:NP,ArrowUpLeftFromSquareIcon:NP,ArrowUpLeftIcon:Lie,ArrowUpLeftSquare:CP,ArrowUpLeftSquareIcon:CP,ArrowUpNarrowWide:MM,ArrowUpNarrowWideIcon:MM,ArrowUpRight:I9,ArrowUpRightFromCircle:nL,ArrowUpRightFromCircleIcon:nL,ArrowUpRightFromSquare:kP,ArrowUpRightFromSquareIcon:kP,ArrowUpRightIcon:I9,ArrowUpRightSquare:AP,ArrowUpRightSquareIcon:AP,ArrowUpSquare:TP,ArrowUpSquareIcon:TP,ArrowUpToLine:Pie,ArrowUpToLineIcon:Pie,ArrowUpWideNarrow:Iie,ArrowUpWideNarrowIcon:Iie,ArrowUpZA:LM,ArrowUpZAIcon:LM,ArrowUpZa:LM,ArrowUpZaIcon:LM,ArrowsUpFromLine:Rie,ArrowsUpFromLineIcon:Rie,Asterisk:Die,AsteriskIcon:Die,AsteriskSquare:EP,AsteriskSquareIcon:EP,AtSign:Oie,AtSignIcon:Oie,Atom:Fie,AtomIcon:Fie,AudioLines:zie,AudioLinesIcon:zie,AudioWaveform:Bie,AudioWaveformIcon:Bie,Award:cu,AwardIcon:cu,Axe:$ie,AxeIcon:$ie,Axis3D:PM,Axis3DIcon:PM,Axis3d:PM,Axis3dIcon:PM,Baby:Uie,BabyIcon:Uie,Backpack:qie,BackpackIcon:qie,Badge:aoe,BadgeAlert:Vie,BadgeAlertIcon:Vie,BadgeCent:Hie,BadgeCentIcon:Hie,BadgeCheck:IM,BadgeCheckIcon:IM,BadgeDollarSign:Gie,BadgeDollarSignIcon:Gie,BadgeEuro:Wie,BadgeEuroIcon:Wie,BadgeHelp:Kie,BadgeHelpIcon:Kie,BadgeIcon:aoe,BadgeIndianRupee:Yie,BadgeIndianRupeeIcon:Yie,BadgeInfo:Zie,BadgeInfoIcon:Zie,BadgeJapaneseYen:Xie,BadgeJapaneseYenIcon:Xie,BadgeMinus:Qie,BadgeMinusIcon:Qie,BadgePercent:Jie,BadgePercentIcon:Jie,BadgePlus:eoe,BadgePlusIcon:eoe,BadgePoundSterling:toe,BadgePoundSterlingIcon:toe,BadgeRussianRuble:soe,BadgeRussianRubleIcon:soe,BadgeSwissFranc:noe,BadgeSwissFrancIcon:noe,BadgeX:roe,BadgeXIcon:roe,BaggageClaim:ioe,BaggageClaimIcon:ioe,Ban:R9,BanIcon:R9,Banana:ooe,BananaIcon:ooe,Bandage:loe,BandageIcon:loe,Banknote:coe,BanknoteIcon:coe,BarChart:WM,BarChart2:KM,BarChart2Icon:KM,BarChart3:ol,BarChart3Icon:ol,BarChart4:HM,BarChart4Icon:HM,BarChartBig:VM,BarChartBigIcon:VM,BarChartHorizontal:UM,BarChartHorizontalBig:$M,BarChartHorizontalBigIcon:$M,BarChartHorizontalIcon:UM,BarChartIcon:WM,Barcode:doe,BarcodeIcon:doe,Baseline:uoe,BaselineIcon:uoe,Bath:t0,BathIcon:t0,Battery:goe,BatteryCharging:hoe,BatteryChargingIcon:hoe,BatteryFull:moe,BatteryFullIcon:moe,BatteryIcon:goe,BatteryLow:poe,BatteryLowIcon:poe,BatteryMedium:foe,BatteryMediumIcon:foe,BatteryWarning:xoe,BatteryWarningIcon:xoe,Beaker:TW,BeakerIcon:TW,Bean:voe,BeanIcon:voe,BeanOff:yoe,BeanOffIcon:yoe,Bed:U_,BedDouble:p3,BedDoubleIcon:p3,BedIcon:U_,BedSingle:boe,BedSingleIcon:boe,Beef:_oe,BeefIcon:_oe,Beer:joe,BeerIcon:joe,BeerOff:woe,BeerOffIcon:woe,Bell:Nx,BellDot:Noe,BellDotIcon:Noe,BellElectric:koe,BellElectricIcon:koe,BellIcon:Nx,BellMinus:Soe,BellMinusIcon:Soe,BellOff:L5,BellOffIcon:L5,BellPlus:Coe,BellPlusIcon:Coe,BellRing:f3,BellRingIcon:f3,BetweenHorizonalEnd:RM,BetweenHorizonalEndIcon:RM,BetweenHorizonalStart:DM,BetweenHorizonalStartIcon:DM,BetweenHorizontalEnd:RM,BetweenHorizontalEndIcon:RM,BetweenHorizontalStart:DM,BetweenHorizontalStartIcon:DM,BetweenVerticalEnd:Aoe,BetweenVerticalEndIcon:Aoe,BetweenVerticalStart:Toe,BetweenVerticalStartIcon:Toe,BicepsFlexed:Eoe,BicepsFlexedIcon:Eoe,Bike:Moe,BikeIcon:Moe,Binary:Loe,BinaryIcon:Loe,Binoculars:Poe,BinocularsIcon:Poe,Biohazard:Ioe,BiohazardIcon:Ioe,Bird:Roe,BirdIcon:Roe,Bitcoin:Doe,BitcoinIcon:Doe,Blend:Ooe,BlendIcon:Ooe,Blinds:Foe,BlindsIcon:Foe,Blocks:zoe,BlocksIcon:zoe,Bluetooth:qoe,BluetoothConnected:Boe,BluetoothConnectedIcon:Boe,BluetoothIcon:qoe,BluetoothOff:$oe,BluetoothOffIcon:$oe,BluetoothSearching:Uoe,BluetoothSearchingIcon:Uoe,Bold:BT,BoldIcon:BT,Bolt:Voe,BoltIcon:Voe,Bomb:Hoe,BombIcon:Hoe,Bone:Goe,BoneIcon:Goe,Book:ple,BookA:Woe,BookAIcon:Woe,BookAudio:Koe,BookAudioIcon:Koe,BookCheck:Yoe,BookCheckIcon:Yoe,BookCopy:Zoe,BookCopyIcon:Zoe,BookDashed:OM,BookDashedIcon:OM,BookDown:Xoe,BookDownIcon:Xoe,BookHeadphones:Qoe,BookHeadphonesIcon:Qoe,BookHeart:Joe,BookHeartIcon:Joe,BookIcon:ple,BookImage:ele,BookImageIcon:ele,BookKey:tle,BookKeyIcon:tle,BookLock:sle,BookLockIcon:sle,BookMarked:nle,BookMarkedIcon:nle,BookMinus:rle,BookMinusIcon:rle,BookOpen:Op,BookOpenCheck:ale,BookOpenCheckIcon:ale,BookOpenIcon:Op,BookOpenText:ile,BookOpenTextIcon:ile,BookPlus:ole,BookPlusIcon:ole,BookTemplate:OM,BookTemplateIcon:OM,BookText:lle,BookTextIcon:lle,BookType:cle,BookTypeIcon:cle,BookUp:ule,BookUp2:dle,BookUp2Icon:dle,BookUpIcon:ule,BookUser:hle,BookUserIcon:hle,BookX:mle,BookXIcon:mle,Bookmark:s1,BookmarkCheck:fle,BookmarkCheckIcon:fle,BookmarkIcon:s1,BookmarkMinus:xle,BookmarkMinusIcon:xle,BookmarkPlus:$T,BookmarkPlusIcon:$T,BookmarkX:gle,BookmarkXIcon:gle,BoomBox:yle,BoomBoxIcon:yle,Bot:UT,BotIcon:UT,BotMessageSquare:vle,BotMessageSquareIcon:vle,BotOff:ble,BotOffIcon:ble,Box:EW,BoxIcon:EW,BoxSelect:BP,BoxSelectIcon:BP,Boxes:_le,BoxesIcon:_le,Braces:FM,BracesIcon:FM,Brackets:wle,BracketsIcon:wle,Brain:MW,BrainCircuit:jle,BrainCircuitIcon:jle,BrainCog:Nle,BrainCogIcon:Nle,BrainIcon:MW,BrickWall:kle,BrickWallIcon:kle,Briefcase:kx,BriefcaseBusiness:Sle,BriefcaseBusinessIcon:Sle,BriefcaseConveyorBelt:Cle,BriefcaseConveyorBeltIcon:Cle,BriefcaseIcon:kx,BriefcaseMedical:Ale,BriefcaseMedicalIcon:Ale,BringToFront:Tle,BringToFrontIcon:Tle,Brush:Ele,BrushIcon:Ele,Bug:Ple,BugIcon:Ple,BugOff:Mle,BugOffIcon:Mle,BugPlay:Lle,BugPlayIcon:Lle,Building:LR,Building2:Ni,Building2Icon:Ni,BuildingIcon:LR,Bus:Rle,BusFront:Ile,BusFrontIcon:Ile,BusIcon:Rle,Cable:Ole,CableCar:Dle,CableCarIcon:Dle,CableIcon:Ole,Cake:Wm,CakeIcon:Wm,CakeSlice:Fle,CakeSliceIcon:Fle,Calculator:P5,CalculatorIcon:P5,Calendar:ra,Calendar1:zle,Calendar1Icon:zle,CalendarArrowDown:Ble,CalendarArrowDownIcon:Ble,CalendarArrowUp:$le,CalendarArrowUpIcon:$le,CalendarCheck:n1,CalendarCheck2:Ule,CalendarCheck2Icon:Ule,CalendarCheckIcon:n1,CalendarClock:ym,CalendarClockIcon:ym,CalendarCog:qle,CalendarCogIcon:qle,CalendarDays:Vc,CalendarDaysIcon:Vc,CalendarFold:Vle,CalendarFoldIcon:Vle,CalendarHeart:hN,CalendarHeartIcon:hN,CalendarIcon:ra,CalendarMinus:Gle,CalendarMinus2:Hle,CalendarMinus2Icon:Hle,CalendarMinusIcon:Gle,CalendarOff:D9,CalendarOffIcon:D9,CalendarPlus:Wy,CalendarPlus2:Wle,CalendarPlus2Icon:Wle,CalendarPlusIcon:Wy,CalendarRange:Kle,CalendarRangeIcon:Kle,CalendarSearch:Yle,CalendarSearchIcon:Yle,CalendarSync:Zle,CalendarSyncIcon:Zle,CalendarX:LW,CalendarX2:Xle,CalendarX2Icon:Xle,CalendarXIcon:LW,Camera:s0,CameraIcon:s0,CameraOff:Qle,CameraOffIcon:Qle,CandlestickChart:qM,CandlestickChartIcon:qM,Candy:tce,CandyCane:Jle,CandyCaneIcon:Jle,CandyIcon:tce,CandyOff:ece,CandyOffIcon:ece,Cannabis:sce,CannabisIcon:sce,Captions:zM,CaptionsIcon:zM,CaptionsOff:nce,CaptionsOffIcon:nce,Car:ice,CarFront:rce,CarFrontIcon:rce,CarIcon:ice,CarTaxiFront:ace,CarTaxiFrontIcon:ace,Caravan:oce,CaravanIcon:oce,Carrot:lce,CarrotIcon:lce,CaseLower:cce,CaseLowerIcon:cce,CaseSensitive:dce,CaseSensitiveIcon:dce,CaseUpper:uce,CaseUpperIcon:uce,CassetteTape:hce,CassetteTapeIcon:hce,Cast:mce,CastIcon:mce,Castle:pce,CastleIcon:pce,Cat:fce,CatIcon:fce,Cctv:xce,CctvIcon:xce,ChartArea:BM,ChartAreaIcon:BM,ChartBar:UM,ChartBarBig:$M,ChartBarBigIcon:$M,ChartBarDecreasing:gce,ChartBarDecreasingIcon:gce,ChartBarIcon:UM,ChartBarIncreasing:yce,ChartBarIncreasingIcon:yce,ChartBarStacked:vce,ChartBarStackedIcon:vce,ChartCandlestick:qM,ChartCandlestickIcon:qM,ChartColumn:ol,ChartColumnBig:VM,ChartColumnBigIcon:VM,ChartColumnDecreasing:bce,ChartColumnDecreasingIcon:bce,ChartColumnIcon:ol,ChartColumnIncreasing:HM,ChartColumnIncreasingIcon:HM,ChartColumnStacked:_ce,ChartColumnStackedIcon:_ce,ChartGantt:wce,ChartGanttIcon:wce,ChartLine:GM,ChartLineIcon:GM,ChartNetwork:jce,ChartNetworkIcon:jce,ChartNoAxesColumn:KM,ChartNoAxesColumnDecreasing:Nce,ChartNoAxesColumnDecreasingIcon:Nce,ChartNoAxesColumnIcon:KM,ChartNoAxesColumnIncreasing:WM,ChartNoAxesColumnIncreasingIcon:WM,ChartNoAxesCombined:kce,ChartNoAxesCombinedIcon:kce,ChartNoAxesGantt:YM,ChartNoAxesGanttIcon:YM,ChartPie:ZM,ChartPieIcon:ZM,ChartScatter:XM,ChartScatterIcon:XM,ChartSpline:Sce,ChartSplineIcon:Sce,Check:da,CheckCheck:PR,CheckCheckIcon:PR,CheckCircle:To,CheckCircle2:Rr,CheckCircle2Icon:Rr,CheckCircleIcon:To,CheckIcon:da,CheckSquare:k4,CheckSquare2:LP,CheckSquare2Icon:LP,CheckSquareIcon:k4,ChefHat:Cce,ChefHatIcon:Cce,Cherry:Ace,CherryIcon:Ace,ChevronDown:Po,ChevronDownCircle:iL,ChevronDownCircleIcon:iL,ChevronDownIcon:Po,ChevronDownSquare:PP,ChevronDownSquareIcon:PP,ChevronFirst:Tce,ChevronFirstIcon:Tce,ChevronLast:Ece,ChevronLastIcon:Ece,ChevronLeft:Cc,ChevronLeftCircle:oL,ChevronLeftCircleIcon:oL,ChevronLeftIcon:Cc,ChevronLeftSquare:IP,ChevronLeftSquareIcon:IP,ChevronRight:Qa,ChevronRightCircle:lL,ChevronRightCircleIcon:lL,ChevronRightIcon:Qa,ChevronRightSquare:RP,ChevronRightSquareIcon:RP,ChevronUp:Qy,ChevronUpCircle:cL,ChevronUpCircleIcon:cL,ChevronUpIcon:Qy,ChevronUpSquare:DP,ChevronUpSquareIcon:DP,ChevronsDown:Lce,ChevronsDownIcon:Lce,ChevronsDownUp:Mce,ChevronsDownUpIcon:Mce,ChevronsLeft:Rce,ChevronsLeftIcon:Rce,ChevronsLeftRight:Ice,ChevronsLeftRightEllipsis:Pce,ChevronsLeftRightEllipsisIcon:Pce,ChevronsLeftRightIcon:Ice,ChevronsRight:Oce,ChevronsRightIcon:Oce,ChevronsRightLeft:Dce,ChevronsRightLeftIcon:Dce,ChevronsUp:Fce,ChevronsUpDown:fb,ChevronsUpDownIcon:fb,ChevronsUpIcon:Fce,Chrome:IR,ChromeIcon:IR,Church:zce,ChurchIcon:zce,Cigarette:$ce,CigaretteIcon:$ce,CigaretteOff:Bce,CigaretteOffIcon:Bce,Circle:Sx,CircleAlert:po,CircleAlertIcon:po,CircleArrowDown:QM,CircleArrowDownIcon:QM,CircleArrowLeft:JM,CircleArrowLeftIcon:JM,CircleArrowOutDownLeft:eL,CircleArrowOutDownLeftIcon:eL,CircleArrowOutDownRight:tL,CircleArrowOutDownRightIcon:tL,CircleArrowOutUpLeft:sL,CircleArrowOutUpLeftIcon:sL,CircleArrowOutUpRight:nL,CircleArrowOutUpRightIcon:nL,CircleArrowRight:rL,CircleArrowRightIcon:rL,CircleArrowUp:aL,CircleArrowUpIcon:aL,CircleCheck:Rr,CircleCheckBig:To,CircleCheckBigIcon:To,CircleCheckIcon:Rr,CircleChevronDown:iL,CircleChevronDownIcon:iL,CircleChevronLeft:oL,CircleChevronLeftIcon:oL,CircleChevronRight:lL,CircleChevronRightIcon:lL,CircleChevronUp:cL,CircleChevronUpIcon:cL,CircleDashed:Uce,CircleDashedIcon:Uce,CircleDivide:dL,CircleDivideIcon:dL,CircleDollarSign:qce,CircleDollarSignIcon:qce,CircleDot:Hce,CircleDotDashed:Vce,CircleDotDashedIcon:Vce,CircleDotIcon:Hce,CircleEllipsis:Gce,CircleEllipsisIcon:Gce,CircleEqual:Wce,CircleEqualIcon:Wce,CircleFadingArrowUp:Kce,CircleFadingArrowUpIcon:Kce,CircleFadingPlus:Yce,CircleFadingPlusIcon:Yce,CircleGauge:uL,CircleGaugeIcon:uL,CircleHelp:c5,CircleHelpIcon:c5,CircleIcon:Sx,CircleMinus:hL,CircleMinusIcon:hL,CircleOff:Zce,CircleOffIcon:Zce,CircleParking:pL,CircleParkingIcon:pL,CircleParkingOff:mL,CircleParkingOffIcon:mL,CirclePause:fL,CirclePauseIcon:fL,CirclePercent:xL,CirclePercentIcon:xL,CirclePlay:vh,CirclePlayIcon:vh,CirclePlus:gL,CirclePlusIcon:gL,CirclePower:yL,CirclePowerIcon:yL,CircleSlash:Xce,CircleSlash2:vL,CircleSlash2Icon:vL,CircleSlashIcon:Xce,CircleSlashed:vL,CircleSlashedIcon:vL,CircleStop:bL,CircleStopIcon:bL,CircleUser:wL,CircleUserIcon:wL,CircleUserRound:_L,CircleUserRoundIcon:_L,CircleX:Rd,CircleXIcon:Rd,CircuitBoard:Qce,CircuitBoardIcon:Qce,Citrus:Jce,CitrusIcon:Jce,Clapperboard:O9,ClapperboardIcon:O9,Clipboard:ide,ClipboardCheck:x3,ClipboardCheckIcon:x3,ClipboardCopy:ede,ClipboardCopyIcon:ede,ClipboardEdit:NL,ClipboardEditIcon:NL,ClipboardIcon:ide,ClipboardList:r1,ClipboardListIcon:r1,ClipboardMinus:tde,ClipboardMinusIcon:tde,ClipboardPaste:sde,ClipboardPasteIcon:sde,ClipboardPen:NL,ClipboardPenIcon:NL,ClipboardPenLine:jL,ClipboardPenLineIcon:jL,ClipboardPlus:nde,ClipboardPlusIcon:nde,ClipboardSignature:jL,ClipboardSignatureIcon:jL,ClipboardType:rde,ClipboardTypeIcon:rde,ClipboardX:ade,ClipboardXIcon:ade,Clock:Vr,Clock1:ode,Clock10:lde,Clock10Icon:lde,Clock11:cde,Clock11Icon:cde,Clock12:dde,Clock12Icon:dde,Clock1Icon:ode,Clock2:ude,Clock2Icon:ude,Clock3:PW,Clock3Icon:PW,Clock4:hde,Clock4Icon:hde,Clock5:mde,Clock5Icon:mde,Clock6:pde,Clock6Icon:pde,Clock7:fde,Clock7Icon:fde,Clock8:xde,Clock8Icon:xde,Clock9:gde,Clock9Icon:gde,ClockAlert:yde,ClockAlertIcon:yde,ClockArrowDown:vde,ClockArrowDownIcon:vde,ClockArrowUp:bde,ClockArrowUpIcon:bde,ClockIcon:Vr,Cloud:Rde,CloudAlert:_de,CloudAlertIcon:_de,CloudCog:wde,CloudCogIcon:wde,CloudDownload:kL,CloudDownloadIcon:kL,CloudDrizzle:jde,CloudDrizzleIcon:jde,CloudFog:Nde,CloudFogIcon:Nde,CloudHail:kde,CloudHailIcon:kde,CloudIcon:Rde,CloudLightning:Sde,CloudLightningIcon:Sde,CloudMoon:Ade,CloudMoonIcon:Ade,CloudMoonRain:Cde,CloudMoonRainIcon:Cde,CloudOff:Tde,CloudOffIcon:Tde,CloudRain:Mde,CloudRainIcon:Mde,CloudRainWind:Ede,CloudRainWindIcon:Ede,CloudSnow:Lde,CloudSnowIcon:Lde,CloudSun:Ide,CloudSunIcon:Ide,CloudSunRain:Pde,CloudSunRainIcon:Pde,CloudUpload:SL,CloudUploadIcon:SL,Cloudy:Dde,CloudyIcon:Dde,Clover:a3,CloverIcon:a3,Club:Ode,ClubIcon:Ode,Code:qT,Code2:j4,Code2Icon:j4,CodeIcon:qT,CodeSquare:OP,CodeSquareIcon:OP,CodeXml:j4,CodeXmlIcon:j4,Codepen:Fde,CodepenIcon:Fde,Codesandbox:zde,CodesandboxIcon:zde,Coffee:xb,CoffeeIcon:xb,Cog:Bde,CogIcon:Bde,Coins:IW,CoinsIcon:IW,Columns:CL,Columns2:CL,Columns2Icon:CL,Columns3:lA,Columns3Icon:lA,Columns4:$de,Columns4Icon:$de,ColumnsIcon:CL,Combine:Ude,CombineIcon:Ude,Command:qde,CommandIcon:qde,Compass:RR,CompassIcon:RR,Component:Vde,ComponentIcon:Vde,Computer:Hde,ComputerIcon:Hde,ConciergeBell:Gde,ConciergeBellIcon:Gde,Cone:Wde,ConeIcon:Wde,Construction:Kde,ConstructionIcon:Kde,Contact:DR,Contact2:AL,Contact2Icon:AL,ContactIcon:DR,ContactRound:AL,ContactRoundIcon:AL,Container:Yde,ContainerIcon:Yde,Contrast:Zde,ContrastIcon:Zde,Cookie:Xde,CookieIcon:Xde,CookingPot:Qde,CookingPotIcon:Qde,Copy:ja,CopyCheck:Jde,CopyCheckIcon:Jde,CopyIcon:ja,CopyMinus:eue,CopyMinusIcon:eue,CopyPlus:tue,CopyPlusIcon:tue,CopySlash:sue,CopySlashIcon:sue,CopyX:nue,CopyXIcon:nue,Copyleft:rue,CopyleftIcon:rue,Copyright:aue,CopyrightIcon:aue,CornerDownLeft:iue,CornerDownLeftIcon:iue,CornerDownRight:oue,CornerDownRightIcon:oue,CornerLeftDown:lue,CornerLeftDownIcon:lue,CornerLeftUp:cue,CornerLeftUpIcon:cue,CornerRightDown:due,CornerRightDownIcon:due,CornerRightUp:uue,CornerRightUpIcon:uue,CornerUpLeft:hue,CornerUpLeftIcon:hue,CornerUpRight:mue,CornerUpRightIcon:mue,Cpu:pue,CpuIcon:pue,CreativeCommons:fue,CreativeCommonsIcon:fue,CreditCard:ty,CreditCardIcon:ty,Croissant:xue,CroissantIcon:xue,Crop:gue,CropIcon:gue,Cross:yue,CrossIcon:yue,Crosshair:vue,CrosshairIcon:vue,Crown:sy,CrownIcon:sy,Cuboid:bue,CuboidIcon:bue,CupSoda:_ue,CupSodaIcon:_ue,CurlyBraces:FM,CurlyBracesIcon:FM,Currency:wue,CurrencyIcon:wue,Cylinder:jue,CylinderIcon:jue,Dam:Nue,DamIcon:Nue,Database:RW,DatabaseBackup:kue,DatabaseBackupIcon:kue,DatabaseIcon:RW,DatabaseZap:Sue,DatabaseZapIcon:Sue,Delete:Cue,DeleteIcon:Cue,Dessert:Aue,DessertIcon:Aue,Diameter:Tue,DiameterIcon:Tue,Diamond:Lue,DiamondIcon:Lue,DiamondMinus:Eue,DiamondMinusIcon:Eue,DiamondPercent:TL,DiamondPercentIcon:TL,DiamondPlus:Mue,DiamondPlusIcon:Mue,Dice1:Pue,Dice1Icon:Pue,Dice2:Iue,Dice2Icon:Iue,Dice3:Rue,Dice3Icon:Rue,Dice4:Due,Dice4Icon:Due,Dice5:Oue,Dice5Icon:Oue,Dice6:Fue,Dice6Icon:Fue,Dices:zue,DicesIcon:zue,Diff:Bue,DiffIcon:Bue,Disc:Vue,Disc2:$ue,Disc2Icon:$ue,Disc3:Uue,Disc3Icon:Uue,DiscAlbum:que,DiscAlbumIcon:que,DiscIcon:Vue,Divide:Hue,DivideCircle:dL,DivideCircleIcon:dL,DivideIcon:Hue,DivideSquare:$P,DivideSquareIcon:$P,Dna:Wue,DnaIcon:Wue,DnaOff:Gue,DnaOffIcon:Gue,Dock:Kue,DockIcon:Kue,Dog:Yue,DogIcon:Yue,DollarSign:Od,DollarSignIcon:Od,Donut:Zue,DonutIcon:Zue,DoorClosed:Xue,DoorClosedIcon:Xue,DoorOpen:wj,DoorOpenIcon:wj,Dot:Que,DotIcon:Que,DotSquare:UP,DotSquareIcon:UP,Download:ii,DownloadCloud:kL,DownloadCloudIcon:kL,DownloadIcon:ii,DraftingCompass:Jue,DraftingCompassIcon:Jue,Drama:ehe,DramaIcon:ehe,Dribbble:the,DribbbleIcon:the,Drill:she,DrillIcon:she,Droplet:nhe,DropletIcon:nhe,Droplets:mN,DropletsIcon:mN,Drum:rhe,DrumIcon:rhe,Drumstick:ahe,DrumstickIcon:ahe,Dumbbell:ihe,DumbbellIcon:ihe,Ear:lhe,EarIcon:lhe,EarOff:ohe,EarOffIcon:ohe,Earth:EL,EarthIcon:EL,EarthLock:che,EarthLockIcon:che,Eclipse:dhe,EclipseIcon:dhe,Edit:kp,Edit2:oj,Edit2Icon:oj,Edit3:sN,Edit3Icon:sN,EditIcon:kp,Egg:F9,EggFried:uhe,EggFriedIcon:uhe,EggIcon:F9,EggOff:hhe,EggOffIcon:hhe,Ellipsis:Hy,EllipsisIcon:Hy,EllipsisVertical:W0,EllipsisVerticalIcon:W0,Equal:fhe,EqualApproximately:mhe,EqualApproximatelyIcon:mhe,EqualIcon:fhe,EqualNot:phe,EqualNotIcon:phe,EqualSquare:qP,EqualSquareIcon:qP,Eraser:xhe,EraserIcon:xhe,EthernetPort:ghe,EthernetPortIcon:ghe,Euro:yhe,EuroIcon:yhe,Expand:vhe,ExpandIcon:vhe,ExternalLink:Tr,ExternalLinkIcon:Tr,Eye:ma,EyeClosed:bhe,EyeClosedIcon:bhe,EyeIcon:ma,EyeOff:n0,EyeOffIcon:n0,Facebook:sx,FacebookIcon:sx,Factory:_he,FactoryIcon:_he,Fan:whe,FanIcon:whe,FastForward:jhe,FastForwardIcon:jhe,Feather:Nhe,FeatherIcon:Nhe,Fence:khe,FenceIcon:khe,FerrisWheel:She,FerrisWheelIcon:She,Figma:Che,FigmaIcon:Che,File:z9,FileArchive:Ahe,FileArchiveIcon:Ahe,FileAudio:Ehe,FileAudio2:The,FileAudio2Icon:The,FileAudioIcon:Ehe,FileAxis3D:ML,FileAxis3DIcon:ML,FileAxis3d:ML,FileAxis3dIcon:ML,FileBadge:Lhe,FileBadge2:Mhe,FileBadge2Icon:Mhe,FileBadgeIcon:Lhe,FileBarChart:LL,FileBarChart2:PL,FileBarChart2Icon:PL,FileBarChartIcon:LL,FileBox:Phe,FileBoxIcon:Phe,FileChartColumn:PL,FileChartColumnIcon:PL,FileChartColumnIncreasing:LL,FileChartColumnIncreasingIcon:LL,FileChartLine:IL,FileChartLineIcon:IL,FileChartPie:RL,FileChartPieIcon:RL,FileCheck:DW,FileCheck2:Ihe,FileCheck2Icon:Ihe,FileCheckIcon:DW,FileClock:Rhe,FileClockIcon:Rhe,FileCode:Ohe,FileCode2:Dhe,FileCode2Icon:Dhe,FileCodeIcon:Ohe,FileCog:DL,FileCog2:DL,FileCog2Icon:DL,FileCogIcon:DL,FileDiff:Fhe,FileDiffIcon:Fhe,FileDigit:zhe,FileDigitIcon:zhe,FileDown:jj,FileDownIcon:jj,FileEdit:OL,FileEditIcon:OL,FileHeart:Bhe,FileHeartIcon:Bhe,FileIcon:z9,FileImage:g3,FileImageIcon:g3,FileInput:$he,FileInputIcon:$he,FileJson:qhe,FileJson2:Uhe,FileJson2Icon:Uhe,FileJsonIcon:qhe,FileKey:Hhe,FileKey2:Vhe,FileKey2Icon:Vhe,FileKeyIcon:Hhe,FileLineChart:IL,FileLineChartIcon:IL,FileLock:Whe,FileLock2:Ghe,FileLock2Icon:Ghe,FileLockIcon:Whe,FileMinus:Yhe,FileMinus2:Khe,FileMinus2Icon:Khe,FileMinusIcon:Yhe,FileMusic:Zhe,FileMusicIcon:Zhe,FileOutput:Xhe,FileOutputIcon:Xhe,FilePen:OL,FilePenIcon:OL,FilePenLine:cA,FilePenLineIcon:cA,FilePieChart:RL,FilePieChartIcon:RL,FilePlus:Jhe,FilePlus2:Qhe,FilePlus2Icon:Qhe,FilePlusIcon:Jhe,FileQuestion:eme,FileQuestionIcon:eme,FileScan:tme,FileScanIcon:tme,FileSearch:nme,FileSearch2:sme,FileSearch2Icon:sme,FileSearchIcon:nme,FileSignature:cA,FileSignatureIcon:cA,FileSliders:rme,FileSlidersIcon:rme,FileSpreadsheet:pN,FileSpreadsheetIcon:pN,FileStack:OW,FileStackIcon:OW,FileSymlink:ame,FileSymlinkIcon:ame,FileTerminal:ime,FileTerminalIcon:ime,FileText:$r,FileTextIcon:$r,FileType:lme,FileType2:ome,FileType2Icon:ome,FileTypeIcon:lme,FileUp:cme,FileUpIcon:cme,FileUser:dme,FileUserIcon:dme,FileVideo:FW,FileVideo2:ume,FileVideo2Icon:ume,FileVideoIcon:FW,FileVolume:mme,FileVolume2:hme,FileVolume2Icon:hme,FileVolumeIcon:mme,FileWarning:pme,FileWarningIcon:pme,FileX:xme,FileX2:fme,FileX2Icon:fme,FileXIcon:xme,Files:gme,FilesIcon:gme,Film:wh,FilmIcon:wh,Filter:Nj,FilterIcon:Nj,FilterX:yme,FilterXIcon:yme,Fingerprint:vme,FingerprintIcon:vme,FireExtinguisher:bme,FireExtinguisherIcon:bme,Fish:jme,FishIcon:jme,FishOff:_me,FishOffIcon:_me,FishSymbol:wme,FishSymbolIcon:wme,Flag:y3,FlagIcon:y3,FlagOff:Nme,FlagOffIcon:Nme,FlagTriangleLeft:kme,FlagTriangleLeftIcon:kme,FlagTriangleRight:Sme,FlagTriangleRightIcon:Sme,Flame:Fd,FlameIcon:Fd,FlameKindling:Cme,FlameKindlingIcon:Cme,Flashlight:Tme,FlashlightIcon:Tme,FlashlightOff:Ame,FlashlightOffIcon:Ame,FlaskConical:VT,FlaskConicalIcon:VT,FlaskConicalOff:Eme,FlaskConicalOffIcon:Eme,FlaskRound:Mme,FlaskRoundIcon:Mme,FlipHorizontal:zW,FlipHorizontal2:Lme,FlipHorizontal2Icon:Lme,FlipHorizontalIcon:zW,FlipVertical:Ime,FlipVertical2:Pme,FlipVertical2Icon:Pme,FlipVerticalIcon:Ime,Flower:Rme,Flower2:oN,Flower2Icon:oN,FlowerIcon:Rme,Focus:Dme,FocusIcon:Dme,FoldHorizontal:Ome,FoldHorizontalIcon:Ome,FoldVertical:Fme,FoldVerticalIcon:Fme,Folder:upe,FolderArchive:zme,FolderArchiveIcon:zme,FolderCheck:Bme,FolderCheckIcon:Bme,FolderClock:$me,FolderClockIcon:$me,FolderClosed:Ume,FolderClosedIcon:Ume,FolderCode:qme,FolderCodeIcon:qme,FolderCog:FL,FolderCog2:FL,FolderCog2Icon:FL,FolderCogIcon:FL,FolderDot:Vme,FolderDotIcon:Vme,FolderDown:Hme,FolderDownIcon:Hme,FolderEdit:zL,FolderEditIcon:zL,FolderGit:Wme,FolderGit2:Gme,FolderGit2Icon:Gme,FolderGitIcon:Wme,FolderHeart:Kme,FolderHeartIcon:Kme,FolderIcon:upe,FolderInput:Yme,FolderInputIcon:Yme,FolderKanban:Zme,FolderKanbanIcon:Zme,FolderKey:Xme,FolderKeyIcon:Xme,FolderLock:Qme,FolderLockIcon:Qme,FolderMinus:Jme,FolderMinusIcon:Jme,FolderOpen:ny,FolderOpenDot:epe,FolderOpenDotIcon:epe,FolderOpenIcon:ny,FolderOutput:tpe,FolderOutputIcon:tpe,FolderPen:zL,FolderPenIcon:zL,FolderPlus:spe,FolderPlusIcon:spe,FolderRoot:npe,FolderRootIcon:npe,FolderSearch:ape,FolderSearch2:rpe,FolderSearch2Icon:rpe,FolderSearchIcon:ape,FolderSymlink:ipe,FolderSymlinkIcon:ipe,FolderSync:ope,FolderSyncIcon:ope,FolderTree:lpe,FolderTreeIcon:lpe,FolderUp:cpe,FolderUpIcon:cpe,FolderX:dpe,FolderXIcon:dpe,Folders:hpe,FoldersIcon:hpe,Footprints:mpe,FootprintsIcon:mpe,ForkKnife:CI,ForkKnifeCrossed:SI,ForkKnifeCrossedIcon:SI,ForkKnifeIcon:CI,Forklift:ppe,ForkliftIcon:ppe,FormInput:cP,FormInputIcon:cP,Forward:fpe,ForwardIcon:fpe,Frame:xpe,FrameIcon:xpe,Framer:gpe,FramerIcon:gpe,Frown:ype,FrownIcon:ype,Fuel:vpe,FuelIcon:vpe,Fullscreen:bpe,FullscreenIcon:bpe,FunctionSquare:VP,FunctionSquareIcon:VP,GalleryHorizontal:wpe,GalleryHorizontalEnd:_pe,GalleryHorizontalEndIcon:_pe,GalleryHorizontalIcon:wpe,GalleryThumbnails:jpe,GalleryThumbnailsIcon:jpe,GalleryVertical:kpe,GalleryVerticalEnd:Npe,GalleryVerticalEndIcon:Npe,GalleryVerticalIcon:kpe,Gamepad:Cpe,Gamepad2:Spe,Gamepad2Icon:Spe,GamepadIcon:Cpe,GanttChart:YM,GanttChartIcon:YM,GanttChartSquare:Tk,GanttChartSquareIcon:Tk,Gauge:Ape,GaugeCircle:uL,GaugeCircleIcon:uL,GaugeIcon:Ape,Gavel:Tpe,GavelIcon:Tpe,Gem:Epe,GemIcon:Epe,Ghost:OR,GhostIcon:OR,Gift:zo,GiftIcon:zo,GitBranch:Lpe,GitBranchIcon:Lpe,GitBranchPlus:Mpe,GitBranchPlusIcon:Mpe,GitCommit:BL,GitCommitHorizontal:BL,GitCommitHorizontalIcon:BL,GitCommitIcon:BL,GitCommitVertical:Ppe,GitCommitVerticalIcon:Ppe,GitCompare:Rpe,GitCompareArrows:Ipe,GitCompareArrowsIcon:Ipe,GitCompareIcon:Rpe,GitFork:Dpe,GitForkIcon:Dpe,GitGraph:Ope,GitGraphIcon:Ope,GitMerge:Fpe,GitMergeIcon:Fpe,GitPullRequest:Vpe,GitPullRequestArrow:zpe,GitPullRequestArrowIcon:zpe,GitPullRequestClosed:Bpe,GitPullRequestClosedIcon:Bpe,GitPullRequestCreate:Upe,GitPullRequestCreateArrow:$pe,GitPullRequestCreateArrowIcon:$pe,GitPullRequestCreateIcon:Upe,GitPullRequestDraft:qpe,GitPullRequestDraftIcon:qpe,GitPullRequestIcon:Vpe,Github:Hpe,GithubIcon:Hpe,Gitlab:Gpe,GitlabIcon:Gpe,GlassWater:Wpe,GlassWaterIcon:Wpe,Glasses:Kpe,GlassesIcon:Kpe,Globe:Ql,Globe2:EL,Globe2Icon:EL,GlobeIcon:Ql,GlobeLock:Ype,GlobeLockIcon:Ype,Goal:Zpe,GoalIcon:Zpe,Grab:Xpe,GrabIcon:Xpe,GraduationCap:Uh,GraduationCapIcon:Uh,Grape:Qpe,GrapeIcon:Qpe,Grid:k_,Grid2X2:UL,Grid2X2Icon:UL,Grid2X2Plus:$L,Grid2X2PlusIcon:$L,Grid2x2:UL,Grid2x2Check:Jpe,Grid2x2CheckIcon:Jpe,Grid2x2Icon:UL,Grid2x2Plus:$L,Grid2x2PlusIcon:$L,Grid2x2X:efe,Grid2x2XIcon:efe,Grid3X3:k_,Grid3X3Icon:k_,Grid3x3:k_,Grid3x3Icon:k_,GridIcon:k_,Grip:sfe,GripHorizontal:tfe,GripHorizontalIcon:tfe,GripIcon:sfe,GripVertical:Fp,GripVerticalIcon:Fp,Group:nfe,GroupIcon:nfe,Guitar:rfe,GuitarIcon:rfe,Ham:afe,HamIcon:afe,Hammer:BW,HammerIcon:BW,Hand:$W,HandCoins:ife,HandCoinsIcon:ife,HandHeart:FR,HandHeartIcon:FR,HandHelping:tN,HandHelpingIcon:tN,HandIcon:$W,HandMetal:ofe,HandMetalIcon:ofe,HandPlatter:lfe,HandPlatterIcon:lfe,Handshake:fN,HandshakeIcon:fN,HardDrive:UW,HardDriveDownload:cfe,HardDriveDownloadIcon:cfe,HardDriveIcon:UW,HardDriveUpload:dfe,HardDriveUploadIcon:dfe,HardHat:ufe,HardHatIcon:ufe,Hash:HT,HashIcon:HT,Haze:hfe,HazeIcon:hfe,HdmiPort:mfe,HdmiPortIcon:mfe,Heading:gfe,Heading1:B9,Heading1Icon:B9,Heading2:$9,Heading2Icon:$9,Heading3:qW,Heading3Icon:qW,Heading4:pfe,Heading4Icon:pfe,Heading5:ffe,Heading5Icon:ffe,Heading6:xfe,Heading6Icon:xfe,HeadingIcon:gfe,HeadphoneOff:yfe,HeadphoneOffIcon:yfe,Headphones:vfe,HeadphonesIcon:vfe,Headset:bfe,HeadsetIcon:bfe,Heart:mo,HeartCrack:_fe,HeartCrackIcon:_fe,HeartHandshake:zR,HeartHandshakeIcon:zR,HeartIcon:mo,HeartOff:wfe,HeartOffIcon:wfe,HeartPulse:jfe,HeartPulseIcon:jfe,Heater:Nfe,HeaterIcon:Nfe,HelpCircle:c5,HelpCircleIcon:c5,HelpingHand:tN,HelpingHandIcon:tN,Hexagon:kfe,HexagonIcon:kfe,Highlighter:Sfe,HighlighterIcon:Sfe,History:GT,HistoryIcon:GT,Home:ia,HomeIcon:ia,Hop:Afe,HopIcon:Afe,HopOff:Cfe,HopOffIcon:Cfe,Hospital:Tfe,HospitalIcon:Tfe,Hotel:Efe,HotelIcon:Efe,Hourglass:Mfe,HourglassIcon:Mfe,House:ia,HouseIcon:ia,HousePlug:Lfe,HousePlugIcon:Lfe,HousePlus:Pfe,HousePlusIcon:Pfe,IceCream:VL,IceCream2:qL,IceCream2Icon:qL,IceCreamBowl:qL,IceCreamBowlIcon:qL,IceCreamCone:VL,IceCreamConeIcon:VL,IceCreamIcon:VL,Icon:G_t,IdCard:Ife,IdCardIcon:Ife,Image:ac,ImageDown:Rfe,ImageDownIcon:Rfe,ImageIcon:ac,ImageMinus:Dfe,ImageMinusIcon:Dfe,ImageOff:Ofe,ImageOffIcon:Ofe,ImagePlay:Ffe,ImagePlayIcon:Ffe,ImagePlus:a1,ImagePlusIcon:a1,ImageUp:zfe,ImageUpIcon:zfe,ImageUpscale:Bfe,ImageUpscaleIcon:Bfe,Images:$fe,ImagesIcon:$fe,Import:Ufe,ImportIcon:Ufe,Inbox:WT,InboxIcon:WT,Indent:GL,IndentDecrease:HL,IndentDecreaseIcon:HL,IndentIcon:GL,IndentIncrease:GL,IndentIncreaseIcon:GL,IndianRupee:qfe,IndianRupeeIcon:qfe,Infinity:Vfe,InfinityIcon:Vfe,Info:I5,InfoIcon:I5,Inspect:ZP,InspectIcon:ZP,InspectionPanel:Hfe,InspectionPanelIcon:Hfe,Instagram:vm,InstagramIcon:vm,Italic:KT,ItalicIcon:KT,IterationCcw:Gfe,IterationCcwIcon:Gfe,IterationCw:Wfe,IterationCwIcon:Wfe,JapaneseYen:Kfe,JapaneseYenIcon:Kfe,Joystick:Yfe,JoystickIcon:Yfe,Kanban:v3,KanbanIcon:v3,KanbanSquare:HP,KanbanSquareDashed:FP,KanbanSquareDashedIcon:FP,KanbanSquareIcon:HP,Key:gb,KeyIcon:gb,KeyRound:b3,KeyRoundIcon:b3,KeySquare:Zfe,KeySquareIcon:Zfe,Keyboard:Jfe,KeyboardIcon:Jfe,KeyboardMusic:Xfe,KeyboardMusicIcon:Xfe,KeyboardOff:Qfe,KeyboardOffIcon:Qfe,Lamp:axe,LampCeiling:exe,LampCeilingIcon:exe,LampDesk:txe,LampDeskIcon:txe,LampFloor:sxe,LampFloorIcon:sxe,LampIcon:axe,LampWallDown:nxe,LampWallDownIcon:nxe,LampWallUp:rxe,LampWallUpIcon:rxe,LandPlot:ixe,LandPlotIcon:ixe,Landmark:VW,LandmarkIcon:VW,Languages:oxe,LanguagesIcon:oxe,Laptop:cxe,Laptop2:WL,Laptop2Icon:WL,LaptopIcon:cxe,LaptopMinimal:WL,LaptopMinimalCheck:lxe,LaptopMinimalCheckIcon:lxe,LaptopMinimalIcon:WL,Lasso:uxe,LassoIcon:uxe,LassoSelect:dxe,LassoSelectIcon:dxe,Laugh:hxe,LaughIcon:hxe,Layers:U9,Layers2:mxe,Layers2Icon:mxe,Layers3:pxe,Layers3Icon:pxe,LayersIcon:U9,Layout:N4,LayoutDashboard:BR,LayoutDashboardIcon:BR,LayoutGrid:r0,LayoutGridIcon:r0,LayoutIcon:N4,LayoutList:fxe,LayoutListIcon:fxe,LayoutPanelLeft:xxe,LayoutPanelLeftIcon:xxe,LayoutPanelTop:gxe,LayoutPanelTopIcon:gxe,LayoutTemplate:q_,LayoutTemplateIcon:q_,Leaf:yxe,LeafIcon:yxe,LeafyGreen:vxe,LeafyGreenIcon:vxe,Lectern:bxe,LecternIcon:bxe,LetterText:_xe,LetterTextIcon:_xe,Library:i1,LibraryBig:wxe,LibraryBigIcon:wxe,LibraryIcon:i1,LibrarySquare:GP,LibrarySquareIcon:GP,LifeBuoy:q9,LifeBuoyIcon:q9,Ligature:jxe,LigatureIcon:jxe,Lightbulb:xN,LightbulbIcon:xN,LightbulbOff:Nxe,LightbulbOffIcon:Nxe,LineChart:GM,LineChartIcon:GM,Link:vc,Link2:Rc,Link2Icon:Rc,Link2Off:kxe,Link2OffIcon:kxe,LinkIcon:vc,Linkedin:ry,LinkedinIcon:ry,List:ug,ListCheck:Sxe,ListCheckIcon:Sxe,ListChecks:zp,ListChecksIcon:zp,ListCollapse:Cxe,ListCollapseIcon:Cxe,ListEnd:Axe,ListEndIcon:Axe,ListFilter:HW,ListFilterIcon:HW,ListIcon:ug,ListMinus:Txe,ListMinusIcon:Txe,ListMusic:Exe,ListMusicIcon:Exe,ListOrdered:kj,ListOrderedIcon:kj,ListPlus:Mxe,ListPlusIcon:Mxe,ListRestart:Lxe,ListRestartIcon:Lxe,ListStart:Pxe,ListStartIcon:Pxe,ListTodo:Ixe,ListTodoIcon:Ixe,ListTree:Rxe,ListTreeIcon:Rxe,ListVideo:Dxe,ListVideoIcon:Dxe,ListX:Oxe,ListXIcon:Oxe,Loader:zxe,Loader2:Wt,Loader2Icon:Wt,LoaderCircle:Wt,LoaderCircleIcon:Wt,LoaderIcon:zxe,LoaderPinwheel:Fxe,LoaderPinwheelIcon:Fxe,Locate:V9,LocateFixed:Bxe,LocateFixedIcon:Bxe,LocateIcon:V9,LocateOff:$xe,LocateOffIcon:$xe,Lock:du,LockIcon:du,LockKeyhole:Uxe,LockKeyholeIcon:Uxe,LockKeyholeOpen:KL,LockKeyholeOpenIcon:KL,LockOpen:YL,LockOpenIcon:YL,LogIn:$R,LogInIcon:$R,LogOut:UR,LogOutIcon:UR,Logs:qxe,LogsIcon:qxe,Lollipop:Vxe,LollipopIcon:Vxe,LucideAArrowDown:pae,LucideAArrowUp:fae,LucideALargeSmall:xae,LucideAccessibility:gae,LucideActivity:vf,LucideActivitySquare:gP,LucideAirVent:yae,LucideAirplay:vae,LucideAlarmCheck:NM,LucideAlarmClock:_ae,LucideAlarmClockCheck:NM,LucideAlarmClockMinus:kM,LucideAlarmClockOff:bae,LucideAlarmClockPlus:SM,LucideAlarmMinus:kM,LucideAlarmPlus:SM,LucideAlarmSmoke:wae,LucideAlbum:jae,LucideAlertCircle:po,LucideAlertOctagon:d5,LucideAlertTriangle:hd,LucideAlignCenter:TR,LucideAlignCenterHorizontal:Nae,LucideAlignCenterVertical:kae,LucideAlignEndHorizontal:Sae,LucideAlignEndVertical:Cae,LucideAlignHorizontalDistributeCenter:Aae,LucideAlignHorizontalDistributeEnd:Tae,LucideAlignHorizontalDistributeStart:Eae,LucideAlignHorizontalJustifyCenter:Mae,LucideAlignHorizontalJustifyEnd:Lae,LucideAlignHorizontalJustifyStart:Pae,LucideAlignHorizontalSpaceAround:Iae,LucideAlignHorizontalSpaceBetween:Rae,LucideAlignJustify:Dae,LucideAlignLeft:ER,LucideAlignRight:MR,LucideAlignStartHorizontal:Oae,LucideAlignStartVertical:Fae,LucideAlignVerticalDistributeCenter:zae,LucideAlignVerticalDistributeEnd:Bae,LucideAlignVerticalDistributeStart:$ae,LucideAlignVerticalJustifyCenter:Uae,LucideAlignVerticalJustifyEnd:qae,LucideAlignVerticalJustifyStart:Vae,LucideAlignVerticalSpaceAround:Hae,LucideAlignVerticalSpaceBetween:Gae,LucideAmbulance:Wae,LucideAmpersand:Kae,LucideAmpersands:Yae,LucideAmphora:Zae,LucideAnchor:Xae,LucideAngry:Qae,LucideAnnoyed:Jae,LucideAntenna:eie,LucideAnvil:tie,LucideAperture:sie,LucideAppWindow:rie,LucideAppWindowMac:nie,LucideApple:aie,LucideArchive:gm,LucideArchiveRestore:zT,LucideArchiveX:iie,LucideAreaChart:BM,LucideArmchair:oie,LucideArrowBigDown:cie,LucideArrowBigDownDash:lie,LucideArrowBigLeft:uie,LucideArrowBigLeftDash:die,LucideArrowBigRight:mie,LucideArrowBigRightDash:hie,LucideArrowBigUp:fie,LucideArrowBigUpDash:pie,LucideArrowDown:tx,LucideArrowDown01:xie,LucideArrowDown10:gie,LucideArrowDownAZ:CM,LucideArrowDownAz:CM,LucideArrowDownCircle:QM,LucideArrowDownFromLine:yie,LucideArrowDownLeft:vie,LucideArrowDownLeftFromCircle:eL,LucideArrowDownLeftFromSquare:wP,LucideArrowDownLeftSquare:yP,LucideArrowDownNarrowWide:bie,LucideArrowDownRight:CW,LucideArrowDownRightFromCircle:tL,LucideArrowDownRightFromSquare:jP,LucideArrowDownRightSquare:vP,LucideArrowDownSquare:bP,LucideArrowDownToDot:_ie,LucideArrowDownToLine:wie,LucideArrowDownUp:jie,LucideArrowDownWideNarrow:AM,LucideArrowDownZA:TM,LucideArrowDownZa:TM,LucideArrowLeft:_a,LucideArrowLeftCircle:JM,LucideArrowLeftFromLine:Nie,LucideArrowLeftRight:AW,LucideArrowLeftSquare:_P,LucideArrowLeftToLine:kie,LucideArrowRight:Xa,LucideArrowRightCircle:rL,LucideArrowRightFromLine:Sie,LucideArrowRightLeft:M5,LucideArrowRightSquare:SP,LucideArrowRightToLine:Cie,LucideArrowUp:Gm,LucideArrowUp01:Aie,LucideArrowUp10:Tie,LucideArrowUpAZ:EM,LucideArrowUpAz:EM,LucideArrowUpCircle:aL,LucideArrowUpDown:_x,LucideArrowUpFromDot:Eie,LucideArrowUpFromLine:Mie,LucideArrowUpLeft:Lie,LucideArrowUpLeftFromCircle:sL,LucideArrowUpLeftFromSquare:NP,LucideArrowUpLeftSquare:CP,LucideArrowUpNarrowWide:MM,LucideArrowUpRight:I9,LucideArrowUpRightFromCircle:nL,LucideArrowUpRightFromSquare:kP,LucideArrowUpRightSquare:AP,LucideArrowUpSquare:TP,LucideArrowUpToLine:Pie,LucideArrowUpWideNarrow:Iie,LucideArrowUpZA:LM,LucideArrowUpZa:LM,LucideArrowsUpFromLine:Rie,LucideAsterisk:Die,LucideAsteriskSquare:EP,LucideAtSign:Oie,LucideAtom:Fie,LucideAudioLines:zie,LucideAudioWaveform:Bie,LucideAward:cu,LucideAxe:$ie,LucideAxis3D:PM,LucideAxis3d:PM,LucideBaby:Uie,LucideBackpack:qie,LucideBadge:aoe,LucideBadgeAlert:Vie,LucideBadgeCent:Hie,LucideBadgeCheck:IM,LucideBadgeDollarSign:Gie,LucideBadgeEuro:Wie,LucideBadgeHelp:Kie,LucideBadgeIndianRupee:Yie,LucideBadgeInfo:Zie,LucideBadgeJapaneseYen:Xie,LucideBadgeMinus:Qie,LucideBadgePercent:Jie,LucideBadgePlus:eoe,LucideBadgePoundSterling:toe,LucideBadgeRussianRuble:soe,LucideBadgeSwissFranc:noe,LucideBadgeX:roe,LucideBaggageClaim:ioe,LucideBan:R9,LucideBanana:ooe,LucideBandage:loe,LucideBanknote:coe,LucideBarChart:WM,LucideBarChart2:KM,LucideBarChart3:ol,LucideBarChart4:HM,LucideBarChartBig:VM,LucideBarChartHorizontal:UM,LucideBarChartHorizontalBig:$M,LucideBarcode:doe,LucideBaseline:uoe,LucideBath:t0,LucideBattery:goe,LucideBatteryCharging:hoe,LucideBatteryFull:moe,LucideBatteryLow:poe,LucideBatteryMedium:foe,LucideBatteryWarning:xoe,LucideBeaker:TW,LucideBean:voe,LucideBeanOff:yoe,LucideBed:U_,LucideBedDouble:p3,LucideBedSingle:boe,LucideBeef:_oe,LucideBeer:joe,LucideBeerOff:woe,LucideBell:Nx,LucideBellDot:Noe,LucideBellElectric:koe,LucideBellMinus:Soe,LucideBellOff:L5,LucideBellPlus:Coe,LucideBellRing:f3,LucideBetweenHorizonalEnd:RM,LucideBetweenHorizonalStart:DM,LucideBetweenHorizontalEnd:RM,LucideBetweenHorizontalStart:DM,LucideBetweenVerticalEnd:Aoe,LucideBetweenVerticalStart:Toe,LucideBicepsFlexed:Eoe,LucideBike:Moe,LucideBinary:Loe,LucideBinoculars:Poe,LucideBiohazard:Ioe,LucideBird:Roe,LucideBitcoin:Doe,LucideBlend:Ooe,LucideBlinds:Foe,LucideBlocks:zoe,LucideBluetooth:qoe,LucideBluetoothConnected:Boe,LucideBluetoothOff:$oe,LucideBluetoothSearching:Uoe,LucideBold:BT,LucideBolt:Voe,LucideBomb:Hoe,LucideBone:Goe,LucideBook:ple,LucideBookA:Woe,LucideBookAudio:Koe,LucideBookCheck:Yoe,LucideBookCopy:Zoe,LucideBookDashed:OM,LucideBookDown:Xoe,LucideBookHeadphones:Qoe,LucideBookHeart:Joe,LucideBookImage:ele,LucideBookKey:tle,LucideBookLock:sle,LucideBookMarked:nle,LucideBookMinus:rle,LucideBookOpen:Op,LucideBookOpenCheck:ale,LucideBookOpenText:ile,LucideBookPlus:ole,LucideBookTemplate:OM,LucideBookText:lle,LucideBookType:cle,LucideBookUp:ule,LucideBookUp2:dle,LucideBookUser:hle,LucideBookX:mle,LucideBookmark:s1,LucideBookmarkCheck:fle,LucideBookmarkMinus:xle,LucideBookmarkPlus:$T,LucideBookmarkX:gle,LucideBoomBox:yle,LucideBot:UT,LucideBotMessageSquare:vle,LucideBotOff:ble,LucideBox:EW,LucideBoxSelect:BP,LucideBoxes:_le,LucideBraces:FM,LucideBrackets:wle,LucideBrain:MW,LucideBrainCircuit:jle,LucideBrainCog:Nle,LucideBrickWall:kle,LucideBriefcase:kx,LucideBriefcaseBusiness:Sle,LucideBriefcaseConveyorBelt:Cle,LucideBriefcaseMedical:Ale,LucideBringToFront:Tle,LucideBrush:Ele,LucideBug:Ple,LucideBugOff:Mle,LucideBugPlay:Lle,LucideBuilding:LR,LucideBuilding2:Ni,LucideBus:Rle,LucideBusFront:Ile,LucideCable:Ole,LucideCableCar:Dle,LucideCake:Wm,LucideCakeSlice:Fle,LucideCalculator:P5,LucideCalendar:ra,LucideCalendar1:zle,LucideCalendarArrowDown:Ble,LucideCalendarArrowUp:$le,LucideCalendarCheck:n1,LucideCalendarCheck2:Ule,LucideCalendarClock:ym,LucideCalendarCog:qle,LucideCalendarDays:Vc,LucideCalendarFold:Vle,LucideCalendarHeart:hN,LucideCalendarMinus:Gle,LucideCalendarMinus2:Hle,LucideCalendarOff:D9,LucideCalendarPlus:Wy,LucideCalendarPlus2:Wle,LucideCalendarRange:Kle,LucideCalendarSearch:Yle,LucideCalendarSync:Zle,LucideCalendarX:LW,LucideCalendarX2:Xle,LucideCamera:s0,LucideCameraOff:Qle,LucideCandlestickChart:qM,LucideCandy:tce,LucideCandyCane:Jle,LucideCandyOff:ece,LucideCannabis:sce,LucideCaptions:zM,LucideCaptionsOff:nce,LucideCar:ice,LucideCarFront:rce,LucideCarTaxiFront:ace,LucideCaravan:oce,LucideCarrot:lce,LucideCaseLower:cce,LucideCaseSensitive:dce,LucideCaseUpper:uce,LucideCassetteTape:hce,LucideCast:mce,LucideCastle:pce,LucideCat:fce,LucideCctv:xce,LucideChartArea:BM,LucideChartBar:UM,LucideChartBarBig:$M,LucideChartBarDecreasing:gce,LucideChartBarIncreasing:yce,LucideChartBarStacked:vce,LucideChartCandlestick:qM,LucideChartColumn:ol,LucideChartColumnBig:VM,LucideChartColumnDecreasing:bce,LucideChartColumnIncreasing:HM,LucideChartColumnStacked:_ce,LucideChartGantt:wce,LucideChartLine:GM,LucideChartNetwork:jce,LucideChartNoAxesColumn:KM,LucideChartNoAxesColumnDecreasing:Nce,LucideChartNoAxesColumnIncreasing:WM,LucideChartNoAxesCombined:kce,LucideChartNoAxesGantt:YM,LucideChartPie:ZM,LucideChartScatter:XM,LucideChartSpline:Sce,LucideCheck:da,LucideCheckCheck:PR,LucideCheckCircle:To,LucideCheckCircle2:Rr,LucideCheckSquare:k4,LucideCheckSquare2:LP,LucideChefHat:Cce,LucideCherry:Ace,LucideChevronDown:Po,LucideChevronDownCircle:iL,LucideChevronDownSquare:PP,LucideChevronFirst:Tce,LucideChevronLast:Ece,LucideChevronLeft:Cc,LucideChevronLeftCircle:oL,LucideChevronLeftSquare:IP,LucideChevronRight:Qa,LucideChevronRightCircle:lL,LucideChevronRightSquare:RP,LucideChevronUp:Qy,LucideChevronUpCircle:cL,LucideChevronUpSquare:DP,LucideChevronsDown:Lce,LucideChevronsDownUp:Mce,LucideChevronsLeft:Rce,LucideChevronsLeftRight:Ice,LucideChevronsLeftRightEllipsis:Pce,LucideChevronsRight:Oce,LucideChevronsRightLeft:Dce,LucideChevronsUp:Fce,LucideChevronsUpDown:fb,LucideChrome:IR,LucideChurch:zce,LucideCigarette:$ce,LucideCigaretteOff:Bce,LucideCircle:Sx,LucideCircleAlert:po,LucideCircleArrowDown:QM,LucideCircleArrowLeft:JM,LucideCircleArrowOutDownLeft:eL,LucideCircleArrowOutDownRight:tL,LucideCircleArrowOutUpLeft:sL,LucideCircleArrowOutUpRight:nL,LucideCircleArrowRight:rL,LucideCircleArrowUp:aL,LucideCircleCheck:Rr,LucideCircleCheckBig:To,LucideCircleChevronDown:iL,LucideCircleChevronLeft:oL,LucideCircleChevronRight:lL,LucideCircleChevronUp:cL,LucideCircleDashed:Uce,LucideCircleDivide:dL,LucideCircleDollarSign:qce,LucideCircleDot:Hce,LucideCircleDotDashed:Vce,LucideCircleEllipsis:Gce,LucideCircleEqual:Wce,LucideCircleFadingArrowUp:Kce,LucideCircleFadingPlus:Yce,LucideCircleGauge:uL,LucideCircleHelp:c5,LucideCircleMinus:hL,LucideCircleOff:Zce,LucideCircleParking:pL,LucideCircleParkingOff:mL,LucideCirclePause:fL,LucideCirclePercent:xL,LucideCirclePlay:vh,LucideCirclePlus:gL,LucideCirclePower:yL,LucideCircleSlash:Xce,LucideCircleSlash2:vL,LucideCircleSlashed:vL,LucideCircleStop:bL,LucideCircleUser:wL,LucideCircleUserRound:_L,LucideCircleX:Rd,LucideCircuitBoard:Qce,LucideCitrus:Jce,LucideClapperboard:O9,LucideClipboard:ide,LucideClipboardCheck:x3,LucideClipboardCopy:ede,LucideClipboardEdit:NL,LucideClipboardList:r1,LucideClipboardMinus:tde,LucideClipboardPaste:sde,LucideClipboardPen:NL,LucideClipboardPenLine:jL,LucideClipboardPlus:nde,LucideClipboardSignature:jL,LucideClipboardType:rde,LucideClipboardX:ade,LucideClock:Vr,LucideClock1:ode,LucideClock10:lde,LucideClock11:cde,LucideClock12:dde,LucideClock2:ude,LucideClock3:PW,LucideClock4:hde,LucideClock5:mde,LucideClock6:pde,LucideClock7:fde,LucideClock8:xde,LucideClock9:gde,LucideClockAlert:yde,LucideClockArrowDown:vde,LucideClockArrowUp:bde,LucideCloud:Rde,LucideCloudAlert:_de,LucideCloudCog:wde,LucideCloudDownload:kL,LucideCloudDrizzle:jde,LucideCloudFog:Nde,LucideCloudHail:kde,LucideCloudLightning:Sde,LucideCloudMoon:Ade,LucideCloudMoonRain:Cde,LucideCloudOff:Tde,LucideCloudRain:Mde,LucideCloudRainWind:Ede,LucideCloudSnow:Lde,LucideCloudSun:Ide,LucideCloudSunRain:Pde,LucideCloudUpload:SL,LucideCloudy:Dde,LucideClover:a3,LucideClub:Ode,LucideCode:qT,LucideCode2:j4,LucideCodeSquare:OP,LucideCodeXml:j4,LucideCodepen:Fde,LucideCodesandbox:zde,LucideCoffee:xb,LucideCog:Bde,LucideCoins:IW,LucideColumns:CL,LucideColumns2:CL,LucideColumns3:lA,LucideColumns4:$de,LucideCombine:Ude,LucideCommand:qde,LucideCompass:RR,LucideComponent:Vde,LucideComputer:Hde,LucideConciergeBell:Gde,LucideCone:Wde,LucideConstruction:Kde,LucideContact:DR,LucideContact2:AL,LucideContactRound:AL,LucideContainer:Yde,LucideContrast:Zde,LucideCookie:Xde,LucideCookingPot:Qde,LucideCopy:ja,LucideCopyCheck:Jde,LucideCopyMinus:eue,LucideCopyPlus:tue,LucideCopySlash:sue,LucideCopyX:nue,LucideCopyleft:rue,LucideCopyright:aue,LucideCornerDownLeft:iue,LucideCornerDownRight:oue,LucideCornerLeftDown:lue,LucideCornerLeftUp:cue,LucideCornerRightDown:due,LucideCornerRightUp:uue,LucideCornerUpLeft:hue,LucideCornerUpRight:mue,LucideCpu:pue,LucideCreativeCommons:fue,LucideCreditCard:ty,LucideCroissant:xue,LucideCrop:gue,LucideCross:yue,LucideCrosshair:vue,LucideCrown:sy,LucideCuboid:bue,LucideCupSoda:_ue,LucideCurlyBraces:FM,LucideCurrency:wue,LucideCylinder:jue,LucideDam:Nue,LucideDatabase:RW,LucideDatabaseBackup:kue,LucideDatabaseZap:Sue,LucideDelete:Cue,LucideDessert:Aue,LucideDiameter:Tue,LucideDiamond:Lue,LucideDiamondMinus:Eue,LucideDiamondPercent:TL,LucideDiamondPlus:Mue,LucideDice1:Pue,LucideDice2:Iue,LucideDice3:Rue,LucideDice4:Due,LucideDice5:Oue,LucideDice6:Fue,LucideDices:zue,LucideDiff:Bue,LucideDisc:Vue,LucideDisc2:$ue,LucideDisc3:Uue,LucideDiscAlbum:que,LucideDivide:Hue,LucideDivideCircle:dL,LucideDivideSquare:$P,LucideDna:Wue,LucideDnaOff:Gue,LucideDock:Kue,LucideDog:Yue,LucideDollarSign:Od,LucideDonut:Zue,LucideDoorClosed:Xue,LucideDoorOpen:wj,LucideDot:Que,LucideDotSquare:UP,LucideDownload:ii,LucideDownloadCloud:kL,LucideDraftingCompass:Jue,LucideDrama:ehe,LucideDribbble:the,LucideDrill:she,LucideDroplet:nhe,LucideDroplets:mN,LucideDrum:rhe,LucideDrumstick:ahe,LucideDumbbell:ihe,LucideEar:lhe,LucideEarOff:ohe,LucideEarth:EL,LucideEarthLock:che,LucideEclipse:dhe,LucideEdit:kp,LucideEdit2:oj,LucideEdit3:sN,LucideEgg:F9,LucideEggFried:uhe,LucideEggOff:hhe,LucideEllipsis:Hy,LucideEllipsisVertical:W0,LucideEqual:fhe,LucideEqualApproximately:mhe,LucideEqualNot:phe,LucideEqualSquare:qP,LucideEraser:xhe,LucideEthernetPort:ghe,LucideEuro:yhe,LucideExpand:vhe,LucideExternalLink:Tr,LucideEye:ma,LucideEyeClosed:bhe,LucideEyeOff:n0,LucideFacebook:sx,LucideFactory:_he,LucideFan:whe,LucideFastForward:jhe,LucideFeather:Nhe,LucideFence:khe,LucideFerrisWheel:She,LucideFigma:Che,LucideFile:z9,LucideFileArchive:Ahe,LucideFileAudio:Ehe,LucideFileAudio2:The,LucideFileAxis3D:ML,LucideFileAxis3d:ML,LucideFileBadge:Lhe,LucideFileBadge2:Mhe,LucideFileBarChart:LL,LucideFileBarChart2:PL,LucideFileBox:Phe,LucideFileChartColumn:PL,LucideFileChartColumnIncreasing:LL,LucideFileChartLine:IL,LucideFileChartPie:RL,LucideFileCheck:DW,LucideFileCheck2:Ihe,LucideFileClock:Rhe,LucideFileCode:Ohe,LucideFileCode2:Dhe,LucideFileCog:DL,LucideFileCog2:DL,LucideFileDiff:Fhe,LucideFileDigit:zhe,LucideFileDown:jj,LucideFileEdit:OL,LucideFileHeart:Bhe,LucideFileImage:g3,LucideFileInput:$he,LucideFileJson:qhe,LucideFileJson2:Uhe,LucideFileKey:Hhe,LucideFileKey2:Vhe,LucideFileLineChart:IL,LucideFileLock:Whe,LucideFileLock2:Ghe,LucideFileMinus:Yhe,LucideFileMinus2:Khe,LucideFileMusic:Zhe,LucideFileOutput:Xhe,LucideFilePen:OL,LucideFilePenLine:cA,LucideFilePieChart:RL,LucideFilePlus:Jhe,LucideFilePlus2:Qhe,LucideFileQuestion:eme,LucideFileScan:tme,LucideFileSearch:nme,LucideFileSearch2:sme,LucideFileSignature:cA,LucideFileSliders:rme,LucideFileSpreadsheet:pN,LucideFileStack:OW,LucideFileSymlink:ame,LucideFileTerminal:ime,LucideFileText:$r,LucideFileType:lme,LucideFileType2:ome,LucideFileUp:cme,LucideFileUser:dme,LucideFileVideo:FW,LucideFileVideo2:ume,LucideFileVolume:mme,LucideFileVolume2:hme,LucideFileWarning:pme,LucideFileX:xme,LucideFileX2:fme,LucideFiles:gme,LucideFilm:wh,LucideFilter:Nj,LucideFilterX:yme,LucideFingerprint:vme,LucideFireExtinguisher:bme,LucideFish:jme,LucideFishOff:_me,LucideFishSymbol:wme,LucideFlag:y3,LucideFlagOff:Nme,LucideFlagTriangleLeft:kme,LucideFlagTriangleRight:Sme,LucideFlame:Fd,LucideFlameKindling:Cme,LucideFlashlight:Tme,LucideFlashlightOff:Ame,LucideFlaskConical:VT,LucideFlaskConicalOff:Eme,LucideFlaskRound:Mme,LucideFlipHorizontal:zW,LucideFlipHorizontal2:Lme,LucideFlipVertical:Ime,LucideFlipVertical2:Pme,LucideFlower:Rme,LucideFlower2:oN,LucideFocus:Dme,LucideFoldHorizontal:Ome,LucideFoldVertical:Fme,LucideFolder:upe,LucideFolderArchive:zme,LucideFolderCheck:Bme,LucideFolderClock:$me,LucideFolderClosed:Ume,LucideFolderCode:qme,LucideFolderCog:FL,LucideFolderCog2:FL,LucideFolderDot:Vme,LucideFolderDown:Hme,LucideFolderEdit:zL,LucideFolderGit:Wme,LucideFolderGit2:Gme,LucideFolderHeart:Kme,LucideFolderInput:Yme,LucideFolderKanban:Zme,LucideFolderKey:Xme,LucideFolderLock:Qme,LucideFolderMinus:Jme,LucideFolderOpen:ny,LucideFolderOpenDot:epe,LucideFolderOutput:tpe,LucideFolderPen:zL,LucideFolderPlus:spe,LucideFolderRoot:npe,LucideFolderSearch:ape,LucideFolderSearch2:rpe,LucideFolderSymlink:ipe,LucideFolderSync:ope,LucideFolderTree:lpe,LucideFolderUp:cpe,LucideFolderX:dpe,LucideFolders:hpe,LucideFootprints:mpe,LucideForkKnife:CI,LucideForkKnifeCrossed:SI,LucideForklift:ppe,LucideFormInput:cP,LucideForward:fpe,LucideFrame:xpe,LucideFramer:gpe,LucideFrown:ype,LucideFuel:vpe,LucideFullscreen:bpe,LucideFunctionSquare:VP,LucideGalleryHorizontal:wpe,LucideGalleryHorizontalEnd:_pe,LucideGalleryThumbnails:jpe,LucideGalleryVertical:kpe,LucideGalleryVerticalEnd:Npe,LucideGamepad:Cpe,LucideGamepad2:Spe,LucideGanttChart:YM,LucideGanttChartSquare:Tk,LucideGauge:Ape,LucideGaugeCircle:uL,LucideGavel:Tpe,LucideGem:Epe,LucideGhost:OR,LucideGift:zo,LucideGitBranch:Lpe,LucideGitBranchPlus:Mpe,LucideGitCommit:BL,LucideGitCommitHorizontal:BL,LucideGitCommitVertical:Ppe,LucideGitCompare:Rpe,LucideGitCompareArrows:Ipe,LucideGitFork:Dpe,LucideGitGraph:Ope,LucideGitMerge:Fpe,LucideGitPullRequest:Vpe,LucideGitPullRequestArrow:zpe,LucideGitPullRequestClosed:Bpe,LucideGitPullRequestCreate:Upe,LucideGitPullRequestCreateArrow:$pe,LucideGitPullRequestDraft:qpe,LucideGithub:Hpe,LucideGitlab:Gpe,LucideGlassWater:Wpe,LucideGlasses:Kpe,LucideGlobe:Ql,LucideGlobe2:EL,LucideGlobeLock:Ype,LucideGoal:Zpe,LucideGrab:Xpe,LucideGraduationCap:Uh,LucideGrape:Qpe,LucideGrid:k_,LucideGrid2X2:UL,LucideGrid2X2Plus:$L,LucideGrid2x2:UL,LucideGrid2x2Check:Jpe,LucideGrid2x2Plus:$L,LucideGrid2x2X:efe,LucideGrid3X3:k_,LucideGrid3x3:k_,LucideGrip:sfe,LucideGripHorizontal:tfe,LucideGripVertical:Fp,LucideGroup:nfe,LucideGuitar:rfe,LucideHam:afe,LucideHammer:BW,LucideHand:$W,LucideHandCoins:ife,LucideHandHeart:FR,LucideHandHelping:tN,LucideHandMetal:ofe,LucideHandPlatter:lfe,LucideHandshake:fN,LucideHardDrive:UW,LucideHardDriveDownload:cfe,LucideHardDriveUpload:dfe,LucideHardHat:ufe,LucideHash:HT,LucideHaze:hfe,LucideHdmiPort:mfe,LucideHeading:gfe,LucideHeading1:B9,LucideHeading2:$9,LucideHeading3:qW,LucideHeading4:pfe,LucideHeading5:ffe,LucideHeading6:xfe,LucideHeadphoneOff:yfe,LucideHeadphones:vfe,LucideHeadset:bfe,LucideHeart:mo,LucideHeartCrack:_fe,LucideHeartHandshake:zR,LucideHeartOff:wfe,LucideHeartPulse:jfe,LucideHeater:Nfe,LucideHelpCircle:c5,LucideHelpingHand:tN,LucideHexagon:kfe,LucideHighlighter:Sfe,LucideHistory:GT,LucideHome:ia,LucideHop:Afe,LucideHopOff:Cfe,LucideHospital:Tfe,LucideHotel:Efe,LucideHourglass:Mfe,LucideHouse:ia,LucideHousePlug:Lfe,LucideHousePlus:Pfe,LucideIceCream:VL,LucideIceCream2:qL,LucideIceCreamBowl:qL,LucideIceCreamCone:VL,LucideIdCard:Ife,LucideImage:ac,LucideImageDown:Rfe,LucideImageMinus:Dfe,LucideImageOff:Ofe,LucideImagePlay:Ffe,LucideImagePlus:a1,LucideImageUp:zfe,LucideImageUpscale:Bfe,LucideImages:$fe,LucideImport:Ufe,LucideInbox:WT,LucideIndent:GL,LucideIndentDecrease:HL,LucideIndentIncrease:GL,LucideIndianRupee:qfe,LucideInfinity:Vfe,LucideInfo:I5,LucideInspect:ZP,LucideInspectionPanel:Hfe,LucideInstagram:vm,LucideItalic:KT,LucideIterationCcw:Gfe,LucideIterationCw:Wfe,LucideJapaneseYen:Kfe,LucideJoystick:Yfe,LucideKanban:v3,LucideKanbanSquare:HP,LucideKanbanSquareDashed:FP,LucideKey:gb,LucideKeyRound:b3,LucideKeySquare:Zfe,LucideKeyboard:Jfe,LucideKeyboardMusic:Xfe,LucideKeyboardOff:Qfe,LucideLamp:axe,LucideLampCeiling:exe,LucideLampDesk:txe,LucideLampFloor:sxe,LucideLampWallDown:nxe,LucideLampWallUp:rxe,LucideLandPlot:ixe,LucideLandmark:VW,LucideLanguages:oxe,LucideLaptop:cxe,LucideLaptop2:WL,LucideLaptopMinimal:WL,LucideLaptopMinimalCheck:lxe,LucideLasso:uxe,LucideLassoSelect:dxe,LucideLaugh:hxe,LucideLayers:U9,LucideLayers2:mxe,LucideLayers3:pxe,LucideLayout:N4,LucideLayoutDashboard:BR,LucideLayoutGrid:r0,LucideLayoutList:fxe,LucideLayoutPanelLeft:xxe,LucideLayoutPanelTop:gxe,LucideLayoutTemplate:q_,LucideLeaf:yxe,LucideLeafyGreen:vxe,LucideLectern:bxe,LucideLetterText:_xe,LucideLibrary:i1,LucideLibraryBig:wxe,LucideLibrarySquare:GP,LucideLifeBuoy:q9,LucideLigature:jxe,LucideLightbulb:xN,LucideLightbulbOff:Nxe,LucideLineChart:GM,LucideLink:vc,LucideLink2:Rc,LucideLink2Off:kxe,LucideLinkedin:ry,LucideList:ug,LucideListCheck:Sxe,LucideListChecks:zp,LucideListCollapse:Cxe,LucideListEnd:Axe,LucideListFilter:HW,LucideListMinus:Txe,LucideListMusic:Exe,LucideListOrdered:kj,LucideListPlus:Mxe,LucideListRestart:Lxe,LucideListStart:Pxe,LucideListTodo:Ixe,LucideListTree:Rxe,LucideListVideo:Dxe,LucideListX:Oxe,LucideLoader:zxe,LucideLoader2:Wt,LucideLoaderCircle:Wt,LucideLoaderPinwheel:Fxe,LucideLocate:V9,LucideLocateFixed:Bxe,LucideLocateOff:$xe,LucideLock:du,LucideLockKeyhole:Uxe,LucideLockKeyholeOpen:KL,LucideLockOpen:YL,LucideLogIn:$R,LucideLogOut:UR,LucideLogs:qxe,LucideLollipop:Vxe,LucideLuggage:Hxe,LucideMSquare:WP,LucideMagnet:Gxe,LucideMail:on,LucideMailCheck:H9,LucideMailMinus:Wxe,LucideMailOpen:G9,LucideMailPlus:GW,LucideMailQuestion:Kxe,LucideMailSearch:Yxe,LucideMailWarning:Zxe,LucideMailX:W9,LucideMailbox:Xxe,LucideMails:Qxe,LucideMap:qR,LucideMapPin:oi,LucideMapPinCheck:ege,LucideMapPinCheckInside:Jxe,LucideMapPinHouse:tge,LucideMapPinMinus:nge,LucideMapPinMinusInside:sge,LucideMapPinOff:rge,LucideMapPinPlus:ige,LucideMapPinPlusInside:age,LucideMapPinX:lge,LucideMapPinXInside:oge,LucideMapPinned:cge,LucideMartini:dge,LucideMaximize:VR,LucideMaximize2:WW,LucideMedal:_3,LucideMegaphone:jh,LucideMegaphoneOff:uge,LucideMeh:hge,LucideMemoryStick:mge,LucideMenu:YT,LucideMenuSquare:KP,LucideMerge:pge,LucideMessageCircle:Yd,LucideMessageCircleCode:fge,LucideMessageCircleDashed:xge,LucideMessageCircleHeart:K9,LucideMessageCircleMore:gge,LucideMessageCircleOff:yge,LucideMessageCirclePlus:vge,LucideMessageCircleQuestion:Y9,LucideMessageCircleReply:bge,LucideMessageCircleWarning:_ge,LucideMessageCircleX:wge,LucideMessageSquare:ro,LucideMessageSquareCode:jge,LucideMessageSquareDashed:Nge,LucideMessageSquareDiff:kge,LucideMessageSquareDot:Sge,LucideMessageSquareHeart:Z9,LucideMessageSquareLock:Cge,LucideMessageSquareMore:KW,LucideMessageSquareOff:Age,LucideMessageSquarePlus:v5,LucideMessageSquareQuote:w3,LucideMessageSquareReply:Tge,LucideMessageSquareShare:Ege,LucideMessageSquareText:Mge,LucideMessageSquareWarning:Lge,LucideMessageSquareX:Pge,LucideMessagesSquare:X9,LucideMic:Sj,LucideMic2:ZL,LucideMicOff:Ige,LucideMicVocal:ZL,LucideMicrochip:Rge,LucideMicroscope:Dge,LucideMicrowave:Oge,LucideMilestone:Fge,LucideMilk:Bge,LucideMilkOff:zge,LucideMinimize:Uge,LucideMinimize2:$ge,LucideMinus:gN,LucideMinusCircle:hL,LucideMinusSquare:YP,LucideMonitor:Cj,LucideMonitorCheck:qge,LucideMonitorCog:Vge,LucideMonitorDot:Hge,LucideMonitorDown:Gge,LucideMonitorOff:Wge,LucideMonitorPause:Kge,LucideMonitorPlay:Q9,LucideMonitorSmartphone:Yge,LucideMonitorSpeaker:Zge,LucideMonitorStop:Xge,LucideMonitorUp:HR,LucideMonitorX:Qge,LucideMoon:e0e,LucideMoonStar:Jge,LucideMoreHorizontal:Hy,LucideMoreVertical:W0,LucideMountain:s0e,LucideMountainSnow:t0e,LucideMouse:i0e,LucideMouseOff:n0e,LucideMousePointer:ag,LucideMousePointer2:r0e,LucideMousePointerBan:a0e,LucideMousePointerClick:lu,LucideMousePointerSquareDashed:zP,LucideMove:YW,LucideMove3D:XL,LucideMove3d:XL,LucideMoveDiagonal:l0e,LucideMoveDiagonal2:o0e,LucideMoveDown:u0e,LucideMoveDownLeft:c0e,LucideMoveDownRight:d0e,LucideMoveHorizontal:h0e,LucideMoveLeft:m0e,LucideMoveRight:p0e,LucideMoveUp:g0e,LucideMoveUpLeft:f0e,LucideMoveUpRight:x0e,LucideMoveVertical:y0e,LucideMusic:J9,LucideMusic2:v0e,LucideMusic3:b0e,LucideMusic4:_0e,LucideNavigation:ZW,LucideNavigation2:j0e,LucideNavigation2Off:w0e,LucideNavigationOff:N0e,LucideNetwork:k0e,LucideNewspaper:V_,LucideNfc:S0e,LucideNotebook:E0e,LucideNotebookPen:C0e,LucideNotebookTabs:A0e,LucideNotebookText:T0e,LucideNotepadText:L0e,LucideNotepadTextDashed:M0e,LucideNut:I0e,LucideNutOff:P0e,LucideOctagon:D0e,LucideOctagonAlert:d5,LucideOctagonMinus:R0e,LucideOctagonPause:QL,LucideOctagonX:JL,LucideOmega:O0e,LucideOption:F0e,LucideOrbit:z0e,LucideOrigami:B0e,LucideOutdent:HL,LucidePackage:Eu,LucidePackage2:$0e,LucidePackageCheck:U0e,LucidePackageMinus:q0e,LucidePackageOpen:V0e,LucidePackagePlus:XW,LucidePackageSearch:H0e,LucidePackageX:G0e,LucidePaintBucket:W0e,LucidePaintRoller:K0e,LucidePaintbrush:Y0e,LucidePaintbrush2:eP,LucidePaintbrushVertical:eP,LucidePalette:Ac,LucidePalmtree:gI,LucidePanelBottom:Q0e,LucidePanelBottomClose:Z0e,LucidePanelBottomDashed:tP,LucidePanelBottomInactive:tP,LucidePanelBottomOpen:X0e,LucidePanelLeft:aP,LucidePanelLeftClose:sP,LucidePanelLeftDashed:nP,LucidePanelLeftInactive:nP,LucidePanelLeftOpen:rP,LucidePanelRight:tye,LucidePanelRightClose:J0e,LucidePanelRightDashed:iP,LucidePanelRightInactive:iP,LucidePanelRightOpen:eye,LucidePanelTop:rye,LucidePanelTopClose:sye,LucidePanelTopDashed:oP,LucidePanelTopInactive:oP,LucidePanelTopOpen:nye,LucidePanelsLeftBottom:aye,LucidePanelsLeftRight:lA,LucidePanelsRightBottom:iye,LucidePanelsTopBottom:hP,LucidePanelsTopLeft:N4,LucidePaperclip:ZT,LucideParentheses:oye,LucideParkingCircle:pL,LucideParkingCircleOff:mL,LucideParkingMeter:lye,LucideParkingSquare:QP,LucideParkingSquareOff:XP,LucidePartyPopper:bf,LucidePause:ay,LucidePauseCircle:fL,LucidePauseOctagon:QL,LucidePawPrint:cye,LucidePcCase:dye,LucidePen:oj,LucidePenBox:kp,LucidePenLine:sN,LucidePenOff:uye,LucidePenSquare:kp,LucidePenTool:XT,LucidePencil:Za,LucidePencilLine:ez,LucidePencilOff:hye,LucidePencilRuler:mye,LucidePentagon:pye,LucidePercent:QT,LucidePercentCircle:xL,LucidePercentDiamond:TL,LucidePercentSquare:JP,LucidePersonStanding:fye,LucidePhilippinePeso:xye,LucidePhone:pa,LucidePhoneCall:QW,LucidePhoneForwarded:gye,LucidePhoneIncoming:yye,LucidePhoneMissed:vye,LucidePhoneOff:bye,LucidePhoneOutgoing:_ye,LucidePi:wye,LucidePiSquare:eI,LucidePiano:jye,LucidePickaxe:Nye,LucidePictureInPicture:Sye,LucidePictureInPicture2:kye,LucidePieChart:ZM,LucidePiggyBank:Cye,LucidePilcrow:Eye,LucidePilcrowLeft:Aye,LucidePilcrowRight:Tye,LucidePilcrowSquare:tI,LucidePill:Lye,LucidePillBottle:Mye,LucidePin:JT,LucidePinOff:JW,LucidePipette:Pye,LucidePizza:Iye,LucidePlane:eK,LucidePlaneLanding:Rye,LucidePlaneTakeoff:Dye,LucidePlay:fd,LucidePlayCircle:vh,LucidePlaySquare:sI,LucidePlug:R5,LucidePlug2:Oye,LucidePlugZap:lP,LucidePlugZap2:lP,LucidePlus:Js,LucidePlusCircle:gL,LucidePlusSquare:nI,LucidePocket:zye,LucidePocketKnife:Fye,LucidePodcast:Bye,LucidePointer:Uye,LucidePointerOff:$ye,LucidePopcorn:qye,LucidePopsicle:Vye,LucidePoundSterling:Hye,LucidePower:tK,LucidePowerCircle:yL,LucidePowerOff:Gye,LucidePowerSquare:rI,LucidePresentation:yb,LucidePrinter:GR,LucidePrinterCheck:Wye,LucideProjector:Kye,LucideProportions:Yye,LucidePuzzle:Zye,LucidePyramid:Xye,LucideQrCode:hg,LucideQuote:yN,LucideRabbit:Qye,LucideRadar:tz,LucideRadiation:Jye,LucideRadical:eve,LucideRadio:iy,LucideRadioReceiver:tve,LucideRadioTower:sve,LucideRadius:nve,LucideRailSymbol:rve,LucideRainbow:ave,LucideRat:ive,LucideRatio:ove,LucideReceipt:xve,LucideReceiptCent:lve,LucideReceiptEuro:cve,LucideReceiptIndianRupee:dve,LucideReceiptJapaneseYen:uve,LucideReceiptPoundSterling:hve,LucideReceiptRussianRuble:mve,LucideReceiptSwissFranc:pve,LucideReceiptText:fve,LucideRectangleEllipsis:cP,LucideRectangleHorizontal:gve,LucideRectangleVertical:yve,LucideRecycle:vve,LucideRedo:eE,LucideRedo2:bve,LucideRedoDot:_ve,LucideRefreshCcw:sz,LucideRefreshCcwDot:wve,LucideRefreshCw:Ki,LucideRefreshCwOff:jve,LucideRefrigerator:Nve,LucideRegex:kve,LucideRemoveFormatting:Sve,LucideRepeat:nz,LucideRepeat1:Cve,LucideRepeat2:Ave,LucideReplace:Eve,LucideReplaceAll:Tve,LucideReply:sK,LucideReplyAll:Mve,LucideRewind:Lve,LucideRibbon:Pve,LucideRocket:oy,LucideRockingChair:Ive,LucideRollerCoaster:Rve,LucideRotate3D:dP,LucideRotate3d:dP,LucideRotateCcw:bm,LucideRotateCcwSquare:Dve,LucideRotateCw:WR,LucideRotateCwSquare:Ove,LucideRoute:rz,LucideRouteOff:Fve,LucideRouter:zve,LucideRows:uP,LucideRows2:uP,LucideRows3:hP,LucideRows4:Bve,LucideRss:$ve,LucideRuler:j3,LucideRussianRuble:Uve,LucideSailboat:qve,LucideSalad:Vve,LucideSandwich:Hve,LucideSatellite:Wve,LucideSatelliteDish:Gve,LucideSave:Jo,LucideSaveAll:Kve,LucideSaveOff:Yve,LucideScale:az,LucideScale3D:mP,LucideScale3d:mP,LucideScaling:Zve,LucideScan:r1e,LucideScanBarcode:Xve,LucideScanEye:Qve,LucideScanFace:Jve,LucideScanLine:e1e,LucideScanQrCode:t1e,LucideScanSearch:s1e,LucideScanText:n1e,LucideScatterChart:XM,LucideSchool:a1e,LucideSchool2:vI,LucideScissors:o1e,LucideScissorsLineDashed:i1e,LucideScissorsSquare:aI,LucideScissorsSquareDashedBottom:MP,LucideScreenShare:c1e,LucideScreenShareOff:l1e,LucideScroll:d1e,LucideScrollText:nK,LucideSearch:Fr,LucideSearchCheck:u1e,LucideSearchCode:h1e,LucideSearchSlash:m1e,LucideSearchX:rK,LucideSection:p1e,LucideSend:Dr,LucideSendHorizonal:pP,LucideSendHorizontal:pP,LucideSendToBack:f1e,LucideSeparatorHorizontal:x1e,LucideSeparatorVertical:g1e,LucideServer:_1e,LucideServerCog:y1e,LucideServerCrash:v1e,LucideServerOff:b1e,LucideSettings:ic,LucideSettings2:tE,LucideShapes:w1e,LucideShare:aK,LucideShare2:zd,LucideSheet:j1e,LucideShell:N1e,LucideShield:_f,LucideShieldAlert:iz,LucideShieldBan:k1e,LucideShieldCheck:a0,LucideShieldClose:fP,LucideShieldEllipsis:S1e,LucideShieldHalf:C1e,LucideShieldMinus:A1e,LucideShieldOff:KR,LucideShieldPlus:T1e,LucideShieldQuestion:E1e,LucideShieldX:fP,LucideShip:L1e,LucideShipWheel:M1e,LucideShirt:P1e,LucideShoppingBag:D5,LucideShoppingBasket:I1e,LucideShoppingCart:ib,LucideShovel:R1e,LucideShowerHead:D1e,LucideShrink:O1e,LucideShrub:F1e,LucideShuffle:YR,LucideSidebar:aP,LucideSidebarClose:sP,LucideSidebarOpen:rP,LucideSigma:z1e,LucideSigmaSquare:iI,LucideSignal:V1e,LucideSignalHigh:B1e,LucideSignalLow:$1e,LucideSignalMedium:U1e,LucideSignalZero:q1e,LucideSignature:H1e,LucideSignpost:W1e,LucideSignpostBig:G1e,LucideSiren:K1e,LucideSkipBack:Y1e,LucideSkipForward:iK,LucideSkull:Z1e,LucideSlack:X1e,LucideSlash:Q1e,LucideSlashSquare:oI,LucideSlice:J1e,LucideSliders:xP,LucideSlidersHorizontal:sE,LucideSlidersVertical:xP,LucideSmartphone:Jy,LucideSmartphoneCharging:ebe,LucideSmartphoneNfc:tbe,LucideSmile:nbe,LucideSmilePlus:sbe,LucideSnail:rbe,LucideSnowflake:gj,LucideSofa:abe,LucideSortAsc:MM,LucideSortDesc:AM,LucideSoup:ibe,LucideSpace:obe,LucideSpade:lbe,LucideSparkle:N3,LucideSparkles:yn,LucideSpeaker:cbe,LucideSpeech:dbe,LucideSpellCheck:hbe,LucideSpellCheck2:ube,LucideSpline:mbe,LucideSplit:pbe,LucideSplitSquareHorizontal:lI,LucideSplitSquareVertical:cI,LucideSprayCan:fbe,LucideSprout:nE,LucideSquare:H_,LucideSquareActivity:gP,LucideSquareArrowDown:bP,LucideSquareArrowDownLeft:yP,LucideSquareArrowDownRight:vP,LucideSquareArrowLeft:_P,LucideSquareArrowOutDownLeft:wP,LucideSquareArrowOutDownRight:jP,LucideSquareArrowOutUpLeft:NP,LucideSquareArrowOutUpRight:kP,LucideSquareArrowRight:SP,LucideSquareArrowUp:TP,LucideSquareArrowUpLeft:CP,LucideSquareArrowUpRight:AP,LucideSquareAsterisk:EP,LucideSquareBottomDashedScissors:MP,LucideSquareChartGantt:Tk,LucideSquareCheck:LP,LucideSquareCheckBig:k4,LucideSquareChevronDown:PP,LucideSquareChevronLeft:IP,LucideSquareChevronRight:RP,LucideSquareChevronUp:DP,LucideSquareCode:OP,LucideSquareDashed:BP,LucideSquareDashedBottom:gbe,LucideSquareDashedBottomCode:xbe,LucideSquareDashedKanban:FP,LucideSquareDashedMousePointer:zP,LucideSquareDivide:$P,LucideSquareDot:UP,LucideSquareEqual:qP,LucideSquareFunction:VP,LucideSquareGanttChart:Tk,LucideSquareKanban:HP,LucideSquareLibrary:GP,LucideSquareM:WP,LucideSquareMenu:KP,LucideSquareMinus:YP,LucideSquareMousePointer:ZP,LucideSquareParking:QP,LucideSquareParkingOff:XP,LucideSquarePen:kp,LucideSquarePercent:JP,LucideSquarePi:eI,LucideSquarePilcrow:tI,LucideSquarePlay:sI,LucideSquarePlus:nI,LucideSquarePower:rI,LucideSquareRadical:ybe,LucideSquareScissors:aI,LucideSquareSigma:iI,LucideSquareSlash:oI,LucideSquareSplitHorizontal:lI,LucideSquareSplitVertical:cI,LucideSquareSquare:vbe,LucideSquareStack:bbe,LucideSquareTerminal:dI,LucideSquareUser:hI,LucideSquareUserRound:uI,LucideSquareX:mI,LucideSquircle:_be,LucideSquirrel:wbe,LucideStamp:jbe,LucideStar:Wa,LucideStarHalf:Nbe,LucideStarOff:kbe,LucideStars:yn,LucideStepBack:Sbe,LucideStepForward:Cbe,LucideStethoscope:Abe,LucideSticker:Tbe,LucideStickyNote:oK,LucideStopCircle:bL,LucideStore:lK,LucideStretchHorizontal:Ebe,LucideStretchVertical:Mbe,LucideStrikethrough:cK,LucideSubscript:Lbe,LucideSubtitles:zM,LucideSun:Aj,LucideSunDim:Pbe,LucideSunMedium:Ibe,LucideSunMoon:Rbe,LucideSunSnow:Dbe,LucideSunrise:Obe,LucideSunset:Fbe,LucideSuperscript:zbe,LucideSwatchBook:Bbe,LucideSwissFranc:$be,LucideSwitchCamera:Ube,LucideSword:qbe,LucideSwords:Vbe,LucideSyringe:Hbe,LucideTable:lz,LucideTable2:oz,LucideTableCellsMerge:Gbe,LucideTableCellsSplit:Wbe,LucideTableColumnsSplit:Kbe,LucideTableOfContents:Ybe,LucideTableProperties:Zbe,LucideTableRowsSplit:Xbe,LucideTablet:cz,LucideTabletSmartphone:Qbe,LucideTablets:Jbe,LucideTag:wf,LucideTags:dK,LucideTally1:e_e,LucideTally2:t_e,LucideTally3:s_e,LucideTally4:n_e,LucideTally5:r_e,LucideTangent:a_e,LucideTarget:uu,LucideTelescope:i_e,LucideTent:l_e,LucideTentTree:o_e,LucideTerminal:c_e,LucideTerminalSquare:dI,LucideTestTube:d_e,LucideTestTube2:pI,LucideTestTubeDiagonal:pI,LucideTestTubes:u_e,LucideText:x_e,LucideTextCursor:m_e,LucideTextCursorInput:h_e,LucideTextQuote:p_e,LucideTextSearch:f_e,LucideTextSelect:fI,LucideTextSelection:fI,LucideTheater:g_e,LucideThermometer:uK,LucideThermometerSnowflake:y_e,LucideThermometerSun:v_e,LucideThumbsDown:hK,LucideThumbsUp:mg,LucideTicket:mK,LucideTicketCheck:b_e,LucideTicketMinus:__e,LucideTicketPercent:w_e,LucideTicketPlus:j_e,LucideTicketSlash:N_e,LucideTicketX:k_e,LucideTickets:C_e,LucideTicketsPlane:S_e,LucideTimer:E_e,LucideTimerOff:A_e,LucideTimerReset:T_e,LucideToggleLeft:M_e,LucideToggleRight:L_e,LucideToilet:P_e,LucideTornado:I_e,LucideTorus:R_e,LucideTouchpad:O_e,LucideTouchpadOff:D_e,LucideTowerControl:F_e,LucideToyBrick:z_e,LucideTractor:B_e,LucideTrafficCone:$_e,LucideTrain:xI,LucideTrainFront:q_e,LucideTrainFrontTunnel:U_e,LucideTrainTrack:V_e,LucideTramFront:xI,LucideTrash:H_e,LucideTrash2:Rn,LucideTreeDeciduous:G_e,LucideTreePalm:gI,LucideTreePine:rE,LucideTrees:W_e,LucideTrello:K_e,LucideTrendingDown:vN,LucideTrendingUp:kl,LucideTrendingUpDown:Y_e,LucideTriangle:X_e,LucideTriangleAlert:hd,LucideTriangleRight:Z_e,LucideTrophy:ll,LucideTruck:pK,LucideTurtle:Q_e,LucideTv:ewe,LucideTv2:yI,LucideTvMinimal:yI,LucideTvMinimalPlay:J_e,LucideTwitch:twe,LucideTwitter:swe,LucideType:rwe,LucideTypeOutline:nwe,LucideUmbrella:iwe,LucideUmbrellaOff:awe,LucideUnderline:dz,LucideUndo:aE,LucideUndo2:fK,LucideUndoDot:owe,LucideUnfoldHorizontal:lwe,LucideUnfoldVertical:cwe,LucideUngroup:dwe,LucideUniversity:vI,LucideUnlink:ZR,LucideUnlink2:uwe,LucideUnlock:YL,LucideUnlockKeyhole:KL,LucideUnplug:xK,LucideUpload:Ja,LucideUploadCloud:SL,LucideUsb:hwe,LucideUser:Eo,LucideUser2:kI,LucideUserCheck:bN,LucideUserCheck2:bI,LucideUserCircle:wL,LucideUserCircle2:_L,LucideUserCog:gK,LucideUserCog2:_I,LucideUserMinus:uz,LucideUserMinus2:wI,LucideUserPen:mwe,LucideUserPlus:Sl,LucideUserPlus2:jI,LucideUserRound:kI,LucideUserRoundCheck:bI,LucideUserRoundCog:_I,LucideUserRoundMinus:wI,LucideUserRoundPen:pwe,LucideUserRoundPlus:jI,LucideUserRoundSearch:fwe,LucideUserRoundX:NI,LucideUserSearch:xwe,LucideUserSquare:hI,LucideUserSquare2:uI,LucideUserX:gwe,LucideUserX2:NI,LucideUsers:Bn,LucideUsers2:qv,LucideUsersRound:qv,LucideUtensils:CI,LucideUtensilsCrossed:SI,LucideUtilityPole:ywe,LucideVariable:hz,LucideVault:vwe,LucideVegan:bwe,LucideVenetianMask:_we,LucideVerified:IM,LucideVibrate:jwe,LucideVibrateOff:wwe,LucideVideo:Zr,LucideVideoOff:Nwe,LucideVideotape:kwe,LucideView:Swe,LucideVoicemail:Cwe,LucideVolleyball:Awe,LucideVolume:Mwe,LucideVolume1:Twe,LucideVolume2:yK,LucideVolumeOff:Ewe,LucideVolumeX:vK,LucideVote:Lwe,LucideWallet:mz,LucideWallet2:AI,LucideWalletCards:Pwe,LucideWalletMinimal:AI,LucideWallpaper:Iwe,LucideWand:Rwe,LucideWand2:um,LucideWandSparkles:um,LucideWarehouse:Dwe,LucideWashingMachine:Owe,LucideWatch:Fwe,LucideWaves:zwe,LucideWaypoints:Bwe,LucideWebcam:$we,LucideWebhook:qwe,LucideWebhookOff:Uwe,LucideWeight:Vwe,LucideWheat:Gwe,LucideWheatOff:Hwe,LucideWholeWord:Wwe,LucideWifi:Qwe,LucideWifiHigh:Kwe,LucideWifiLow:Ywe,LucideWifiOff:Zwe,LucideWifiZero:Xwe,LucideWind:eje,LucideWindArrowDown:Jwe,LucideWine:bK,LucideWineOff:tje,LucideWorkflow:_K,LucideWorm:sje,LucideWrapText:nje,LucideWrench:O5,LucideX:dr,LucideXCircle:Rd,LucideXOctagon:JL,LucideXSquare:mI,LucideYoutube:rje,LucideZap:jf,LucideZapOff:aje,LucideZoomIn:iE,LucideZoomOut:pz,Luggage:Hxe,LuggageIcon:Hxe,MSquare:WP,MSquareIcon:WP,Magnet:Gxe,MagnetIcon:Gxe,Mail:on,MailCheck:H9,MailCheckIcon:H9,MailIcon:on,MailMinus:Wxe,MailMinusIcon:Wxe,MailOpen:G9,MailOpenIcon:G9,MailPlus:GW,MailPlusIcon:GW,MailQuestion:Kxe,MailQuestionIcon:Kxe,MailSearch:Yxe,MailSearchIcon:Yxe,MailWarning:Zxe,MailWarningIcon:Zxe,MailX:W9,MailXIcon:W9,Mailbox:Xxe,MailboxIcon:Xxe,Mails:Qxe,MailsIcon:Qxe,Map:qR,MapIcon:qR,MapPin:oi,MapPinCheck:ege,MapPinCheckIcon:ege,MapPinCheckInside:Jxe,MapPinCheckInsideIcon:Jxe,MapPinHouse:tge,MapPinHouseIcon:tge,MapPinIcon:oi,MapPinMinus:nge,MapPinMinusIcon:nge,MapPinMinusInside:sge,MapPinMinusInsideIcon:sge,MapPinOff:rge,MapPinOffIcon:rge,MapPinPlus:ige,MapPinPlusIcon:ige,MapPinPlusInside:age,MapPinPlusInsideIcon:age,MapPinX:lge,MapPinXIcon:lge,MapPinXInside:oge,MapPinXInsideIcon:oge,MapPinned:cge,MapPinnedIcon:cge,Martini:dge,MartiniIcon:dge,Maximize:VR,Maximize2:WW,Maximize2Icon:WW,MaximizeIcon:VR,Medal:_3,MedalIcon:_3,Megaphone:jh,MegaphoneIcon:jh,MegaphoneOff:uge,MegaphoneOffIcon:uge,Meh:hge,MehIcon:hge,MemoryStick:mge,MemoryStickIcon:mge,Menu:YT,MenuIcon:YT,MenuSquare:KP,MenuSquareIcon:KP,Merge:pge,MergeIcon:pge,MessageCircle:Yd,MessageCircleCode:fge,MessageCircleCodeIcon:fge,MessageCircleDashed:xge,MessageCircleDashedIcon:xge,MessageCircleHeart:K9,MessageCircleHeartIcon:K9,MessageCircleIcon:Yd,MessageCircleMore:gge,MessageCircleMoreIcon:gge,MessageCircleOff:yge,MessageCircleOffIcon:yge,MessageCirclePlus:vge,MessageCirclePlusIcon:vge,MessageCircleQuestion:Y9,MessageCircleQuestionIcon:Y9,MessageCircleReply:bge,MessageCircleReplyIcon:bge,MessageCircleWarning:_ge,MessageCircleWarningIcon:_ge,MessageCircleX:wge,MessageCircleXIcon:wge,MessageSquare:ro,MessageSquareCode:jge,MessageSquareCodeIcon:jge,MessageSquareDashed:Nge,MessageSquareDashedIcon:Nge,MessageSquareDiff:kge,MessageSquareDiffIcon:kge,MessageSquareDot:Sge,MessageSquareDotIcon:Sge,MessageSquareHeart:Z9,MessageSquareHeartIcon:Z9,MessageSquareIcon:ro,MessageSquareLock:Cge,MessageSquareLockIcon:Cge,MessageSquareMore:KW,MessageSquareMoreIcon:KW,MessageSquareOff:Age,MessageSquareOffIcon:Age,MessageSquarePlus:v5,MessageSquarePlusIcon:v5,MessageSquareQuote:w3,MessageSquareQuoteIcon:w3,MessageSquareReply:Tge,MessageSquareReplyIcon:Tge,MessageSquareShare:Ege,MessageSquareShareIcon:Ege,MessageSquareText:Mge,MessageSquareTextIcon:Mge,MessageSquareWarning:Lge,MessageSquareWarningIcon:Lge,MessageSquareX:Pge,MessageSquareXIcon:Pge,MessagesSquare:X9,MessagesSquareIcon:X9,Mic:Sj,Mic2:ZL,Mic2Icon:ZL,MicIcon:Sj,MicOff:Ige,MicOffIcon:Ige,MicVocal:ZL,MicVocalIcon:ZL,Microchip:Rge,MicrochipIcon:Rge,Microscope:Dge,MicroscopeIcon:Dge,Microwave:Oge,MicrowaveIcon:Oge,Milestone:Fge,MilestoneIcon:Fge,Milk:Bge,MilkIcon:Bge,MilkOff:zge,MilkOffIcon:zge,Minimize:Uge,Minimize2:$ge,Minimize2Icon:$ge,MinimizeIcon:Uge,Minus:gN,MinusCircle:hL,MinusCircleIcon:hL,MinusIcon:gN,MinusSquare:YP,MinusSquareIcon:YP,Monitor:Cj,MonitorCheck:qge,MonitorCheckIcon:qge,MonitorCog:Vge,MonitorCogIcon:Vge,MonitorDot:Hge,MonitorDotIcon:Hge,MonitorDown:Gge,MonitorDownIcon:Gge,MonitorIcon:Cj,MonitorOff:Wge,MonitorOffIcon:Wge,MonitorPause:Kge,MonitorPauseIcon:Kge,MonitorPlay:Q9,MonitorPlayIcon:Q9,MonitorSmartphone:Yge,MonitorSmartphoneIcon:Yge,MonitorSpeaker:Zge,MonitorSpeakerIcon:Zge,MonitorStop:Xge,MonitorStopIcon:Xge,MonitorUp:HR,MonitorUpIcon:HR,MonitorX:Qge,MonitorXIcon:Qge,Moon:e0e,MoonIcon:e0e,MoonStar:Jge,MoonStarIcon:Jge,MoreHorizontal:Hy,MoreHorizontalIcon:Hy,MoreVertical:W0,MoreVerticalIcon:W0,Mountain:s0e,MountainIcon:s0e,MountainSnow:t0e,MountainSnowIcon:t0e,Mouse:i0e,MouseIcon:i0e,MouseOff:n0e,MouseOffIcon:n0e,MousePointer:ag,MousePointer2:r0e,MousePointer2Icon:r0e,MousePointerBan:a0e,MousePointerBanIcon:a0e,MousePointerClick:lu,MousePointerClickIcon:lu,MousePointerIcon:ag,MousePointerSquareDashed:zP,MousePointerSquareDashedIcon:zP,Move:YW,Move3D:XL,Move3DIcon:XL,Move3d:XL,Move3dIcon:XL,MoveDiagonal:l0e,MoveDiagonal2:o0e,MoveDiagonal2Icon:o0e,MoveDiagonalIcon:l0e,MoveDown:u0e,MoveDownIcon:u0e,MoveDownLeft:c0e,MoveDownLeftIcon:c0e,MoveDownRight:d0e,MoveDownRightIcon:d0e,MoveHorizontal:h0e,MoveHorizontalIcon:h0e,MoveIcon:YW,MoveLeft:m0e,MoveLeftIcon:m0e,MoveRight:p0e,MoveRightIcon:p0e,MoveUp:g0e,MoveUpIcon:g0e,MoveUpLeft:f0e,MoveUpLeftIcon:f0e,MoveUpRight:x0e,MoveUpRightIcon:x0e,MoveVertical:y0e,MoveVerticalIcon:y0e,Music:J9,Music2:v0e,Music2Icon:v0e,Music3:b0e,Music3Icon:b0e,Music4:_0e,Music4Icon:_0e,MusicIcon:J9,Navigation:ZW,Navigation2:j0e,Navigation2Icon:j0e,Navigation2Off:w0e,Navigation2OffIcon:w0e,NavigationIcon:ZW,NavigationOff:N0e,NavigationOffIcon:N0e,Network:k0e,NetworkIcon:k0e,Newspaper:V_,NewspaperIcon:V_,Nfc:S0e,NfcIcon:S0e,Notebook:E0e,NotebookIcon:E0e,NotebookPen:C0e,NotebookPenIcon:C0e,NotebookTabs:A0e,NotebookTabsIcon:A0e,NotebookText:T0e,NotebookTextIcon:T0e,NotepadText:L0e,NotepadTextDashed:M0e,NotepadTextDashedIcon:M0e,NotepadTextIcon:L0e,Nut:I0e,NutIcon:I0e,NutOff:P0e,NutOffIcon:P0e,Octagon:D0e,OctagonAlert:d5,OctagonAlertIcon:d5,OctagonIcon:D0e,OctagonMinus:R0e,OctagonMinusIcon:R0e,OctagonPause:QL,OctagonPauseIcon:QL,OctagonX:JL,OctagonXIcon:JL,Omega:O0e,OmegaIcon:O0e,Option:F0e,OptionIcon:F0e,Orbit:z0e,OrbitIcon:z0e,Origami:B0e,OrigamiIcon:B0e,Outdent:HL,OutdentIcon:HL,Package:Eu,Package2:$0e,Package2Icon:$0e,PackageCheck:U0e,PackageCheckIcon:U0e,PackageIcon:Eu,PackageMinus:q0e,PackageMinusIcon:q0e,PackageOpen:V0e,PackageOpenIcon:V0e,PackagePlus:XW,PackagePlusIcon:XW,PackageSearch:H0e,PackageSearchIcon:H0e,PackageX:G0e,PackageXIcon:G0e,PaintBucket:W0e,PaintBucketIcon:W0e,PaintRoller:K0e,PaintRollerIcon:K0e,Paintbrush:Y0e,Paintbrush2:eP,Paintbrush2Icon:eP,PaintbrushIcon:Y0e,PaintbrushVertical:eP,PaintbrushVerticalIcon:eP,Palette:Ac,PaletteIcon:Ac,Palmtree:gI,PalmtreeIcon:gI,PanelBottom:Q0e,PanelBottomClose:Z0e,PanelBottomCloseIcon:Z0e,PanelBottomDashed:tP,PanelBottomDashedIcon:tP,PanelBottomIcon:Q0e,PanelBottomInactive:tP,PanelBottomInactiveIcon:tP,PanelBottomOpen:X0e,PanelBottomOpenIcon:X0e,PanelLeft:aP,PanelLeftClose:sP,PanelLeftCloseIcon:sP,PanelLeftDashed:nP,PanelLeftDashedIcon:nP,PanelLeftIcon:aP,PanelLeftInactive:nP,PanelLeftInactiveIcon:nP,PanelLeftOpen:rP,PanelLeftOpenIcon:rP,PanelRight:tye,PanelRightClose:J0e,PanelRightCloseIcon:J0e,PanelRightDashed:iP,PanelRightDashedIcon:iP,PanelRightIcon:tye,PanelRightInactive:iP,PanelRightInactiveIcon:iP,PanelRightOpen:eye,PanelRightOpenIcon:eye,PanelTop:rye,PanelTopClose:sye,PanelTopCloseIcon:sye,PanelTopDashed:oP,PanelTopDashedIcon:oP,PanelTopIcon:rye,PanelTopInactive:oP,PanelTopInactiveIcon:oP,PanelTopOpen:nye,PanelTopOpenIcon:nye,PanelsLeftBottom:aye,PanelsLeftBottomIcon:aye,PanelsLeftRight:lA,PanelsLeftRightIcon:lA,PanelsRightBottom:iye,PanelsRightBottomIcon:iye,PanelsTopBottom:hP,PanelsTopBottomIcon:hP,PanelsTopLeft:N4,PanelsTopLeftIcon:N4,Paperclip:ZT,PaperclipIcon:ZT,Parentheses:oye,ParenthesesIcon:oye,ParkingCircle:pL,ParkingCircleIcon:pL,ParkingCircleOff:mL,ParkingCircleOffIcon:mL,ParkingMeter:lye,ParkingMeterIcon:lye,ParkingSquare:QP,ParkingSquareIcon:QP,ParkingSquareOff:XP,ParkingSquareOffIcon:XP,PartyPopper:bf,PartyPopperIcon:bf,Pause:ay,PauseCircle:fL,PauseCircleIcon:fL,PauseIcon:ay,PauseOctagon:QL,PauseOctagonIcon:QL,PawPrint:cye,PawPrintIcon:cye,PcCase:dye,PcCaseIcon:dye,Pen:oj,PenBox:kp,PenBoxIcon:kp,PenIcon:oj,PenLine:sN,PenLineIcon:sN,PenOff:uye,PenOffIcon:uye,PenSquare:kp,PenSquareIcon:kp,PenTool:XT,PenToolIcon:XT,Pencil:Za,PencilIcon:Za,PencilLine:ez,PencilLineIcon:ez,PencilOff:hye,PencilOffIcon:hye,PencilRuler:mye,PencilRulerIcon:mye,Pentagon:pye,PentagonIcon:pye,Percent:QT,PercentCircle:xL,PercentCircleIcon:xL,PercentDiamond:TL,PercentDiamondIcon:TL,PercentIcon:QT,PercentSquare:JP,PercentSquareIcon:JP,PersonStanding:fye,PersonStandingIcon:fye,PhilippinePeso:xye,PhilippinePesoIcon:xye,Phone:pa,PhoneCall:QW,PhoneCallIcon:QW,PhoneForwarded:gye,PhoneForwardedIcon:gye,PhoneIcon:pa,PhoneIncoming:yye,PhoneIncomingIcon:yye,PhoneMissed:vye,PhoneMissedIcon:vye,PhoneOff:bye,PhoneOffIcon:bye,PhoneOutgoing:_ye,PhoneOutgoingIcon:_ye,Pi:wye,PiIcon:wye,PiSquare:eI,PiSquareIcon:eI,Piano:jye,PianoIcon:jye,Pickaxe:Nye,PickaxeIcon:Nye,PictureInPicture:Sye,PictureInPicture2:kye,PictureInPicture2Icon:kye,PictureInPictureIcon:Sye,PieChart:ZM,PieChartIcon:ZM,PiggyBank:Cye,PiggyBankIcon:Cye,Pilcrow:Eye,PilcrowIcon:Eye,PilcrowLeft:Aye,PilcrowLeftIcon:Aye,PilcrowRight:Tye,PilcrowRightIcon:Tye,PilcrowSquare:tI,PilcrowSquareIcon:tI,Pill:Lye,PillBottle:Mye,PillBottleIcon:Mye,PillIcon:Lye,Pin:JT,PinIcon:JT,PinOff:JW,PinOffIcon:JW,Pipette:Pye,PipetteIcon:Pye,Pizza:Iye,PizzaIcon:Iye,Plane:eK,PlaneIcon:eK,PlaneLanding:Rye,PlaneLandingIcon:Rye,PlaneTakeoff:Dye,PlaneTakeoffIcon:Dye,Play:fd,PlayCircle:vh,PlayCircleIcon:vh,PlayIcon:fd,PlaySquare:sI,PlaySquareIcon:sI,Plug:R5,Plug2:Oye,Plug2Icon:Oye,PlugIcon:R5,PlugZap:lP,PlugZap2:lP,PlugZap2Icon:lP,PlugZapIcon:lP,Plus:Js,PlusCircle:gL,PlusCircleIcon:gL,PlusIcon:Js,PlusSquare:nI,PlusSquareIcon:nI,Pocket:zye,PocketIcon:zye,PocketKnife:Fye,PocketKnifeIcon:Fye,Podcast:Bye,PodcastIcon:Bye,Pointer:Uye,PointerIcon:Uye,PointerOff:$ye,PointerOffIcon:$ye,Popcorn:qye,PopcornIcon:qye,Popsicle:Vye,PopsicleIcon:Vye,PoundSterling:Hye,PoundSterlingIcon:Hye,Power:tK,PowerCircle:yL,PowerCircleIcon:yL,PowerIcon:tK,PowerOff:Gye,PowerOffIcon:Gye,PowerSquare:rI,PowerSquareIcon:rI,Presentation:yb,PresentationIcon:yb,Printer:GR,PrinterCheck:Wye,PrinterCheckIcon:Wye,PrinterIcon:GR,Projector:Kye,ProjectorIcon:Kye,Proportions:Yye,ProportionsIcon:Yye,Puzzle:Zye,PuzzleIcon:Zye,Pyramid:Xye,PyramidIcon:Xye,QrCode:hg,QrCodeIcon:hg,Quote:yN,QuoteIcon:yN,Rabbit:Qye,RabbitIcon:Qye,Radar:tz,RadarIcon:tz,Radiation:Jye,RadiationIcon:Jye,Radical:eve,RadicalIcon:eve,Radio:iy,RadioIcon:iy,RadioReceiver:tve,RadioReceiverIcon:tve,RadioTower:sve,RadioTowerIcon:sve,Radius:nve,RadiusIcon:nve,RailSymbol:rve,RailSymbolIcon:rve,Rainbow:ave,RainbowIcon:ave,Rat:ive,RatIcon:ive,Ratio:ove,RatioIcon:ove,Receipt:xve,ReceiptCent:lve,ReceiptCentIcon:lve,ReceiptEuro:cve,ReceiptEuroIcon:cve,ReceiptIcon:xve,ReceiptIndianRupee:dve,ReceiptIndianRupeeIcon:dve,ReceiptJapaneseYen:uve,ReceiptJapaneseYenIcon:uve,ReceiptPoundSterling:hve,ReceiptPoundSterlingIcon:hve,ReceiptRussianRuble:mve,ReceiptRussianRubleIcon:mve,ReceiptSwissFranc:pve,ReceiptSwissFrancIcon:pve,ReceiptText:fve,ReceiptTextIcon:fve,RectangleEllipsis:cP,RectangleEllipsisIcon:cP,RectangleHorizontal:gve,RectangleHorizontalIcon:gve,RectangleVertical:yve,RectangleVerticalIcon:yve,Recycle:vve,RecycleIcon:vve,Redo:eE,Redo2:bve,Redo2Icon:bve,RedoDot:_ve,RedoDotIcon:_ve,RedoIcon:eE,RefreshCcw:sz,RefreshCcwDot:wve,RefreshCcwDotIcon:wve,RefreshCcwIcon:sz,RefreshCw:Ki,RefreshCwIcon:Ki,RefreshCwOff:jve,RefreshCwOffIcon:jve,Refrigerator:Nve,RefrigeratorIcon:Nve,Regex:kve,RegexIcon:kve,RemoveFormatting:Sve,RemoveFormattingIcon:Sve,Repeat:nz,Repeat1:Cve,Repeat1Icon:Cve,Repeat2:Ave,Repeat2Icon:Ave,RepeatIcon:nz,Replace:Eve,ReplaceAll:Tve,ReplaceAllIcon:Tve,ReplaceIcon:Eve,Reply:sK,ReplyAll:Mve,ReplyAllIcon:Mve,ReplyIcon:sK,Rewind:Lve,RewindIcon:Lve,Ribbon:Pve,RibbonIcon:Pve,Rocket:oy,RocketIcon:oy,RockingChair:Ive,RockingChairIcon:Ive,RollerCoaster:Rve,RollerCoasterIcon:Rve,Rotate3D:dP,Rotate3DIcon:dP,Rotate3d:dP,Rotate3dIcon:dP,RotateCcw:bm,RotateCcwIcon:bm,RotateCcwSquare:Dve,RotateCcwSquareIcon:Dve,RotateCw:WR,RotateCwIcon:WR,RotateCwSquare:Ove,RotateCwSquareIcon:Ove,Route:rz,RouteIcon:rz,RouteOff:Fve,RouteOffIcon:Fve,Router:zve,RouterIcon:zve,Rows:uP,Rows2:uP,Rows2Icon:uP,Rows3:hP,Rows3Icon:hP,Rows4:Bve,Rows4Icon:Bve,RowsIcon:uP,Rss:$ve,RssIcon:$ve,Ruler:j3,RulerIcon:j3,RussianRuble:Uve,RussianRubleIcon:Uve,Sailboat:qve,SailboatIcon:qve,Salad:Vve,SaladIcon:Vve,Sandwich:Hve,SandwichIcon:Hve,Satellite:Wve,SatelliteDish:Gve,SatelliteDishIcon:Gve,SatelliteIcon:Wve,Save:Jo,SaveAll:Kve,SaveAllIcon:Kve,SaveIcon:Jo,SaveOff:Yve,SaveOffIcon:Yve,Scale:az,Scale3D:mP,Scale3DIcon:mP,Scale3d:mP,Scale3dIcon:mP,ScaleIcon:az,Scaling:Zve,ScalingIcon:Zve,Scan:r1e,ScanBarcode:Xve,ScanBarcodeIcon:Xve,ScanEye:Qve,ScanEyeIcon:Qve,ScanFace:Jve,ScanFaceIcon:Jve,ScanIcon:r1e,ScanLine:e1e,ScanLineIcon:e1e,ScanQrCode:t1e,ScanQrCodeIcon:t1e,ScanSearch:s1e,ScanSearchIcon:s1e,ScanText:n1e,ScanTextIcon:n1e,ScatterChart:XM,ScatterChartIcon:XM,School:a1e,School2:vI,School2Icon:vI,SchoolIcon:a1e,Scissors:o1e,ScissorsIcon:o1e,ScissorsLineDashed:i1e,ScissorsLineDashedIcon:i1e,ScissorsSquare:aI,ScissorsSquareDashedBottom:MP,ScissorsSquareDashedBottomIcon:MP,ScissorsSquareIcon:aI,ScreenShare:c1e,ScreenShareIcon:c1e,ScreenShareOff:l1e,ScreenShareOffIcon:l1e,Scroll:d1e,ScrollIcon:d1e,ScrollText:nK,ScrollTextIcon:nK,Search:Fr,SearchCheck:u1e,SearchCheckIcon:u1e,SearchCode:h1e,SearchCodeIcon:h1e,SearchIcon:Fr,SearchSlash:m1e,SearchSlashIcon:m1e,SearchX:rK,SearchXIcon:rK,Section:p1e,SectionIcon:p1e,Send:Dr,SendHorizonal:pP,SendHorizonalIcon:pP,SendHorizontal:pP,SendHorizontalIcon:pP,SendIcon:Dr,SendToBack:f1e,SendToBackIcon:f1e,SeparatorHorizontal:x1e,SeparatorHorizontalIcon:x1e,SeparatorVertical:g1e,SeparatorVerticalIcon:g1e,Server:_1e,ServerCog:y1e,ServerCogIcon:y1e,ServerCrash:v1e,ServerCrashIcon:v1e,ServerIcon:_1e,ServerOff:b1e,ServerOffIcon:b1e,Settings:ic,Settings2:tE,Settings2Icon:tE,SettingsIcon:ic,Shapes:w1e,ShapesIcon:w1e,Share:aK,Share2:zd,Share2Icon:zd,ShareIcon:aK,Sheet:j1e,SheetIcon:j1e,Shell:N1e,ShellIcon:N1e,Shield:_f,ShieldAlert:iz,ShieldAlertIcon:iz,ShieldBan:k1e,ShieldBanIcon:k1e,ShieldCheck:a0,ShieldCheckIcon:a0,ShieldClose:fP,ShieldCloseIcon:fP,ShieldEllipsis:S1e,ShieldEllipsisIcon:S1e,ShieldHalf:C1e,ShieldHalfIcon:C1e,ShieldIcon:_f,ShieldMinus:A1e,ShieldMinusIcon:A1e,ShieldOff:KR,ShieldOffIcon:KR,ShieldPlus:T1e,ShieldPlusIcon:T1e,ShieldQuestion:E1e,ShieldQuestionIcon:E1e,ShieldX:fP,ShieldXIcon:fP,Ship:L1e,ShipIcon:L1e,ShipWheel:M1e,ShipWheelIcon:M1e,Shirt:P1e,ShirtIcon:P1e,ShoppingBag:D5,ShoppingBagIcon:D5,ShoppingBasket:I1e,ShoppingBasketIcon:I1e,ShoppingCart:ib,ShoppingCartIcon:ib,Shovel:R1e,ShovelIcon:R1e,ShowerHead:D1e,ShowerHeadIcon:D1e,Shrink:O1e,ShrinkIcon:O1e,Shrub:F1e,ShrubIcon:F1e,Shuffle:YR,ShuffleIcon:YR,Sidebar:aP,SidebarClose:sP,SidebarCloseIcon:sP,SidebarIcon:aP,SidebarOpen:rP,SidebarOpenIcon:rP,Sigma:z1e,SigmaIcon:z1e,SigmaSquare:iI,SigmaSquareIcon:iI,Signal:V1e,SignalHigh:B1e,SignalHighIcon:B1e,SignalIcon:V1e,SignalLow:$1e,SignalLowIcon:$1e,SignalMedium:U1e,SignalMediumIcon:U1e,SignalZero:q1e,SignalZeroIcon:q1e,Signature:H1e,SignatureIcon:H1e,Signpost:W1e,SignpostBig:G1e,SignpostBigIcon:G1e,SignpostIcon:W1e,Siren:K1e,SirenIcon:K1e,SkipBack:Y1e,SkipBackIcon:Y1e,SkipForward:iK,SkipForwardIcon:iK,Skull:Z1e,SkullIcon:Z1e,Slack:X1e,SlackIcon:X1e,Slash:Q1e,SlashIcon:Q1e,SlashSquare:oI,SlashSquareIcon:oI,Slice:J1e,SliceIcon:J1e,Sliders:xP,SlidersHorizontal:sE,SlidersHorizontalIcon:sE,SlidersIcon:xP,SlidersVertical:xP,SlidersVerticalIcon:xP,Smartphone:Jy,SmartphoneCharging:ebe,SmartphoneChargingIcon:ebe,SmartphoneIcon:Jy,SmartphoneNfc:tbe,SmartphoneNfcIcon:tbe,Smile:nbe,SmileIcon:nbe,SmilePlus:sbe,SmilePlusIcon:sbe,Snail:rbe,SnailIcon:rbe,Snowflake:gj,SnowflakeIcon:gj,Sofa:abe,SofaIcon:abe,SortAsc:MM,SortAscIcon:MM,SortDesc:AM,SortDescIcon:AM,Soup:ibe,SoupIcon:ibe,Space:obe,SpaceIcon:obe,Spade:lbe,SpadeIcon:lbe,Sparkle:N3,SparkleIcon:N3,Sparkles:yn,SparklesIcon:yn,Speaker:cbe,SpeakerIcon:cbe,Speech:dbe,SpeechIcon:dbe,SpellCheck:hbe,SpellCheck2:ube,SpellCheck2Icon:ube,SpellCheckIcon:hbe,Spline:mbe,SplineIcon:mbe,Split:pbe,SplitIcon:pbe,SplitSquareHorizontal:lI,SplitSquareHorizontalIcon:lI,SplitSquareVertical:cI,SplitSquareVerticalIcon:cI,SprayCan:fbe,SprayCanIcon:fbe,Sprout:nE,SproutIcon:nE,Square:H_,SquareActivity:gP,SquareActivityIcon:gP,SquareArrowDown:bP,SquareArrowDownIcon:bP,SquareArrowDownLeft:yP,SquareArrowDownLeftIcon:yP,SquareArrowDownRight:vP,SquareArrowDownRightIcon:vP,SquareArrowLeft:_P,SquareArrowLeftIcon:_P,SquareArrowOutDownLeft:wP,SquareArrowOutDownLeftIcon:wP,SquareArrowOutDownRight:jP,SquareArrowOutDownRightIcon:jP,SquareArrowOutUpLeft:NP,SquareArrowOutUpLeftIcon:NP,SquareArrowOutUpRight:kP,SquareArrowOutUpRightIcon:kP,SquareArrowRight:SP,SquareArrowRightIcon:SP,SquareArrowUp:TP,SquareArrowUpIcon:TP,SquareArrowUpLeft:CP,SquareArrowUpLeftIcon:CP,SquareArrowUpRight:AP,SquareArrowUpRightIcon:AP,SquareAsterisk:EP,SquareAsteriskIcon:EP,SquareBottomDashedScissors:MP,SquareBottomDashedScissorsIcon:MP,SquareChartGantt:Tk,SquareChartGanttIcon:Tk,SquareCheck:LP,SquareCheckBig:k4,SquareCheckBigIcon:k4,SquareCheckIcon:LP,SquareChevronDown:PP,SquareChevronDownIcon:PP,SquareChevronLeft:IP,SquareChevronLeftIcon:IP,SquareChevronRight:RP,SquareChevronRightIcon:RP,SquareChevronUp:DP,SquareChevronUpIcon:DP,SquareCode:OP,SquareCodeIcon:OP,SquareDashed:BP,SquareDashedBottom:gbe,SquareDashedBottomCode:xbe,SquareDashedBottomCodeIcon:xbe,SquareDashedBottomIcon:gbe,SquareDashedIcon:BP,SquareDashedKanban:FP,SquareDashedKanbanIcon:FP,SquareDashedMousePointer:zP,SquareDashedMousePointerIcon:zP,SquareDivide:$P,SquareDivideIcon:$P,SquareDot:UP,SquareDotIcon:UP,SquareEqual:qP,SquareEqualIcon:qP,SquareFunction:VP,SquareFunctionIcon:VP,SquareGanttChart:Tk,SquareGanttChartIcon:Tk,SquareIcon:H_,SquareKanban:HP,SquareKanbanIcon:HP,SquareLibrary:GP,SquareLibraryIcon:GP,SquareM:WP,SquareMIcon:WP,SquareMenu:KP,SquareMenuIcon:KP,SquareMinus:YP,SquareMinusIcon:YP,SquareMousePointer:ZP,SquareMousePointerIcon:ZP,SquareParking:QP,SquareParkingIcon:QP,SquareParkingOff:XP,SquareParkingOffIcon:XP,SquarePen:kp,SquarePenIcon:kp,SquarePercent:JP,SquarePercentIcon:JP,SquarePi:eI,SquarePiIcon:eI,SquarePilcrow:tI,SquarePilcrowIcon:tI,SquarePlay:sI,SquarePlayIcon:sI,SquarePlus:nI,SquarePlusIcon:nI,SquarePower:rI,SquarePowerIcon:rI,SquareRadical:ybe,SquareRadicalIcon:ybe,SquareScissors:aI,SquareScissorsIcon:aI,SquareSigma:iI,SquareSigmaIcon:iI,SquareSlash:oI,SquareSlashIcon:oI,SquareSplitHorizontal:lI,SquareSplitHorizontalIcon:lI,SquareSplitVertical:cI,SquareSplitVerticalIcon:cI,SquareSquare:vbe,SquareSquareIcon:vbe,SquareStack:bbe,SquareStackIcon:bbe,SquareTerminal:dI,SquareTerminalIcon:dI,SquareUser:hI,SquareUserIcon:hI,SquareUserRound:uI,SquareUserRoundIcon:uI,SquareX:mI,SquareXIcon:mI,Squircle:_be,SquircleIcon:_be,Squirrel:wbe,SquirrelIcon:wbe,Stamp:jbe,StampIcon:jbe,Star:Wa,StarHalf:Nbe,StarHalfIcon:Nbe,StarIcon:Wa,StarOff:kbe,StarOffIcon:kbe,Stars:yn,StarsIcon:yn,StepBack:Sbe,StepBackIcon:Sbe,StepForward:Cbe,StepForwardIcon:Cbe,Stethoscope:Abe,StethoscopeIcon:Abe,Sticker:Tbe,StickerIcon:Tbe,StickyNote:oK,StickyNoteIcon:oK,StopCircle:bL,StopCircleIcon:bL,Store:lK,StoreIcon:lK,StretchHorizontal:Ebe,StretchHorizontalIcon:Ebe,StretchVertical:Mbe,StretchVerticalIcon:Mbe,Strikethrough:cK,StrikethroughIcon:cK,Subscript:Lbe,SubscriptIcon:Lbe,Subtitles:zM,SubtitlesIcon:zM,Sun:Aj,SunDim:Pbe,SunDimIcon:Pbe,SunIcon:Aj,SunMedium:Ibe,SunMediumIcon:Ibe,SunMoon:Rbe,SunMoonIcon:Rbe,SunSnow:Dbe,SunSnowIcon:Dbe,Sunrise:Obe,SunriseIcon:Obe,Sunset:Fbe,SunsetIcon:Fbe,Superscript:zbe,SuperscriptIcon:zbe,SwatchBook:Bbe,SwatchBookIcon:Bbe,SwissFranc:$be,SwissFrancIcon:$be,SwitchCamera:Ube,SwitchCameraIcon:Ube,Sword:qbe,SwordIcon:qbe,Swords:Vbe,SwordsIcon:Vbe,Syringe:Hbe,SyringeIcon:Hbe,Table:lz,Table2:oz,Table2Icon:oz,TableCellsMerge:Gbe,TableCellsMergeIcon:Gbe,TableCellsSplit:Wbe,TableCellsSplitIcon:Wbe,TableColumnsSplit:Kbe,TableColumnsSplitIcon:Kbe,TableIcon:lz,TableOfContents:Ybe,TableOfContentsIcon:Ybe,TableProperties:Zbe,TablePropertiesIcon:Zbe,TableRowsSplit:Xbe,TableRowsSplitIcon:Xbe,Tablet:cz,TabletIcon:cz,TabletSmartphone:Qbe,TabletSmartphoneIcon:Qbe,Tablets:Jbe,TabletsIcon:Jbe,Tag:wf,TagIcon:wf,Tags:dK,TagsIcon:dK,Tally1:e_e,Tally1Icon:e_e,Tally2:t_e,Tally2Icon:t_e,Tally3:s_e,Tally3Icon:s_e,Tally4:n_e,Tally4Icon:n_e,Tally5:r_e,Tally5Icon:r_e,Tangent:a_e,TangentIcon:a_e,Target:uu,TargetIcon:uu,Telescope:i_e,TelescopeIcon:i_e,Tent:l_e,TentIcon:l_e,TentTree:o_e,TentTreeIcon:o_e,Terminal:c_e,TerminalIcon:c_e,TerminalSquare:dI,TerminalSquareIcon:dI,TestTube:d_e,TestTube2:pI,TestTube2Icon:pI,TestTubeDiagonal:pI,TestTubeDiagonalIcon:pI,TestTubeIcon:d_e,TestTubes:u_e,TestTubesIcon:u_e,Text:x_e,TextCursor:m_e,TextCursorIcon:m_e,TextCursorInput:h_e,TextCursorInputIcon:h_e,TextIcon:x_e,TextQuote:p_e,TextQuoteIcon:p_e,TextSearch:f_e,TextSearchIcon:f_e,TextSelect:fI,TextSelectIcon:fI,TextSelection:fI,TextSelectionIcon:fI,Theater:g_e,TheaterIcon:g_e,Thermometer:uK,ThermometerIcon:uK,ThermometerSnowflake:y_e,ThermometerSnowflakeIcon:y_e,ThermometerSun:v_e,ThermometerSunIcon:v_e,ThumbsDown:hK,ThumbsDownIcon:hK,ThumbsUp:mg,ThumbsUpIcon:mg,Ticket:mK,TicketCheck:b_e,TicketCheckIcon:b_e,TicketIcon:mK,TicketMinus:__e,TicketMinusIcon:__e,TicketPercent:w_e,TicketPercentIcon:w_e,TicketPlus:j_e,TicketPlusIcon:j_e,TicketSlash:N_e,TicketSlashIcon:N_e,TicketX:k_e,TicketXIcon:k_e,Tickets:C_e,TicketsIcon:C_e,TicketsPlane:S_e,TicketsPlaneIcon:S_e,Timer:E_e,TimerIcon:E_e,TimerOff:A_e,TimerOffIcon:A_e,TimerReset:T_e,TimerResetIcon:T_e,ToggleLeft:M_e,ToggleLeftIcon:M_e,ToggleRight:L_e,ToggleRightIcon:L_e,Toilet:P_e,ToiletIcon:P_e,Tornado:I_e,TornadoIcon:I_e,Torus:R_e,TorusIcon:R_e,Touchpad:O_e,TouchpadIcon:O_e,TouchpadOff:D_e,TouchpadOffIcon:D_e,TowerControl:F_e,TowerControlIcon:F_e,ToyBrick:z_e,ToyBrickIcon:z_e,Tractor:B_e,TractorIcon:B_e,TrafficCone:$_e,TrafficConeIcon:$_e,Train:xI,TrainFront:q_e,TrainFrontIcon:q_e,TrainFrontTunnel:U_e,TrainFrontTunnelIcon:U_e,TrainIcon:xI,TrainTrack:V_e,TrainTrackIcon:V_e,TramFront:xI,TramFrontIcon:xI,Trash:H_e,Trash2:Rn,Trash2Icon:Rn,TrashIcon:H_e,TreeDeciduous:G_e,TreeDeciduousIcon:G_e,TreePalm:gI,TreePalmIcon:gI,TreePine:rE,TreePineIcon:rE,Trees:W_e,TreesIcon:W_e,Trello:K_e,TrelloIcon:K_e,TrendingDown:vN,TrendingDownIcon:vN,TrendingUp:kl,TrendingUpDown:Y_e,TrendingUpDownIcon:Y_e,TrendingUpIcon:kl,Triangle:X_e,TriangleAlert:hd,TriangleAlertIcon:hd,TriangleIcon:X_e,TriangleRight:Z_e,TriangleRightIcon:Z_e,Trophy:ll,TrophyIcon:ll,Truck:pK,TruckIcon:pK,Turtle:Q_e,TurtleIcon:Q_e,Tv:ewe,Tv2:yI,Tv2Icon:yI,TvIcon:ewe,TvMinimal:yI,TvMinimalIcon:yI,TvMinimalPlay:J_e,TvMinimalPlayIcon:J_e,Twitch:twe,TwitchIcon:twe,Twitter:swe,TwitterIcon:swe,Type:rwe,TypeIcon:rwe,TypeOutline:nwe,TypeOutlineIcon:nwe,Umbrella:iwe,UmbrellaIcon:iwe,UmbrellaOff:awe,UmbrellaOffIcon:awe,Underline:dz,UnderlineIcon:dz,Undo:aE,Undo2:fK,Undo2Icon:fK,UndoDot:owe,UndoDotIcon:owe,UndoIcon:aE,UnfoldHorizontal:lwe,UnfoldHorizontalIcon:lwe,UnfoldVertical:cwe,UnfoldVerticalIcon:cwe,Ungroup:dwe,UngroupIcon:dwe,University:vI,UniversityIcon:vI,Unlink:ZR,Unlink2:uwe,Unlink2Icon:uwe,UnlinkIcon:ZR,Unlock:YL,UnlockIcon:YL,UnlockKeyhole:KL,UnlockKeyholeIcon:KL,Unplug:xK,UnplugIcon:xK,Upload:Ja,UploadCloud:SL,UploadCloudIcon:SL,UploadIcon:Ja,Usb:hwe,UsbIcon:hwe,User:Eo,User2:kI,User2Icon:kI,UserCheck:bN,UserCheck2:bI,UserCheck2Icon:bI,UserCheckIcon:bN,UserCircle:wL,UserCircle2:_L,UserCircle2Icon:_L,UserCircleIcon:wL,UserCog:gK,UserCog2:_I,UserCog2Icon:_I,UserCogIcon:gK,UserIcon:Eo,UserMinus:uz,UserMinus2:wI,UserMinus2Icon:wI,UserMinusIcon:uz,UserPen:mwe,UserPenIcon:mwe,UserPlus:Sl,UserPlus2:jI,UserPlus2Icon:jI,UserPlusIcon:Sl,UserRound:kI,UserRoundCheck:bI,UserRoundCheckIcon:bI,UserRoundCog:_I,UserRoundCogIcon:_I,UserRoundIcon:kI,UserRoundMinus:wI,UserRoundMinusIcon:wI,UserRoundPen:pwe,UserRoundPenIcon:pwe,UserRoundPlus:jI,UserRoundPlusIcon:jI,UserRoundSearch:fwe,UserRoundSearchIcon:fwe,UserRoundX:NI,UserRoundXIcon:NI,UserSearch:xwe,UserSearchIcon:xwe,UserSquare:hI,UserSquare2:uI,UserSquare2Icon:uI,UserSquareIcon:hI,UserX:gwe,UserX2:NI,UserX2Icon:NI,UserXIcon:gwe,Users:Bn,Users2:qv,Users2Icon:qv,UsersIcon:Bn,UsersRound:qv,UsersRoundIcon:qv,Utensils:CI,UtensilsCrossed:SI,UtensilsCrossedIcon:SI,UtensilsIcon:CI,UtilityPole:ywe,UtilityPoleIcon:ywe,Variable:hz,VariableIcon:hz,Vault:vwe,VaultIcon:vwe,Vegan:bwe,VeganIcon:bwe,VenetianMask:_we,VenetianMaskIcon:_we,Verified:IM,VerifiedIcon:IM,Vibrate:jwe,VibrateIcon:jwe,VibrateOff:wwe,VibrateOffIcon:wwe,Video:Zr,VideoIcon:Zr,VideoOff:Nwe,VideoOffIcon:Nwe,Videotape:kwe,VideotapeIcon:kwe,View:Swe,ViewIcon:Swe,Voicemail:Cwe,VoicemailIcon:Cwe,Volleyball:Awe,VolleyballIcon:Awe,Volume:Mwe,Volume1:Twe,Volume1Icon:Twe,Volume2:yK,Volume2Icon:yK,VolumeIcon:Mwe,VolumeOff:Ewe,VolumeOffIcon:Ewe,VolumeX:vK,VolumeXIcon:vK,Vote:Lwe,VoteIcon:Lwe,Wallet:mz,Wallet2:AI,Wallet2Icon:AI,WalletCards:Pwe,WalletCardsIcon:Pwe,WalletIcon:mz,WalletMinimal:AI,WalletMinimalIcon:AI,Wallpaper:Iwe,WallpaperIcon:Iwe,Wand:Rwe,Wand2:um,Wand2Icon:um,WandIcon:Rwe,WandSparkles:um,WandSparklesIcon:um,Warehouse:Dwe,WarehouseIcon:Dwe,WashingMachine:Owe,WashingMachineIcon:Owe,Watch:Fwe,WatchIcon:Fwe,Waves:zwe,WavesIcon:zwe,Waypoints:Bwe,WaypointsIcon:Bwe,Webcam:$we,WebcamIcon:$we,Webhook:qwe,WebhookIcon:qwe,WebhookOff:Uwe,WebhookOffIcon:Uwe,Weight:Vwe,WeightIcon:Vwe,Wheat:Gwe,WheatIcon:Gwe,WheatOff:Hwe,WheatOffIcon:Hwe,WholeWord:Wwe,WholeWordIcon:Wwe,Wifi:Qwe,WifiHigh:Kwe,WifiHighIcon:Kwe,WifiIcon:Qwe,WifiLow:Ywe,WifiLowIcon:Ywe,WifiOff:Zwe,WifiOffIcon:Zwe,WifiZero:Xwe,WifiZeroIcon:Xwe,Wind:eje,WindArrowDown:Jwe,WindArrowDownIcon:Jwe,WindIcon:eje,Wine:bK,WineIcon:bK,WineOff:tje,WineOffIcon:tje,Workflow:_K,WorkflowIcon:_K,Worm:sje,WormIcon:sje,WrapText:nje,WrapTextIcon:nje,Wrench:O5,WrenchIcon:O5,X:dr,XCircle:Rd,XCircleIcon:Rd,XIcon:dr,XOctagon:JL,XOctagonIcon:JL,XSquare:mI,XSquareIcon:mI,Youtube:rje,YoutubeIcon:rje,Zap:jf,ZapIcon:jf,ZapOff:aje,ZapOffIcon:aje,ZoomIn:iE,ZoomInIcon:iE,ZoomOut:pz,ZoomOutIcon:pz,createLucideIcon:ce,icons:TXt},Symbol.toStringTag,{value:"Module"})),fUe="-",EXt=s=>{const t=LXt(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(fUe);return o[0]===""&&o.length!==1&&o.shift(),W_t(o,t)||MXt(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},W_t=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?W_t(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(fUe);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Utt=/^\[(.+)\]$/,MXt=s=>{if(Utt.test(s)){const t=Utt.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},LXt=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return IXt(Object.entries(s.classGroups),n).forEach(([i,l])=>{JRe(l,r,i,t)}),r},JRe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:qtt(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(PXt(a)){JRe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{JRe(l,qtt(t,i),n,r)})})},qtt=(s,t)=>{let n=s;return t.split(fUe).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},PXt=s=>s.isThemeGetter,IXt=(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,RXt=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)}}},K_t="!",DXt=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 g=0;gu?h-u:void 0;return{modifiers:c,hasImportantModifier:p,baseClassName:x,maybePostfixModifierPosition:y}};return n?o=>n({className:o,parseClassName:l}):l},OXt=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},FXt=s=>({cache:RXt(s.cacheSize),parseClassName:DXt(s),...EXt(s)}),zXt=/\s+/,BXt=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(zXt);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:p}=n(d);let x=!!p,y=r(x?m.substring(0,p):m);if(!y){if(!x){o=d+(o.length>0?" "+o:o);continue}if(y=r(m),!y){o=d+(o.length>0?" "+o:o);continue}x=!1}const g=OXt(u).join(":"),b=h?g+K_t:g,v=b+y;if(i.includes(v))continue;i.push(v);const k=a(y,x);for(let C=0;C0?" "+o:o)}return o};function $Xt(){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=FXt(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=BXt(c,n);return a(c,u),u}return function(){return i($Xt.apply(null,arguments))}}const am=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},Z_t=/^\[(?:([a-z-]+):)?(.+)\]$/i,qXt=/^\d+\/\d+$/,VXt=new Set(["px","full","screen"]),HXt=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,GXt=/\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$/,WXt=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,KXt=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,YXt=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,GS=s=>fz(s)||VXt.has(s)||qXt.test(s),AC=s=>PU(s,"length",nQt),fz=s=>!!s&&!Number.isNaN(Number(s)),Q6e=s=>PU(s,"number",fz),lH=s=>!!s&&Number.isInteger(Number(s)),ZXt=s=>s.endsWith("%")&&fz(s.slice(0,-1)),sc=s=>Z_t.test(s),TC=s=>HXt.test(s),XXt=new Set(["length","size","percentage"]),QXt=s=>PU(s,XXt,X_t),JXt=s=>PU(s,"position",X_t),eQt=new Set(["image","url"]),tQt=s=>PU(s,eQt,aQt),sQt=s=>PU(s,"",rQt),cH=()=>!0,PU=(s,t,n)=>{const r=Z_t.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},nQt=s=>GXt.test(s)&&!WXt.test(s),X_t=()=>!1,rQt=s=>KXt.test(s),aQt=s=>YXt.test(s),iQt=()=>{const s=am("colors"),t=am("spacing"),n=am("blur"),r=am("brightness"),a=am("borderColor"),i=am("borderRadius"),l=am("borderSpacing"),o=am("borderWidth"),c=am("contrast"),d=am("grayscale"),u=am("hueRotate"),h=am("invert"),m=am("gap"),p=am("gradientColorStops"),x=am("gradientColorStopPositions"),y=am("inset"),g=am("margin"),b=am("opacity"),v=am("padding"),k=am("saturate"),C=am("scale"),T=am("sepia"),M=am("skew"),P=am("space"),L=am("translate"),I=()=>["auto","contain","none"],O=()=>["auto","hidden","clip","visible","scroll"],$=()=>["auto",sc,t],q=()=>[sc,t],W=()=>["",GS,AC],G=()=>["auto",fz,sc],K=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],ee=()=>["solid","dashed","dotted","double","none"],J=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],le=()=>["start","end","center","between","around","evenly","stretch"],ue=()=>["","0",sc],oe=()=>["auto","avoid","all","avoid-page","page","left","right","column"],ie=()=>[fz,sc];return{cacheSize:500,separator:":",theme:{colors:[cH],spacing:[GS,AC],blur:["none","",TC,sc],brightness:ie(),borderColor:[s],borderRadius:["none","","full",TC,sc],borderSpacing:q(),borderWidth:W(),contrast:ie(),grayscale:ue(),hueRotate:ie(),invert:ue(),gap:q(),gradientColorStops:[s],gradientColorStopPositions:[ZXt,AC],inset:$(),margin:$(),opacity:ie(),padding:q(),saturate:ie(),scale:ie(),sepia:ue(),skew:ie(),space:q(),translate:q()},classGroups:{aspect:[{aspect:["auto","square","video",sc]}],container:["container"],columns:[{columns:[TC]}],"break-after":[{"break-after":oe()}],"break-before":[{"break-before":oe()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...K(),sc]}],overflow:[{overflow:O()}],"overflow-x":[{"overflow-x":O()}],"overflow-y":[{"overflow-y":O()}],overscroll:[{overscroll:I()}],"overscroll-x":[{"overscroll-x":I()}],"overscroll-y":[{"overscroll-y":I()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[y]}],"inset-x":[{"inset-x":[y]}],"inset-y":[{"inset-y":[y]}],start:[{start:[y]}],end:[{end:[y]}],top:[{top:[y]}],right:[{right:[y]}],bottom:[{bottom:[y]}],left:[{left:[y]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",lH,sc]}],basis:[{basis:$()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",sc]}],grow:[{grow:ue()}],shrink:[{shrink:ue()}],order:[{order:["first","last","none",lH,sc]}],"grid-cols":[{"grid-cols":[cH]}],"col-start-end":[{col:["auto",{span:["full",lH,sc]},sc]}],"col-start":[{"col-start":G()}],"col-end":[{"col-end":G()}],"grid-rows":[{"grid-rows":[cH]}],"row-start-end":[{row:["auto",{span:[lH,sc]},sc]}],"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",sc]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",sc]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...le()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...le(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...le(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[v]}],px:[{px:[v]}],py:[{py:[v]}],ps:[{ps:[v]}],pe:[{pe:[v]}],pt:[{pt:[v]}],pr:[{pr:[v]}],pb:[{pb:[v]}],pl:[{pl:[v]}],m:[{m:[g]}],mx:[{mx:[g]}],my:[{my:[g]}],ms:[{ms:[g]}],me:[{me:[g]}],mt:[{mt:[g]}],mr:[{mr:[g]}],mb:[{mb:[g]}],ml:[{ml:[g]}],"space-x":[{"space-x":[P]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[P]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",sc,t]}],"min-w":[{"min-w":[sc,t,"min","max","fit"]}],"max-w":[{"max-w":[sc,t,"none","full","min","max","fit","prose",{screen:[TC]},TC]}],h:[{h:[sc,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[sc,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[sc,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[sc,t,"auto","min","max","fit"]}],"font-size":[{text:["base",TC,AC]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Q6e]}],"font-family":[{font:[cH]}],"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",sc]}],"line-clamp":[{"line-clamp":["none",fz,Q6e]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",GS,sc]}],"list-image":[{"list-image":["none",sc]}],"list-style-type":[{list:["none","disc","decimal",sc]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[b]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[b]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ee(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",GS,AC]}],"underline-offset":[{"underline-offset":["auto",GS,sc]}],"text-decoration-color":[{decoration:[s]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:q()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",sc]}],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",sc]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[b]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...K(),JXt]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",QXt]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},tQt]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[p]}],"gradient-via":[{via:[p]}],"gradient-to":[{to:[p]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[b]}],"border-style":[{border:[...ee(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[b]}],"divide-style":[{divide:ee()}],"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:["",...ee()]}],"outline-offset":[{"outline-offset":[GS,sc]}],"outline-w":[{outline:[GS,AC]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[b]}],"ring-offset-w":[{"ring-offset":[GS,AC]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",TC,sQt]}],"shadow-color":[{shadow:[cH]}],opacity:[{opacity:[b]}],"mix-blend":[{"mix-blend":[...J(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":J()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",TC,sc]}],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":[b]}],"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",sc]}],duration:[{duration:ie()}],ease:[{ease:["linear","in","out","in-out",sc]}],delay:[{delay:ie()}],animate:[{animate:["none","spin","ping","pulse","bounce",sc]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[C]}],"scale-x":[{"scale-x":[C]}],"scale-y":[{"scale-y":[C]}],rotate:[{rotate:[lH,sc]}],"translate-x":[{"translate-x":[L]}],"translate-y":[{"translate-y":[L]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",sc]}],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",sc]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":q()}],"scroll-mx":[{"scroll-mx":q()}],"scroll-my":[{"scroll-my":q()}],"scroll-ms":[{"scroll-ms":q()}],"scroll-me":[{"scroll-me":q()}],"scroll-mt":[{"scroll-mt":q()}],"scroll-mr":[{"scroll-mr":q()}],"scroll-mb":[{"scroll-mb":q()}],"scroll-ml":[{"scroll-ml":q()}],"scroll-p":[{"scroll-p":q()}],"scroll-px":[{"scroll-px":q()}],"scroll-py":[{"scroll-py":q()}],"scroll-ps":[{"scroll-ps":q()}],"scroll-pe":[{"scroll-pe":q()}],"scroll-pt":[{"scroll-pt":q()}],"scroll-pr":[{"scroll-pr":q()}],"scroll-pb":[{"scroll-pb":q()}],"scroll-pl":[{"scroll-pl":q()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",sc]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[GS,AC,Q6e]}],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"]}}},oQt=UXt(iQt);function Et(...s){return oQt(Il(s))}function Su(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 Vtt(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function zY(s){return s?s.replace(/<[^>]*>/g,""):""}const lQt=SXt,Q_t=j.forwardRef(({className:s,...t},n)=>e.jsx(F_t,{ref:n,className:Et("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}));Q_t.displayName=F_t.displayName;const cQt=hO("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"}}),J_t=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(z_t,{ref:r,className:Et(cQt({variant:t}),s),...n}));J_t.displayName=z_t.displayName;const dQt=j.forwardRef(({className:s,...t},n)=>e.jsx(U_t,{ref:n,className:Et("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}));dQt.displayName=U_t.displayName;const ewt=j.forwardRef(({className:s,...t},n)=>e.jsx(q_t,{ref:n,className:Et("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(dr,{className:"h-4 w-4"})}));ewt.displayName=q_t.displayName;const twt=j.forwardRef(({className:s,...t},n)=>e.jsx(B_t,{ref:n,className:Et("text-sm font-semibold",s),...t}));twt.displayName=B_t.displayName;const swt=j.forwardRef(({className:s,...t},n)=>e.jsx($_t,{ref:n,className:Et("text-sm opacity-90",s),...t}));swt.displayName=$_t.displayName;function uQt(){const{toasts:s}=pi();return e.jsxs(lQt,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(J_t,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(twt,{children:n}),r&&e.jsx(swt,{children:r})]}),a,e.jsx(ewt,{})]},t)}),e.jsx(Q_t,{})]})}var Htt=["light","dark"],hQt="(prefers-color-scheme: dark)",mQt=j.createContext(void 0),pQt={setTheme:s=>{},themes:[]},fQt=()=>{var s;return(s=j.useContext(mQt))!=null?s:pQt};j.memo(({forcedTheme:s,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",u=n==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(x=>`'${x}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,h=a?Htt.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",m=(x,y=!1,g=!0)=>{let b=l?l[x]:x,v=y?x+"|| ''":`'${b}'`,k="";return a&&g&&!y&&Htt.includes(x)&&(k+=`d.style.colorScheme = '${x}';`),n==="class"?y||b?k+=`c.add(${v})`:k+="null":b&&(k+=`d[s](n,${v})`),k},p=s?`!function(){${u}${m(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${hQt}',m=window.matchMedia(t);if(m.media!==t||m.matches){${m("dark")}}else{${m("light")}}}else if(e){${l?`var x=${JSON.stringify(l)};`:""}${m(l?"x[e]":"e",!0)}}${d?"":"else{"+m(i,!1,!1)+"}"}${h}}catch(e){}}()`:`!function(){try{${u}var e=localStorage.getItem('${t}');if(e){${l?`var x=${JSON.stringify(l)};`:""}${m(l?"x[e]":"e",!0)}}else{${m(i,!1,!1)};}${h}}catch(t){}}();`;return j.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:p}})});var xQt=s=>{switch(s){case"success":return vQt;case"info":return _Qt;case"warning":return bQt;case"error":return wQt;default:return null}},gQt=Array(12).fill(0),yQt=({visible:s,className:t})=>Lt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Lt.createElement("div",{className:"sonner-spinner"},gQt.map((n,r)=>Lt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),vQt=Lt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Lt.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"})),bQt=Lt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Lt.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"})),_Qt=Lt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Lt.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"})),wQt=Lt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Lt.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"})),jQt=Lt.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"},Lt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Lt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),NQt=()=>{let[s,t]=Lt.useState(document.hidden);return Lt.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},eDe=1,kQt=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:eDe++,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],Lt.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(CQt(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)||eDe++;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}},J1=new kQt,SQt=(s,t)=>{let n=(t==null?void 0:t.id)||eDe++;return J1.addToast({title:s,...t,id:n}),n},CQt=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",AQt=SQt,TQt=()=>J1.toasts,EQt=()=>J1.getActiveToasts(),re=Object.assign(AQt,{success:J1.success,info:J1.info,warning:J1.warning,error:J1.error,custom:J1.custom,message:J1.message,promise:J1.promise,dismiss:J1.dismiss,loading:J1.loading},{getHistory:TQt,getToasts:EQt});function MQt(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))}MQt(`: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 ose(s){return s.label!==void 0}var LQt=3,PQt="32px",IQt="16px",Gtt=4e3,RQt=356,DQt=14,OQt=20,FQt=200;function _2(...s){return s.filter(Boolean).join(" ")}function zQt(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var BQt=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:m,toast:p,unstyled:x,interacting:y,setHeights:g,visibleToasts:b,heights:v,index:k,toasts:C,expanded:T,removeToast:M,defaultRichColors:P,closeButton:L,style:I,cancelButtonStyle:O,actionButtonStyle:$,className:q="",descriptionClassName:W="",duration:G,position:K,gap:ee,loadingIcon:J,expandByDefault:le,classNames:ue,icons:oe,closeButtonAriaLabel:ie="Close toast",pauseWhenPageIsHidden:de}=s,[we,je]=Lt.useState(null),[xe,fe]=Lt.useState(null),[Se,Ee]=Lt.useState(!1),[Le,De]=Lt.useState(!1),[Be,Ne]=Lt.useState(!1),[Ge,_e]=Lt.useState(!1),[Oe,Ae]=Lt.useState(!1),[Xe,Ue]=Lt.useState(0),[Ze,Qe]=Lt.useState(0),Ye=Lt.useRef(p.duration||G||Gtt),nt=Lt.useRef(null),rt=Lt.useRef(null),Fe=k===0,dt=k+1<=b,Dt=p.type,pt=p.dismissible!==!1,zt=p.className||"",Gt=p.descriptionClassName||"",qs=Lt.useMemo(()=>v.findIndex(_n=>_n.toastId===p.id)||0,[v,p.id]),As=Lt.useMemo(()=>{var _n;return(_n=p.closeButton)!=null?_n:L},[p.closeButton,L]),Bt=Lt.useMemo(()=>p.duration||G||Gtt,[p.duration,G]),At=Lt.useRef(0),Is=Lt.useRef(0),jt=Lt.useRef(0),Qs=Lt.useRef(null),[cn,qt]=K.split("-"),Gs=Lt.useMemo(()=>v.reduce((_n,Cn,Un)=>Un>=qs?_n:_n+Cn.height,0),[v,qs]),Ls=NQt(),sn=p.invert||m,Hs=Dt==="loading";Is.current=Lt.useMemo(()=>qs*ee+Gs,[qs,Gs]),Lt.useEffect(()=>{Ye.current=Bt},[Bt]),Lt.useEffect(()=>{Ee(!0)},[]),Lt.useEffect(()=>{let _n=rt.current;if(_n){let Cn=_n.getBoundingClientRect().height;return Qe(Cn),g(Un=>[{toastId:p.id,height:Cn,position:p.position},...Un]),()=>g(Un=>Un.filter(Kr=>Kr.toastId!==p.id))}},[g,p.id]),Lt.useLayoutEffect(()=>{if(!Se)return;let _n=rt.current,Cn=_n.style.height;_n.style.height="auto";let Un=_n.getBoundingClientRect().height;_n.style.height=Cn,Qe(Un),g(Kr=>Kr.find(jr=>jr.toastId===p.id)?Kr.map(jr=>jr.toastId===p.id?{...jr,height:Un}:jr):[{toastId:p.id,height:Un,position:p.position},...Kr])},[Se,p.title,p.description,g,p.id]);let nn=Lt.useCallback(()=>{De(!0),Ue(Is.current),g(_n=>_n.filter(Cn=>Cn.toastId!==p.id)),setTimeout(()=>{M(p)},FQt)},[p,M,g,Is]);Lt.useEffect(()=>{if(p.promise&&Dt==="loading"||p.duration===1/0||p.type==="loading")return;let _n;return T||y||de&&Ls?(()=>{if(jt.current{var Cn;(Cn=p.onAutoClose)==null||Cn.call(p,p),nn()},Ye.current)),()=>clearTimeout(_n)},[T,y,p,Dt,de,Ls,nn]),Lt.useEffect(()=>{p.delete&&nn()},[nn,p.delete]);function tn(){var _n,Cn,Un;return oe!=null&&oe.loading?Lt.createElement("div",{className:_2(ue==null?void 0:ue.loader,(_n=p==null?void 0:p.classNames)==null?void 0:_n.loader,"sonner-loader"),"data-visible":Dt==="loading"},oe.loading):J?Lt.createElement("div",{className:_2(ue==null?void 0:ue.loader,(Cn=p==null?void 0:p.classNames)==null?void 0:Cn.loader,"sonner-loader"),"data-visible":Dt==="loading"},J):Lt.createElement(yQt,{className:_2(ue==null?void 0:ue.loader,(Un=p==null?void 0:p.classNames)==null?void 0:Un.loader),visible:Dt==="loading"})}return Lt.createElement("li",{tabIndex:0,ref:rt,className:_2(q,zt,ue==null?void 0:ue.toast,(t=p==null?void 0:p.classNames)==null?void 0:t.toast,ue==null?void 0:ue.default,ue==null?void 0:ue[Dt],(n=p==null?void 0:p.classNames)==null?void 0:n[Dt]),"data-sonner-toast":"","data-rich-colors":(r=p.richColors)!=null?r:P,"data-styled":!(p.jsx||p.unstyled||x),"data-mounted":Se,"data-promise":!!p.promise,"data-swiped":Oe,"data-removed":Le,"data-visible":dt,"data-y-position":cn,"data-x-position":qt,"data-index":k,"data-front":Fe,"data-swiping":Be,"data-dismissible":pt,"data-type":Dt,"data-invert":sn,"data-swipe-out":Ge,"data-swipe-direction":xe,"data-expanded":!!(T||le&&Se),style:{"--index":k,"--toasts-before":k,"--z-index":C.length-k,"--offset":`${Le?Xe:Is.current}px`,"--initial-height":le?"auto":`${Ze}px`,...I,...p.style},onDragEnd:()=>{Ne(!1),je(null),Qs.current=null},onPointerDown:_n=>{Hs||!pt||(nt.current=new Date,Ue(Is.current),_n.target.setPointerCapture(_n.pointerId),_n.target.tagName!=="BUTTON"&&(Ne(!0),Qs.current={x:_n.clientX,y:_n.clientY}))},onPointerUp:()=>{var _n,Cn,Un,Kr;if(Ge||!pt)return;Qs.current=null;let jr=Number(((_n=rt.current)==null?void 0:_n.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Xs=Number(((Cn=rt.current)==null?void 0:Cn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Ba=new Date().getTime()-((Un=nt.current)==null?void 0:Un.getTime()),Hr=we==="x"?jr:Xs,mr=Math.abs(Hr)/Ba;if(Math.abs(Hr)>=OQt||mr>.11){Ue(Is.current),(Kr=p.onDismiss)==null||Kr.call(p,p),fe(we==="x"?jr>0?"right":"left":Xs>0?"down":"up"),nn(),_e(!0),Ae(!1);return}Ne(!1),je(null)},onPointerMove:_n=>{var Cn,Un,Kr,jr;if(!Qs.current||!pt||((Cn=window.getSelection())==null?void 0:Cn.toString().length)>0)return;let Xs=_n.clientY-Qs.current.y,Ba=_n.clientX-Qs.current.x,Hr=(Un=s.swipeDirections)!=null?Un:zQt(K);!we&&(Math.abs(Ba)>1||Math.abs(Xs)>1)&&je(Math.abs(Ba)>Math.abs(Xs)?"x":"y");let mr={x:0,y:0};we==="y"?(Hr.includes("top")||Hr.includes("bottom"))&&(Hr.includes("top")&&Xs<0||Hr.includes("bottom")&&Xs>0)&&(mr.y=Xs):we==="x"&&(Hr.includes("left")||Hr.includes("right"))&&(Hr.includes("left")&&Ba<0||Hr.includes("right")&&Ba>0)&&(mr.x=Ba),(Math.abs(mr.x)>0||Math.abs(mr.y)>0)&&Ae(!0),(Kr=rt.current)==null||Kr.style.setProperty("--swipe-amount-x",`${mr.x}px`),(jr=rt.current)==null||jr.style.setProperty("--swipe-amount-y",`${mr.y}px`)}},As&&!p.jsx?Lt.createElement("button",{"aria-label":ie,"data-disabled":Hs,"data-close-button":!0,onClick:Hs||!pt?()=>{}:()=>{var _n;nn(),(_n=p.onDismiss)==null||_n.call(p,p)},className:_2(ue==null?void 0:ue.closeButton,(a=p==null?void 0:p.classNames)==null?void 0:a.closeButton)},(i=oe==null?void 0:oe.close)!=null?i:jQt):null,p.jsx||j.isValidElement(p.title)?p.jsx?p.jsx:typeof p.title=="function"?p.title():p.title:Lt.createElement(Lt.Fragment,null,Dt||p.icon||p.promise?Lt.createElement("div",{"data-icon":"",className:_2(ue==null?void 0:ue.icon,(l=p==null?void 0:p.classNames)==null?void 0:l.icon)},p.promise||p.type==="loading"&&!p.icon?p.icon||tn():null,p.type!=="loading"?p.icon||(oe==null?void 0:oe[Dt])||xQt(Dt):null):null,Lt.createElement("div",{"data-content":"",className:_2(ue==null?void 0:ue.content,(o=p==null?void 0:p.classNames)==null?void 0:o.content)},Lt.createElement("div",{"data-title":"",className:_2(ue==null?void 0:ue.title,(c=p==null?void 0:p.classNames)==null?void 0:c.title)},typeof p.title=="function"?p.title():p.title),p.description?Lt.createElement("div",{"data-description":"",className:_2(W,Gt,ue==null?void 0:ue.description,(d=p==null?void 0:p.classNames)==null?void 0:d.description)},typeof p.description=="function"?p.description():p.description):null),j.isValidElement(p.cancel)?p.cancel:p.cancel&&ose(p.cancel)?Lt.createElement("button",{"data-button":!0,"data-cancel":!0,style:p.cancelButtonStyle||O,onClick:_n=>{var Cn,Un;ose(p.cancel)&&pt&&((Un=(Cn=p.cancel).onClick)==null||Un.call(Cn,_n),nn())},className:_2(ue==null?void 0:ue.cancelButton,(u=p==null?void 0:p.classNames)==null?void 0:u.cancelButton)},p.cancel.label):null,j.isValidElement(p.action)?p.action:p.action&&ose(p.action)?Lt.createElement("button",{"data-button":!0,"data-action":!0,style:p.actionButtonStyle||$,onClick:_n=>{var Cn,Un;ose(p.action)&&((Un=(Cn=p.action).onClick)==null||Un.call(Cn,_n),!_n.defaultPrevented&&nn())},className:_2(ue==null?void 0:ue.actionButton,(h=p==null?void 0:p.classNames)==null?void 0:h.actionButton)},p.action.label):null))};function Wtt(){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 $Qt(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?IQt:PQt;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 UQt=j.forwardRef(function(s,t){let{invert:n,position:r="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:u="light",richColors:h,duration:m,style:p,visibleToasts:x=LQt,toastOptions:y,dir:g=Wtt(),gap:b=DQt,loadingIcon:v,icons:k,containerAriaLabel:C="Notifications",pauseWhenPageIsHidden:T}=s,[M,P]=Lt.useState([]),L=Lt.useMemo(()=>Array.from(new Set([r].concat(M.filter(de=>de.position).map(de=>de.position)))),[M,r]),[I,O]=Lt.useState([]),[$,q]=Lt.useState(!1),[W,G]=Lt.useState(!1),[K,ee]=Lt.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),J=Lt.useRef(null),le=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),ue=Lt.useRef(null),oe=Lt.useRef(!1),ie=Lt.useCallback(de=>{P(we=>{var je;return(je=we.find(xe=>xe.id===de.id))!=null&&je.delete||J1.dismiss(de.id),we.filter(({id:xe})=>xe!==de.id)})},[]);return Lt.useEffect(()=>J1.subscribe(de=>{if(de.dismiss){P(we=>we.map(je=>je.id===de.id?{...je,delete:!0}:je));return}setTimeout(()=>{cUe.flushSync(()=>{P(we=>{let je=we.findIndex(xe=>xe.id===de.id);return je!==-1?[...we.slice(0,je),{...we[je],...de},...we.slice(je+1)]:[de,...we]})})})}),[]),Lt.useEffect(()=>{if(u!=="system"){ee(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?ee("dark"):ee("light")),typeof window>"u")return;let de=window.matchMedia("(prefers-color-scheme: dark)");try{de.addEventListener("change",({matches:we})=>{ee(we?"dark":"light")})}catch{de.addListener(({matches:je})=>{try{ee(je?"dark":"light")}catch(xe){console.error(xe)}})}},[u]),Lt.useEffect(()=>{M.length<=1&&q(!1)},[M]),Lt.useEffect(()=>{let de=we=>{var je,xe;a.every(fe=>we[fe]||we.code===fe)&&(q(!0),(je=J.current)==null||je.focus()),we.code==="Escape"&&(document.activeElement===J.current||(xe=J.current)!=null&&xe.contains(document.activeElement))&&q(!1)};return document.addEventListener("keydown",de),()=>document.removeEventListener("keydown",de)},[a]),Lt.useEffect(()=>{if(J.current)return()=>{ue.current&&(ue.current.focus({preventScroll:!0}),ue.current=null,oe.current=!1)}},[J.current]),Lt.createElement("section",{ref:t,"aria-label":`${C} ${le}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},L.map((de,we)=>{var je;let[xe,fe]=de.split("-");return M.length?Lt.createElement("ol",{key:de,dir:g==="auto"?Wtt():g,tabIndex:-1,ref:J,className:o,"data-sonner-toaster":!0,"data-theme":K,"data-y-position":xe,"data-lifted":$&&M.length>1&&!i,"data-x-position":fe,style:{"--front-toast-height":`${((je=I[0])==null?void 0:je.height)||0}px`,"--width":`${RQt}px`,"--gap":`${b}px`,...p,...$Qt(c,d)},onBlur:Se=>{oe.current&&!Se.currentTarget.contains(Se.relatedTarget)&&(oe.current=!1,ue.current&&(ue.current.focus({preventScroll:!0}),ue.current=null))},onFocus:Se=>{Se.target instanceof HTMLElement&&Se.target.dataset.dismissible==="false"||oe.current||(oe.current=!0,ue.current=Se.relatedTarget)},onMouseEnter:()=>q(!0),onMouseMove:()=>q(!0),onMouseLeave:()=>{W||q(!1)},onDragEnd:()=>q(!1),onPointerDown:Se=>{Se.target instanceof HTMLElement&&Se.target.dataset.dismissible==="false"||G(!0)},onPointerUp:()=>G(!1)},M.filter(Se=>!Se.position&&we===0||Se.position===de).map((Se,Ee)=>{var Le,De;return Lt.createElement(BQt,{key:Se.id,icons:k,index:Ee,toast:Se,defaultRichColors:h,duration:(Le=y==null?void 0:y.duration)!=null?Le:m,className:y==null?void 0:y.className,descriptionClassName:y==null?void 0:y.descriptionClassName,invert:n,visibleToasts:x,closeButton:(De=y==null?void 0:y.closeButton)!=null?De:l,interacting:W,position:de,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:ie,toasts:M.filter(Be=>Be.position==Se.position),heights:I.filter(Be=>Be.position==Se.position),setHeights:O,expandByDefault:i,gap:b,loadingIcon:v,expanded:$,pauseWhenPageIsHidden:T,swipeDirections:s.swipeDirections})})):null}))});const qQt=({...s})=>{const{theme:t="system"}=fQt();return e.jsx(UQt,{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 VQt=y$e[" useId ".trim().toString()]||(()=>{}),HQt=0;function Cx(s){const[t,n]=j.useState(VQt());return Nf(()=>{s||n(r=>r??String(HQt++))},[s]),s||(t?`radix-${t}`:"")}var J6e="focusScope.autoFocusOnMount",eMe="focusScope.autoFocusOnUnmount",Ktt={bubbles:!1,cancelable:!0},GQt="FocusScope",eJ=j.forwardRef((s,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=j.useState(null),d=gf(a),u=gf(i),h=j.useRef(null),m=ko(t,y=>c(y)),p=j.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;j.useEffect(()=>{if(r){let y=function(k){if(p.paused||!o)return;const C=k.target;o.contains(C)?h.current=C:GC(h.current,{select:!0})},g=function(k){if(p.paused||!o)return;const C=k.relatedTarget;C!==null&&(o.contains(C)||GC(h.current,{select:!0}))},b=function(k){if(document.activeElement===document.body)for(const T of k)T.removedNodes.length>0&&GC(o)};document.addEventListener("focusin",y),document.addEventListener("focusout",g);const v=new MutationObserver(b);return o&&v.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",g),v.disconnect()}}},[r,o,p.paused]),j.useEffect(()=>{if(o){Ztt.add(p);const y=document.activeElement;if(!o.contains(y)){const b=new CustomEvent(J6e,Ktt);o.addEventListener(J6e,d),o.dispatchEvent(b),b.defaultPrevented||(WQt(QQt(nwt(o)),{select:!0}),document.activeElement===y&&GC(o))}return()=>{o.removeEventListener(J6e,d),setTimeout(()=>{const b=new CustomEvent(eMe,Ktt);o.addEventListener(eMe,u),o.dispatchEvent(b),b.defaultPrevented||GC(y??document.body,{select:!0}),o.removeEventListener(eMe,u),Ztt.remove(p)},0)}}},[o,d,u,p]);const x=j.useCallback(y=>{if(!n&&!r||p.paused)return;const g=y.key==="Tab"&&!y.altKey&&!y.ctrlKey&&!y.metaKey,b=document.activeElement;if(g&&b){const v=y.currentTarget,[k,C]=KQt(v);k&&C?!y.shiftKey&&b===C?(y.preventDefault(),n&&GC(k,{select:!0})):y.shiftKey&&b===k&&(y.preventDefault(),n&&GC(C,{select:!0})):b===v&&y.preventDefault()}},[n,r,p.paused]);return e.jsx(Ua.div,{tabIndex:-1,...l,ref:m,onKeyDown:x})});eJ.displayName=GQt;function WQt(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(GC(r,{select:t}),document.activeElement!==n)return}function KQt(s){const t=nwt(s),n=Ytt(t,s),r=Ytt(t.reverse(),s);return[n,r]}function nwt(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 Ytt(s,t){for(const n of s)if(!YQt(n,{upTo:t}))return n}function YQt(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 ZQt(s){return s instanceof HTMLInputElement&&"select"in s}function GC(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&ZQt(s)&&t&&s.select()}}var Ztt=XQt();function XQt(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=Xtt(s,t),s.unshift(t)},remove(t){var n;s=Xtt(s,t),(n=s[0])==null||n.resume()}}}function Xtt(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function QQt(s){return s.filter(t=>t.tagName!=="A")}var tMe=0;function E4e(){j.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??Qtt()),document.body.insertAdjacentElement("beforeend",s[1]??Qtt()),tMe++,()=>{tMe===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),tMe--}},[])}function Qtt(){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 p5=function(){return p5=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return fJt;var t=xJt(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])}},yJt=owt(),xz="data-scroll-locked",vJt=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(eJt,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(xz,`] { 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(ije,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(oje,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(ije," .").concat(ije,` { right: 0 `).concat(r,`; } .`).concat(oje," .").concat(oje,` { margin-right: 0 `).concat(r,`; } body[`).concat(xz,`] { `).concat(tJt,": ").concat(o,`px; } `)},est=function(){var s=parseInt(document.body.getAttribute(xz)||"0",10);return isFinite(s)?s:0},bJt=function(){j.useEffect(function(){return document.body.setAttribute(xz,(est()+1).toString()),function(){var s=est()-1;s<=0?document.body.removeAttribute(xz):document.body.setAttribute(xz,s.toString())}},[])},_Jt=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;bJt();var i=j.useMemo(function(){return gJt(a)},[a]);return j.createElement(yJt,{styles:vJt(i,!t,a,n?"":"!important")})},tDe=!1;if(typeof window<"u")try{var lse=Object.defineProperty({},"passive",{get:function(){return tDe=!0,!0}});window.addEventListener("test",lse,lse),window.removeEventListener("test",lse,lse)}catch{tDe=!1}var TF=tDe?{passive:!1}:!1,wJt=function(s){return s.tagName==="TEXTAREA"},lwt=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!wJt(s)&&n[t]==="visible")},jJt=function(s){return lwt(s,"overflowY")},NJt=function(s){return lwt(s,"overflowX")},tst=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=cwt(s,r);if(a){var i=dwt(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},kJt=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},SJt=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},cwt=function(s,t){return s==="v"?jJt(t):NJt(t)},dwt=function(s,t){return s==="v"?kJt(t):SJt(t)},CJt=function(s,t){return s==="h"&&t==="rtl"?-1:1},AJt=function(s,t,n,r,a){var i=CJt(s,window.getComputedStyle(t).direction),l=i*r,o=n.target,c=t.contains(o),d=!1,u=l>0,h=0,m=0;do{if(!o)break;var p=dwt(s,o),x=p[0],y=p[1],g=p[2],b=y-g-i*x;(x||b)&&cwt(s,o)&&(h+=b,m+=x);var v=o.parentNode;o=v&&v.nodeType===Node.DOCUMENT_FRAGMENT_NODE?v.host:v}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(u&&(Math.abs(h)<1||!a)||!u&&(Math.abs(m)<1||!a))&&(d=!0),d},cse=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},sst=function(s){return[s.deltaX,s.deltaY]},nst=function(s){return s&&"current"in s?s.current:s},TJt=function(s,t){return s[0]===t[0]&&s[1]===t[1]},EJt=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},MJt=0,EF=[];function LJt(s){var t=j.useRef([]),n=j.useRef([0,0]),r=j.useRef(),a=j.useState(MJt++)[0],i=j.useState(owt)[0],l=j.useRef(s);j.useEffect(function(){l.current=s},[s]),j.useEffect(function(){if(s.inert){document.body.classList.add("block-interactivity-".concat(a));var y=JQt([s.lockRef.current],(s.shards||[]).map(nst),!0).filter(Boolean);return y.forEach(function(g){return g.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),y.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=j.useCallback(function(y,g){if("touches"in y&&y.touches.length===2||y.type==="wheel"&&y.ctrlKey)return!l.current.allowPinchZoom;var b=cse(y),v=n.current,k="deltaX"in y?y.deltaX:v[0]-b[0],C="deltaY"in y?y.deltaY:v[1]-b[1],T,M=y.target,P=Math.abs(k)>Math.abs(C)?"h":"v";if("touches"in y&&P==="h"&&M.type==="range")return!1;var L=tst(P,M);if(!L)return!0;if(L?T=P:(T=P==="v"?"h":"v",L=tst(P,M)),!L)return!1;if(!r.current&&"changedTouches"in y&&(k||C)&&(r.current=T),!T)return!0;var I=r.current||T;return AJt(I,g,y,I==="h"?k:C,!0)},[]),c=j.useCallback(function(y){var g=y;if(!(!EF.length||EF[EF.length-1]!==i)){var b="deltaY"in g?sst(g):cse(g),v=t.current.filter(function(T){return T.name===g.type&&(T.target===g.target||g.target===T.shadowParent)&&TJt(T.delta,b)})[0];if(v&&v.should){g.cancelable&&g.preventDefault();return}if(!v){var k=(l.current.shards||[]).map(nst).filter(Boolean).filter(function(T){return T.contains(g.target)}),C=k.length>0?o(g,k[0]):!l.current.noIsolation;C&&g.cancelable&&g.preventDefault()}}},[]),d=j.useCallback(function(y,g,b,v){var k={name:y,delta:g,target:b,should:v,shadowParent:PJt(b)};t.current.push(k),setTimeout(function(){t.current=t.current.filter(function(C){return C!==k})},1)},[]),u=j.useCallback(function(y){n.current=cse(y),r.current=void 0},[]),h=j.useCallback(function(y){d(y.type,sst(y),y.target,o(y,s.lockRef.current))},[]),m=j.useCallback(function(y){d(y.type,cse(y),y.target,o(y,s.lockRef.current))},[]);j.useEffect(function(){return EF.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:m}),document.addEventListener("wheel",c,TF),document.addEventListener("touchmove",c,TF),document.addEventListener("touchstart",u,TF),function(){EF=EF.filter(function(y){return y!==i}),document.removeEventListener("wheel",c,TF),document.removeEventListener("touchmove",c,TF),document.removeEventListener("touchstart",u,TF)}},[]);var p=s.removeScrollBar,x=s.inert;return j.createElement(j.Fragment,null,x?j.createElement(i,{styles:EJt(a)}):null,p?j.createElement(_Jt,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function PJt(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const IJt=lJt(iwt,LJt);var tJ=j.forwardRef(function(s,t){return j.createElement(M4e,p5({},s,{ref:t,sideCar:IJt}))});tJ.classNames=M4e.classNames;var RJt=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},MF=new WeakMap,dse=new WeakMap,use={},aMe=0,uwt=function(s){return s&&(s.host||uwt(s.parentNode))},DJt=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=uwt(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})},OJt=function(s,t,n,r){var a=DJt(t,Array.isArray(s)?s:[s]);use[n]||(use[n]=new WeakMap);var i=use[n],l=[],o=new Set,c=new Set(a),d=function(h){!h||o.has(h)||(o.add(h),d(h.parentNode))};a.forEach(d);var u=function(h){!h||c.has(h)||Array.prototype.forEach.call(h.children,function(m){if(o.has(m))u(m);else try{var p=m.getAttribute(r),x=p!==null&&p!=="false",y=(MF.get(m)||0)+1,g=(i.get(m)||0)+1;MF.set(m,y),i.set(m,g),l.push(m),y===1&&x&&dse.set(m,!0),g===1&&m.setAttribute(n,"true"),x||m.setAttribute(r,"true")}catch(b){console.error("aria-hidden: cannot operate on ",m,b)}})};return u(t),o.clear(),aMe++,function(){l.forEach(function(h){var m=MF.get(h)-1,p=i.get(h)-1;MF.set(h,m),i.set(h,p),m||(dse.has(h)||h.removeAttribute(r),dse.delete(h)),p||h.removeAttribute(n)}),aMe--,aMe||(MF=new WeakMap,MF=new WeakMap,dse=new WeakMap,use={})}},L4e=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=RJt(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live]"))),OJt(r,a,n,"aria-hidden")):function(){return null}},P4e="Dialog",[hwt,mwt]=Zm(P4e),[FJt,IN]=hwt(P4e),pwt=s=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=j.useRef(null),c=j.useRef(null),[d,u]=Mx({prop:r,defaultProp:a??!1,onChange:i,caller:P4e});return e.jsx(FJt,{scope:t,triggerRef:o,contentRef:c,contentId:Cx(),titleId:Cx(),descriptionId:Cx(),open:d,onOpenChange:u,onOpenToggle:j.useCallback(()=>u(h=>!h),[u]),modal:l,children:n})};pwt.displayName=P4e;var fwt="DialogTrigger",xwt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=IN(fwt,n),i=ko(t,a.triggerRef);return e.jsx(Ua.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":yUe(a.open),...r,ref:i,onClick:ua(s.onClick,a.onOpenToggle)})});xwt.displayName=fwt;var xUe="DialogPortal",[zJt,gwt]=hwt(xUe,{forceMount:void 0}),ywt=s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=IN(xUe,t);return e.jsx(zJt,{scope:t,forceMount:n,children:j.Children.map(r,l=>e.jsx(ax,{present:n||i.open,children:e.jsx(LU,{asChild:!0,container:a,children:l})}))})};ywt.displayName=xUe;var cNe="DialogOverlay",vwt=j.forwardRef((s,t)=>{const n=gwt(cNe,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=IN(cNe,s.__scopeDialog);return i.modal?e.jsx(ax,{present:r||i.open,children:e.jsx($Jt,{...a,ref:t})}):null});vwt.displayName=cNe;var BJt=NE("DialogOverlay.RemoveScroll"),$Jt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=IN(cNe,n);return e.jsx(tJ,{as:BJt,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(Ua.div,{"data-state":yUe(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),jD="DialogContent",bwt=j.forwardRef((s,t)=>{const n=gwt(jD,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=IN(jD,s.__scopeDialog);return e.jsx(ax,{present:r||i.open,children:i.modal?e.jsx(UJt,{...a,ref:t}):e.jsx(qJt,{...a,ref:t})})});bwt.displayName=jD;var UJt=j.forwardRef((s,t)=>{const n=IN(jD,s.__scopeDialog),r=j.useRef(null),a=ko(t,n.contentRef,r);return j.useEffect(()=>{const i=r.current;if(i)return L4e(i)},[]),e.jsx(_wt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ua(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:ua(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:ua(s.onFocusOutside,i=>i.preventDefault())})}),qJt=j.forwardRef((s,t)=>{const n=IN(jD,s.__scopeDialog),r=j.useRef(!1),a=j.useRef(!1);return e.jsx(_wt,{...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()}})}),_wt=j.forwardRef((s,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=IN(jD,n),c=j.useRef(null),d=ko(t,c);return E4e(),e.jsxs(e.Fragment,{children:[e.jsx(eJ,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(ZE,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":yUe(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(HJt,{titleId:o.titleId}),e.jsx(WJt,{contentRef:c,descriptionId:o.descriptionId})]})]})}),gUe="DialogTitle",wwt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=IN(gUe,n);return e.jsx(Ua.h2,{id:a.titleId,...r,ref:t})});wwt.displayName=gUe;var jwt="DialogDescription",Nwt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=IN(jwt,n);return e.jsx(Ua.p,{id:a.descriptionId,...r,ref:t})});Nwt.displayName=jwt;var kwt="DialogClose",Swt=j.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=IN(kwt,n);return e.jsx(Ua.button,{type:"button",...r,ref:t,onClick:ua(s.onClick,()=>a.onOpenChange(!1))})});Swt.displayName=kwt;function yUe(s){return s?"open":"closed"}var Cwt="DialogTitleWarning",[VJt,Awt]=FZt(Cwt,{contentName:jD,titleName:gUe,docsSlug:"dialog"}),HJt=({titleId:s})=>{const t=Awt(Cwt),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return j.useEffect(()=>{s&&(document.getElementById(s)||console.error(n))},[n,s]),null},GJt="DialogDescriptionWarning",WJt=({contentRef:s,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Awt(GJt).contentName}}.`;return j.useEffect(()=>{var i;const a=(i=s.current)==null?void 0:i.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(r))},[r,s,t]),null},I4e=pwt,vUe=xwt,R4e=ywt,IU=vwt,RU=bwt,sJ=wwt,nJ=Nwt,rJ=Swt,Twt="AlertDialog",[KJt,Kzn]=Zm(Twt,[mwt]),X3=mwt(),Ewt=s=>{const{__scopeAlertDialog:t,...n}=s,r=X3(t);return e.jsx(I4e,{...r,...n,modal:!0})};Ewt.displayName=Twt;var YJt="AlertDialogTrigger",Mwt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=X3(n);return e.jsx(vUe,{...a,...r,ref:t})});Mwt.displayName=YJt;var ZJt="AlertDialogPortal",Lwt=s=>{const{__scopeAlertDialog:t,...n}=s,r=X3(t);return e.jsx(R4e,{...r,...n})};Lwt.displayName=ZJt;var XJt="AlertDialogOverlay",Pwt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=X3(n);return e.jsx(IU,{...a,...r,ref:t})});Pwt.displayName=XJt;var gz="AlertDialogContent",[QJt,JJt]=KJt(gz),ees=b_t("AlertDialogContent"),Iwt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,children:r,...a}=s,i=X3(n),l=j.useRef(null),o=ko(t,l),c=j.useRef(null);return e.jsx(VJt,{contentName:gz,titleName:Rwt,docsSlug:"alert-dialog",children:e.jsx(QJt,{scope:n,cancelRef:c,children:e.jsxs(RU,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:ua(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(ees,{children:r}),e.jsx(ses,{contentRef:l})]})})})});Iwt.displayName=gz;var Rwt="AlertDialogTitle",Dwt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=X3(n);return e.jsx(sJ,{...a,...r,ref:t})});Dwt.displayName=Rwt;var Owt="AlertDialogDescription",Fwt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=X3(n);return e.jsx(nJ,{...a,...r,ref:t})});Fwt.displayName=Owt;var tes="AlertDialogAction",zwt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=X3(n);return e.jsx(rJ,{...a,...r,ref:t})});zwt.displayName=tes;var Bwt="AlertDialogCancel",$wt=j.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,{cancelRef:a}=JJt(Bwt,n),i=X3(n),l=ko(t,a);return e.jsx(rJ,{...i,...r,ref:l})});$wt.displayName=Bwt;var ses=({contentRef:s})=>{const t=`\`${gz}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${gz}\` by passing a \`${Owt}\` 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 \`${gz}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component. For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return j.useEffect(()=>{var r;document.getElementById((r=s.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(t)},[t,s]),null},nes=Ewt,res=Mwt,aes=Lwt,Uwt=Pwt,qwt=Iwt,Vwt=zwt,Hwt=$wt,Gwt=Dwt,Wwt=Fwt;const h$=hO("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=j.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},i)=>{const l=r?dUe:"button";return e.jsx(l,{className:Et(h$({variant:t,size:n,className:s})),ref:i,...a})});B.displayName="Button";const Nl=nes,yf=res,ies=aes,Kwt=j.forwardRef(({className:s,...t},n)=>e.jsx(Uwt,{className:Et("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}));Kwt.displayName=Uwt.displayName;const hl=j.forwardRef(({className:s,...t},n)=>e.jsxs(ies,{children:[e.jsx(Kwt,{}),e.jsx(qwt,{ref:n,className:Et("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})]}));hl.displayName=qwt.displayName;const ml=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col space-y-2 text-center sm:text-left",s),...t});ml.displayName="AlertDialogHeader";const pl=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});pl.displayName="AlertDialogFooter";const fl=j.forwardRef(({className:s,...t},n)=>e.jsx(Gwt,{ref:n,className:Et("text-lg font-semibold",s),...t}));fl.displayName=Gwt.displayName;const xl=j.forwardRef(({className:s,...t},n)=>e.jsx(Wwt,{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));xl.displayName=Wwt.displayName;const cl=j.forwardRef(({className:s,...t},n)=>e.jsx(Vwt,{ref:n,className:Et(h$(),s),...t}));cl.displayName=Vwt.displayName;const gl=j.forwardRef(({className:s,...t},n)=>e.jsx(Hwt,{ref:n,className:Et(h$({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));gl.displayName=Hwt.displayName;let dNe=null;const oes=["delete","remove","revoke","cannot be undone","permanently"];function Bi(s,t={}){const n=typeof s=="string"?{description:s,...t}:s,r=`${n.title??""} ${n.description??""}`.toLowerCase(),a=n.destructive??oes.some(i=>r.includes(i));return new Promise(i=>{if(!dNe){i(window.confirm(n.description??n.title??"Are you sure?"));return}dNe({...n,destructive:a,resolve:i})})}function les(){const[s,t]=j.useState(null);j.useEffect(()=>(dNe=a=>t(a),()=>{dNe=null}),[]);const n=a=>{s==null||s.resolve(a),t(null)},r=!!(s!=null&&s.destructive);return e.jsx(Nl,{open:!!s,onOpenChange:a=>!a&&n(!1),children:e.jsxs(hl,{className:"sm:max-w-md",children:[e.jsx(ml,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Et("mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-full",r?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"),children:e.jsx(hd,{className:"h-5 w-5"})}),e.jsxs("div",{className:"space-y-1.5 text-left",children:[e.jsx(fl,{children:(s==null?void 0:s.title)??(r?"Are you sure?":"Please confirm")}),(s==null?void 0:s.description)&&e.jsx(xl,{className:"leading-relaxed",children:s.description})]})]})}),e.jsxs(pl,{className:"gap-2 sm:gap-2",children:[e.jsx(gl,{onClick:()=>n(!1),children:(s==null?void 0:s.cancelText)??"Cancel"}),e.jsx(cl,{onClick:()=>n(!0),className:Et(r&&"bg-destructive text-destructive-foreground hover:bg-destructive/90"),children:(s==null?void 0:s.confirmText)??(r?"Delete":"Continue")})]})]})})}const ces=["top","right","bottom","left"],kE=Math.min,M_=Math.max,uNe=Math.round,hse=Math.floor,SE=s=>({x:s,y:s}),des={left:"right",right:"left",bottom:"top",top:"bottom"},ues={start:"end",end:"start"};function sDe(s,t,n){return M_(s,kE(t,n))}function F3(s,t){return typeof s=="function"?s(t):s}function z3(s){return s.split("-")[0]}function DU(s){return s.split("-")[1]}function bUe(s){return s==="x"?"y":"x"}function _Ue(s){return s==="y"?"height":"width"}function CE(s){return["top","bottom"].includes(z3(s))?"y":"x"}function wUe(s){return bUe(CE(s))}function hes(s,t,n){n===void 0&&(n=!1);const r=DU(s),a=wUe(s),i=_Ue(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=hNe(l)),[l,hNe(l)]}function mes(s){const t=hNe(s);return[nDe(s),t,nDe(t)]}function nDe(s){return s.replace(/start|end/g,t=>ues[t])}function pes(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 fes(s,t,n,r){const a=DU(s);let i=pes(z3(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(nDe)))),i}function hNe(s){return s.replace(/left|right|bottom|top/g,t=>des[t])}function xes(s){return{top:0,right:0,bottom:0,left:0,...s}}function Ywt(s){return typeof s!="number"?xes(s):{top:s,right:s,bottom:s,left:s}}function mNe(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 rst(s,t,n){let{reference:r,floating:a}=s;const i=CE(t),l=wUe(t),o=_Ue(l),c=z3(t),d=i==="y",u=r.x+r.width/2-a.width/2,h=r.y+r.height/2-a.height/2,m=r[o]/2-a[o]/2;let p;switch(c){case"top":p={x:u,y:r.y-a.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:h};break;case"left":p={x:r.x-a.width,y:h};break;default:p={x:r.x,y:r.y}}switch(DU(t)){case"start":p[l]-=m*(n&&d?-1:1);break;case"end":p[l]+=m*(n&&d?-1:1);break}return p}const ges=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}=rst(d,r,c),m=r,p={},x=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}=F3(s,t)||{};if(d==null)return{};const h=Ywt(u),m={x:n,y:r},p=wUe(a),x=_Ue(p),y=await l.getDimensions(d),g=p==="y",b=g?"top":"left",v=g?"bottom":"right",k=g?"clientHeight":"clientWidth",C=i.reference[x]+i.reference[p]-m[p]-i.floating[x],T=m[p]-i.reference[p],M=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let P=M?M[k]:0;(!P||!await(l.isElement==null?void 0:l.isElement(M)))&&(P=o.floating[k]||i.floating[x]);const L=C/2-T/2,I=P/2-y[x]/2-1,O=kE(h[b],I),$=kE(h[v],I),q=O,W=P-y[x]-$,G=P/2-y[x]/2+L,K=sDe(q,G,W),ee=!c.arrow&&DU(a)!=null&&G!==K&&i.reference[x]/2-(GG<=0)){var $,q;const G=((($=i.flip)==null?void 0:$.index)||0)+1,K=P[G];if(K)return{data:{index:G,overflows:O},reset:{placement:K}};let ee=(q=O.filter(J=>J.overflows[0]<=0).sort((J,le)=>J.overflows[1]-le.overflows[1])[0])==null?void 0:q.placement;if(!ee)switch(p){case"bestFit":{var W;const J=(W=O.filter(le=>{if(M){const ue=CE(le.placement);return ue===v||ue==="y"}return!0}).map(le=>[le.placement,le.overflows.filter(ue=>ue>0).reduce((ue,oe)=>ue+oe,0)]).sort((le,ue)=>le[1]-ue[1])[0])==null?void 0:W[0];J&&(ee=J);break}case"initialPlacement":ee=o;break}if(a!==ee)return{reset:{placement:ee}}}return{}}}};function ast(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function ist(s){return ces.some(t=>s[t]>=0)}const bes=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...a}=F3(s,t);switch(r){case"referenceHidden":{const i=await BY(t,{...a,elementContext:"reference"}),l=ast(i,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:ist(l)}}}case"escaped":{const i=await BY(t,{...a,altBoundary:!0}),l=ast(i,n.floating);return{data:{escapedOffsets:l,escaped:ist(l)}}}default:return{}}}}};async function _es(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=z3(n),o=DU(n),c=CE(n)==="y",d=["left","top"].includes(l)?-1:1,u=i&&c?-1:1,h=F3(t,s);let{mainAxis:m,crossAxis:p,alignmentAxis:x}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return o&&typeof x=="number"&&(p=o==="end"?x*-1:x),c?{x:p*u,y:m*d}:{x:m*d,y:p*u}}const wes=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 _es(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}}}}},jes=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:g=>{let{x:b,y:v}=g;return{x:b,y:v}}},...c}=F3(s,t),d={x:n,y:r},u=await BY(t,c),h=CE(z3(a)),m=bUe(h);let p=d[m],x=d[h];if(i){const g=m==="y"?"top":"left",b=m==="y"?"bottom":"right",v=p+u[g],k=p-u[b];p=sDe(v,p,k)}if(l){const g=h==="y"?"top":"left",b=h==="y"?"bottom":"right",v=x+u[g],k=x-u[b];x=sDe(v,x,k)}const y=o.fn({...t,[m]:p,[h]:x});return{...y,data:{x:y.x-n,y:y.y-r,enabled:{[m]:i,[h]:l}}}}}},Nes=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}=F3(s,t),u={x:n,y:r},h=CE(a),m=bUe(h);let p=u[m],x=u[h];const y=F3(o,t),g=typeof y=="number"?{mainAxis:y,crossAxis:0}:{mainAxis:0,crossAxis:0,...y};if(c){const k=m==="y"?"height":"width",C=i.reference[m]-i.floating[k]+g.mainAxis,T=i.reference[m]+i.reference[k]-g.mainAxis;pT&&(p=T)}if(d){var b,v;const k=m==="y"?"width":"height",C=["top","left"].includes(z3(a)),T=i.reference[h]-i.floating[k]+(C&&((b=l.offset)==null?void 0:b[h])||0)+(C?0:g.crossAxis),M=i.reference[h]+i.reference[k]+(C?0:((v=l.offset)==null?void 0:v[h])||0)-(C?g.crossAxis:0);xM&&(x=M)}return{[m]:p,[h]:x}}}},kes=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}=F3(s,t),u=await BY(t,d),h=z3(a),m=DU(a),p=CE(a)==="y",{width:x,height:y}=i.floating;let g,b;h==="top"||h==="bottom"?(g=h,b=m===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(b=h,g=m==="end"?"top":"bottom");const v=y-u.top-u.bottom,k=x-u.left-u.right,C=kE(y-u[g],v),T=kE(x-u[b],k),M=!t.middlewareData.shift;let P=C,L=T;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(L=k),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(P=v),M&&!m){const O=M_(u.left,0),$=M_(u.right,0),q=M_(u.top,0),W=M_(u.bottom,0);p?L=x-2*(O!==0||$!==0?O+$:M_(u.left,u.right)):P=y-2*(q!==0||W!==0?q+W:M_(u.top,u.bottom))}await c({...t,availableWidth:L,availableHeight:P});const I=await l.getDimensions(o.floating);return x!==I.width||y!==I.height?{reset:{rects:!0}}:{}}}};function D4e(){return typeof window<"u"}function OU(s){return Zwt(s)?(s.nodeName||"").toLowerCase():"#document"}function G_(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function nS(s){var t;return(t=(Zwt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function Zwt(s){return D4e()?s instanceof Node||s instanceof G_(s).Node:!1}function SN(s){return D4e()?s instanceof Element||s instanceof G_(s).Element:!1}function W5(s){return D4e()?s instanceof HTMLElement||s instanceof G_(s).HTMLElement:!1}function ost(s){return!D4e()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof G_(s).ShadowRoot}function aJ(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=CN(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(a)}function Ses(s){return["table","td","th"].includes(OU(s))}function O4e(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function jUe(s){const t=NUe(),n=SN(s)?CN(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 Ces(s){let t=AE(s);for(;W5(t)&&!m$(t);){if(jUe(t))return t;if(O4e(t))return null;t=AE(t)}return null}function NUe(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function m$(s){return["html","body","#document"].includes(OU(s))}function CN(s){return G_(s).getComputedStyle(s)}function F4e(s){return SN(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function AE(s){if(OU(s)==="html")return s;const t=s.assignedSlot||s.parentNode||ost(s)&&s.host||nS(s);return ost(t)?t.host:t}function Xwt(s){const t=AE(s);return m$(t)?s.ownerDocument?s.ownerDocument.body:s.body:W5(t)&&aJ(t)?t:Xwt(t)}function $Y(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=Xwt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=G_(a);if(i){const o=rDe(l);return t.concat(l,l.visualViewport||[],aJ(a)?a:[],o&&n?$Y(o):[])}return t.concat(a,$Y(a,[],n))}function rDe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function Qwt(s){const t=CN(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=W5(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=uNe(n)!==i||uNe(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function kUe(s){return SN(s)?s:s.contextElement}function yz(s){const t=kUe(s);if(!W5(t))return SE(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=Qwt(t);let l=(i?uNe(n.width):n.width)/r,o=(i?uNe(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const Aes=SE(0);function Jwt(s){const t=G_(s);return!NUe()||!t.visualViewport?Aes:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Tes(s,t,n){return t===void 0&&(t=!1),!n||t&&n!==G_(s)?!1:t}function ND(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=kUe(s);let l=SE(1);t&&(r?SN(r)&&(l=yz(r)):l=yz(s));const o=Tes(i,n,r)?Jwt(i):SE(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=G_(i),p=r&&SN(r)?G_(r):r;let x=m,y=rDe(x);for(;y&&r&&p!==x;){const g=yz(y),b=y.getBoundingClientRect(),v=CN(y),k=b.left+(y.clientLeft+parseFloat(v.paddingLeft))*g.x,C=b.top+(y.clientTop+parseFloat(v.paddingTop))*g.y;c*=g.x,d*=g.y,u*=g.x,h*=g.y,c+=k,d+=C,x=G_(y),y=rDe(x)}}return mNe({width:u,height:h,x:c,y:d})}function Ees(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=nS(r),o=t?O4e(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=SE(1);const u=SE(0),h=W5(r);if((h||!h&&!i)&&((OU(r)!=="body"||aJ(l))&&(c=F4e(r)),W5(r))){const m=ND(r);d=yz(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 Mes(s){return Array.from(s.getClientRects())}function aDe(s,t){const n=F4e(s).scrollLeft;return t?t.left+n:ND(nS(s)).left+n}function Les(s){const t=nS(s),n=F4e(s),r=s.ownerDocument.body,a=M_(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=M_(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+aDe(s);const o=-n.scrollTop;return CN(r).direction==="rtl"&&(l+=M_(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:l,y:o}}function Pes(s,t){const n=G_(s),r=nS(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=NUe();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function Ies(s,t){const n=ND(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=W5(s)?yz(s):SE(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 lst(s,t,n){let r;if(t==="viewport")r=Pes(s,n);else if(t==="document")r=Les(nS(s));else if(SN(t))r=Ies(t,n);else{const a=Jwt(s);r={...t,x:t.x-a.x,y:t.y-a.y}}return mNe(r)}function ejt(s,t){const n=AE(s);return n===t||!SN(n)||m$(n)?!1:CN(n).position==="fixed"||ejt(n,t)}function Res(s,t){const n=t.get(s);if(n)return n;let r=$Y(s,[],!1).filter(o=>SN(o)&&OU(o)!=="body"),a=null;const i=CN(s).position==="fixed";let l=i?AE(s):s;for(;SN(l)&&!m$(l);){const o=CN(l),c=jUe(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||aJ(l)&&!c&&ejt(s,l))?r=r.filter(u=>u!==l):a=o,l=AE(l)}return t.set(s,r),r}function Des(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?O4e(t)?[]:Res(t,this._c):[].concat(n),r],o=l[0],c=l.reduce((d,u)=>{const h=lst(t,u,a);return d.top=M_(h.top,d.top),d.right=kE(h.right,d.right),d.bottom=kE(h.bottom,d.bottom),d.left=M_(h.left,d.left),d},lst(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function Oes(s){const{width:t,height:n}=Qwt(s);return{width:t,height:n}}function Fes(s,t,n){const r=W5(t),a=nS(t),i=n==="fixed",l=ND(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=SE(0);if(r||!r&&!i)if((OU(t)!=="body"||aJ(a))&&(o=F4e(t)),r){const p=ND(t,!0,i,t);c.x=p.x+t.clientLeft,c.y=p.y+t.clientTop}else a&&(c.x=aDe(a));let d=0,u=0;if(a&&!r&&!i){const p=a.getBoundingClientRect();u=p.top+o.scrollTop,d=p.left+o.scrollLeft-aDe(a,p)}const h=l.left+o.scrollLeft-c.x-d,m=l.top+o.scrollTop-c.y-u;return{x:h,y:m,width:l.width,height:l.height}}function iMe(s){return CN(s).position==="static"}function cst(s,t){if(!W5(s)||CN(s).position==="fixed")return null;if(t)return t(s);let n=s.offsetParent;return nS(s)===n&&(n=n.ownerDocument.body),n}function tjt(s,t){const n=G_(s);if(O4e(s))return n;if(!W5(s)){let a=AE(s);for(;a&&!m$(a);){if(SN(a)&&!iMe(a))return a;a=AE(a)}return n}let r=cst(s,t);for(;r&&Ses(r)&&iMe(r);)r=cst(r,t);return r&&m$(r)&&iMe(r)&&!jUe(r)?n:r||Ces(s)||n}const zes=async function(s){const t=this.getOffsetParent||tjt,n=this.getDimensions,r=await n(s.floating);return{reference:Fes(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function Bes(s){return CN(s).direction==="rtl"}const $es={convertOffsetParentRelativeRectToViewportRelativeRect:Ees,getDocumentElement:nS,getClippingRect:Des,getOffsetParent:tjt,getElementRects:zes,getClientRects:Mes,getDimensions:Oes,getScale:yz,isElement:SN,isRTL:Bes};function Ues(s,t){let n=null,r;const a=nS(s);function i(){var o;clearTimeout(r),(o=n)==null||o.disconnect(),n=null}function l(o,c){o===void 0&&(o=!1),c===void 0&&(c=1),i();const{left:d,top:u,width:h,height:m}=s.getBoundingClientRect();if(o||t(),!h||!m)return;const p=hse(u),x=hse(a.clientWidth-(d+h)),y=hse(a.clientHeight-(u+m)),g=hse(d),v={rootMargin:-p+"px "+-x+"px "+-y+"px "+-g+"px",threshold:M_(0,kE(1,c))||1};let k=!0;function C(T){const M=T[0].intersectionRatio;if(M!==c){if(!k)return l();M?l(!1,M):r=setTimeout(()=>{l(!1,1e-7)},1e3)}k=!1}try{n=new IntersectionObserver(C,{...v,root:a.ownerDocument})}catch{n=new IntersectionObserver(C,v)}n.observe(s)}return l(!0),i}function qes(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=kUe(s),u=a||i?[...d?$Y(d):[],...$Y(t)]:[];u.forEach(b=>{a&&b.addEventListener("scroll",n,{passive:!0}),i&&b.addEventListener("resize",n)});const h=d&&o?Ues(d,n):null;let m=-1,p=null;l&&(p=new ResizeObserver(b=>{let[v]=b;v&&v.target===d&&p&&(p.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var k;(k=p)==null||k.observe(t)})),n()}),d&&!c&&p.observe(d),p.observe(t));let x,y=c?ND(s):null;c&&g();function g(){const b=ND(s);y&&(b.x!==y.x||b.y!==y.y||b.width!==y.width||b.height!==y.height)&&n(),y=b,x=requestAnimationFrame(g)}return n(),()=>{var b;u.forEach(v=>{a&&v.removeEventListener("scroll",n),i&&v.removeEventListener("resize",n)}),h==null||h(),(b=p)==null||b.disconnect(),p=null,c&&cancelAnimationFrame(x)}}const Ves=wes,Hes=jes,Ges=ves,Wes=kes,Kes=bes,dst=yes,Yes=Nes,Zes=(s,t,n)=>{const r=new Map,a={platform:$es,...n},i={...a.platform,_c:r};return ges(s,t,{...a,platform:i})};var lje=typeof document<"u"?j.useLayoutEffect:j.useEffect;function pNe(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(!pNe(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)&&!pNe(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function sjt(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function ust(s,t){const n=sjt(s);return Math.round(t*n)/n}function oMe(s){const t=j.useRef(s);return lje(()=>{t.current=s}),t}function Xes(s){s===void 0&&(s={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:l}={},transform:o=!0,whileElementsMounted:c,open:d}=s,[u,h]=j.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,p]=j.useState(r);pNe(m,r)||p(r);const[x,y]=j.useState(null),[g,b]=j.useState(null),v=j.useCallback(le=>{le!==M.current&&(M.current=le,y(le))},[]),k=j.useCallback(le=>{le!==P.current&&(P.current=le,b(le))},[]),C=i||x,T=l||g,M=j.useRef(null),P=j.useRef(null),L=j.useRef(u),I=c!=null,O=oMe(c),$=oMe(a),q=oMe(d),W=j.useCallback(()=>{if(!M.current||!P.current)return;const le={placement:t,strategy:n,middleware:m};$.current&&(le.platform=$.current),Zes(M.current,P.current,le).then(ue=>{const oe={...ue,isPositioned:q.current!==!1};G.current&&!pNe(L.current,oe)&&(L.current=oe,Hv.flushSync(()=>{h(oe)}))})},[m,t,n,$,q]);lje(()=>{d===!1&&L.current.isPositioned&&(L.current.isPositioned=!1,h(le=>({...le,isPositioned:!1})))},[d]);const G=j.useRef(!1);lje(()=>(G.current=!0,()=>{G.current=!1}),[]),lje(()=>{if(C&&(M.current=C),T&&(P.current=T),C&&T){if(O.current)return O.current(C,T,W);W()}},[C,T,W,O,I]);const K=j.useMemo(()=>({reference:M,floating:P,setReference:v,setFloating:k}),[v,k]),ee=j.useMemo(()=>({reference:C,floating:T}),[C,T]),J=j.useMemo(()=>{const le={position:n,left:0,top:0};if(!ee.floating)return le;const ue=ust(ee.floating,u.x),oe=ust(ee.floating,u.y);return o?{...le,transform:"translate("+ue+"px, "+oe+"px)",...sjt(ee.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ue,top:oe}},[n,o,ee.floating,u.x,u.y]);return j.useMemo(()=>({...u,update:W,refs:K,elements:ee,floatingStyles:J}),[u,W,K,ee,J])}const Qes=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?dst({element:r.current,padding:a}).fn(n):{}:r?dst({element:r,padding:a}).fn(n):{}}}},Jes=(s,t)=>({...Ves(s),options:[s,t]}),ets=(s,t)=>({...Hes(s),options:[s,t]}),tts=(s,t)=>({...Yes(s),options:[s,t]}),sts=(s,t)=>({...Ges(s),options:[s,t]}),nts=(s,t)=>({...Wes(s),options:[s,t]}),rts=(s,t)=>({...Kes(s),options:[s,t]}),ats=(s,t)=>({...Qes(s),options:[s,t]});var its="Arrow",njt=j.forwardRef((s,t)=>{const{children:n,width:r=10,height:a=5,...i}=s;return e.jsx(Ua.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"})})});njt.displayName=its;var ots=njt;function iJ(s){const[t,n]=j.useState(void 0);return Nf(()=>{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 SUe="Popper",[rjt,rS]=Zm(SUe),[lts,ajt]=rjt(SUe),ijt=s=>{const{__scopePopper:t,children:n}=s,[r,a]=j.useState(null);return e.jsx(lts,{scope:t,anchor:r,onAnchorChange:a,children:n})};ijt.displayName=SUe;var ojt="PopperAnchor",ljt=j.forwardRef((s,t)=>{const{__scopePopper:n,virtualRef:r,...a}=s,i=ajt(ojt,n),l=j.useRef(null),o=ko(t,l);return j.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||l.current)}),r?null:e.jsx(Ua.div,{...a,ref:o})});ljt.displayName=ojt;var CUe="PopperContent",[cts,dts]=rjt(CUe),cjt=j.forwardRef((s,t)=>{var Se,Ee,Le,De,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:p="optimized",onPlaced:x,...y}=s,g=ajt(CUe,n),[b,v]=j.useState(null),k=ko(t,Ge=>v(Ge)),[C,T]=j.useState(null),M=iJ(C),P=(M==null?void 0:M.width)??0,L=(M==null?void 0:M.height)??0,I=r+(i!=="center"?"-"+i:""),O=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},$=Array.isArray(d)?d:[d],q=$.length>0,W={padding:O,boundary:$.filter(hts),altBoundary:q},{refs:G,floatingStyles:K,placement:ee,isPositioned:J,middlewareData:le}=Xes({strategy:"fixed",placement:I,whileElementsMounted:(...Ge)=>qes(...Ge,{animationFrame:p==="always"}),elements:{reference:g.anchor},middleware:[Jes({mainAxis:a+L,alignmentAxis:l}),c&&ets({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?tts():void 0,...W}),c&&sts({...W}),nts({...W,apply:({elements:Ge,rects:_e,availableWidth:Oe,availableHeight:Ae})=>{const{width:Xe,height:Ue}=_e.reference,Ze=Ge.floating.style;Ze.setProperty("--radix-popper-available-width",`${Oe}px`),Ze.setProperty("--radix-popper-available-height",`${Ae}px`),Ze.setProperty("--radix-popper-anchor-width",`${Xe}px`),Ze.setProperty("--radix-popper-anchor-height",`${Ue}px`)}}),C&&ats({element:C,padding:o}),mts({arrowWidth:P,arrowHeight:L}),m&&rts({strategy:"referenceHidden",...W})]}),[ue,oe]=hjt(ee),ie=gf(x);Nf(()=>{J&&(ie==null||ie())},[J,ie]);const de=(Se=le.arrow)==null?void 0:Se.x,we=(Ee=le.arrow)==null?void 0:Ee.y,je=((Le=le.arrow)==null?void 0:Le.centerOffset)!==0,[xe,fe]=j.useState();return Nf(()=>{b&&fe(window.getComputedStyle(b).zIndex)},[b]),e.jsx("div",{ref:G.setFloating,"data-radix-popper-content-wrapper":"",style:{...K,transform:J?K.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:xe,"--radix-popper-transform-origin":[(De=le.transformOrigin)==null?void 0:De.x,(Be=le.transformOrigin)==null?void 0:Be.y].join(" "),...((Ne=le.hide)==null?void 0:Ne.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(cts,{scope:n,placedSide:ue,onArrowChange:T,arrowX:de,arrowY:we,shouldHideArrow:je,children:e.jsx(Ua.div,{"data-side":ue,"data-align":oe,...y,ref:k,style:{...y.style,animation:J?void 0:"none"}})})})});cjt.displayName=CUe;var djt="PopperArrow",uts={top:"bottom",right:"left",bottom:"top",left:"right"},ujt=j.forwardRef(function(t,n){const{__scopePopper:r,...a}=t,i=dts(djt,r),l=uts[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(ots,{...a,ref:n,style:{...a.style,display:"block"}})})});ujt.displayName=djt;function hts(s){return s!==null}var mts=s=>({name:"transformOrigin",options:s,fn(t){var g,b,v;const{placement:n,rects:r,middlewareData:a}=t,l=((g=a.arrow)==null?void 0:g.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,u]=hjt(n),h={start:"0%",center:"50%",end:"100%"}[u],m=(((b=a.arrow)==null?void 0:b.x)??0)+o/2,p=(((v=a.arrow)==null?void 0:v.y)??0)+c/2;let x="",y="";return d==="bottom"?(x=l?h:`${m}px`,y=`${-c}px`):d==="top"?(x=l?h:`${m}px`,y=`${r.floating.height+c}px`):d==="right"?(x=`${-c}px`,y=l?h:`${p}px`):d==="left"&&(x=`${r.floating.width+c}px`,y=l?h:`${p}px`),{data:{x,y}}}});function hjt(s){const[t,n="center"]=s.split("-");return[t,n]}var oJ=ijt,FU=ljt,lJ=cjt,cJ=ujt,[z4e,Yzn]=Zm("Tooltip",[rS]),B4e=rS(),mjt="TooltipProvider",pts=700,iDe="tooltip.open",[fts,AUe]=z4e(mjt),pjt=s=>{const{__scopeTooltip:t,delayDuration:n=pts,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:i}=s,l=j.useRef(!0),o=j.useRef(!1),c=j.useRef(0);return j.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(fts,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:j.useCallback(()=>{window.clearTimeout(c.current),l.current=!1},[]),onClose:j.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,r)},[r]),isPointerInTransitRef:o,onPointerInTransitChange:j.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})};pjt.displayName=mjt;var UY="Tooltip",[xts,$4e]=z4e(UY),fjt=s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=AUe(UY,s.__scopeTooltip),d=B4e(t),[u,h]=j.useState(null),m=Cx(),p=j.useRef(0),x=l??c.disableHoverableContent,y=o??c.delayDuration,g=j.useRef(!1),[b,v]=Mx({prop:r,defaultProp:a??!1,onChange:P=>{P?(c.onOpen(),document.dispatchEvent(new CustomEvent(iDe))):c.onClose(),i==null||i(P)},caller:UY}),k=j.useMemo(()=>b?g.current?"delayed-open":"instant-open":"closed",[b]),C=j.useCallback(()=>{window.clearTimeout(p.current),p.current=0,g.current=!1,v(!0)},[v]),T=j.useCallback(()=>{window.clearTimeout(p.current),p.current=0,v(!1)},[v]),M=j.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{g.current=!0,v(!0),p.current=0},y)},[y,v]);return j.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),e.jsx(oJ,{...d,children:e.jsx(xts,{scope:t,contentId:m,open:b,stateAttribute:k,trigger:u,onTriggerChange:h,onTriggerEnter:j.useCallback(()=>{c.isOpenDelayedRef.current?M():C()},[c.isOpenDelayedRef,M,C]),onTriggerLeave:j.useCallback(()=>{x?T():(window.clearTimeout(p.current),p.current=0)},[T,x]),onOpen:C,onClose:T,disableHoverableContent:x,children:n})})};fjt.displayName=UY;var oDe="TooltipTrigger",xjt=j.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=$4e(oDe,n),i=AUe(oDe,n),l=B4e(n),o=j.useRef(null),c=ko(t,o,a.onTriggerChange),d=j.useRef(!1),u=j.useRef(!1),h=j.useCallback(()=>d.current=!1,[]);return j.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),e.jsx(FU,{asChild:!0,...l,children:e.jsx(Ua.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:c,onPointerMove:ua(s.onPointerMove,m=>{m.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:ua(s.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:ua(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:ua(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:ua(s.onBlur,a.onClose),onClick:ua(s.onClick,a.onClose)})})});xjt.displayName=oDe;var gts="TooltipPortal",[Zzn,yts]=z4e(gts,{forceMount:void 0}),p$="TooltipContent",gjt=j.forwardRef((s,t)=>{const n=yts(p$,s.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...i}=s,l=$4e(p$,s.__scopeTooltip);return e.jsx(ax,{present:r||l.open,children:l.disableHoverableContent?e.jsx(yjt,{side:a,...i,ref:t}):e.jsx(vts,{side:a,...i,ref:t})})}),vts=j.forwardRef((s,t)=>{const n=$4e(p$,s.__scopeTooltip),r=AUe(p$,s.__scopeTooltip),a=j.useRef(null),i=ko(t,a),[l,o]=j.useState(null),{trigger:c,onClose:d}=n,u=a.current,{onPointerInTransitChange:h}=r,m=j.useCallback(()=>{o(null),h(!1)},[h]),p=j.useCallback((x,y)=>{const g=x.currentTarget,b={x:x.clientX,y:x.clientY},v=Nts(b,g.getBoundingClientRect()),k=kts(b,v),C=Sts(y.getBoundingClientRect()),T=Ats([...k,...C]);o(T),h(!0)},[h]);return j.useEffect(()=>()=>m(),[m]),j.useEffect(()=>{if(c&&u){const x=g=>p(g,u),y=g=>p(g,c);return c.addEventListener("pointerleave",x),u.addEventListener("pointerleave",y),()=>{c.removeEventListener("pointerleave",x),u.removeEventListener("pointerleave",y)}}},[c,u,p,m]),j.useEffect(()=>{if(l){const x=y=>{const g=y.target,b={x:y.clientX,y:y.clientY},v=(c==null?void 0:c.contains(g))||(u==null?void 0:u.contains(g)),k=!Cts(b,l);v?m():k&&(m(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[c,u,l,d,m]),e.jsx(yjt,{...s,ref:i})}),[bts,_ts]=z4e(UY,{isInside:!1}),wts=b_t("TooltipContent"),yjt=j.forwardRef((s,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=$4e(p$,n),d=B4e(n),{onClose:u}=c;return j.useEffect(()=>(document.addEventListener(iDe,u),()=>document.removeEventListener(iDe,u)),[u]),j.useEffect(()=>{if(c.trigger){const h=m=>{const p=m.target;p!=null&&p.contains(c.trigger)&&u()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[c.trigger,u]),e.jsx(ZE,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:h=>h.preventDefault(),onDismiss:u,children:e.jsxs(lJ,{"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(wts,{children:r}),e.jsx(bts,{scope:n,isInside:!0,children:e.jsx(lXt,{id:c.contentId,role:"tooltip",children:a||r})})]})})});gjt.displayName=p$;var vjt="TooltipArrow",jts=j.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=B4e(n);return _ts(vjt,n).isInside?null:e.jsx(cJ,{...a,...r,ref:t})});jts.displayName=vjt;function Nts(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 kts(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 Sts(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 Cts(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 Ats(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),Tts(t)}function Tts(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 Ets=pjt,Mts=fjt,Lts=xjt,bjt=gjt;const RN=Ets,Cu=Mts,Au=Lts,ou=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(bjt,{ref:r,sideOffset:t,className:Et("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}));ou.displayName=bjt.displayName;var zU=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(){}},kD=typeof window>"u"||"Deno"in globalThis;function Bv(){}function Pts(s,t){return typeof s=="function"?s(t):s}function lDe(s){return typeof s=="number"&&s>=0&&s!==1/0}function _jt(s,t){return Math.max(s+(t||0)-Date.now(),0)}function oE(s,t){return typeof s=="function"?s(t):s}function sj(s,t){return typeof s=="function"?s(t):s}function hst(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==TUe(l,t.options))return!1}else if(!qY(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 mst(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(SD(t.options.mutationKey)!==SD(i))return!1}else if(!qY(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function TUe(s,t){return((t==null?void 0:t.queryKeyHashFn)||SD)(s)}function SD(s){return JSON.stringify(s,(t,n)=>cDe(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function qY(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(n=>qY(s[n],t[n])):!1}function wjt(s,t){if(s===t)return s;const n=pst(s)&&pst(t);if(n||cDe(s)&&cDe(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 dDe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?wjt(s,t):t}function Rts(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function Dts(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}var EUe=Symbol();function jjt(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===EUe?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function Njt(s,t){return typeof s=="function"?s(...t):!!s}var _8,IA,Yz,Gvt,Ots=(Gvt=class extends zU{constructor(){super();rs(this,_8);rs(this,IA);rs(this,Yz);Ot(this,Yz,t=>{if(!kD&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){me(this,IA)||this.setEventListener(me(this,Yz))}onUnsubscribe(){var t;this.hasListeners()||((t=me(this,IA))==null||t.call(this),Ot(this,IA,void 0))}setEventListener(t){var n;Ot(this,Yz,t),(n=me(this,IA))==null||n.call(this),Ot(this,IA,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){me(this,_8)!==t&&(Ot(this,_8,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof me(this,_8)=="boolean"?me(this,_8):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},_8=new WeakMap,IA=new WeakMap,Yz=new WeakMap,Gvt),MUe=new Ots,Zz,RA,Xz,Wvt,Fts=(Wvt=class extends zU{constructor(){super();rs(this,Zz,!0);rs(this,RA);rs(this,Xz);Ot(this,Xz,t=>{if(!kD&&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(){me(this,RA)||this.setEventListener(me(this,Xz))}onUnsubscribe(){var t;this.hasListeners()||((t=me(this,RA))==null||t.call(this),Ot(this,RA,void 0))}setEventListener(t){var n;Ot(this,Xz,t),(n=me(this,RA))==null||n.call(this),Ot(this,RA,t(this.setOnline.bind(this)))}setOnline(t){me(this,Zz)!==t&&(Ot(this,Zz,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return me(this,Zz)}},Zz=new WeakMap,RA=new WeakMap,Xz=new WeakMap,Wvt),xNe=new Fts;function uDe(){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 zts(s){return Math.min(1e3*2**s,3e4)}function kjt(s){return(s??"online")==="online"?xNe.isOnline():!0}var Sjt=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function lMe(s){return s instanceof Sjt}function Cjt(s){let t=!1,n=0,r=!1,a;const i=uDe(),l=y=>{var g;r||(m(new Sjt(y)),(g=s.abort)==null||g.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>MUe.isFocused()&&(s.networkMode==="always"||xNe.isOnline())&&s.canRun(),u=()=>kjt(s.networkMode)&&s.canRun(),h=y=>{var g;r||(r=!0,(g=s.onSuccess)==null||g.call(s,y),a==null||a(),i.resolve(y))},m=y=>{var g;r||(r=!0,(g=s.onError)==null||g.call(s,y),a==null||a(),i.reject(y))},p=()=>new Promise(y=>{var g;a=b=>{(r||d())&&y(b)},(g=s.onPause)==null||g.call(s)}).then(()=>{var y;a=void 0,r||(y=s.onContinue)==null||y.call(s)}),x=()=>{if(r)return;let y;const g=n===0?s.initialPromise:void 0;try{y=g??s.fn()}catch(b){y=Promise.reject(b)}Promise.resolve(y).then(h).catch(b=>{var M;if(r)return;const v=s.retry??(kD?0:3),k=s.retryDelay??zts,C=typeof k=="function"?k(n,b):k,T=v===!0||typeof v=="number"&&nd()?void 0:p()).then(()=>{t?m(b):x()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?x():p().then(x),i)}}var Bts=s=>setTimeout(s,0);function $ts(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=Bts;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 ng=$ts(),w8,Kvt,Ajt=(Kvt=class{constructor(){rs(this,w8)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),lDe(this.gcTime)&&Ot(this,w8,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(kD?1/0:5*60*1e3))}clearGcTimeout(){me(this,w8)&&(clearTimeout(me(this,w8)),Ot(this,w8,void 0))}},w8=new WeakMap,Kvt),Qz,j8,Zw,N8,Dy,TX,k8,P2,l4,Yvt,Uts=(Yvt=class extends Ajt{constructor(t){super();rs(this,P2);rs(this,Qz);rs(this,j8);rs(this,Zw);rs(this,N8);rs(this,Dy);rs(this,TX);rs(this,k8);Ot(this,k8,!1),Ot(this,TX,t.defaultOptions),this.setOptions(t.options),this.observers=[],Ot(this,N8,t.client),Ot(this,Zw,me(this,N8).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Ot(this,Qz,qts(this.options)),this.state=t.state??me(this,Qz),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=me(this,Dy))==null?void 0:t.promise}setOptions(t){this.options={...me(this,TX),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&me(this,Zw).remove(this)}setData(t,n){const r=dDe(this.state.data,t,this.options);return Kt(this,P2,l4).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Kt(this,P2,l4).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=me(this,Dy))==null?void 0:r.promise;return(a=me(this,Dy))==null||a.cancel(t),n?n.then(Bv).catch(Bv):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(me(this,Qz))}isActive(){return this.observers.some(t=>sj(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===EUe||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>oE(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:!_jt(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=me(this,Dy))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=me(this,Dy))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),me(this,Zw).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(me(this,Dy)&&(me(this,k8)?me(this,Dy).cancel({revert:!0}):me(this,Dy).cancelRetry()),this.scheduleGc()),me(this,Zw).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Kt(this,P2,l4).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(me(this,Dy))return me(this,Dy).continueRetry(),me(this,Dy).promise}if(t&&this.setOptions(t),!this.options.queryFn){const m=this.observers.find(p=>p.options.queryFn);m&&this.setOptions(m.options)}const r=new AbortController,a=m=>{Object.defineProperty(m,"signal",{enumerable:!0,get:()=>(Ot(this,k8,!0),r.signal)})},i=()=>{const m=jjt(this.options,n),x=(()=>{const y={client:me(this,N8),queryKey:this.queryKey,meta:this.meta};return a(y),y})();return Ot(this,k8,!1),this.options.persister?this.options.persister(m,x,this):m(x)},o=(()=>{const m={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:me(this,N8),state:this.state,fetchFn:i};return a(m),m})();(d=this.options.behavior)==null||d.onFetch(o,this),Ot(this,j8,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&Kt(this,P2,l4).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta});const c=m=>{var p,x,y,g;lMe(m)&&m.silent||Kt(this,P2,l4).call(this,{type:"error",error:m}),lMe(m)||((x=(p=me(this,Zw).config).onError)==null||x.call(p,m,this),(g=(y=me(this,Zw).config).onSettled)==null||g.call(y,this.state.data,m,this)),this.scheduleGc()};return Ot(this,Dy,Cjt({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:m=>{var p,x,y,g;if(m===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(m)}catch(b){c(b);return}(x=(p=me(this,Zw).config).onSuccess)==null||x.call(p,m,this),(g=(y=me(this,Zw).config).onSettled)==null||g.call(y,m,this.state.error,this),this.scheduleGc()},onError:c,onFail:(m,p)=>{Kt(this,P2,l4).call(this,{type:"failed",failureCount:m,error:p})},onPause:()=>{Kt(this,P2,l4).call(this,{type:"pause"})},onContinue:()=>{Kt(this,P2,l4).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),me(this,Dy).start()}},Qz=new WeakMap,j8=new WeakMap,Zw=new WeakMap,N8=new WeakMap,Dy=new WeakMap,TX=new WeakMap,k8=new WeakMap,P2=new WeakSet,l4=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,...Tjt(r.data,this.options),fetchMeta:t.meta??null};case"success":return Ot(this,j8,void 0),{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const a=t.error;return lMe(a)&&a.revert&&me(this,j8)?{...me(this,j8),fetchStatus:"idle"}:{...r,error:a,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),ng.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),me(this,Zw).notify({query:this,type:"updated",action:t})})},Yvt);function Tjt(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:kjt(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function qts(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 Uk,Zvt,Vts=(Zvt=class extends zU{constructor(t={}){super();rs(this,Uk);this.config=t,Ot(this,Uk,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??TUe(a,n);let l=this.get(i);return l||(l=new Uts({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){me(this,Uk).has(t.queryHash)||(me(this,Uk).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=me(this,Uk).get(t.queryHash);n&&(t.destroy(),n===t&&me(this,Uk).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){ng.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return me(this,Uk).get(t)}getAll(){return[...me(this,Uk).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>hst(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>hst(t,r)):n}notify(t){ng.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){ng.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){ng.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Uk=new WeakMap,Zvt),qk,Ov,S8,Vk,WC,Xvt,Hts=(Xvt=class extends Ajt{constructor(t){super();rs(this,Vk);rs(this,qk);rs(this,Ov);rs(this,S8);this.mutationId=t.mutationId,Ot(this,Ov,t.mutationCache),Ot(this,qk,[]),this.state=t.state||Ejt(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){me(this,qk).includes(t)||(me(this,qk).push(t),this.clearGcTimeout(),me(this,Ov).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Ot(this,qk,me(this,qk).filter(n=>n!==t)),this.scheduleGc(),me(this,Ov).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){me(this,qk).length||(this.state.status==="pending"?this.scheduleGc():me(this,Ov).remove(this))}continue(){var t;return((t=me(this,S8))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,u,h,m,p,x,y,g,b,v,k,C,T,M,P,L;const n=()=>{Kt(this,Vk,WC).call(this,{type:"continue"})};Ot(this,S8,Cjt({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(I,O)=>{Kt(this,Vk,WC).call(this,{type:"failed",failureCount:I,error:O})},onPause:()=>{Kt(this,Vk,WC).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>me(this,Ov).canRun(this)}));const r=this.state.status==="pending",a=!me(this,S8).canStart();try{if(r)n();else{Kt(this,Vk,WC).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=me(this,Ov).config).onMutate)==null?void 0:l.call(i,t,this));const O=await((c=(o=this.options).onMutate)==null?void 0:c.call(o,t));O!==this.state.context&&Kt(this,Vk,WC).call(this,{type:"pending",context:O,variables:t,isPaused:a})}const I=await me(this,S8).start();return await((u=(d=me(this,Ov).config).onSuccess)==null?void 0:u.call(d,I,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,I,t,this.state.context)),await((x=(p=me(this,Ov).config).onSettled)==null?void 0:x.call(p,I,null,this.state.variables,this.state.context,this)),await((g=(y=this.options).onSettled)==null?void 0:g.call(y,I,null,t,this.state.context)),Kt(this,Vk,WC).call(this,{type:"success",data:I}),I}catch(I){try{throw await((v=(b=me(this,Ov).config).onError)==null?void 0:v.call(b,I,t,this.state.context,this)),await((C=(k=this.options).onError)==null?void 0:C.call(k,I,t,this.state.context)),await((M=(T=me(this,Ov).config).onSettled)==null?void 0:M.call(T,void 0,I,this.state.variables,this.state.context,this)),await((L=(P=this.options).onSettled)==null?void 0:L.call(P,void 0,I,t,this.state.context)),I}finally{Kt(this,Vk,WC).call(this,{type:"error",error:I})}}finally{me(this,Ov).runNext(this)}}},qk=new WeakMap,Ov=new WeakMap,S8=new WeakMap,Vk=new WeakSet,WC=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),ng.batch(()=>{me(this,qk).forEach(r=>{r.onMutationUpdate(t)}),me(this,Ov).notify({mutation:this,type:"updated",action:t})})},Xvt);function Ejt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var A4,I2,EX,Qvt,Gts=(Qvt=class extends zU{constructor(t={}){super();rs(this,A4);rs(this,I2);rs(this,EX);this.config=t,Ot(this,A4,new Set),Ot(this,I2,new Map),Ot(this,EX,0)}build(t,n,r){const a=new Hts({mutationCache:this,mutationId:++Ig(this,EX)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){me(this,A4).add(t);const n=mse(t);if(typeof n=="string"){const r=me(this,I2).get(n);r?r.push(t):me(this,I2).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(me(this,A4).delete(t)){const n=mse(t);if(typeof n=="string"){const r=me(this,I2).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&me(this,I2).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=mse(t);if(typeof n=="string"){const r=me(this,I2).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=mse(t);if(typeof n=="string"){const a=(r=me(this,I2).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(){ng.batch(()=>{me(this,A4).forEach(t=>{this.notify({type:"removed",mutation:t})}),me(this,A4).clear(),me(this,I2).clear()})}getAll(){return Array.from(me(this,A4))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>mst(n,r))}findAll(t={}){return this.getAll().filter(n=>mst(t,n))}notify(t){ng.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return ng.batch(()=>Promise.all(t.map(n=>n.continue().catch(Bv))))}},A4=new WeakMap,I2=new WeakMap,EX=new WeakMap,Qvt);function mse(s){var t;return(t=s.options.scope)==null?void 0:t.id}function gNe(s){return{onFetch:(t,n)=>{var u,h,m,p,x;const r=t.options,a=(m=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:m.direction,i=((p=t.state.data)==null?void 0:p.pages)||[],l=((x=t.state.data)==null?void 0:x.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let y=!1;const g=k=>{Object.defineProperty(k,"signal",{enumerable:!0,get:()=>(t.signal.aborted?y=!0:t.signal.addEventListener("abort",()=>{y=!0}),t.signal)})},b=jjt(t.options,t.fetchOptions),v=async(k,C,T)=>{if(y)return Promise.reject();if(C==null&&k.pages.length)return Promise.resolve(k);const P=(()=>{const $={client:t.client,queryKey:t.queryKey,pageParam:C,direction:T?"backward":"forward",meta:t.options.meta};return g($),$})(),L=await b(P),{maxPages:I}=t.options,O=T?Dts:Rts;return{pages:O(k.pages,L,I),pageParams:O(k.pageParams,C,I)}};if(a&&i.length){const k=a==="backward",C=k?Mjt:hDe,T={pages:i,pageParams:l},M=C(r,T);o=await v(T,M,k)}else{const k=s??i.length;do{const C=c===0?l[0]??r.initialPageParam:hDe(r,o);if(c>0&&C==null)break;o=await v(o,C),c++}while(c{var y,g;return(g=(y=t.options).persister)==null?void 0:g.call(y,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function hDe(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 Mjt(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 Wts(s,t){return t?hDe(s,t)!=null:!1}function Kts(s,t){return!t||!s.getPreviousPageParam?!1:Mjt(s,t)!=null}var lf,DA,OA,Jz,eB,FA,tB,sB,Jvt,Yts=(Jvt=class{constructor(s={}){rs(this,lf);rs(this,DA);rs(this,OA);rs(this,Jz);rs(this,eB);rs(this,FA);rs(this,tB);rs(this,sB);Ot(this,lf,s.queryCache||new Vts),Ot(this,DA,s.mutationCache||new Gts),Ot(this,OA,s.defaultOptions||{}),Ot(this,Jz,new Map),Ot(this,eB,new Map),Ot(this,FA,0)}mount(){Ig(this,FA)._++,me(this,FA)===1&&(Ot(this,tB,MUe.subscribe(async s=>{s&&(await this.resumePausedMutations(),me(this,lf).onFocus())})),Ot(this,sB,xNe.subscribe(async s=>{s&&(await this.resumePausedMutations(),me(this,lf).onOnline())})))}unmount(){var s,t;Ig(this,FA)._--,me(this,FA)===0&&((s=me(this,tB))==null||s.call(this),Ot(this,tB,void 0),(t=me(this,sB))==null||t.call(this),Ot(this,sB,void 0))}isFetching(s){return me(this,lf).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return me(this,DA).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=me(this,lf).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=me(this,lf).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(oE(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return me(this,lf).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=me(this,lf).get(r.queryHash),i=a==null?void 0:a.state.data,l=Pts(t,i);if(l!==void 0)return me(this,lf).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(s,t,n){return ng.batch(()=>me(this,lf).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=me(this,lf).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=me(this,lf);ng.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=me(this,lf);return ng.batch(()=>(n.findAll(s).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const n={revert:!0,...t},r=ng.batch(()=>me(this,lf).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(Bv).catch(Bv)}invalidateQueries(s,t={}){return ng.batch(()=>(me(this,lf).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=ng.batch(()=>me(this,lf).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(Bv)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Bv)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=me(this,lf).build(this,t);return n.isStaleByTime(oE(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(Bv).catch(Bv)}fetchInfiniteQuery(s){return s.behavior=gNe(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(Bv).catch(Bv)}ensureInfiniteQueryData(s){return s.behavior=gNe(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return xNe.isOnline()?me(this,DA).resumePausedMutations():Promise.resolve()}getQueryCache(){return me(this,lf)}getMutationCache(){return me(this,DA)}getDefaultOptions(){return me(this,OA)}setDefaultOptions(s){Ot(this,OA,s)}setQueryDefaults(s,t){me(this,Jz).set(SD(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...me(this,Jz).values()],n={};return t.forEach(r=>{qY(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){me(this,eB).set(SD(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...me(this,eB).values()],n={};return t.forEach(r=>{qY(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...me(this,OA).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=TUe(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===EUe&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...me(this,OA).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){me(this,lf).clear(),me(this,DA).clear()}},lf=new WeakMap,DA=new WeakMap,OA=new WeakMap,Jz=new WeakMap,eB=new WeakMap,FA=new WeakMap,tB=new WeakMap,sB=new WeakMap,Jvt),W1,cd,MX,Fv,C8,nB,zA,BA,LX,rB,aB,A8,T8,$A,iB,Tu,CG,mDe,pDe,fDe,xDe,gDe,yDe,vDe,Pjt,e1t,Ljt=(e1t=class extends zU{constructor(t,n){super();rs(this,Tu);rs(this,W1);rs(this,cd);rs(this,MX);rs(this,Fv);rs(this,C8);rs(this,nB);rs(this,zA);rs(this,BA);rs(this,LX);rs(this,rB);rs(this,aB);rs(this,A8);rs(this,T8);rs(this,$A);rs(this,iB,new Set);this.options=n,Ot(this,W1,t),Ot(this,BA,null),Ot(this,zA,uDe()),this.options.experimental_prefetchInRender||me(this,zA).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&&(me(this,cd).addObserver(this),xst(me(this,cd),this.options)?Kt(this,Tu,CG).call(this):this.updateResult(),Kt(this,Tu,xDe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return bDe(me(this,cd),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return bDe(me(this,cd),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Kt(this,Tu,gDe).call(this),Kt(this,Tu,yDe).call(this),me(this,cd).removeObserver(this)}setOptions(t){const n=this.options,r=me(this,cd);if(this.options=me(this,W1).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof sj(this.options.enabled,me(this,cd))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Kt(this,Tu,vDe).call(this),me(this,cd).setOptions(this.options),n._defaulted&&!fNe(this.options,n)&&me(this,W1).getQueryCache().notify({type:"observerOptionsUpdated",query:me(this,cd),observer:this});const a=this.hasListeners();a&&gst(me(this,cd),r,this.options,n)&&Kt(this,Tu,CG).call(this),this.updateResult(),a&&(me(this,cd)!==r||sj(this.options.enabled,me(this,cd))!==sj(n.enabled,me(this,cd))||oE(this.options.staleTime,me(this,cd))!==oE(n.staleTime,me(this,cd)))&&Kt(this,Tu,mDe).call(this);const i=Kt(this,Tu,pDe).call(this);a&&(me(this,cd)!==r||sj(this.options.enabled,me(this,cd))!==sj(n.enabled,me(this,cd))||i!==me(this,$A))&&Kt(this,Tu,fDe).call(this,i)}getOptimisticResult(t){const n=me(this,W1).getQueryCache().build(me(this,W1),t),r=this.createResult(n,t);return Xts(this,r)&&(Ot(this,Fv,r),Ot(this,nB,this.options),Ot(this,C8,me(this,cd).state)),r}getCurrentResult(){return me(this,Fv)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),Reflect.get(r,a))})}trackProp(t){me(this,iB).add(t)}getCurrentQuery(){return me(this,cd)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=me(this,W1).defaultQueryOptions(t),r=me(this,W1).getQueryCache().build(me(this,W1),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Kt(this,Tu,CG).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),me(this,Fv)))}createResult(t,n){var I;const r=me(this,cd),a=this.options,i=me(this,Fv),l=me(this,C8),o=me(this,nB),d=t!==r?t.state:me(this,MX),{state:u}=t;let h={...u},m=!1,p;if(n._optimisticResults){const O=this.hasListeners(),$=!O&&xst(t,n),q=O&&gst(t,r,n,a);($||q)&&(h={...h,...Tjt(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:x,errorUpdatedAt:y,status:g}=h;p=h.data;let b=!1;if(n.placeholderData!==void 0&&p===void 0&&g==="pending"){let O;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(O=i.data,b=!0):O=typeof n.placeholderData=="function"?n.placeholderData((I=me(this,aB))==null?void 0:I.state.data,me(this,aB)):n.placeholderData,O!==void 0&&(g="success",p=dDe(i==null?void 0:i.data,O,n),m=!0)}if(n.select&&p!==void 0&&!b)if(i&&p===(l==null?void 0:l.data)&&n.select===me(this,LX))p=me(this,rB);else try{Ot(this,LX,n.select),p=n.select(p),p=dDe(i==null?void 0:i.data,p,n),Ot(this,rB,p),Ot(this,BA,null)}catch(O){Ot(this,BA,O)}me(this,BA)&&(x=me(this,BA),p=me(this,rB),y=Date.now(),g="error");const v=h.fetchStatus==="fetching",k=g==="pending",C=g==="error",T=k&&v,M=p!==void 0,L={status:g,fetchStatus:h.fetchStatus,isPending:k,isSuccess:g==="success",isError:C,isInitialLoading:T,isLoading:T,data:p,dataUpdatedAt:h.dataUpdatedAt,error:x,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:v,isRefetching:v&&!k,isLoadingError:C&&!M,isPaused:h.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:C&&M,isStale:LUe(t,n),refetch:this.refetch,promise:me(this,zA),isEnabled:sj(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const O=W=>{L.status==="error"?W.reject(L.error):L.data!==void 0&&W.resolve(L.data)},$=()=>{const W=Ot(this,zA,L.promise=uDe());O(W)},q=me(this,zA);switch(q.status){case"pending":t.queryHash===r.queryHash&&O(q);break;case"fulfilled":(L.status==="error"||L.data!==q.value)&&$();break;case"rejected":(L.status!=="error"||L.error!==q.reason)&&$();break}}return L}updateResult(){const t=me(this,Fv),n=this.createResult(me(this,cd),this.options);if(Ot(this,C8,me(this,cd).state),Ot(this,nB,this.options),me(this,C8).data!==void 0&&Ot(this,aB,me(this,cd)),fNe(n,t))return;Ot(this,Fv,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!me(this,iB).size)return!0;const l=new Set(i??me(this,iB));return this.options.throwOnError&&l.add("error"),Object.keys(me(this,Fv)).some(o=>{const c=o;return me(this,Fv)[c]!==t[c]&&l.has(c)})};Kt(this,Tu,Pjt).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Kt(this,Tu,xDe).call(this)}},W1=new WeakMap,cd=new WeakMap,MX=new WeakMap,Fv=new WeakMap,C8=new WeakMap,nB=new WeakMap,zA=new WeakMap,BA=new WeakMap,LX=new WeakMap,rB=new WeakMap,aB=new WeakMap,A8=new WeakMap,T8=new WeakMap,$A=new WeakMap,iB=new WeakMap,Tu=new WeakSet,CG=function(t){Kt(this,Tu,vDe).call(this);let n=me(this,cd).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Bv)),n},mDe=function(){Kt(this,Tu,gDe).call(this);const t=oE(this.options.staleTime,me(this,cd));if(kD||me(this,Fv).isStale||!lDe(t))return;const r=_jt(me(this,Fv).dataUpdatedAt,t)+1;Ot(this,A8,setTimeout(()=>{me(this,Fv).isStale||this.updateResult()},r))},pDe=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(me(this,cd)):this.options.refetchInterval)??!1},fDe=function(t){Kt(this,Tu,yDe).call(this),Ot(this,$A,t),!(kD||sj(this.options.enabled,me(this,cd))===!1||!lDe(me(this,$A))||me(this,$A)===0)&&Ot(this,T8,setInterval(()=>{(this.options.refetchIntervalInBackground||MUe.isFocused())&&Kt(this,Tu,CG).call(this)},me(this,$A)))},xDe=function(){Kt(this,Tu,mDe).call(this),Kt(this,Tu,fDe).call(this,Kt(this,Tu,pDe).call(this))},gDe=function(){me(this,A8)&&(clearTimeout(me(this,A8)),Ot(this,A8,void 0))},yDe=function(){me(this,T8)&&(clearInterval(me(this,T8)),Ot(this,T8,void 0))},vDe=function(){const t=me(this,W1).getQueryCache().build(me(this,W1),this.options);if(t===me(this,cd))return;const n=me(this,cd);Ot(this,cd,t),Ot(this,MX,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},Pjt=function(t){ng.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(me(this,Fv))}),me(this,W1).getQueryCache().notify({query:me(this,cd),type:"observerResultsUpdated"})})},e1t);function Zts(s,t){return sj(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function xst(s,t){return Zts(s,t)||s.state.data!==void 0&&bDe(s,t,t.refetchOnMount)}function bDe(s,t,n){if(sj(t.enabled,s)!==!1&&oE(t.staleTime,s)!=="static"){const r=typeof n=="function"?n(s):n;return r==="always"||r!==!1&&LUe(s,t)}return!1}function gst(s,t,n,r){return(s!==t||sj(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&LUe(s,n)}function LUe(s,t){return sj(t.enabled,s)!==!1&&s.isStaleByTime(oE(t.staleTime,s))}function Xts(s,t){return!fNe(s.getCurrentResult(),t)}var Qts=class extends Ljt{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:gNe()})}getOptimisticResult(s){return s.behavior=gNe(),super.getOptimisticResult(s)}fetchNextPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(s){return this.fetch({...s,meta:{fetchMore:{direction:"backward"}}})}createResult(s,t){var x,y;const{state:n}=s,r=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=r,c=(y=(x=n.fetchMeta)==null?void 0:x.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:Wts(t,n.data),hasPreviousPage:Kts(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:m,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!m}}},UA,qA,K1,T4,E3,cje,_De,t1t,Jts=(t1t=class extends zU{constructor(n,r){super();rs(this,E3);rs(this,UA);rs(this,qA);rs(this,K1);rs(this,T4);Ot(this,UA,n),this.setOptions(r),this.bindMethods(),Kt(this,E3,cje).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=me(this,UA).defaultMutationOptions(n),fNe(this.options,r)||me(this,UA).getMutationCache().notify({type:"observerOptionsUpdated",mutation:me(this,K1),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&SD(r.mutationKey)!==SD(this.options.mutationKey)?this.reset():((a=me(this,K1))==null?void 0:a.state.status)==="pending"&&me(this,K1).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=me(this,K1))==null||n.removeObserver(this)}onMutationUpdate(n){Kt(this,E3,cje).call(this),Kt(this,E3,_De).call(this,n)}getCurrentResult(){return me(this,qA)}reset(){var n;(n=me(this,K1))==null||n.removeObserver(this),Ot(this,K1,void 0),Kt(this,E3,cje).call(this),Kt(this,E3,_De).call(this)}mutate(n,r){var a;return Ot(this,T4,r),(a=me(this,K1))==null||a.removeObserver(this),Ot(this,K1,me(this,UA).getMutationCache().build(me(this,UA),this.options)),me(this,K1).addObserver(this),me(this,K1).execute(n)}},UA=new WeakMap,qA=new WeakMap,K1=new WeakMap,T4=new WeakMap,E3=new WeakSet,cje=function(){var r;const n=((r=me(this,K1))==null?void 0:r.state)??Ejt();Ot(this,qA,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},_De=function(n){ng.batch(()=>{var r,a,i,l,o,c,d,u;if(me(this,T4)&&this.hasListeners()){const h=me(this,qA).variables,m=me(this,qA).context;(n==null?void 0:n.type)==="success"?((a=(r=me(this,T4)).onSuccess)==null||a.call(r,n.data,h,m),(l=(i=me(this,T4)).onSettled)==null||l.call(i,n.data,null,h,m)):(n==null?void 0:n.type)==="error"&&((c=(o=me(this,T4)).onError)==null||c.call(o,n.error,h,m),(u=(d=me(this,T4)).onSettled)==null||u.call(d,void 0,n.error,h,m))}this.listeners.forEach(h=>{h(me(this,qA))})})},t1t),Ijt=j.createContext(void 0),as=s=>{const t=j.useContext(Ijt);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},ess=({client:s,children:t})=>(j.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(Ijt.Provider,{value:s,children:t})),Rjt=j.createContext(!1),tss=()=>j.useContext(Rjt);Rjt.Provider;function sss(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var nss=j.createContext(sss()),rss=()=>j.useContext(nss),ass=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},iss=s=>{j.useEffect(()=>{s.clearReset()},[s])},oss=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||Njt(n,[s.error,r])),lss=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))}},css=(s,t)=>s.isLoading&&s.isFetching&&!t,dss=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,yst=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function Djt(s,t,n){var h,m,p,x,y;const r=tss(),a=rss(),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",lss(l),ass(l,a),iss(a);const o=!i.getQueryCache().get(l.queryHash),[c]=j.useState(()=>new t(i,l)),d=c.getOptimisticResult(l),u=!r&&s.subscribed!==!1;if(j.useSyncExternalStore(j.useCallback(g=>{const b=u?c.subscribe(ng.batchCalls(g)):Bv;return c.updateResult(),b},[c,u]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),j.useEffect(()=>{c.setOptions(l)},[l,c]),dss(l,d))throw yst(l,c,a);if(oss({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((x=(p=i.getDefaultOptions().queries)==null?void 0:p._experimental_afterQuery)==null||x.call(p,l,d),l.experimental_prefetchInRender&&!kD&&css(d,r)){const g=o?yst(l,c,a):(y=i.getQueryCache().get(l.queryHash))==null?void 0:y.promise;g==null||g.catch(Bv).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function mt(s,t){return Djt(s,Ljt)}function vt(s,t){const n=as(),[r]=j.useState(()=>new Jts(n,s));j.useEffect(()=>{r.setOptions(s)},[r,s]);const a=j.useSyncExternalStore(j.useCallback(l=>r.subscribe(ng.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=j.useCallback((l,o)=>{r.mutate(l,o).catch(Bv)},[r]);if(a.error&&Njt(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function uss(s,t){return Djt(s,Qts)}/** * @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 VY(){return VY=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function Ojt(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function mss(){return Math.random().toString(36).substr(2,8)}function bst(s,t){return{usr:s.state,key:s.key,idx:t}}function wDe(s,t,n,r){return n===void 0&&(n=null),VY({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?BU(t):t,{state:n,key:t&&t.key||r||mss()})}function yNe(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 BU(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 pss(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=vT.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(VY({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=vT.Pop;let g=u(),b=g==null?null:g-d;d=g,c&&c({action:o,location:y.location,delta:b})}function m(g,b){o=vT.Push;let v=wDe(y.location,g,b);d=u()+1;let k=bst(v,d),C=y.createHref(v);try{l.pushState(k,"",C)}catch(T){if(T instanceof DOMException&&T.name==="DataCloneError")throw T;a.location.assign(C)}i&&c&&c({action:o,location:y.location,delta:1})}function p(g,b){o=vT.Replace;let v=wDe(y.location,g,b);d=u();let k=bst(v,d),C=y.createHref(v);l.replaceState(k,"",C),i&&c&&c({action:o,location:y.location,delta:0})}function x(g){let b=a.location.origin!=="null"?a.location.origin:a.location.href,v=typeof g=="string"?g:yNe(g);return v=v.replace(/ $/,"%20"),Bp(b,"No window.location.(origin|href) available to create URL for href: "+v),new URL(v,b)}let y={get action(){return o},get location(){return s(a,l)},listen(g){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(vst,h),c=g,()=>{a.removeEventListener(vst,h),c=null}},createHref(g){return t(a,g)},createURL:x,encodeLocation(g){let b=x(g);return{pathname:b.pathname,search:b.search,hash:b.hash}},push:m,replace:p,go(g){return l.go(g)}};return y}var _st;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(_st||(_st={}));function fss(s,t,n){return n===void 0&&(n="/"),xss(s,t,n,!1)}function xss(s,t,n,r){let a=typeof t=="string"?BU(t):t,i=f$(a.pathname||"/",n);if(i==null)return null;let l=Fjt(s);gss(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("/")&&(Bp(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=lE([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(Bp(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),Fjt(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:Nss(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 zjt(i.path))a(i,l,c)}),t}function zjt(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=zjt(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 gss(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:kss(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const yss=/^:[\w-]+$/,vss=3,bss=2,_ss=1,wss=10,jss=-2,wst=s=>s==="*";function Nss(s,t){let n=s.split("/"),r=n.length;return n.some(wst)&&(r+=jss),t&&(r+=bss),n.filter(a=>!wst(a)).reduce((a,i)=>a+(yss.test(i)?vss:i===""?_ss:wss),r)}function kss(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 Sss(s,t,n){let{routesMeta:r}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:m,isOptional:p}=u;if(m==="*"){let y=o[h]||"";l=i.slice(0,i.length-y.length).replace(/(.)\/+$/,"$1")}const x=o[h];return p&&!x?d[m]=void 0:d[m]=(x||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function Css(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Ojt(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 Ass(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Ojt(!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 f$(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 Tss(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?BU(s):s;return{pathname:n?n.startsWith("/")?n:Ess(n,t):t,search:Pss(r),hash:Iss(a)}}function Ess(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 cMe(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 Mss(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function PUe(s,t){let n=Mss(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function IUe(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=BU(s):(a=VY({},s),Bp(!a.pathname||!a.pathname.includes("?"),cMe("?","pathname","search",a)),Bp(!a.pathname||!a.pathname.includes("#"),cMe("#","pathname","hash",a)),Bp(!a.search||!a.search.includes("#"),cMe("#","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=Tss(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const lE=s=>s.join("/").replace(/\/\/+/g,"/"),Lss=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),Pss=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,Iss=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function Rss(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const Bjt=["post","put","patch","delete"];new Set(Bjt);const Dss=["get",...Bjt];new Set(Dss);/** * 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 HY(){return HY=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),j.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){r.go(d);return}let h=IUe(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:lE([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const zss=j.createContext(null);function Bss(s){let t=j.useContext(aS).outlet;return t&&j.createElement(zss.Provider,{value:s},t)}function $i(){let{matches:s}=j.useContext(aS),t=s[s.length-1];return t?t.params:{}}function V4e(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=j.useContext(Q3),{matches:a}=j.useContext(aS),{pathname:i}=$d(),l=JSON.stringify(PUe(a,r.v7_relativeSplatPath));return j.useMemo(()=>IUe(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function $ss(s,t){return Uss(s,t)}function Uss(s,t,n,r){$U()||Bp(!1);let{navigator:a}=j.useContext(Q3),{matches:i}=j.useContext(aS),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=$d(),u;if(t){var h;let g=typeof t=="string"?BU(t):t;c==="/"||(h=g.pathname)!=null&&h.startsWith(c)||Bp(!1),u=g}else u=d;let m=u.pathname||"/",p=m;if(c!=="/"){let g=c.replace(/^\//,"").split("/");p="/"+m.replace(/^\//,"").split("/").slice(g.length).join("/")}let x=fss(s,{pathname:p}),y=Wss(x&&x.map(g=>Object.assign({},g,{params:Object.assign({},o,g.params),pathname:lE([c,a.encodeLocation?a.encodeLocation(g.pathname).pathname:g.pathname]),pathnameBase:g.pathnameBase==="/"?c:lE([c,a.encodeLocation?a.encodeLocation(g.pathnameBase).pathname:g.pathnameBase])})),i,n,r);return t&&y?j.createElement(q4e.Provider,{value:{location:HY({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:vT.Pop}},y):y}function qss(){let s=Xss(),t=Rss(s)?s.status+" "+s.statusText:s instanceof Error?s.message:JSON.stringify(s),n=s instanceof Error?s.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return j.createElement(j.Fragment,null,j.createElement("h2",null,"Unexpected Application Error!"),j.createElement("h3",{style:{fontStyle:"italic"}},t),n?j.createElement("pre",{style:a},n):null,null)}const Vss=j.createElement(qss,null);class Hss extends j.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?j.createElement(aS.Provider,{value:this.props.routeContext},j.createElement(Ujt.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function Gss(s){let{routeContext:t,match:n,children:r}=s,a=j.useContext(U4e);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),j.createElement(aS.Provider,{value:t},r)}function Wss(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||Bp(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,m)=>{let p,x=!1,y=null,g=null;n&&(p=o&&h.route.id?o[h.route.id]:void 0,y=h.route.errorElement||Vss,c&&(d<0&&m===0?(x=!0,g=null):d===m&&(x=!0,g=h.route.hydrateFallbackElement||null)));let b=t.concat(l.slice(0,m+1)),v=()=>{let k;return p?k=y:x?k=g:h.route.Component?k=j.createElement(h.route.Component,null):h.route.element?k=h.route.element:k=u,j.createElement(Gss,{match:h,routeContext:{outlet:u,matches:b,isDataRoute:n!=null},children:k})};return n&&(h.route.ErrorBoundary||h.route.errorElement||m===0)?j.createElement(Hss,{location:n.location,revalidation:n.revalidation,component:y,error:p,children:v(),routeContext:{outlet:null,matches:b,isDataRoute:!0}}):v()},null)}var Vjt=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(Vjt||{}),bNe=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}(bNe||{});function Kss(s){let t=j.useContext(U4e);return t||Bp(!1),t}function Yss(s){let t=j.useContext($jt);return t||Bp(!1),t}function Zss(s){let t=j.useContext(aS);return t||Bp(!1),t}function Hjt(s){let t=Zss(),n=t.matches[t.matches.length-1];return n.route.id||Bp(!1),n.route.id}function Xss(){var s;let t=j.useContext(Ujt),n=Yss(bNe.UseRouteError),r=Hjt(bNe.UseRouteError);return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function Qss(){let{router:s}=Kss(Vjt.UseNavigateStable),t=Hjt(bNe.UseNavigateStable),n=j.useRef(!1);return qjt(()=>{n.current=!0}),j.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,HY({fromRouteId:t},i)))},[s,t])}function Jss(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function Tj(s){let{to:t,replace:n,state:r,relative:a}=s;$U()||Bp(!1);let{future:i,static:l}=j.useContext(Q3),{matches:o}=j.useContext(aS),{pathname:c}=$d(),d=Hn(),u=IUe(t,PUe(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return j.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function Gjt(s){return Bss(s.context)}function fs(s){Bp(!1)}function ens(s){let{basename:t="/",children:n=null,location:r,navigationType:a=vT.Pop,navigator:i,static:l=!1,future:o}=s;$U()&&Bp(!1);let c=t.replace(/^\/*/,"/"),d=j.useMemo(()=>({basename:c,navigator:i,static:l,future:HY({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=BU(r));let{pathname:u="/",search:h="",hash:m="",state:p=null,key:x="default"}=r,y=j.useMemo(()=>{let g=f$(u,c);return g==null?null:{location:{pathname:g,search:h,hash:m,state:p,key:x},navigationType:a}},[c,u,h,m,p,x,a]);return y==null?null:j.createElement(Q3.Provider,{value:d},j.createElement(q4e.Provider,{children:n,value:y}))}function GY(s){let{children:t,location:n}=s;return $ss(jDe(t),n)}new Promise(()=>{});function jDe(s,t){t===void 0&&(t=[]);let n=[];return j.Children.forEach(s,(r,a)=>{if(!j.isValidElement(r))return;let i=[...t,a];if(r.type===j.Fragment){n.push.apply(n,jDe(r.props.children,i));return}r.type!==fs&&Bp(!1),!r.props.index||!r.props.children||Bp(!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=jDe(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 _Ne(){return _Ne=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(n[a]=s[a]);return n}function tns(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function sns(s,t){return s.button===0&&(!t||t==="_self")&&!tns(s)}function NDe(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 nns(s,t){let n=NDe(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const rns=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],ans=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],ins="6";try{window.__reactRouterVersion=ins}catch{}const ons=j.createContext({isTransitioning:!1}),lns="startTransition",jst=y$e[lns];function cns(s){let{basename:t,children:n,future:r,window:a}=s,i=j.useRef();i.current==null&&(i.current=hss({window:a,v5Compat:!0}));let l=i.current,[o,c]=j.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=j.useCallback(h=>{d&&jst?jst(()=>c(h)):c(h)},[c,d]);return j.useLayoutEffect(()=>l.listen(u),[l,u]),j.useEffect(()=>Jss(r),[r]),j.createElement(ens,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const dns=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",uns=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Yn=j.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:h}=t,m=Wjt(t,rns),{basename:p}=j.useContext(Q3),x,y=!1;if(typeof d=="string"&&uns.test(d)&&(x=d,dns))try{let k=new URL(window.location.href),C=d.startsWith("//")?new URL(k.protocol+d):new URL(d),T=f$(C.pathname,p);C.origin===k.origin&&T!=null?d=T+C.search+C.hash:y=!0}catch{}let g=Oss(d,{relative:a}),b=mns(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function v(k){r&&r(k),k.defaultPrevented||b(k)}return j.createElement("a",_Ne({},m,{href:x||g,onClick:y||i?r:v,ref:n,target:c}))}),KC=j.forwardRef(function(t,n){let{"aria-current":r="page",caseSensitive:a=!1,className:i="",end:l=!1,style:o,to:c,viewTransition:d,children:u}=t,h=Wjt(t,ans),m=V4e(c,{relative:h.relative}),p=$d(),x=j.useContext($jt),{navigator:y,basename:g}=j.useContext(Q3),b=x!=null&&pns(m)&&d===!0,v=y.encodeLocation?y.encodeLocation(m).pathname:m.pathname,k=p.pathname,C=x&&x.navigation&&x.navigation.location?x.navigation.location.pathname:null;a||(k=k.toLowerCase(),C=C?C.toLowerCase():null,v=v.toLowerCase()),C&&g&&(C=f$(C,g)||C);const T=v!=="/"&&v.endsWith("/")?v.length-1:v.length;let M=k===v||!l&&k.startsWith(v)&&k.charAt(T)==="/",P=C!=null&&(C===v||!l&&C.startsWith(v)&&C.charAt(v.length)==="/"),L={isActive:M,isPending:P,isTransitioning:b},I=M?r:void 0,O;typeof i=="function"?O=i(L):O=[i,M?"active":null,P?"pending":null,b?"transitioning":null].filter(Boolean).join(" ");let $=typeof o=="function"?o(L):o;return j.createElement(Yn,_Ne({},h,{"aria-current":I,className:O,ref:n,style:$,to:c,viewTransition:d}),typeof u=="function"?u(L):u)});var kDe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(kDe||(kDe={}));var Nst;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(Nst||(Nst={}));function hns(s){let t=j.useContext(U4e);return t||Bp(!1),t}function mns(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Hn(),d=$d(),u=V4e(s,{relative:l});return j.useCallback(h=>{if(sns(h,n)){h.preventDefault();let m=r!==void 0?r:yNe(d)===yNe(u);c(s,{replace:m,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function dc(s){let t=j.useRef(NDe(s)),n=j.useRef(!1),r=$d(),a=j.useMemo(()=>nns(r.search,n.current?null:t.current),[r.search]),i=Hn(),l=j.useCallback((o,c)=>{const d=NDe(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function pns(s,t){t===void 0&&(t={});let n=j.useContext(ons);n==null&&Bp(!1);let{basename:r}=hns(kDe.useViewTransitionState),a=V4e(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=f$(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=f$(n.nextLocation.pathname,r)||n.nextLocation.pathname;return vNe(a.pathname,l)!=null||vNe(a.pathname,i)!=null}var fns=typeof Element<"u",xns=typeof Map=="function",gns=typeof Set=="function",yns=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function dje(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(!dje(s[r],t[r]))return!1;return!0}var i;if(xns&&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(!dje(r.value[1],t.get(r.value[0])))return!1;return!0}if(gns&&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(yns&&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(fns&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!dje(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var vns=function(t,n){try{return dje(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 bns=sd(vns);var _ns=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}},wns=_ns;const kst=sd(wns);var jns=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))(Kjt||{}),dMe={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"]}},Sst=Object.values(Kjt),RUe={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},kns=Object.entries(RUe).reduce((s,[t,n])=>(s[n]=t,s),{}),lN="data-rh",vz={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},bz=(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},Sns=s=>{let t=bz(s,"title");const n=bz(s,vz.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=bz(s,vz.DEFAULT_TITLE);return t||r||void 0},Cns=s=>bz(s,vz.ON_CHANGE_CLIENT_STATE)||(()=>{}),uMe=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),Ans=(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),dH=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&Tns(`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:Ans(["href"],s),bodyAttributes:uMe("bodyAttributes",s),defer:bz(s,vz.DEFER),encode:bz(s,vz.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:uMe("htmlAttributes",s),linkTags:dH("link",["rel","href"],s),metaTags:dH("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:dH("noscript",["innerHTML"],s),onChangeClientState:Cns(s),scriptTags:dH("script",["src","innerHTML"],s),styleTags:dH("style",["cssText"],s),title:Sns(s),titleAttributes:uMe("titleAttributes",s),prioritizeSeoTags:Ens(s,vz.PRIORITIZE_SEO_TAGS)}),Yjt=s=>Array.isArray(s)?s.join(""):s,Lns=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(Lns(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},Cst=(s,t)=>({...s,[t]:void 0}),Pns=["noscript","script","style"],SDe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),Zjt=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),Ins=(s,t,n,r)=>{const a=Zjt(n),i=Yjt(t);return a?`<${s} ${lN}="true" ${a}>${SDe(i,r)}`:`<${s} ${lN}="true">${SDe(i,r)}`},Rns=(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}="${SDe(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=Pns.indexOf(s)===-1;return`${r}<${s} ${lN}="true" ${l}${c?"/>":`>${o}`}`},""),Xjt=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=RUe[r];return n[a||r]=s[r],n},t),Dns=(s,t,n)=>{const r={key:t,[lN]:!0},a=Xjt(n,r);return[Lt.createElement("title",a,t)]},uje=(s,t)=>t.map((n,r)=>{const a={key:r,[lN]:!0};return Object.keys(n).forEach(i=>{const o=RUe[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),Lt.createElement(s,a)}),Yw=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>Dns(s,t.title,t.titleAttributes),toString:()=>Ins(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>Xjt(t),toString:()=>Zjt(t)};default:return{toComponent:()=>uje(s,t),toString:()=>Rns(s,t,n)}}},Ons=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=hMe(s,dMe.meta),i=hMe(t,dMe.link),l=hMe(n,dMe.script);return{priorityMethods:{toComponent:()=>[...uje("meta",a.priority),...uje("link",i.priority),...uje("script",l.priority)],toString:()=>`${Yw("meta",a.priority,r)} ${Yw("link",i.priority,r)} ${Yw("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},Fns=s=>{const{baseTag:t,bodyAttributes:n,encode:r=!0,htmlAttributes:a,noscriptTags:i,styleTags:l,title:o="",titleAttributes:c,prioritizeSeoTags:d}=s;let{linkTags:u,metaTags:h,scriptTags:m}=s,p={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:p,linkTags:u,metaTags:h,scriptTags:m}=Ons(s)),{priority:p,base:Yw("base",t,r),bodyAttributes:Yw("bodyAttributes",n,r),htmlAttributes:Yw("htmlAttributes",a,r),link:Yw("link",u,r),meta:Yw("meta",h,r),noscript:Yw("noscript",i,r),script:Yw("script",m,r),style:Yw("style",l,r),title:Yw("title",{title:o,titleAttributes:c},r)}},CDe=Fns,pse=[],Qjt=!!(typeof window<"u"&&window.document&&window.document.createElement),ADe=class{constructor(s,t){Ar(this,"instances",[]);Ar(this,"canUseDOM",Qjt);Ar(this,"context");Ar(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?pse:this.instances,add:s=>{(this.canUseDOM?pse:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?pse:this.instances).indexOf(s);(this.canUseDOM?pse:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=CDe({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},zns={},Jjt=Lt.createContext(zns),E8,e2t=(E8=class extends j.Component{constructor(n){super(n);Ar(this,"helmetData");this.helmetData=new ADe(this.props.context||{},E8.canUseDOM)}render(){return Lt.createElement(Jjt.Provider,{value:this.helmetData.value},this.props.children)}},Ar(E8,"canUseDOM",Qjt),E8),LF=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${lN}]`),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(lN,"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}},TDe=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(lN),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(lN):n.getAttribute(lN)!==l.join(",")&&n.setAttribute(lN,l.join(","))},Bns=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=Yjt(s)),TDe("title",t)},Ast=(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;TDe("body",r),TDe("html",a),Bns(h,m);const p={baseTag:LF("base",n),linkTags:LF("link",i),metaTags:LF("meta",l),noscriptTags:LF("noscript",o),scriptTags:LF("script",d),styleTags:LF("style",u)},x={},y={};Object.keys(p).forEach(g=>{const{newTags:b,oldTags:v}=p[g];b.length&&(x[g]=b),v.length&&(y[g]=p[g].oldTags)}),t&&t(),c(s,x,y)},uH=null,$ns=s=>{uH&&cancelAnimationFrame(uH),s.defer?uH=requestAnimationFrame(()=>{Ast(s,()=>{uH=null})}):(Ast(s),uH=null)},Uns=$ns,Tst=class extends j.Component{constructor(){super(...arguments);Ar(this,"rendered",!1)}shouldComponentUpdate(t){return!Nns(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=Mns(t.get().map(i=>{const l={...i.props};return delete l.context,l}));e2t.canUseDOM?Uns(a):CDe&&(r=CDe(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}},sRe,ql=(sRe=class extends j.Component{shouldComponentUpdate(s){return!bns(Cst(this.props,"helmetData"),Cst(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 kst(Sst.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 ${Sst.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),kst(!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 Lt.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[kns[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 ADe)){const a=r;r=new ADe(a.context,!0),delete n.helmetData}return r?Lt.createElement(Tst,{...n,context:r.value}):Lt.createElement(Jjt.Consumer,null,a=>Lt.createElement(Tst,{...n,context:a}))}},Ar(sRe,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),sRe);const qns=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Mi(async()=>{const{default:r}=await Promise.resolve().then(()=>UU);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class DUe extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class Vns extends DUe{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class Hns extends DUe{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class Gns extends DUe{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var EDe;(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"})(EDe||(EDe={}));var Wns=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 Kns{constructor(t,{headers:n={},customFetch:r,region:a=EDe.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=qns(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return Wns(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:l}=n;let o={},{region:c}=n;c||(c=this.region),c&&c!=="any"&&(o["x-region"]=c);let d;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)&&(typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",d=l):typeof l=="string"?(o["Content-Type"]="text/plain",d=l):typeof FormData<"u"&&l instanceof FormData?d=l:(o["Content-Type"]="application/json",d=JSON.stringify(l)));const u=yield this.fetch(`${this.url}/${t}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),a),body:d}).catch(x=>{throw new Vns(x)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new Hns(u);if(!u.ok)throw new Gns(u);let m=((r=u.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),p;return m==="application/json"?p=yield u.json():m==="application/octet-stream"?p=yield u.blob():m==="text/event-stream"?p=u:m==="multipart/form-data"?p=yield u.formData():p=yield u.text(),{data:p,error:null}}catch(a){return{data:null,error:a}}})}}var nb={},OUe={},H4e={},dJ={},G4e={},W4e={},Yns=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")},x$=Yns();const Zns=x$.fetch,t2t=x$.fetch.bind(x$),s2t=x$.Headers,Xns=x$.Request,Qns=x$.Response,UU=Object.freeze(Object.defineProperty({__proto__:null,Headers:s2t,Request:Xns,Response:Qns,default:t2t,fetch:Zns},Symbol.toStringTag,{value:"Module"})),Jns=oKt(UU);var K4e={};Object.defineProperty(K4e,"__esModule",{value:!0});let ers=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};K4e.default=ers;var n2t=Xf&&Xf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(W4e,"__esModule",{value:!0});const trs=n2t(Jns),srs=n2t(K4e);let nrs=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=trs.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,n){return this.headers=Object.assign({},this.headers),this.headers[t]=n,this}then(t,n){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let a=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var l,o,c;let d=null,u=null,h=null,m=i.status,p=i.statusText;if(i.ok){if(this.method!=="HEAD"){const b=await i.text();b===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=b:u=JSON.parse(b))}const y=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),g=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");y&&g&&g.length>1&&(h=parseInt(g[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(d={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,h=null,m=406,p="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const y=await i.text();try{d=JSON.parse(y),Array.isArray(d)&&i.status===404&&(u=[],d=null,m=200,p="OK")}catch{i.status===404&&y===""?(m=204,p="No Content"):d={message:y}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,m=200,p="OK"),d&&this.shouldThrowOnError)throw new srs.default(d)}return{error:d,data:u,count:h,status:m,statusText:p}});return this.shouldThrowOnError||(a=a.catch(i=>{var l,o,c;return{error:{message:`${(l=i==null?void 0:i.name)!==null&&l!==void 0?l:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(o=i==null?void 0:i.stack)!==null&&o!==void 0?o:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),a.then(t,n)}returns(){return this}overrideTypes(){return this}};W4e.default=nrs;var rrs=Xf&&Xf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(G4e,"__esModule",{value:!0});const ars=rrs(W4e);let irs=class extends ars.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}};G4e.default=irs;var ors=Xf&&Xf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(dJ,"__esModule",{value:!0});const lrs=ors(G4e);let crs=class extends lrs.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}};dJ.default=crs;var drs=Xf&&Xf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(H4e,"__esModule",{value:!0});const hH=drs(dJ);let urs=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 hH.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 hH.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 hH.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 hH.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 hH.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};H4e.default=urs;var Y4e={},Z4e={};Object.defineProperty(Z4e,"__esModule",{value:!0});Z4e.version=void 0;Z4e.version="0.0.0-automated";Object.defineProperty(Y4e,"__esModule",{value:!0});Y4e.DEFAULT_HEADERS=void 0;const hrs=Z4e;Y4e.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${hrs.version}`};var r2t=Xf&&Xf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(OUe,"__esModule",{value:!0});const mrs=r2t(H4e),prs=r2t(dJ),frs=Y4e;let xrs=class a2t{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},frs.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new mrs.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new a2t(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 prs.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};OUe.default=xrs;var qU=Xf&&Xf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(nb,"__esModule",{value:!0});nb.PostgrestError=nb.PostgrestBuilder=nb.PostgrestTransformBuilder=nb.PostgrestFilterBuilder=nb.PostgrestQueryBuilder=nb.PostgrestClient=void 0;const i2t=qU(OUe);nb.PostgrestClient=i2t.default;const o2t=qU(H4e);nb.PostgrestQueryBuilder=o2t.default;const l2t=qU(dJ);nb.PostgrestFilterBuilder=l2t.default;const c2t=qU(G4e);nb.PostgrestTransformBuilder=c2t.default;const d2t=qU(W4e);nb.PostgrestBuilder=d2t.default;const u2t=qU(K4e);nb.PostgrestError=u2t.default;var grs=nb.default={PostgrestClient:i2t.default,PostgrestQueryBuilder:o2t.default,PostgrestFilterBuilder:l2t.default,PostgrestTransformBuilder:c2t.default,PostgrestBuilder:d2t.default,PostgrestError:u2t.default};const{PostgrestClient:yrs,PostgrestQueryBuilder:nBn,PostgrestFilterBuilder:rBn,PostgrestTransformBuilder:aBn,PostgrestBuilder:iBn,PostgrestError:oBn}=grs;let MDe;typeof window>"u"?MDe=require("ws"):MDe=window.WebSocket;const vrs=MDe,brs="2.11.10",_rs={"X-Client-Info":`realtime-js/${brs}`},wrs="1.0.0",h2t=1e4,jrs=1e3;var _z;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(_z||(_z={}));var Rv;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(Rv||(Rv={}));var Y2;(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"})(Y2||(Y2={}));var LDe;(function(s){s.websocket="websocket"})(LDe||(LDe={}));var VI;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(VI||(VI={}));class Nrs{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 m2t{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 Ih;(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"})(Ih||(Ih={}));const Est=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=krs(l,s,t,a),i),{})},krs=(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)?p2t(i,l):PDe(l)},p2t=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return Trs(t,n)}switch(s){case Ih.bool:return Srs(t);case Ih.float4:case Ih.float8:case Ih.int2:case Ih.int4:case Ih.int8:case Ih.numeric:case Ih.oid:return Crs(t);case Ih.json:case Ih.jsonb:return Ars(t);case Ih.timestamp:return Ers(t);case Ih.abstime:case Ih.date:case Ih.daterange:case Ih.int4range:case Ih.int8range:case Ih.money:case Ih.reltime:case Ih.text:case Ih.time:case Ih.timestamptz:case Ih.timetz:case Ih.tsrange:case Ih.tstzrange:return PDe(t);default:return PDe(t)}},PDe=s=>s,Srs=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Crs=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},Ars=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},Trs=(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=>p2t(t,o))}return s},Ers=s=>typeof s=="string"?s.replace(" ","T"):s,f2t=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class mMe{constructor(t,n,r={},a=h2t){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 Mst;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Mst||(Mst={}));class wK{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=wK.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=wK.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=wK.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(g=>g.presence_ref),p=h.map(g=>g.presence_ref),x=u.filter(g=>p.indexOf(g.presence_ref)<0),y=h.filter(g=>m.indexOf(g.presence_ref)<0);x.length>0&&(o[d]=x),y.length>0&&(c[d]=y)}else o[d]=u}),this.syncDiff(i,{joins:o,leaves:c},r,a)}static syncDiff(t,n,r,a){const{joins:i,leaves:l}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const u=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),u.length>0){const h=t[o].map(p=>p.presence_ref),m=u.filter(p=>h.indexOf(p.presence_ref)<0);t[o].unshift(...m)}r(o,u,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const u=c.map(h=>h.presence_ref);d=d.filter(h=>u.indexOf(h.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const a=t[r];return"metas"in a?n[r]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):n[r]=a,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var Lst;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Lst||(Lst={}));var Pst;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(Pst||(Pst={}));var f4;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(f4||(f4={}));class FUe{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=Rv.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 mMe(this,Y2.join,this.params,this.timeout),this.rejoinTimer=new m2t(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Rv.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=Rv.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Rv.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Rv.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Y2.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new wK(this),this.broadcastEndpointURL=f2t(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(f4.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(f4.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(f4.SUBSCRIBED);return}else{const m=this.bindings.postgres_changes,p=(h=m==null?void 0:m.length)!==null&&h!==void 0?h:0,x=[];for(let y=0;y{this.state=Rv.errored,t==null||t(f4.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(f4.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=Rv.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Y2.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new mMe(this,Y2.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 mMe(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}=Y2;if(r&&[o,c,d,u].indexOf(l)>=0&&r!==this._joinRef())return;let m=this._onMessage(l,n,r);if(n&&!m)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(l)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(p=>{var x,y,g;return((x=p.filter)===null||x===void 0?void 0:x.event)==="*"||((g=(y=p.filter)===null||y===void 0?void 0:y.event)===null||g===void 0?void 0:g.toLocaleLowerCase())===l}).map(p=>p.callback(m,r)):(i=this.bindings[l])===null||i===void 0||i.filter(p=>{var x,y,g,b,v,k;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in p){const C=p.id,T=(x=p.filter)===null||x===void 0?void 0:x.event;return C&&((y=n.ids)===null||y===void 0?void 0:y.includes(C))&&(T==="*"||(T==null?void 0:T.toLocaleLowerCase())===((g=n.data)===null||g===void 0?void 0:g.type.toLocaleLowerCase()))}else{const C=(v=(b=p==null?void 0:p.filter)===null||b===void 0?void 0:b.event)===null||v===void 0?void 0:v.toLocaleLowerCase();return C==="*"||C===((k=n==null?void 0:n.event)===null||k===void 0?void 0:k.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===l}).map(p=>{if(typeof m=="object"&&"ids"in m){const x=m.data,{schema:y,table:g,commit_timestamp:b,type:v,errors:k}=x;m=Object.assign(Object.assign({},{schema:y,table:g,commit_timestamp:b,eventType:v,new:{},old:{},errors:k}),this._getPayloadRecords(x))}p.callback(m,r)})}_isClosed(){return this.state===Rv.closed}_isJoined(){return this.state===Rv.joined}_isJoining(){return this.state===Rv.joining}_isLeaving(){return this.state===Rv.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&&FUe.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(Y2.close,{},t)}_onError(t){this._on(Y2.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Rv.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=Est(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=Est(t.columns,t.old_record)),n}}const Ist=()=>{},Mrs=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class Lrs{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=_rs,this.params={},this.timeout=h2t,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Ist,this.ref=0,this.logger=Ist,this.conn=null,this.sendBuffer=[],this.serializer=new Nrs,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>Mi(async()=>{const{default:c}=await Promise.resolve().then(()=>UU);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${LDe.websocket}`,this.httpEndpoint=f2t(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 m2t(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=vrs),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 Prs(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:wrs}))}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 _z.connecting:return VI.Connecting;case _z.open:return VI.Open;case _z.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 FUe(`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(Y2.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(jrs,"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(Y2.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([Mrs],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class Prs{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=_z.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class zUe extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function Vg(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class Irs extends zUe{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class IDe extends zUe{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var Rrs=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 x2t=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Mi(async()=>{const{default:r}=await Promise.resolve().then(()=>UU);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Drs=()=>Rrs(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Mi(()=>Promise.resolve().then(()=>UU),void 0)).Response:Response}),RDe=s=>{if(Array.isArray(s))return s.map(n=>RDe(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]=RDe(r)}),t};var mO=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 pMe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),Ors=(s,t,n)=>mO(void 0,void 0,void 0,function*(){const r=yield Drs();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new Irs(pMe(a),s.status||500))}).catch(a=>{t(new IDe(pMe(a),a))}):t(new IDe(pMe(s),s))}),Frs=(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 uJ(s,t,n,r,a,i){return mO(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,Frs(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=>Ors(c,o,r))})})}function wNe(s,t,n,r){return mO(this,void 0,void 0,function*(){return uJ(s,"GET",t,n,r)})}function dA(s,t,n,r,a){return mO(this,void 0,void 0,function*(){return uJ(s,"POST",t,r,a,n)})}function zrs(s,t,n,r,a){return mO(this,void 0,void 0,function*(){return uJ(s,"PUT",t,r,a,n)})}function Brs(s,t,n,r){return mO(this,void 0,void 0,function*(){return uJ(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function g2t(s,t,n,r,a){return mO(this,void 0,void 0,function*(){return uJ(s,"DELETE",t,r,a,n)})}var z1=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 $rs={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Rst={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Urs{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=x2t(a)}uploadOrUpdate(t,n,r,a){return z1(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},Rst),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(Vg(i))return{data:null,error:i};throw i}})}upload(t,n,r){return z1(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return z1(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:Rst.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(Vg(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return z1(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 dA(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 zUe("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(Vg(r))return{data:null,error:r};throw r}})}update(t,n,r){return z1(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return z1(this,void 0,void 0,function*(){try{return{data:yield dA(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(Vg(a))return{data:null,error:a};throw a}})}copy(t,n,r){return z1(this,void 0,void 0,function*(){try{return{data:{path:(yield dA(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(Vg(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return z1(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield dA(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(Vg(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return z1(this,void 0,void 0,function*(){try{const a=yield dA(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(Vg(a))return{data:null,error:a};throw a}})}download(t,n){return z1(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 wNe(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(Vg(o))return{data:null,error:o};throw o}})}info(t){return z1(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield wNe(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:RDe(r),error:null}}catch(r){if(Vg(r))return{data:null,error:r};throw r}})}exists(t){return z1(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield Brs(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(Vg(r)&&r instanceof IDe){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 z1(this,void 0,void 0,function*(){try{return{data:yield g2t(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(Vg(n))return{data:null,error:n};throw n}})}list(t,n,r){return z1(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},$rs),n),{prefix:t||""});return{data:yield dA(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(Vg(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 qrs="2.7.1",Vrs={"X-Client-Info":`storage-js/${qrs}`};var PF=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 Hrs{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},Vrs),n),this.fetch=x2t(r)}listBuckets(){return PF(this,void 0,void 0,function*(){try{return{data:yield wNe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(Vg(t))return{data:null,error:t};throw t}})}getBucket(t){return PF(this,void 0,void 0,function*(){try{return{data:yield wNe(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(Vg(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return PF(this,void 0,void 0,function*(){try{return{data:yield dA(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(Vg(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return PF(this,void 0,void 0,function*(){try{return{data:yield zrs(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(Vg(r))return{data:null,error:r};throw r}})}emptyBucket(t){return PF(this,void 0,void 0,function*(){try{return{data:yield dA(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(Vg(n))return{data:null,error:n};throw n}})}deleteBucket(t){return PF(this,void 0,void 0,function*(){try{return{data:yield g2t(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(Vg(n))return{data:null,error:n};throw n}})}}class Grs extends Hrs{constructor(t,n={},r){super(t,n,r)}from(t){return new Urs(this.url,this.headers,t,this.fetch)}}const Wrs="2.49.10";let AG="";typeof Deno<"u"?AG="deno":typeof document<"u"?AG="web":typeof navigator<"u"&&navigator.product==="ReactNative"?AG="react-native":AG="node";const Krs={"X-Client-Info":`supabase-js-${AG}/${Wrs}`},Yrs={headers:Krs},Zrs={schema:"public"},Xrs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Qrs={};var Jrs=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 eas=s=>{let t;return s?t=s:typeof fetch>"u"?t=t2t:t=fetch,(...n)=>t(...n)},tas=()=>typeof Headers>"u"?s2t:Headers,sas=(s,t,n)=>{const r=eas(n),a=tas();return(i,l)=>Jrs(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 nas=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 ras(s){return s.endsWith("/")?s:s+"/"}function aas(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:()=>nas(this,void 0,void 0,function*(){return""})};return s.accessToken?m.accessToken=s.accessToken:delete m.accessToken,m}const y2t="2.69.1",C7=30*1e3,DDe=3,fMe=DDe*C7,ias="http://localhost:9999",oas="supabase.auth.token",las={"X-Client-Info":`gotrue-js/${y2t}`},ODe="X-Supabase-Api-Version",v2t={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},cas=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,das=6e5;class BUe extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function nc(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class uas extends BUe{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function has(s){return nc(s)&&s.name==="AuthApiError"}class b2t extends BUe{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class XE extends BUe{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class YC extends XE{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function mas(s){return nc(s)&&s.name==="AuthSessionMissingError"}class xMe extends XE{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class fse extends XE{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class xse extends XE{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 pas(s){return nc(s)&&s.name==="AuthImplicitGrantRedirectError"}class Dst extends XE{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 FDe extends XE{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function gMe(s){return nc(s)&&s.name==="AuthRetryableFetchError"}class Ost extends XE{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class jK extends XE{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const Fst="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),zst=` \r=`.split(""),fas=(()=>{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 Bst(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{yas(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 gas(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}xas(r,t)}}function yas(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 vas(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function _as(s){return Math.round(Date.now()/1e3)+s}function was(){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 Ek=()=>typeof window<"u"&&typeof document<"u",iM={tested:!1,writable:!1},NK=()=>{if(!Ek())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(iM.tested)return iM.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),iM.tested=!0,iM.writable=!0}catch{iM.tested=!0,iM.writable=!1}return iM.writable};function jas(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 w2t=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Mi(async()=>{const{default:r}=await Promise.resolve().then(()=>UU);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Nas=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",j2t=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},gse=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},yse=async(s,t)=>{await s.removeItem(t)};class X4e{constructor(){this.promise=new X4e.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}X4e.promiseConstructor=Promise;function yMe(s){const t=s.split(".");if(t.length!==3)throw new jK("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function Sas(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 Cas(s){return("0"+s.toString(16)).substr(-2)}function Aas(){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,Cas).join("")}async function Tas(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 Eas(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 Tas(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function IF(s,t,n=!1){const r=Aas();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await j2t(s,`${t}-code-verifier`,a);const i=await Eas(r);return[i,r===i?"plain":"s256"]}const Mas=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Las(s){const t=s.headers.get(ODe);if(!t||!t.match(Mas))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function Pas(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 Ias(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 Ras=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),Das=[502,503,504];async function $st(s){var t;if(!Nas(s))throw new FDe(TI(s),0);if(Das.includes(s.status))throw new FDe(TI(s),s.status);let n;try{n=await s.json()}catch(i){throw new b2t(TI(i),i)}let r;const a=Las(s);if(a&&a.getTime()>=v2t["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 Ost(TI(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new YC}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 Ost(TI(n),s.status,n.weak_password.reasons);throw new uas(TI(n),s.status||500,r)}const Oas=(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 Jc(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[ODe]||(i[ODe]=v2t["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 Fas(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 Fas(s,t,n,r,a,i){const l=Oas(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new FDe(TI(c),0)}if(o.ok||await $st(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await $st(c)}}function ZC(s){var t;let n=null;Uas(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=_as(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function Ust(s){const t=ZC(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 kA(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function zas(s){return{data:s,error:null}}function Bas(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=Ras(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 $as(s){return s}function Uas(s){return s.access_token&&s.refresh_token&&s.expires_in}var qas=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);a0&&(p.forEach(x=>{const y=parseInt(x.split(";")[0].split("=")[1].substring(0,1)),g=JSON.parse(x.split(";")[1].split("=")[1]);d[`${g}Page`]=y}),d.total=parseInt(m)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(nc(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await Jc(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:kA})}catch(n){if(nc(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await Jc(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:kA})}catch(r){if(nc(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await Jc(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:kA})}catch(r){if(nc(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await Jc(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(nc(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await Jc(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(nc(n))return{data:null,error:n};throw n}}}const Has={getItem:s=>NK()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{NK()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{NK()&&globalThis.localStorage.removeItem(s)}};function qst(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function Gas(){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&&NK()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class N2t extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class Was extends N2t{}async function Kas(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 Was(`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()}}))}Gas();const Yas={url:ias,storageKey:oas,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:las,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Vst(s,t,n){return await n()}class WY{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=WY.nextInstanceID,WY.nextInstanceID+=1,this.instanceID>0&&Ek()&&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({},Yas),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 Vas({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=w2t(a.fetch),this.lock=a.lock||Vst,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:Ek()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=Kas:this.lock=Vst,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:NK()?this.storage=Has:(this.memoryStorage={},this.storage=qst(this.memoryStorage)):(this.memoryStorage={},this.storage=qst(this.memoryStorage)),Ek()&&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} (${y2t}) ${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=jas(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),Ek()&&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),pas(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 nc(n)?{error:n}:{error:new b2t("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await Jc(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:ZC}),{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(nc(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var n,r,a;try{let i;if("email"in t){const{email:u,password:h,options:m}=t;let p=null,x=null;this.flowType==="pkce"&&([p,x]=await IF(this.storage,this.storageKey)),i=await Jc(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m==null?void 0:m.emailRedirectTo,body:{email:u,password:h,data:(n=m==null?void 0:m.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:p,code_challenge_method:x},xform:ZC})}else if("phone"in t){const{phone:u,password:h,options:m}=t;i=await Jc(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:ZC})}else throw new fse("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(nc(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 Jc(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:Ust})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await Jc(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:Ust})}else throw new fse("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 xMe}:(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(nc(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 gse(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await Jc(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:ZC});if(await yse(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new xMe}:(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(nc(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 Jc(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:ZC}),{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 xMe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if(nc(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 IF(this.storage,this.storageKey));const{error:h}=await Jc(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 Jc(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 fse("You must provide either an email or phone number.")}catch(o){if(nc(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 Jc(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:ZC});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(nc(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 IF(this.storage,this.storageKey)),await Jc(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:zas})}catch(i){if(nc(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 YC;const{error:a}=await Jc(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(nc(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 Jc(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 Jc(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 fse("You must provide either an email or phone number and a type")}catch(n){if(nc(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 gse(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 Jc(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:kA}):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 YC}:await Jc(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:kA})})}catch(n){if(nc(n))return mas(n)&&(await this._removeSession(),await yse(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 YC;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await IF(this.storage,this.storageKey));const{data:d,error:u}=await Jc(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:kA});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(nc(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 YC;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=yMe(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(nc(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 YC;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(nc(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!Ek())throw new xse("No browser detected.");if(t.error||t.error_description||t.error_code)throw new xse(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 Dst("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new xse("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 Dst("No code detected.");const{data:v,error:k}=await this._exchangeCodeForSession(t.code);if(k)throw k;const C=new URL(window.location.href);return C.searchParams.delete("code"),window.history.replaceState(window.history.state,"",C.toString()),{data:{session:v.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:a,access_token:i,refresh_token:l,expires_in:o,expires_at:c,token_type:d}=t;if(!i||!o||!l||!d)throw new xse("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(o);let m=u+h;c&&(m=parseInt(c));const p=m-u;p*1e3<=C7&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const x=m-h;u-x>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",x,m,u):u-x<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",x,m,u);const{data:y,error:g}=await this._getUser(i);if(g)throw g;const b={provider_token:r,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:m,refresh_token:l,token_type:d,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:b,redirectType:t.type},error:null}}catch(r){if(nc(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 gse(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&&!(has(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await yse(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=was(),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 IF(this.storage,this.storageKey,!0));try{return await Jc(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(nc(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(nc(n))return{data:null,error:n};throw n}}async linkIdentity(t){var n;try{const{data:r,error:a}=await this._useSession(async i=>{var l,o,c,d,u;const{data:h,error:m}=i;if(m)throw m;const p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(l=t.options)===null||l===void 0?void 0:l.redirectTo,scopes:(o=t.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=t.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await Jc(this.fetch,"GET",p,{headers:this.headers,jwt:(u=(d=h.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(a)throw a;return Ek()&&!(!((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(nc(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 Jc(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(nc(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 Sas(async a=>(a>0&&await kas(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await Jc(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:ZC})),(a,i)=>{const l=200*Math.pow(2,a);return i&&gMe(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(),C7);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)/C7);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${C7}ms, refresh threshold is ${DDe} ticks`),a<=DDe&&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 N2t)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ek()||!(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 IF(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 Jc(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(nc(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 Jc(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(nc(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 Jc(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(nc(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 Jc(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(nc(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}=yMe(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+das>Date.now()))return r;const{data:a,error:i}=await Jc(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 jK("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new jK("No matching signing key found in JWKS");return r}async getClaims(t,n={keys:[]}){try{let r=t;if(!r){const{data:p,error:x}=await this.getSession();if(x||!p.session)return{data:null,error:x};r=p.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=yMe(r);if(Pas(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:a,signature:l},error:null}}const d=Ias(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,bas(`${o}.${c}`)))throw new jK("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if(nc(r))return{data:null,error:r};throw r}}}WY.nextInstanceID=0;const Zas=WY;class Xas extends Zas{constructor(t){super(t)}}var Qas=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 Jas{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=ras(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:Zrs,realtime:Qrs,auth:Object.assign(Object.assign({},Xrs),{storageKey:d}),global:Yrs},h=aas(r??{},u);this.storageKey=(a=h.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(m,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=h.auth)!==null&&l!==void 0?l:{},this.headers,h.global.fetch),this.fetch=sas(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 yrs(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new Kns(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Grs(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 Qas(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 Xas({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 Lrs(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 eis=(s,t,n)=>new Jas(s,t,n),tis="https://relzejiswnotikjgvjhz.supabase.co",sis="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",U=eis(tis,sis,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),nis=Object.freeze(Object.defineProperty({__proto__:null,supabase:U},Symbol.toStringTag,{value:"Module"})),k2t=j.createContext(void 0),ris=({children:s})=>{const[t,n]=j.useState(null),[r,a]=j.useState(null),[i,l]=j.useState(!0),[o,c]=j.useState(!0),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,x]=j.useState(!1),[y,g]=j.useState(null),[b,v]=j.useState([]),[k,C]=j.useState(null),T=j.useRef(null),M=j.useRef(!1),P=j.useRef(!1),L=Hn(),I=()=>{u(!1),m(!1),x(!1),g(null),v([]),C(null),T.current=null,M.current=!1},O=async G=>{if(!(M.current&&T.current===G)&&!P.current){P.current=!0,c(!0);try{console.log("Checking roles via RPC for user:",G);const[{data:K,error:ee},{data:J,error:le},{data:ue,error:oe}]=await Promise.all([U.rpc("has_role",{_user_id:G,_role:"admin"}),U.rpc("has_role",{_user_id:G,_role:"brokerage_manager"}),U.rpc("has_role",{_user_id:G,_role:"coach"})]);if(ee||le)console.error("Role RPC errors:",{isAdminError:ee,isBrokerError:le,isCoachError:oe}),u(!1),m(!1),x(!1);else{const we=!!K,je=!!J,xe=!!ue;console.log("RPC roles result:",{adminValue:we,brokerValue:je,coachValue:xe}),u(we),m(je),x(xe)}const{data:ie,error:de}=await U.from("profiles").select("brokerage_id").eq("id",G).single();if(g(!de&&ie?ie.brokerage_id:null),J){console.log("Fetching managed brokerages for user:",G);const{data:we,error:je}=await U.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",G);if(console.log("Managed brokerage assignments result:",{assignments:we,assignmentsError:je}),je||!we){console.error("Error fetching managed brokerage assignments:",je),v([]);return}const xe=Array.from(new Set(we.map(Le=>Le.brokerage_id).filter(Boolean)));if(xe.length===0){v([]);return}const{data:fe,error:Se}=await U.from("brokerages").select("id, name").in("id",xe);if(console.log("Managed brokerages details result:",{brokeragesData:fe,brokeragesError:Se}),Se||!fe){console.error("Error fetching managed brokerages details:",Se),v([]);return}const Ee=fe.map(Le=>({id:Le.id,name:Le.name})).sort((Le,De)=>xe.indexOf(Le.id)-xe.indexOf(De.id));console.log("Parsed managed brokerages:",Ee),v(Ee),Ee.length>0&&C(Le=>Le??Ee[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),v([]);T.current=G,M.current=!0}catch(K){console.error("Unexpected error in checkRoles:",K),I()}finally{P.current=!1,c(!1)}}};j.useEffect(()=>{let G=!0,K=!1;const ee=()=>{!G||K||(K=!0,l(!1))},{data:{subscription:J}}=U.auth.onAuthStateChange((oe,ie)=>{console.log("Auth event:",oe),G&&(a(ie),n((ie==null?void 0:ie.user)??null),ee(),oe==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{L("/profile?reset=true")},100)),ie!=null&&ie.user?(!M.current||T.current!==ie.user.id)&&setTimeout(()=>{O(ie.user.id)},0):(I(),c(!1)))}),le=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),ee()},4e3);return(async()=>{try{const{data:{session:oe}}=await U.auth.getSession();if(!G)return;a(oe),n((oe==null?void 0:oe.user)??null),oe!=null&&oe.user?await O(oe.user.id):I()}catch(oe){console.error("Error restoring auth session:",oe),G&&(a(null),n(null),I())}finally{ee()}})(),()=>{G=!1,window.clearTimeout(le),J.unsubscribe()}},[]);const $=async(G,K)=>{const{error:ee}=await U.auth.signInWithPassword({email:G,password:K});if(ee)throw re.error(ee.message),ee;re.success("Welcome back!")},q=async(G,K,ee)=>{var ie;const J=`${window.location.origin}/dashboard`,le=localStorage.getItem("levelup_referral_code")||null,{data:ue,error:oe}=await U.auth.signUp({email:G,password:K,options:{emailRedirectTo:J,data:{name:ee,referred_by_code:le}}});if(oe)throw re.error(oe.message),oe;if(le&&((ie=ue.user)!=null&&ie.id))try{await U.from("profiles").update({referred_by_code:le}).eq("id",ue.user.id),localStorage.removeItem("levelup_referral_code")}catch(de){console.warn("Failed to attach referral code to profile",de)}re.success("Account created! Welcome to LevelUp."),L("/dashboard")},W=async()=>{try{const{data:{session:G}}=await U.auth.getSession();if(G){const{error:K}=await U.auth.signOut();K?K.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",K.message):(console.error("Sign out error:",K),re.error(K.message)):re.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),m(!1),g(null),v([]),C(null),L("/auth")}catch(G){console.error("Unexpected sign out error:",G),L("/auth")}};return e.jsx(k2t.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:$,signUp:q,signOut:W,isAdmin:d,isBrokerageManager:h,isCoach:p,brokerageId:y,managedBrokerages:b,selectedBrokerageId:k,setSelectedBrokerageId:C},children:s})},Ns=()=>{const s=j.useContext(k2t);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},S2t=j.createContext({onlineUsers:[],totalOnline:0}),ais=async s=>{try{const{data:t}=await U.storage.from("avatars").list(`${s}`);if(t&&t.length>0){const{data:n}=U.storage.from("avatars").getPublicUrl(`${s}/${t[0].name}`);return n.publicUrl}}catch{}},iis=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=Ns(),[a,i]=j.useState([]),[l,o]=j.useState(null);j.useEffect(()=>{if(!t)return;let d=!1;U.auth.getSession().then(({data:h})=>{var p;const m=(p=h.session)==null?void 0:p.access_token;if(m)try{U.realtime.setAuth(m)}catch{}});const u=U.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(([p,x])=>{if(x&&x.length>0){const y=x[0];m.push({id:p,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 p;if(console.log("[Presence] subscribe status:",h,m),h==="SUBSCRIBED"&&!d){const{data:x}=await U.from("profiles").select("name, brokerage_id").eq("id",t.id).maybeSingle(),y=await ais(t.id),g=await u.track({name:(x==null?void 0:x.name)||((p=t.email)==null?void 0:p.split("@")[0])||"User",avatarUrl:y,brokerageId:x==null?void 0:x.brokerage_id,onlineSince:new Date().toISOString()});console.log("[Presence] track result:",g)}}),o(u),()=>{d=!0;try{u.untrack()}catch{}U.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(S2t.Provider,{value:{onlineUsers:c,totalOnline:a.length},children:s})},C2t=()=>j.useContext(S2t),A2t=j.createContext(void 0),oM="levelup_admin_session",EC="levelup_impersonation",vMe="levelup_impersonation_return",ois=({children:s})=>{const[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1);j.useEffect(()=>{const d=sessionStorage.getItem(EC);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(EC)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await U.auth.getSession();if(!h)return re.error("No active session found"),!1;const m={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(oM,JSON.stringify(m)),u&&sessionStorage.setItem(vMe,u);const p=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({targetUserId:d})}),x=await p.json();if(!p.ok)throw new Error(x.error||"Failed to impersonate user");const y={id:x.targetUser.id,name:x.targetUser.name,email:x.targetUser.email};if(sessionStorage.setItem(EC,JSON.stringify(y)),x.method==="session"){const{error:g}=await U.auth.setSession({access_token:x.access_token,refresh_token:x.refresh_token});if(g)throw console.error("Set session error:",g),sessionStorage.removeItem(oM),sessionStorage.removeItem(EC),new Error("Failed to establish impersonation session")}else{const g=x.type||"recovery",{error:b}=await U.auth.verifyOtp({token_hash:x.token_hash,type:g});if(b)throw console.error("Verify OTP error:",b),sessionStorage.removeItem(oM),sessionStorage.removeItem(EC),new Error("Failed to establish impersonation session")}return n(!0),a(y),re.success(`Now viewing as ${y.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),re.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(oM),sessionStorage.removeItem(EC),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(oM);if(!d){await U.auth.signOut(),window.location.href="/auth";return}const u=JSON.parse(d);await U.auth.signOut();const{error:h}=await U.auth.setSession({access_token:u.access_token,refresh_token:u.refresh_token});if(sessionStorage.removeItem(oM),sessionStorage.removeItem(EC),h){console.error("Failed to restore admin session:",h),re.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),re.success("Returned to your account");const m=sessionStorage.getItem(vMe)||"/admin/members";sessionStorage.removeItem(vMe),window.location.href=m}catch(d){console.error("Stop impersonation error:",d),re.error("Failed to restore admin session"),sessionStorage.removeItem(oM),sessionStorage.removeItem(EC),window.location.href="/auth"}finally{l(!1)}};return e.jsx(A2t.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},Q4e=()=>{const s=j.useContext(A2t);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},lis=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=Q4e();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(hd,{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(Wt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(dr,{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"})]})})]})})},T2t=j.createContext(void 0),DF="levelup_acting_as",vse="levelup_acting_as_self",cis=({children:s})=>{const{user:t}=Ns(),[n,r]=j.useState(!1),[a,i]=j.useState([]),[l,o]=j.useState(null),[c,d]=j.useState({}),[u,h]=j.useState(!0),[m,p]=j.useState(()=>sessionStorage.getItem(vse)==="true");j.useEffect(()=>{if(!(t!=null&&t.id)){r(!1),i([]),o(null),d({}),h(!1);return}(async()=>{h(!0);try{const{data:k}=await U.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!k){r(!1),i([]),o(null),d({}),h(!1);return}r(!0);const{data:C,error:T}=await U.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(T||!C||C.length===0){i([]),h(!1);return}const M=C.map(I=>I.agent_id),{data:P}=await U.from("profiles").select("id, name, email, avatar_url").in("id",M),L=(P||[]).map(I=>({id:I.id,name:I.name||I.email||"Unknown",email:I.email||"",avatar_url:I.avatar_url}));if(i(L),sessionStorage.getItem(vse)==="true")p(!0),o(null),d({});else{const I=sessionStorage.getItem(DF);if(I){const O=L.find($=>$.id===I);if(O){o(O);const $=C.find(q=>q.agent_id===I);d(($==null?void 0:$.permissions)||{})}else if(L.length>0){o(L[0]);const $=C.find(q=>q.agent_id===L[0].id);d(($==null?void 0:$.permissions)||{}),sessionStorage.setItem(DF,L[0].id)}}else if(L.length>0){o(L[0]);const O=C.find($=>$.agent_id===L[0].id);d((O==null?void 0:O.permissions)||{}),sessionStorage.setItem(DF,L[0].id)}}}catch(k){console.error("Error loading assistant data:",k)}finally{h(!1)}})()},[t==null?void 0:t.id]);const x=v=>{o(v),p(!1),sessionStorage.removeItem(vse),v?(sessionStorage.setItem(DF,v.id),U.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",v.id).single().then(({data:k})=>{d((k==null?void 0:k.permissions)||{})})):(sessionStorage.removeItem(DF),d({}))},y=()=>{p(!0),o(null),d({}),sessionStorage.setItem(vse,"true"),sessionStorage.removeItem(DF)},g=v=>!n||m?!0:c[v]===!0,b=n&&l&&!m?l.id:(t==null?void 0:t.id)||null;return e.jsx(T2t.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:x,effectiveUserId:b,permissions:c,hasPermission:g,isLoading:u,isActingAsSelf:m,setActingAsSelf:y},children:s})},J4e=()=>{const s=j.useContext(T2t);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},ei=()=>{const{effectiveUserId:s}=J4e();return s};var E2t={exports:{}},M2t={};/** * @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 g$=j;function dis(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var uis=typeof Object.is=="function"?Object.is:dis,his=g$.useState,mis=g$.useEffect,pis=g$.useLayoutEffect,fis=g$.useDebugValue;function xis(s,t){var n=t(),r=his({inst:{value:n,getSnapshot:t}}),a=r[0].inst,i=r[1];return pis(function(){a.value=n,a.getSnapshot=t,bMe(a)&&i({inst:a})},[s,n,t]),mis(function(){return bMe(a)&&i({inst:a}),s(function(){bMe(a)&&i({inst:a})})},[s]),fis(n),n}function bMe(s){var t=s.getSnapshot;s=s.value;try{var n=t();return!uis(s,n)}catch{return!0}}function gis(s,t){return t()}var yis=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?gis:xis;M2t.useSyncExternalStore=g$.useSyncExternalStore!==void 0?g$.useSyncExternalStore:yis;E2t.exports=M2t;var vis=E2t.exports;function bis(){return vis.useSyncExternalStore(_is,()=>!0,()=>!1)}function _is(){return()=>{}}var $Ue="Avatar",[wis,lBn]=Zm($Ue),[jis,L2t]=wis($Ue),P2t=j.forwardRef((s,t)=>{const{__scopeAvatar:n,...r}=s,[a,i]=j.useState("idle");return e.jsx(jis,{scope:n,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(Ua.span,{...r,ref:t})})});P2t.displayName=$Ue;var I2t="AvatarImage",R2t=j.forwardRef((s,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:a=()=>{},...i}=s,l=L2t(I2t,n),o=Nis(r,i),c=gf(d=>{a(d),l.onImageLoadingStatusChange(d)});return Nf(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(Ua.img,{...i,ref:t,src:r}):null});R2t.displayName=I2t;var D2t="AvatarFallback",O2t=j.forwardRef((s,t)=>{const{__scopeAvatar:n,delayMs:r,...a}=s,i=L2t(D2t,n),[l,o]=j.useState(r===void 0);return j.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>o(!0),r);return()=>window.clearTimeout(c)}},[r]),l&&i.imageLoadingStatus!=="loaded"?e.jsx(Ua.span,{...a,ref:t}):null});O2t.displayName=D2t;function Hst(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Nis(s,{referrerPolicy:t,crossOrigin:n}){const r=bis(),a=j.useRef(null),i=r?(a.current||(a.current=new window.Image),a.current):null,[l,o]=j.useState(()=>Hst(i,s));return Nf(()=>{o(Hst(i,s))},[i,s]),Nf(()=>{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 F2t=P2t,z2t=R2t,B2t=O2t;const Ra=j.forwardRef(({className:s,...t},n)=>e.jsx(F2t,{ref:n,className:Et("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Ra.displayName=F2t.displayName;const Fi=j.forwardRef(({className:s,...t},n)=>e.jsx(z2t,{ref:n,className:Et("aspect-square h-full w-full",s),...t}));Fi.displayName=z2t.displayName;const Da=j.forwardRef(({className:s,...t},n)=>e.jsx(B2t,{ref:n,className:Et("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));Da.displayName=B2t.displayName;const kis=hO("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 qe({className:s,variant:t,...n}){return e.jsx("div",{className:Et(kis({variant:t}),s),...n})}var Sis=j.createContext(void 0);function J3(s){const t=j.useContext(Sis);return s||t||"ltr"}var _Me="rovingFocusGroup.onEntryFocus",Cis={bubbles:!1,cancelable:!0},hJ="RovingFocusGroup",[zDe,$2t,Ais]=MU(hJ),[Tis,QE]=Zm(hJ,[Ais]),[Eis,Mis]=Tis(hJ),U2t=j.forwardRef((s,t)=>e.jsx(zDe.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(zDe.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(Lis,{...s,ref:t})})}));U2t.displayName=hJ;var Lis=j.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:a=!1,dir:i,currentTabStopId:l,defaultCurrentTabStopId:o,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...h}=s,m=j.useRef(null),p=ko(t,m),x=J3(i),[y,g]=Mx({prop:l,defaultProp:o??null,onChange:c,caller:hJ}),[b,v]=j.useState(!1),k=gf(d),C=$2t(n),T=j.useRef(!1),[M,P]=j.useState(0);return j.useEffect(()=>{const L=m.current;if(L)return L.addEventListener(_Me,k),()=>L.removeEventListener(_Me,k)},[k]),e.jsx(Eis,{scope:n,orientation:r,dir:x,loop:a,currentTabStopId:y,onItemFocus:j.useCallback(L=>g(L),[g]),onItemShiftTab:j.useCallback(()=>v(!0),[]),onFocusableItemAdd:j.useCallback(()=>P(L=>L+1),[]),onFocusableItemRemove:j.useCallback(()=>P(L=>L-1),[]),children:e.jsx(Ua.div,{tabIndex:b||M===0?-1:0,"data-orientation":r,...h,ref:p,style:{outline:"none",...s.style},onMouseDown:ua(s.onMouseDown,()=>{T.current=!0}),onFocus:ua(s.onFocus,L=>{const I=!T.current;if(L.target===L.currentTarget&&I&&!b){const O=new CustomEvent(_Me,Cis);if(L.currentTarget.dispatchEvent(O),!O.defaultPrevented){const $=C().filter(ee=>ee.focusable),q=$.find(ee=>ee.active),W=$.find(ee=>ee.id===y),K=[q,W,...$].filter(Boolean).map(ee=>ee.ref.current);H2t(K,u)}}T.current=!1}),onBlur:ua(s.onBlur,()=>v(!1))})})}),q2t="RovingFocusGroupItem",V2t=j.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=Cx(),d=i||c,u=Mis(q2t,n),h=u.currentTabStopId===d,m=$2t(n),{onFocusableItemAdd:p,onFocusableItemRemove:x,currentTabStopId:y}=u;return j.useEffect(()=>{if(r)return p(),()=>x()},[r,p,x]),e.jsx(zDe.ItemSlot,{scope:n,id:d,focusable:r,active:a,children:e.jsx(Ua.span,{tabIndex:h?0:-1,"data-orientation":u.orientation,...o,ref:t,onMouseDown:ua(s.onMouseDown,g=>{r?u.onItemFocus(d):g.preventDefault()}),onFocus:ua(s.onFocus,()=>u.onItemFocus(d)),onKeyDown:ua(s.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){u.onItemShiftTab();return}if(g.target!==g.currentTarget)return;const b=Ris(g,u.orientation,u.dir);if(b!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let k=m().filter(C=>C.focusable).map(C=>C.ref.current);if(b==="last")k.reverse();else if(b==="prev"||b==="next"){b==="prev"&&k.reverse();const C=k.indexOf(g.currentTarget);k=u.loop?Dis(k,C+1):k.slice(C+1)}setTimeout(()=>H2t(k))}}),children:typeof l=="function"?l({isCurrentTabStop:h,hasTabStop:y!=null}):l})})});V2t.displayName=q2t;var Pis={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Iis(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function Ris(s,t,n){const r=Iis(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Pis[r]}function H2t(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Dis(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var e3e=U2t,t3e=V2t,BDe=["Enter"," "],Ois=["ArrowDown","PageUp","Home"],G2t=["ArrowUp","PageDown","End"],Fis=[...Ois,...G2t],zis={ltr:[...BDe,"ArrowRight"],rtl:[...BDe,"ArrowLeft"]},Bis={ltr:["ArrowLeft"],rtl:["ArrowRight"]},mJ="Menu",[KY,$is,Uis]=MU(mJ),[pO,W2t]=Zm(mJ,[Uis,rS,QE]),s3e=rS(),K2t=QE(),[qis,fO]=pO(mJ),[Vis,pJ]=pO(mJ),Y2t=s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=s3e(t),[c,d]=j.useState(null),u=j.useRef(!1),h=gf(i),m=J3(a);return j.useEffect(()=>{const p=()=>{u.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),e.jsx(oJ,{...o,children:e.jsx(qis,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(Vis,{scope:t,onClose:j.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:m,modal:l,children:r})})})};Y2t.displayName=mJ;var His="MenuAnchor",UUe=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=s3e(n);return e.jsx(FU,{...a,...r,ref:t})});UUe.displayName=His;var qUe="MenuPortal",[Gis,Z2t]=pO(qUe,{forceMount:void 0}),X2t=s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=fO(qUe,t);return e.jsx(Gis,{scope:t,forceMount:n,children:e.jsx(ax,{present:n||i.open,children:e.jsx(LU,{asChild:!0,container:a,children:r})})})};X2t.displayName=qUe;var Ej="MenuContent",[Wis,VUe]=pO(Ej),Q2t=j.forwardRef((s,t)=>{const n=Z2t(Ej,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=fO(Ej,s.__scopeMenu),l=pJ(Ej,s.__scopeMenu);return e.jsx(KY.Provider,{scope:s.__scopeMenu,children:e.jsx(ax,{present:r||i.open,children:e.jsx(KY.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(Kis,{...a,ref:t}):e.jsx(Yis,{...a,ref:t})})})})}),Kis=j.forwardRef((s,t)=>{const n=fO(Ej,s.__scopeMenu),r=j.useRef(null),a=ko(t,r);return j.useEffect(()=>{const i=r.current;if(i)return L4e(i)},[]),e.jsx(HUe,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ua(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Yis=j.forwardRef((s,t)=>{const n=fO(Ej,s.__scopeMenu);return e.jsx(HUe,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Zis=NE("MenuContent.ScrollLock"),HUe=j.forwardRef((s,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:m,onDismiss:p,disableOutsideScroll:x,...y}=s,g=fO(Ej,n),b=pJ(Ej,n),v=s3e(n),k=K2t(n),C=$is(n),[T,M]=j.useState(null),P=j.useRef(null),L=ko(t,P,g.onContentChange),I=j.useRef(0),O=j.useRef(""),$=j.useRef(0),q=j.useRef(null),W=j.useRef("right"),G=j.useRef(0),K=x?tJ:j.Fragment,ee=x?{as:Zis,allowPinchZoom:!0}:void 0,J=ue=>{var Se,Ee;const oe=O.current+ue,ie=C().filter(Le=>!Le.disabled),de=document.activeElement,we=(Se=ie.find(Le=>Le.ref.current===de))==null?void 0:Se.textValue,je=ie.map(Le=>Le.textValue),xe=los(je,oe,we),fe=(Ee=ie.find(Le=>Le.textValue===xe))==null?void 0:Ee.ref.current;(function Le(De){O.current=De,window.clearTimeout(I.current),De!==""&&(I.current=window.setTimeout(()=>Le(""),1e3))})(oe),fe&&setTimeout(()=>fe.focus())};j.useEffect(()=>()=>window.clearTimeout(I.current),[]),E4e();const le=j.useCallback(ue=>{var ie,de;return W.current===((ie=q.current)==null?void 0:ie.side)&&dos(ue,(de=q.current)==null?void 0:de.area)},[]);return e.jsx(Wis,{scope:n,searchRef:O,onItemEnter:j.useCallback(ue=>{le(ue)&&ue.preventDefault()},[le]),onItemLeave:j.useCallback(ue=>{var oe;le(ue)||((oe=P.current)==null||oe.focus(),M(null))},[le]),onTriggerLeave:j.useCallback(ue=>{le(ue)&&ue.preventDefault()},[le]),pointerGraceTimerRef:$,onPointerGraceIntentChange:j.useCallback(ue=>{q.current=ue},[]),children:e.jsx(K,{...ee,children:e.jsx(eJ,{asChild:!0,trapped:a,onMountAutoFocus:ua(i,ue=>{var oe;ue.preventDefault(),(oe=P.current)==null||oe.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(ZE,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:m,onDismiss:p,children:e.jsx(e3e,{asChild:!0,...k,dir:b.dir,orientation:"vertical",loop:r,currentTabStopId:T,onCurrentTabStopIdChange:M,onEntryFocus:ua(c,ue=>{b.isUsingKeyboardRef.current||ue.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(lJ,{role:"menu","aria-orientation":"vertical","data-state":pNt(g.open),"data-radix-menu-content":"",dir:b.dir,...v,...y,ref:L,style:{outline:"none",...y.style},onKeyDown:ua(y.onKeyDown,ue=>{const ie=ue.target.closest("[data-radix-menu-content]")===ue.currentTarget,de=ue.ctrlKey||ue.altKey||ue.metaKey,we=ue.key.length===1;ie&&(ue.key==="Tab"&&ue.preventDefault(),!de&&we&&J(ue.key));const je=P.current;if(ue.target!==je||!Fis.includes(ue.key))return;ue.preventDefault();const fe=C().filter(Se=>!Se.disabled).map(Se=>Se.ref.current);G2t.includes(ue.key)&&fe.reverse(),ios(fe)}),onBlur:ua(s.onBlur,ue=>{ue.currentTarget.contains(ue.target)||(window.clearTimeout(I.current),O.current="")}),onPointerMove:ua(s.onPointerMove,YY(ue=>{const oe=ue.target,ie=G.current!==ue.clientX;if(ue.currentTarget.contains(oe)&&ie){const de=ue.clientX>G.current?"right":"left";W.current=de,G.current=ue.clientX}}))})})})})})})});Q2t.displayName=Ej;var Xis="MenuGroup",GUe=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Ua.div,{role:"group",...r,ref:t})});GUe.displayName=Xis;var Qis="MenuLabel",J2t=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Ua.div,{...r,ref:t})});J2t.displayName=Qis;var jNe="MenuItem",Gst="menu.itemSelect",n3e=j.forwardRef((s,t)=>{const{disabled:n=!1,onSelect:r,...a}=s,i=j.useRef(null),l=pJ(jNe,s.__scopeMenu),o=VUe(jNe,s.__scopeMenu),c=ko(t,i),d=j.useRef(!1),u=()=>{const h=i.current;if(!n&&h){const m=new CustomEvent(Gst,{bubbles:!0,cancelable:!0});h.addEventListener(Gst,p=>r==null?void 0:r(p),{once:!0}),uUe(h,m),m.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(eNt,{...a,ref:c,disabled:n,onClick:ua(s.onClick,u),onPointerDown:h=>{var m;(m=s.onPointerDown)==null||m.call(s,h),d.current=!0},onPointerUp:ua(s.onPointerUp,h=>{var m;d.current||(m=h.currentTarget)==null||m.click()}),onKeyDown:ua(s.onKeyDown,h=>{const m=o.searchRef.current!=="";n||m&&h.key===" "||BDe.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});n3e.displayName=jNe;var eNt=j.forwardRef((s,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...i}=s,l=VUe(jNe,n),o=K2t(n),c=j.useRef(null),d=ko(t,c),[u,h]=j.useState(!1),[m,p]=j.useState("");return j.useEffect(()=>{const x=c.current;x&&p((x.textContent??"").trim())},[i.children]),e.jsx(KY.ItemSlot,{scope:n,disabled:r,textValue:a??m,children:e.jsx(t3e,{asChild:!0,...o,focusable:!r,children:e.jsx(Ua.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:ua(s.onPointerMove,YY(x=>{r?l.onItemLeave(x):(l.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ua(s.onPointerLeave,YY(x=>l.onItemLeave(x))),onFocus:ua(s.onFocus,()=>h(!0)),onBlur:ua(s.onBlur,()=>h(!1))})})})}),Jis="MenuCheckboxItem",tNt=j.forwardRef((s,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=s;return e.jsx(iNt,{scope:s.__scopeMenu,checked:n,children:e.jsx(n3e,{role:"menuitemcheckbox","aria-checked":NNe(n)?"mixed":n,...a,ref:t,"data-state":KUe(n),onSelect:ua(a.onSelect,()=>r==null?void 0:r(NNe(n)?!0:!n),{checkForDefaultPrevented:!1})})})});tNt.displayName=Jis;var sNt="MenuRadioGroup",[eos,tos]=pO(sNt,{value:void 0,onValueChange:()=>{}}),nNt=j.forwardRef((s,t)=>{const{value:n,onValueChange:r,...a}=s,i=gf(r);return e.jsx(eos,{scope:s.__scopeMenu,value:n,onValueChange:i,children:e.jsx(GUe,{...a,ref:t})})});nNt.displayName=sNt;var rNt="MenuRadioItem",aNt=j.forwardRef((s,t)=>{const{value:n,...r}=s,a=tos(rNt,s.__scopeMenu),i=n===a.value;return e.jsx(iNt,{scope:s.__scopeMenu,checked:i,children:e.jsx(n3e,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":KUe(i),onSelect:ua(r.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,n)},{checkForDefaultPrevented:!1})})})});aNt.displayName=rNt;var WUe="MenuItemIndicator",[iNt,sos]=pO(WUe,{checked:!1}),oNt=j.forwardRef((s,t)=>{const{__scopeMenu:n,forceMount:r,...a}=s,i=sos(WUe,n);return e.jsx(ax,{present:r||NNe(i.checked)||i.checked===!0,children:e.jsx(Ua.span,{...a,ref:t,"data-state":KUe(i.checked)})})});oNt.displayName=WUe;var nos="MenuSeparator",lNt=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Ua.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});lNt.displayName=nos;var ros="MenuArrow",cNt=j.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=s3e(n);return e.jsx(cJ,{...a,...r,ref:t})});cNt.displayName=ros;var aos="MenuSub",[cBn,dNt]=pO(aos),TG="MenuSubTrigger",uNt=j.forwardRef((s,t)=>{const n=fO(TG,s.__scopeMenu),r=pJ(TG,s.__scopeMenu),a=dNt(TG,s.__scopeMenu),i=VUe(TG,s.__scopeMenu),l=j.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},u=j.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return j.useEffect(()=>u,[u]),j.useEffect(()=>{const h=o.current;return()=>{window.clearTimeout(h),c(null)}},[o,c]),e.jsx(UUe,{asChild:!0,...d,children:e.jsx(eNt,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":pNt(n.open),...s,ref:O3(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:ua(s.onPointerMove,YY(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:ua(s.onPointerLeave,YY(h=>{var p,x;u();const m=(p=n.content)==null?void 0:p.getBoundingClientRect();if(m){const y=(x=n.content)==null?void 0:x.dataset.side,g=y==="right",b=g?-5:5,v=m[g?"left":"right"],k=m[g?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+b,y:h.clientY},{x:v,y:m.top},{x:k,y:m.top},{x:k,y:m.bottom},{x:v,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:ua(s.onKeyDown,h=>{var p;const m=i.searchRef.current!=="";s.disabled||m&&h.key===" "||zis[r.dir].includes(h.key)&&(n.onOpenChange(!0),(p=n.content)==null||p.focus(),h.preventDefault())})})})});uNt.displayName=TG;var hNt="MenuSubContent",mNt=j.forwardRef((s,t)=>{const n=Z2t(Ej,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=fO(Ej,s.__scopeMenu),l=pJ(Ej,s.__scopeMenu),o=dNt(hNt,s.__scopeMenu),c=j.useRef(null),d=ko(t,c);return e.jsx(KY.Provider,{scope:s.__scopeMenu,children:e.jsx(ax,{present:r||i.open,children:e.jsx(KY.Slot,{scope:s.__scopeMenu,children:e.jsx(HUe,{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:ua(s.onFocusOutside,u=>{u.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ua(s.onEscapeKeyDown,u=>{l.onClose(),u.preventDefault()}),onKeyDown:ua(s.onKeyDown,u=>{var p;const h=u.currentTarget.contains(u.target),m=Bis[l.dir].includes(u.key);h&&m&&(i.onOpenChange(!1),(p=o.trigger)==null||p.focus(),u.preventDefault())})})})})})});mNt.displayName=hNt;function pNt(s){return s?"open":"closed"}function NNe(s){return s==="indeterminate"}function KUe(s){return NNe(s)?"indeterminate":s?"checked":"unchecked"}function ios(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}function oos(s,t){return s.map((n,r)=>s[(t+r)%s.length])}function los(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=oos(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 cos(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 dos(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return cos(n,t)}function YY(s){return t=>t.pointerType==="mouse"?s(t):void 0}var uos=Y2t,hos=UUe,mos=X2t,pos=Q2t,fos=GUe,xos=J2t,gos=n3e,yos=tNt,vos=nNt,bos=aNt,_os=oNt,wos=lNt,jos=cNt,Nos=uNt,kos=mNt,r3e="DropdownMenu",[Sos,dBn]=Zm(r3e,[W2t]),y1=W2t(),[Cos,fNt]=Sos(r3e),xNt=s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=y1(t),d=j.useRef(null),[u,h]=Mx({prop:a,defaultProp:i??!1,onChange:l,caller:r3e});return e.jsx(Cos,{scope:t,triggerId:Cx(),triggerRef:d,contentId:Cx(),open:u,onOpenChange:h,onOpenToggle:j.useCallback(()=>h(m=>!m),[h]),modal:o,children:e.jsx(uos,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})};xNt.displayName=r3e;var gNt="DropdownMenuTrigger",yNt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=s,i=fNt(gNt,n),l=y1(n);return e.jsx(hos,{asChild:!0,...l,children:e.jsx(Ua.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:O3(t,i.triggerRef),onPointerDown:ua(s.onPointerDown,o=>{!r&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:ua(s.onKeyDown,o=>{r||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});yNt.displayName=gNt;var Aos="DropdownMenuPortal",vNt=s=>{const{__scopeDropdownMenu:t,...n}=s,r=y1(t);return e.jsx(mos,{...r,...n})};vNt.displayName=Aos;var bNt="DropdownMenuContent",_Nt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=fNt(bNt,n),i=y1(n),l=j.useRef(!1);return e.jsx(pos,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:ua(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:ua(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)"}})});_Nt.displayName=bNt;var Tos="DropdownMenuGroup",Eos=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=y1(n);return e.jsx(fos,{...a,...r,ref:t})});Eos.displayName=Tos;var Mos="DropdownMenuLabel",wNt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=y1(n);return e.jsx(xos,{...a,...r,ref:t})});wNt.displayName=Mos;var Los="DropdownMenuItem",jNt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=y1(n);return e.jsx(gos,{...a,...r,ref:t})});jNt.displayName=Los;var Pos="DropdownMenuCheckboxItem",NNt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=y1(n);return e.jsx(yos,{...a,...r,ref:t})});NNt.displayName=Pos;var Ios="DropdownMenuRadioGroup",Ros=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=y1(n);return e.jsx(vos,{...a,...r,ref:t})});Ros.displayName=Ios;var Dos="DropdownMenuRadioItem",kNt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=y1(n);return e.jsx(bos,{...a,...r,ref:t})});kNt.displayName=Dos;var Oos="DropdownMenuItemIndicator",SNt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=y1(n);return e.jsx(_os,{...a,...r,ref:t})});SNt.displayName=Oos;var Fos="DropdownMenuSeparator",CNt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=y1(n);return e.jsx(wos,{...a,...r,ref:t})});CNt.displayName=Fos;var zos="DropdownMenuArrow",Bos=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=y1(n);return e.jsx(jos,{...a,...r,ref:t})});Bos.displayName=zos;var $os="DropdownMenuSubTrigger",ANt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=y1(n);return e.jsx(Nos,{...a,...r,ref:t})});ANt.displayName=$os;var Uos="DropdownMenuSubContent",TNt=j.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=y1(n);return e.jsx(kos,{...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)"}})});TNt.displayName=Uos;var qos=xNt,Vos=yNt,Hos=vNt,ENt=_Nt,MNt=wNt,LNt=jNt,PNt=NNt,INt=kNt,RNt=SNt,DNt=CNt,ONt=ANt,FNt=TNt;const kd=qos,Sd=Vos,Gos=j.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(ONt,{ref:a,className:Et("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"})]}));Gos.displayName=ONt.displayName;const Wos=j.forwardRef(({className:s,...t},n)=>e.jsx(FNt,{ref:n,className:Et("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}));Wos.displayName=FNt.displayName;const xd=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(Hos,{children:e.jsx(ENt,{ref:r,sideOffset:t,className:Et("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})}));xd.displayName=ENt.displayName;const wa=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(LNt,{ref:r,className:Et("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}));wa.displayName=LNt.displayName;const Kos=j.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(PNt,{ref:a,className:Et("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(RNt,{children:e.jsx(da,{className:"h-4 w-4"})})}),t]}));Kos.displayName=PNt.displayName;const Yos=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(INt,{ref:r,className:Et("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(RNt,{children:e.jsx(Sx,{className:"h-2 w-2 fill-current"})})}),t]}));Yos.displayName=INt.displayName;const TE=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(MNt,{ref:r,className:Et("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));TE.displayName=MNt.displayName;const uy=j.forwardRef(({className:s,...t},n)=>e.jsx(DNt,{ref:n,className:Et("-mx-1 my-1 h-px bg-muted",s),...t}));uy.displayName=DNt.displayName;const Zos=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=J4e();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(Eo,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"My Account"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Bn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(kd,{children:[e.jsx(Sd,{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(Eo,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(Ra,{className:"h-5 w-5",children:[e.jsx(Fi,{src:t.avatar_url||void 0}),e.jsx(Da,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(Po,{className:"h-3 w-3"})]})}),e.jsxs(xd,{align:"start",className:"z-[2147483647]",children:[e.jsxs(wa,{onClick:i,className:"gap-2",children:[e.jsx(Eo,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(qe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(uy,{}),n.map(o=>e.jsxs(wa,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(Ra,{className:"h-6 w-6",children:[e.jsx(Fi,{src:o.avatar_url||void 0}),e.jsx(Da,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(qe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(qe,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})},bn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=Ns(),c=$d();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(Tj,{to:"/auth",replace:!0})}return t&&!l?e.jsx(Tj,{to:"/dashboard",replace:!0}):n&&!o&&!l?e.jsx(Tj,{to:"/dashboard",replace:!0}):e.jsx(e.Fragment,{children:s})};var YUe={};(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 oe=new OffscreenCanvas(1,1),ie=oe.getContext("2d");ie.fillRect(0,0,1,1);var de=oe.transferToImageBitmap();ie.createPattern(de,"no-repeat")}catch{return!1}return!0}();function c(){}function d(oe){var ie=n.exports.Promise,de=ie!==void 0?ie:t.Promise;return typeof de=="function"?new de(oe):(oe(c,c),null)}var u=function(oe,ie){return{transform:function(de){if(oe)return de;if(ie.has(de))return ie.get(de);var we=new OffscreenCanvas(de.width,de.height),je=we.getContext("2d");return je.drawImage(de,0,0),ie.set(de,we),we},clear:function(){ie.clear()}}}(o,new Map),h=function(){var oe=Math.floor(16.666666666666668),ie,de,we={},je=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(ie=function(xe){var fe=Math.random();return we[fe]=requestAnimationFrame(function Se(Ee){je===Ee||je+oe-1{const{data:t,error:n}=await U.from("celebration_queue").select("*").eq("user_id",s.id).is("seen_at",null).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!(s!=null&&s.id),refetchOnWindowFocus:!0,staleTime:0})}function Qos(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function Jos(){const s=as(),{user:t}=Ns();return vt({mutationFn:async n=>{const{error:r}=await U.from("celebration_queue").insert({user_id:n.user_id,celebration_type:n.celebration_type,title:n.title,message:n.message||null,points_amount:n.points_amount||null,created_by:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}const Fs=I4e,Io=vUe,els=R4e,uBn=rJ,zNt=j.forwardRef(({className:s,...t},n)=>e.jsx(IU,{ref:n,className:Et("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}));zNt.displayName=IU.displayName;const Os=j.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(els,{children:[e.jsx(zNt,{className:n}),e.jsxs(RU,{ref:a,className:Et("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(rJ,{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(dr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Os.displayName=RU.displayName;const $s=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});$s.displayName="DialogHeader";const Nr=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Nr.displayName="DialogFooter";const zs=j.forwardRef(({className:s,...t},n)=>e.jsx(sJ,{ref:n,className:Et("text-lg font-semibold leading-none tracking-tight",s),...t}));zs.displayName=sJ.displayName;const kr=j.forwardRef(({className:s,...t},n)=>e.jsx(nJ,{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));kr.displayName=nJ.displayName;const tls={points_earned:ll,listing_created:ia,deal_closed:Od,custom:Wa},Kst={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"},Yst=()=>{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 sls(){const{user:s}=Ns(),t=as(),{data:n}=Xos(),r=Qos(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=j.useCallback(()=>{const p=Date.now()+3e3,x={startVelocity:30,spread:360,ticks:60,zIndex:9999},y=(b,v)=>Math.random()*(v-b)+b,g=setInterval(()=>{const b=p-Date.now();if(b<=0){clearInterval(g);return}const v=50*(b/3e3);Wst({...x,particleCount:v,origin:{x:y(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),Wst({...x,particleCount:v,origin:{x:y(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);j.useEffect(()=>{Yst()||n&&n.length>0&&!a&&(i(n[0]),o(!0),setTimeout(c,100))},[n,a,c]);const d=async()=>{if(a){const m=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],p=>(p==null?void 0:p.filter(x=>x.id!==m))??[]),await r.mutateAsync(m)}};if(Yst()||!a)return null;const u=tls[a.celebration_type]||Wa,h=Kst[a.celebration_type]||Kst.custom;return e.jsx(Fs,{open:l,onOpenChange:m=>!m&&d(),children:e.jsxs(Os,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${h} opacity-10`}),e.jsxs("div",{className:"relative z-10 py-6",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${h} flex items-center justify-center animate-bounce`,children:e.jsx(u,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(yn,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(yn,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(yn,{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 gn({className:s,...t}){return e.jsx("div",{className:Et("animate-pulse rounded-md bg-muted",s),...t})}const ye=j.forwardRef(({className:s,type:t,...n},r)=>e.jsx("input",{type:t,className:Et("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}));ye.displayName="Input";var nls="Label",BNt=j.forwardRef((s,t)=>e.jsx(Ua.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())}}));BNt.displayName=nls;var $Nt=BNt;const rls=hO("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),se=j.forwardRef(({className:s,...t},n)=>e.jsx($Nt,{ref:n,className:Et(rls(),s),...t}));se.displayName=$Nt.displayName;const Ds=j.forwardRef(({className:s,...t},n)=>e.jsx("textarea",{className:Et("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}));Ds.displayName="Textarea";var a3e="Tabs",[als,hBn]=Zm(a3e,[QE]),UNt=QE(),[ils,ZUe]=als(a3e),qNt=j.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,u=J3(o),[h,m]=Mx({prop:r,onChange:a,defaultProp:i??"",caller:a3e});return e.jsx(ils,{scope:n,baseId:Cx(),value:h,onValueChange:m,orientation:l,dir:u,activationMode:c,children:e.jsx(Ua.div,{dir:u,"data-orientation":l,...d,ref:t})})});qNt.displayName=a3e;var VNt="TabsList",HNt=j.forwardRef((s,t)=>{const{__scopeTabs:n,loop:r=!0,...a}=s,i=ZUe(VNt,n),l=UNt(n);return e.jsx(e3e,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:r,children:e.jsx(Ua.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});HNt.displayName=VNt;var GNt="TabsTrigger",WNt=j.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,disabled:a=!1,...i}=s,l=ZUe(GNt,n),o=UNt(n),c=ZNt(l.baseId,r),d=XNt(l.baseId,r),u=r===l.value;return e.jsx(t3e,{asChild:!0,...o,focusable:!a,active:u,children:e.jsx(Ua.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:ua(s.onMouseDown,h=>{!a&&h.button===0&&h.ctrlKey===!1?l.onValueChange(r):h.preventDefault()}),onKeyDown:ua(s.onKeyDown,h=>{[" ","Enter"].includes(h.key)&&l.onValueChange(r)}),onFocus:ua(s.onFocus,()=>{const h=l.activationMode!=="manual";!u&&!a&&h&&l.onValueChange(r)})})})});WNt.displayName=GNt;var KNt="TabsContent",YNt=j.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,forceMount:a,children:i,...l}=s,o=ZUe(KNt,n),c=ZNt(o.baseId,r),d=XNt(o.baseId,r),u=r===o.value,h=j.useRef(u);return j.useEffect(()=>{const m=requestAnimationFrame(()=>h.current=!1);return()=>cancelAnimationFrame(m)},[]),e.jsx(ax,{present:a||u,children:({present:m})=>e.jsx(Ua.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})})});YNt.displayName=KNt;function ZNt(s,t){return`${s}-trigger-${t}`}function XNt(s,t){return`${s}-content-${t}`}var ols=qNt,QNt=HNt,JNt=WNt,ekt=YNt;const fa=ols,xa=j.forwardRef(({className:s,...t},n)=>e.jsx(QNt,{ref:n,className:Et("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));xa.displayName=QNt.displayName;const ss=j.forwardRef(({className:s,...t},n)=>e.jsx(JNt,{ref:n,className:Et("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}));ss.displayName=JNt.displayName;const ns=j.forwardRef(({className:s,...t},n)=>e.jsx(ekt,{ref:n,className:Et("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));ns.displayName=ekt.displayName;const ZY="#0d0d0d",kNe="#1a1a1a",X0="#c9a84c",fJ="#f0d78c",K5={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function i3e(s){const t={...s,source_page:typeof window<"u"?window.location.pathname:null,user_agent:typeof navigator<"u"?navigator.userAgent:null,referrer:typeof document<"u"?document.referrer:null},{data:n,error:r}=await U.functions.invoke("public-site-lead",{body:t});if(r)throw r;try{localStorage.setItem(K5.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function XUe(){try{return!!localStorage.getItem(K5.captured)}catch{return!1}}function lls(){try{const s=localStorage.getItem(K5.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function QUe({open:s,onClose:t,children:n}){return j.useEffect(()=>{if(!s)return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[s]),s?Hv.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, ${kNe} 0%, ${ZY} 100%)`,border:`1px solid ${X0}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${X0}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(dr,{className:"h-4 w-4"})}),n]})}),document.body):null}function JUe(){const[s,t]=j.useState({first_name:"",email:"",phone:"",area:""}),[n,r]=j.useState(!1),[a,i]=j.useState("");return{values:s,setValues:t,loading:n,setLoading:r,honeypot:a,setHoneypot:i}}function eqe({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(Eo,{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(on,{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(pa,{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(oi,{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 tqe({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, ${fJ} 0%, ${X0} 100%)`,color:ZY,boxShadow:`0 8px 24px ${X0}55`},children:s})}function Zst({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=JUe(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await i3e({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(K5.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{re.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(QUe,{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(Nx,{className:"h-4 w-4",style:{color:X0}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:fJ},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:`${X0}22`,border:`1px solid ${X0}55`},children:e.jsx(yn,{className:"h-5 w-5",style:{color:X0}})}),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(eqe,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(tqe,{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 cls(){const[s,t]=j.useState(!0),[n,r]=j.useState(!1);j.useEffect(()=>{try{const i=!!localStorage.getItem(K5.stickyDismissed)||XUe();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(K5.stickyDismissed,"1")}catch{}};return s?e.jsx(Zst,{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, ${kNe} 0%, ${ZY} 100%)`,borderTop:`1px solid ${X0}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:`${X0}22`,border:`1px solid ${X0}55`},children:e.jsx(Nx,{className:"h-4 w-4",style:{color:X0}})}),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, ${fJ} 0%, ${X0} 100%)`,color:ZY},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(dr,{className:"h-4 w-4"})})]})}),e.jsx(Zst,{open:n,onClose:()=>r(!1)})]})}function dls(){const[s,t]=j.useState(!1),n=j.useRef(!1);j.useEffect(()=>{try{if(sessionStorage.getItem(K5.exitShown)||XUe())return}catch{}const m=setTimeout(()=>{n.current=!0},8e3),p=x=>{if(n.current&&!(x.clientY>0)){t(!0);try{sessionStorage.setItem(K5.exitShown,"1")}catch{}window.removeEventListener("mouseleave",p),document.removeEventListener("mouseleave",p)}};return document.addEventListener("mouseleave",p),()=>{clearTimeout(m),document.removeEventListener("mouseleave",p)}},[]);const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=JUe(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await i3e({lead_type:"exit_intent",email:r.email.trim().toLowerCase(),first_name:r.first_name.trim()||void 0,phone:r.phone.trim()||void 0,criteria:r.area.trim()?{area:r.area.trim()}:void 0}),u(!0),setTimeout(()=>t(!1),2200)}catch{re.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(QUe,{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, ${ZY} 0%, ${kNe} 60%, ${X0} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:fJ},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:kNe,border:`1px solid ${X0}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(yn,{className:"h-6 w-6",style:{color:X0}})}),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(eqe,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(tqe,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function uls(){const[s,t]=j.useState([]);j.useEffect(()=>{try{const o=localStorage.getItem(K5.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(K5.savedListings,JSON.stringify(o))}catch{}},r=j.useCallback(o=>s.includes(o),[s]),a=o=>{s.includes(o)||n([...s,o])},i=o=>n(s.filter(c=>c!==o));return{ids:s,has:r,add:a,remove:i,toggle:o=>s.includes(o)?i(o):a(o)}}function hls({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=uls(),l=r(s),[o,c]=j.useState(!1),d=()=>{if(l){i(s);return}if(XUe()){a(s),re.success("Saved to your favorites"),i3e({lead_type:"saved_listing",email:lls()||"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(mo,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(mls,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function mls({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=JUe(),h=async m=>{if(m.preventDefault(),!!i.email){c(!0);try{await i3e({lead_type:"saved_listing",email:i.email.trim().toLowerCase(),first_name:i.first_name.trim()||void 0,phone:i.phone.trim()||void 0,listing_id:n,listing_address:r}),a(),re.success("Saved to your favorites"),t()}catch{re.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx(QUe,{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(mo,{className:"h-4 w-4",style:{color:X0}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:fJ},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(eqe,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(tqe,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}function XY(s,[t,n]){return Math.min(n,Math.max(t,s))}function xJ(s){const t=j.useRef({value:s,previous:s});return j.useMemo(()=>(t.current.value!==s&&(t.current.previous=t.current.value,t.current.value=s),t.current.previous),[s])}var tkt=["PageUp","PageDown"],skt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],nkt={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},VU="Slider",[$De,pls,fls]=MU(VU),[rkt,mBn]=Zm(VU,[fls]),[xls,o3e]=rkt(VU),akt=j.forwardRef((s,t)=>{const{name:n,min:r=0,max:a=100,step:i=1,orientation:l="horizontal",disabled:o=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[r],value:u,onValueChange:h=()=>{},onValueCommit:m=()=>{},inverted:p=!1,form:x,...y}=s,g=j.useRef(new Set),b=j.useRef(0),k=l==="horizontal"?gls:yls,[C=[],T]=Mx({prop:u,defaultProp:d,onChange:$=>{var W;(W=[...g.current][b.current])==null||W.focus(),h($)}}),M=j.useRef(C);function P($){const q=jls(C,$);O($,q)}function L($){O($,b.current)}function I(){const $=M.current[b.current];C[b.current]!==$&&m(C)}function O($,q,{commit:W}={commit:!1}){const G=Cls(i),K=Als(Math.round(($-r)/i)*i+r,G),ee=XY(K,[r,a]);T((J=[])=>{const le=_ls(J,ee,q);if(Sls(le,c*i)){b.current=le.indexOf(ee);const ue=String(le)!==String(J);return ue&&W&&m(le),ue?le:J}else return J})}return e.jsx(xls,{scope:s.__scopeSlider,name:n,disabled:o,min:r,max:a,valueIndexToChangeRef:b,thumbs:g.current,values:C,orientation:l,form:x,children:e.jsx($De.Provider,{scope:s.__scopeSlider,children:e.jsx($De.Slot,{scope:s.__scopeSlider,children:e.jsx(k,{"aria-disabled":o,"data-disabled":o?"":void 0,...y,ref:t,onPointerDown:ua(y.onPointerDown,()=>{o||(M.current=C)}),min:r,max:a,inverted:p,onSlideStart:o?void 0:P,onSlideMove:o?void 0:L,onSlideEnd:o?void 0:I,onHomeKeyDown:()=>!o&&O(r,0,{commit:!0}),onEndKeyDown:()=>!o&&O(a,C.length-1,{commit:!0}),onStepKeyDown:({event:$,direction:q})=>{if(!o){const K=tkt.includes($.key)||$.shiftKey&&skt.includes($.key)?10:1,ee=b.current,J=C[ee],le=i*K*q;O(J+le,ee,{commit:!0})}}})})})})});akt.displayName=VU;var[ikt,okt]=rkt(VU,{startEdge:"left",endEdge:"right",size:"width",direction:1}),gls=j.forwardRef((s,t)=>{const{min:n,max:r,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...u}=s,[h,m]=j.useState(null),p=ko(t,k=>m(k)),x=j.useRef(void 0),y=J3(a),g=y==="ltr",b=g&&!i||!g&&i;function v(k){const C=x.current||h.getBoundingClientRect(),T=[0,C.width],P=sqe(T,b?[n,r]:[r,n]);return x.current=C,P(k-C.left)}return e.jsx(ikt,{scope:s.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:e.jsx(lkt,{dir:y,"data-orientation":"horizontal",...u,ref:p,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:k=>{const C=v(k.clientX);l==null||l(C)},onSlideMove:k=>{const C=v(k.clientX);o==null||o(C)},onSlideEnd:()=>{x.current=void 0,c==null||c()},onStepKeyDown:k=>{const T=nkt[b?"from-left":"from-right"].includes(k.key);d==null||d({event:k,direction:T?-1:1})}})})}),yls=j.forwardRef((s,t)=>{const{min:n,max:r,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,u=j.useRef(null),h=ko(t,u),m=j.useRef(void 0),p=!a;function x(y){const g=m.current||u.current.getBoundingClientRect(),b=[0,g.height],k=sqe(b,p?[r,n]:[n,r]);return m.current=g,k(y-g.top)}return e.jsx(ikt,{scope:s.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:e.jsx(lkt,{"data-orientation":"vertical",...d,ref:h,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{const g=x(y.clientY);i==null||i(g)},onSlideMove:y=>{const g=x(y.clientY);l==null||l(g)},onSlideEnd:()=>{m.current=void 0,o==null||o()},onStepKeyDown:y=>{const b=nkt[p?"from-bottom":"from-top"].includes(y.key);c==null||c({event:y,direction:b?-1:1})}})})}),lkt=j.forwardRef((s,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,u=o3e(VU,n);return e.jsx(Ua.span,{...d,ref:t,onKeyDown:ua(s.onKeyDown,h=>{h.key==="Home"?(l(h),h.preventDefault()):h.key==="End"?(o(h),h.preventDefault()):tkt.concat(skt).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:ua(s.onPointerDown,h=>{const m=h.target;m.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(m)?m.focus():r(h)}),onPointerMove:ua(s.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&a(h)}),onPointerUp:ua(s.onPointerUp,h=>{const m=h.target;m.hasPointerCapture(h.pointerId)&&(m.releasePointerCapture(h.pointerId),i(h))})})}),ckt="SliderTrack",dkt=j.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=o3e(ckt,n);return e.jsx(Ua.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...r,ref:t})});dkt.displayName=ckt;var UDe="SliderRange",ukt=j.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=o3e(UDe,n),i=okt(UDe,n),l=j.useRef(null),o=ko(t,l),c=a.values.length,d=a.values.map(m=>pkt(m,a.min,a.max)),u=c>1?Math.min(...d):0,h=100-Math.max(...d);return e.jsx(Ua.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...r,ref:o,style:{...s.style,[i.startEdge]:u+"%",[i.endEdge]:h+"%"}})});ukt.displayName=UDe;var qDe="SliderThumb",hkt=j.forwardRef((s,t)=>{const n=pls(s.__scopeSlider),[r,a]=j.useState(null),i=ko(t,o=>a(o)),l=j.useMemo(()=>r?n().findIndex(o=>o.ref.current===r):-1,[n,r]);return e.jsx(vls,{...s,ref:i,index:l})}),vls=j.forwardRef((s,t)=>{const{__scopeSlider:n,index:r,name:a,...i}=s,l=o3e(qDe,n),o=okt(qDe,n),[c,d]=j.useState(null),u=ko(t,v=>d(v)),h=c?l.form||!!c.closest("form"):!0,m=iJ(c),p=l.values[r],x=p===void 0?0:pkt(p,l.min,l.max),y=wls(r,l.values.length),g=m==null?void 0:m[o.size],b=g?Nls(g,x,o.direction):0;return j.useEffect(()=>{if(c)return l.thumbs.add(c),()=>{l.thumbs.delete(c)}},[c,l.thumbs]),e.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${x}% + ${b}px)`},children:[e.jsx($De.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(Ua.span,{role:"slider","aria-label":s["aria-label"]||y,"aria-valuemin":l.min,"aria-valuenow":p,"aria-valuemax":l.max,"aria-orientation":l.orientation,"data-orientation":l.orientation,"data-disabled":l.disabled?"":void 0,tabIndex:l.disabled?void 0:0,...i,ref:u,style:p===void 0?{display:"none"}:s.style,onFocus:ua(s.onFocus,()=>{l.valueIndexToChangeRef.current=r})})}),h&&e.jsx(mkt,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:p},r)]})});hkt.displayName=qDe;var bls="RadioBubbleInput",mkt=j.forwardRef(({__scopeSlider:s,value:t,...n},r)=>{const a=j.useRef(null),i=ko(a,r),l=xJ(t);return j.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const h=new Event("input",{bubbles:!0});u.call(o,t),o.dispatchEvent(h)}},[l,t]),e.jsx(Ua.input,{style:{display:"none"},...n,ref:i,defaultValue:t})});mkt.displayName=bls;function _ls(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}function pkt(s,t,n){const i=100/(n-t)*(s-t);return XY(i,[0,100])}function wls(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function jls(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 Nls(s,t,n){const r=s/2,i=sqe([0,50],[0,r]);return(r-i(t)*n)*n}function kls(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}function Sls(s,t){if(t>0){const n=kls(s);return Math.min(...n)>=t}return!0}function sqe(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 Cls(s){return(String(s).split(".")[1]||"").length}function Als(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}var fkt=akt,Tls=dkt,Els=ukt,Mls=hkt;const Qf=j.forwardRef(({className:s,...t},n)=>e.jsxs(fkt,{ref:n,className:Et("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(Tls,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(Els,{className:"absolute h-full bg-primary"})}),e.jsx(Mls,{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=fkt.displayName;var Lls=[" ","Enter","ArrowUp","ArrowDown"],Pls=[" ","Enter"],CD="Select",[l3e,c3e,Ils]=MU(CD),[HU,pBn]=Zm(CD,[Ils,rS]),d3e=rS(),[Rls,JE]=HU(CD),[Dls,Ols]=HU(CD),xkt=s=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:u,autoComplete:h,disabled:m,required:p,form:x}=s,y=d3e(t),[g,b]=j.useState(null),[v,k]=j.useState(null),[C,T]=j.useState(!1),M=J3(d),[P,L]=Mx({prop:r,defaultProp:a??!1,onChange:i,caller:CD}),[I,O]=Mx({prop:l,defaultProp:o,onChange:c,caller:CD}),$=j.useRef(null),q=g?x||!!g.closest("form"):!0,[W,G]=j.useState(new Set),K=Array.from(W).map(ee=>ee.props.value).join(";");return e.jsx(oJ,{...y,children:e.jsxs(Rls,{required:p,scope:t,trigger:g,onTriggerChange:b,valueNode:v,onValueNodeChange:k,valueNodeHasChildren:C,onValueNodeHasChildrenChange:T,contentId:Cx(),value:I,onValueChange:O,open:P,onOpenChange:L,dir:M,triggerPointerDownPosRef:$,disabled:m,children:[e.jsx(l3e.Provider,{scope:t,children:e.jsx(Dls,{scope:s.__scopeSelect,onNativeOptionAdd:j.useCallback(ee=>{G(J=>new Set(J).add(ee))},[]),onNativeOptionRemove:j.useCallback(ee=>{G(J=>{const le=new Set(J);return le.delete(ee),le})},[]),children:n})}),q?e.jsxs(Bkt,{"aria-hidden":!0,required:p,tabIndex:-1,name:u,autoComplete:h,value:I,onChange:ee=>O(ee.target.value),disabled:m,form:x,children:[I===void 0?e.jsx("option",{value:""}):null,Array.from(W)]},K):null]})})};xkt.displayName=CD;var gkt="SelectTrigger",ykt=j.forwardRef((s,t)=>{const{__scopeSelect:n,disabled:r=!1,...a}=s,i=d3e(n),l=JE(gkt,n),o=l.disabled||r,c=ko(t,l.onTriggerChange),d=c3e(n),u=j.useRef("touch"),[h,m,p]=Ukt(y=>{const g=d().filter(k=>!k.disabled),b=g.find(k=>k.value===l.value),v=qkt(g,y,b);v!==void 0&&l.onValueChange(v.value)}),x=y=>{o||(l.onOpenChange(!0),p()),y&&(l.triggerPointerDownPosRef.current={x:Math.round(y.pageX),y:Math.round(y.pageY)})};return e.jsx(FU,{asChild:!0,...i,children:e.jsx(Ua.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":$kt(l.value)?"":void 0,...a,ref:c,onClick:ua(a.onClick,y=>{y.currentTarget.focus(),u.current!=="mouse"&&x(y)}),onPointerDown:ua(a.onPointerDown,y=>{u.current=y.pointerType;const g=y.target;g.hasPointerCapture(y.pointerId)&&g.releasePointerCapture(y.pointerId),y.button===0&&y.ctrlKey===!1&&y.pointerType==="mouse"&&(x(y),y.preventDefault())}),onKeyDown:ua(a.onKeyDown,y=>{const g=h.current!=="";!(y.ctrlKey||y.altKey||y.metaKey)&&y.key.length===1&&m(y.key),!(g&&y.key===" ")&&Lls.includes(y.key)&&(x(),y.preventDefault())})})})});ykt.displayName=gkt;var vkt="SelectValue",bkt=j.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,children:i,placeholder:l="",...o}=s,c=JE(vkt,n),{onValueNodeHasChildrenChange:d}=c,u=i!==void 0,h=ko(t,c.onValueNodeChange);return Nf(()=>{d(u)},[d,u]),e.jsx(Ua.span,{...o,ref:h,style:{pointerEvents:"none"},children:$kt(c.value)?e.jsx(e.Fragment,{children:l}):i})});bkt.displayName=vkt;var Fls="SelectIcon",_kt=j.forwardRef((s,t)=>{const{__scopeSelect:n,children:r,...a}=s;return e.jsx(Ua.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});_kt.displayName=Fls;var zls="SelectPortal",wkt=s=>e.jsx(LU,{asChild:!0,...s});wkt.displayName=zls;var AD="SelectContent",jkt=j.forwardRef((s,t)=>{const n=JE(AD,s.__scopeSelect),[r,a]=j.useState();if(Nf(()=>{a(new DocumentFragment)},[]),!n.open){const i=r;return i?Hv.createPortal(e.jsx(Nkt,{scope:s.__scopeSelect,children:e.jsx(l3e.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(kkt,{...s,ref:t})});jkt.displayName=AD;var C2=10,[Nkt,e6]=HU(AD),Bls="SelectContentImpl",$ls=NE("SelectContent.RemoveScroll"),kkt=j.forwardRef((s,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:l,side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:m,collisionPadding:p,sticky:x,hideWhenDetached:y,avoidCollisions:g,...b}=s,v=JE(AD,n),[k,C]=j.useState(null),[T,M]=j.useState(null),P=ko(t,Se=>C(Se)),[L,I]=j.useState(null),[O,$]=j.useState(null),q=c3e(n),[W,G]=j.useState(!1),K=j.useRef(!1);j.useEffect(()=>{if(k)return L4e(k)},[k]),E4e();const ee=j.useCallback(Se=>{const[Ee,...Le]=q().map(Ne=>Ne.ref.current),[De]=Le.slice(-1),Be=document.activeElement;for(const Ne of Se)if(Ne===Be||(Ne==null||Ne.scrollIntoView({block:"nearest"}),Ne===Ee&&T&&(T.scrollTop=0),Ne===De&&T&&(T.scrollTop=T.scrollHeight),Ne==null||Ne.focus(),document.activeElement!==Be))return},[q,T]),J=j.useCallback(()=>ee([L,k]),[ee,L,k]);j.useEffect(()=>{W&&J()},[W,J]);const{onOpenChange:le,triggerPointerDownPosRef:ue}=v;j.useEffect(()=>{if(k){let Se={x:0,y:0};const Ee=De=>{var Be,Ne;Se={x:Math.abs(Math.round(De.pageX)-(((Be=ue.current)==null?void 0:Be.x)??0)),y:Math.abs(Math.round(De.pageY)-(((Ne=ue.current)==null?void 0:Ne.y)??0))}},Le=De=>{Se.x<=10&&Se.y<=10?De.preventDefault():k.contains(De.target)||le(!1),document.removeEventListener("pointermove",Ee),ue.current=null};return ue.current!==null&&(document.addEventListener("pointermove",Ee),document.addEventListener("pointerup",Le,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Ee),document.removeEventListener("pointerup",Le,{capture:!0})}}},[k,le,ue]),j.useEffect(()=>{const Se=()=>le(!1);return window.addEventListener("blur",Se),window.addEventListener("resize",Se),()=>{window.removeEventListener("blur",Se),window.removeEventListener("resize",Se)}},[le]);const[oe,ie]=Ukt(Se=>{const Ee=q().filter(Be=>!Be.disabled),Le=Ee.find(Be=>Be.ref.current===document.activeElement),De=qkt(Ee,Se,Le);De&&setTimeout(()=>De.ref.current.focus())}),de=j.useCallback((Se,Ee,Le)=>{const De=!K.current&&!Le;(v.value!==void 0&&v.value===Ee||De)&&(I(Se),De&&(K.current=!0))},[v.value]),we=j.useCallback(()=>k==null?void 0:k.focus(),[k]),je=j.useCallback((Se,Ee,Le)=>{const De=!K.current&&!Le;(v.value!==void 0&&v.value===Ee||De)&&$(Se)},[v.value]),xe=r==="popper"?VDe:Skt,fe=xe===VDe?{side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:m,collisionPadding:p,sticky:x,hideWhenDetached:y,avoidCollisions:g}:{};return e.jsx(Nkt,{scope:n,content:k,viewport:T,onViewportChange:M,itemRefCallback:de,selectedItem:L,onItemLeave:we,itemTextRefCallback:je,focusSelectedItem:J,selectedItemText:O,position:r,isPositioned:W,searchRef:oe,children:e.jsx(tJ,{as:$ls,allowPinchZoom:!0,children:e.jsx(eJ,{asChild:!0,trapped:v.open,onMountAutoFocus:Se=>{Se.preventDefault()},onUnmountAutoFocus:ua(a,Se=>{var Ee;(Ee=v.trigger)==null||Ee.focus({preventScroll:!0}),Se.preventDefault()}),children:e.jsx(ZE,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:Se=>Se.preventDefault(),onDismiss:()=>v.onOpenChange(!1),children:e.jsx(xe,{role:"listbox",id:v.contentId,"data-state":v.open?"open":"closed",dir:v.dir,onContextMenu:Se=>Se.preventDefault(),...b,...fe,onPlaced:()=>G(!0),ref:P,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:ua(b.onKeyDown,Se=>{const Ee=Se.ctrlKey||Se.altKey||Se.metaKey;if(Se.key==="Tab"&&Se.preventDefault(),!Ee&&Se.key.length===1&&ie(Se.key),["ArrowUp","ArrowDown","Home","End"].includes(Se.key)){let De=q().filter(Be=>!Be.disabled).map(Be=>Be.ref.current);if(["ArrowUp","End"].includes(Se.key)&&(De=De.slice().reverse()),["ArrowUp","ArrowDown"].includes(Se.key)){const Be=Se.target,Ne=De.indexOf(Be);De=De.slice(Ne+1)}setTimeout(()=>ee(De)),Se.preventDefault()}})})})})})})});kkt.displayName=Bls;var Uls="SelectItemAlignedPosition",Skt=j.forwardRef((s,t)=>{const{__scopeSelect:n,onPlaced:r,...a}=s,i=JE(AD,n),l=e6(AD,n),[o,c]=j.useState(null),[d,u]=j.useState(null),h=ko(t,P=>u(P)),m=c3e(n),p=j.useRef(!1),x=j.useRef(!0),{viewport:y,selectedItem:g,selectedItemText:b,focusSelectedItem:v}=l,k=j.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&y&&g&&b){const P=i.trigger.getBoundingClientRect(),L=d.getBoundingClientRect(),I=i.valueNode.getBoundingClientRect(),O=b.getBoundingClientRect();if(i.dir!=="rtl"){const Be=O.left-L.left,Ne=I.left-Be,Ge=P.left-Ne,_e=P.width+Ge,Oe=Math.max(_e,L.width),Ae=window.innerWidth-C2,Xe=XY(Ne,[C2,Math.max(C2,Ae-Oe)]);o.style.minWidth=_e+"px",o.style.left=Xe+"px"}else{const Be=L.right-O.right,Ne=window.innerWidth-I.right-Be,Ge=window.innerWidth-P.right-Ne,_e=P.width+Ge,Oe=Math.max(_e,L.width),Ae=window.innerWidth-C2,Xe=XY(Ne,[C2,Math.max(C2,Ae-Oe)]);o.style.minWidth=_e+"px",o.style.right=Xe+"px"}const $=m(),q=window.innerHeight-C2*2,W=y.scrollHeight,G=window.getComputedStyle(d),K=parseInt(G.borderTopWidth,10),ee=parseInt(G.paddingTop,10),J=parseInt(G.borderBottomWidth,10),le=parseInt(G.paddingBottom,10),ue=K+ee+W+le+J,oe=Math.min(g.offsetHeight*5,ue),ie=window.getComputedStyle(y),de=parseInt(ie.paddingTop,10),we=parseInt(ie.paddingBottom,10),je=P.top+P.height/2-C2,xe=q-je,fe=g.offsetHeight/2,Se=g.offsetTop+fe,Ee=K+ee+Se,Le=ue-Ee;if(Ee<=je){const Be=$.length>0&&g===$[$.length-1].ref.current;o.style.bottom="0px";const Ne=d.clientHeight-y.offsetTop-y.offsetHeight,Ge=Math.max(xe,fe+(Be?we:0)+Ne+J),_e=Ee+Ge;o.style.height=_e+"px"}else{const Be=$.length>0&&g===$[0].ref.current;o.style.top="0px";const Ge=Math.max(je,K+y.offsetTop+(Be?de:0)+fe)+Le;o.style.height=Ge+"px",y.scrollTop=Ee-je+y.offsetTop}o.style.margin=`${C2}px 0`,o.style.minHeight=oe+"px",o.style.maxHeight=q+"px",r==null||r(),requestAnimationFrame(()=>p.current=!0)}},[m,i.trigger,i.valueNode,o,d,y,g,b,i.dir,r]);Nf(()=>k(),[k]);const[C,T]=j.useState();Nf(()=>{d&&T(window.getComputedStyle(d).zIndex)},[d]);const M=j.useCallback(P=>{P&&x.current===!0&&(k(),v==null||v(),x.current=!1)},[k,v]);return e.jsx(Vls,{scope:n,contentWrapper:o,shouldExpandOnScrollRef:p,onScrollButtonChange:M,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:C},children:e.jsx(Ua.div,{...a,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});Skt.displayName=Uls;var qls="SelectPopperPosition",VDe=j.forwardRef((s,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:a=C2,...i}=s,l=d3e(n);return e.jsx(lJ,{...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)"}})});VDe.displayName=qls;var[Vls,nqe]=HU(AD,{}),HDe="SelectViewport",Ckt=j.forwardRef((s,t)=>{const{__scopeSelect:n,nonce:r,...a}=s,i=e6(HDe,n),l=nqe(HDe,n),o=ko(t,i.onViewportChange),c=j.useRef(0);return e.jsxs(e.Fragment,{children:[e.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),e.jsx(l3e.Slot,{scope:n,children:e.jsx(Ua.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:ua(a.onScroll,d=>{const u=d.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=l;if(m!=null&&m.current&&h){const p=Math.abs(c.current-u.scrollTop);if(p>0){const x=window.innerHeight-C2*2,y=parseFloat(h.style.minHeight),g=parseFloat(h.style.height),b=Math.max(y,g);if(b0?C:0,h.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});Ckt.displayName=HDe;var Akt="SelectGroup",[Hls,Gls]=HU(Akt),Wls=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=Cx();return e.jsx(Hls,{scope:n,id:a,children:e.jsx(Ua.div,{role:"group","aria-labelledby":a,...r,ref:t})})});Wls.displayName=Akt;var Tkt="SelectLabel",Ekt=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=Gls(Tkt,n);return e.jsx(Ua.div,{id:a.id,...r,ref:t})});Ekt.displayName=Tkt;var SNe="SelectItem",[Kls,Mkt]=HU(SNe),Lkt=j.forwardRef((s,t)=>{const{__scopeSelect:n,value:r,disabled:a=!1,textValue:i,...l}=s,o=JE(SNe,n),c=e6(SNe,n),d=o.value===r,[u,h]=j.useState(i??""),[m,p]=j.useState(!1),x=ko(t,v=>{var k;return(k=c.itemRefCallback)==null?void 0:k.call(c,v,r,a)}),y=Cx(),g=j.useRef("touch"),b=()=>{a||(o.onValueChange(r),o.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return e.jsx(Kls,{scope:n,value:r,disabled:a,textId:y,isSelected:d,onItemTextChange:j.useCallback(v=>{h(k=>k||((v==null?void 0:v.textContent)??"").trim())},[]),children:e.jsx(l3e.ItemSlot,{scope:n,value:r,disabled:a,textValue:u,children:e.jsx(Ua.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:x,onFocus:ua(l.onFocus,()=>p(!0)),onBlur:ua(l.onBlur,()=>p(!1)),onClick:ua(l.onClick,()=>{g.current!=="mouse"&&b()}),onPointerUp:ua(l.onPointerUp,()=>{g.current==="mouse"&&b()}),onPointerDown:ua(l.onPointerDown,v=>{g.current=v.pointerType}),onPointerMove:ua(l.onPointerMove,v=>{var k;g.current=v.pointerType,a?(k=c.onItemLeave)==null||k.call(c):g.current==="mouse"&&v.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ua(l.onPointerLeave,v=>{var k;v.currentTarget===document.activeElement&&((k=c.onItemLeave)==null||k.call(c))}),onKeyDown:ua(l.onKeyDown,v=>{var C;((C=c.searchRef)==null?void 0:C.current)!==""&&v.key===" "||(Pls.includes(v.key)&&b(),v.key===" "&&v.preventDefault())})})})})});Lkt.displayName=SNe;var EG="SelectItemText",Pkt=j.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,...i}=s,l=JE(EG,n),o=e6(EG,n),c=Mkt(EG,n),d=Ols(EG,n),[u,h]=j.useState(null),m=ko(t,b=>h(b),c.onItemTextChange,b=>{var v;return(v=o.itemTextRefCallback)==null?void 0:v.call(o,b,c.value,c.disabled)}),p=u==null?void 0:u.textContent,x=j.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:p},c.value),[c.disabled,c.value,p]),{onNativeOptionAdd:y,onNativeOptionRemove:g}=d;return Nf(()=>(y(x),()=>g(x)),[y,g,x]),e.jsxs(e.Fragment,{children:[e.jsx(Ua.span,{id:c.textId,...i,ref:m}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?Hv.createPortal(i.children,l.valueNode):null]})});Pkt.displayName=EG;var Ikt="SelectItemIndicator",Rkt=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return Mkt(Ikt,n).isSelected?e.jsx(Ua.span,{"aria-hidden":!0,...r,ref:t}):null});Rkt.displayName=Ikt;var GDe="SelectScrollUpButton",Dkt=j.forwardRef((s,t)=>{const n=e6(GDe,s.__scopeSelect),r=nqe(GDe,s.__scopeSelect),[a,i]=j.useState(!1),l=ko(t,r.onScrollButtonChange);return Nf(()=>{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(Fkt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});Dkt.displayName=GDe;var WDe="SelectScrollDownButton",Okt=j.forwardRef((s,t)=>{const n=e6(WDe,s.__scopeSelect),r=nqe(WDe,s.__scopeSelect),[a,i]=j.useState(!1),l=ko(t,r.onScrollButtonChange);return Nf(()=>{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(Fkt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});Okt.displayName=WDe;var Fkt=j.forwardRef((s,t)=>{const{__scopeSelect:n,onAutoScroll:r,...a}=s,i=e6("SelectScrollButton",n),l=j.useRef(null),o=c3e(n),c=j.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return j.useEffect(()=>()=>c(),[c]),Nf(()=>{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(Ua.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:ua(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(r,50))}),onPointerMove:ua(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(r,50))}),onPointerLeave:ua(a.onPointerLeave,()=>{c()})})}),Yls="SelectSeparator",zkt=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return e.jsx(Ua.div,{"aria-hidden":!0,...r,ref:t})});zkt.displayName=Yls;var KDe="SelectArrow",Zls=j.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=d3e(n),i=JE(KDe,n),l=e6(KDe,n);return i.open&&l.position==="popper"?e.jsx(cJ,{...a,...r,ref:t}):null});Zls.displayName=KDe;var Xls="SelectBubbleInput",Bkt=j.forwardRef(({__scopeSelect:s,value:t,...n},r)=>{const a=j.useRef(null),i=ko(r,a),l=xJ(t);return j.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const h=new Event("change",{bubbles:!0});u.call(o,t),o.dispatchEvent(h)}},[l,t]),e.jsx(Ua.select,{...n,style:{...N_t,...n.style},ref:i,defaultValue:t})});Bkt.displayName=Xls;function $kt(s){return s===""||s===void 0}function Ukt(s){const t=gf(s),n=j.useRef(""),r=j.useRef(0),a=j.useCallback(l=>{const o=n.current+l;t(o),function c(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(o)},[t]),i=j.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return j.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}function qkt(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=Qls(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 Qls(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var Jls=xkt,Vkt=ykt,ecs=bkt,tcs=_kt,scs=wkt,Hkt=jkt,ncs=Ckt,Gkt=Ekt,Wkt=Lkt,rcs=Pkt,acs=Rkt,Kkt=Dkt,Ykt=Okt,Zkt=zkt;const vs=Jls,bs=ecs,gs=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Vkt,{ref:r,className:Et("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(tcs,{asChild:!0,children:e.jsx(Po,{className:"h-4 w-4 opacity-50"})})]}));gs.displayName=Vkt.displayName;const Xkt=j.forwardRef(({className:s,...t},n)=>e.jsx(Kkt,{ref:n,className:Et("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(Qy,{className:"h-4 w-4"})}));Xkt.displayName=Kkt.displayName;const Qkt=j.forwardRef(({className:s,...t},n)=>e.jsx(Ykt,{ref:n,className:Et("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(Po,{className:"h-4 w-4"})}));Qkt.displayName=Ykt.displayName;const ys=j.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(scs,{children:e.jsxs(Hkt,{ref:a,className:Et("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(Xkt,{}),e.jsx(ncs,{className:Et("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Qkt,{})]})}));ys.displayName=Hkt.displayName;const ics=j.forwardRef(({className:s,...t},n)=>e.jsx(Gkt,{ref:n,className:Et("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));ics.displayName=Gkt.displayName;const Je=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Wkt,{ref:r,className:Et("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(acs,{children:e.jsx(da,{className:"h-4 w-4"})})}),e.jsx(rcs,{children:t})]}));Je.displayName=Wkt.displayName;const ocs=j.forwardRef(({className:s,...t},n)=>e.jsx(Zkt,{ref:n,className:Et("-mx-1 my-1 h-px bg-muted",s),...t}));ocs.displayName=Zkt.displayName;const lcs=s=>mt({queryKey:["public-listings",s],queryFn:async()=>{let t=U.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).order("created_at",{ascending:!1});if(s!=null&&s.status&&(t=t.eq("status",s.status)),s!=null&&s.propertyType&&(t=t.eq("property_type",s.propertyType)),s!=null&&s.city){const a=s.city.replace(/[%,()]/g," ").trim();if(a){const i=`%${a}%`;t=t.or(`city.ilike.${i},neighborhood.ilike.${i},property_address.ilike.${i}`)}}s!=null&&s.minPrice&&(t=t.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(t=t.lte("price",s.maxPrice));const{data:n,error:r}=await t;if(r)throw r;return n}}),ccs=()=>mt({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await U.from("listings").select("city, state, neighborhood, property_address").eq("is_approved",!0).eq("is_public",!0);if(t)throw t;const n=new Map,r=new Map,a=new Map;return(s||[]).forEach(i=>{if(i.city){const l=`${i.city}|${i.state||""}`.toLowerCase(),o=i.state?`${i.city}, ${i.state}`:i.city,c=n.get(l);c?c.count++:n.set(l,{label:o,city:i.city,state:i.state,count:1})}if(i.neighborhood){const l=`${i.neighborhood}|${i.city||""}`.toLowerCase(),o=i.city?`${i.neighborhood} — ${i.city}`:i.neighborhood,c=r.get(l);c?c.count++:r.set(l,{label:o,city:i.city||"",neighborhood:i.neighborhood,count:1})}if(i.property_address){const l=String(i.property_address).match(/\b(\d{5})(?:-\d{4})?\b/);if(l){const o=l[1],c=a.get(o);c?c.count++:a.set(o,{label:o,zip:o,count:1})}}}),{cities:Array.from(n.values()).sort((i,l)=>l.count-i.count),neighborhoods:Array.from(r.values()).sort((i,l)=>l.count-i.count),zips:Array.from(a.values()).sort((i,l)=>l.count-i.count)}}}),dcs=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=U.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, page_config, page_theme, created_at, updated_at, co_agent_name, co_agent_email, co_agent_phone, co_agent_brokerage, co_agent_photo_url, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);t?n=n.eq("id",s):n=n.eq("slug",s);const{data:r,error:a}=await n.single();if(a)throw a;return r},enabled:!!s}),ucs=()=>vt({mutationFn:async({listingId:s,agentId:t,firstName:n,lastName:r,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:u,message:h})=>{let m=null,p=null;if(l){const{data:b}=await U.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();b&&(m=b.id,p=b.sharing_agent_id)}const{data:x,error:y}=await U.from("listing_leads").insert({listing_id:s,agent_id:p||t,first_name:n,last_name:r,email:a,phone:i,share_id:m,referred_by_agent_id:p,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:u||null,message:h||null}).select().single();if(y)throw y;const{error:g}=await U.functions.invoke("process-listing-lead",{body:{leadId:x.id}});return g&&console.error("Error processing lead:",g),x}}),hcs=()=>vt({mutationFn:async s=>{const{error:t}=await U.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),Xst="/assets/levelup-logo-color-BeKd2k_g.png",mcs={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"},pcs={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"},Qst={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},bse=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),mH=s=>new Intl.NumberFormat("en-US").format(s);function Jkt({slugOverride:s}={}){var zt,Gt,qs,As,Bt;const t=$i(),n=s||t.slugOrId,[r]=dc(),{data:a,isLoading:i}=dcs(n||""),l=ucs(),o=hcs(),c=r.get("ref"),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(""),[y,g]=j.useState(""),[b,v]=j.useState(""),[k,C]=j.useState(""),[T,M]=j.useState(""),[P,L]=j.useState("in_person"),[I,O]=j.useState("info"),[$,q]=j.useState(!1),[W,G]=j.useState(!1),[K,ee]=j.useState(null),[J,le]=j.useState(!1);j.useState(!1);const[ue,oe]=j.useState(!1),[ie,de]=j.useState(20),[we,je]=j.useState(6.5),[xe,fe]=j.useState(30),Se=j.useRef(null),[Ee,Le]=j.useState(!1);j.useEffect(()=>{const At=()=>Le(window.scrollY>300);return window.addEventListener("scroll",At,{passive:!0}),()=>window.removeEventListener("scroll",At)},[]),j.useEffect(()=>{c&&o.mutate(c)},[c]),j.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const De=(a==null?void 0:a.photos)||[],Be=De.find(At=>At.is_primary)||De[0],Ne=j.useMemo(()=>{if(!(a!=null&&a.price))return 0;const At=a.price*(1-ie/100),Is=we/100/12,jt=xe*12;return Is===0?At/jt:At*Is/(1-Math.pow(1+Is,-jt))},[a==null?void 0:a.price,ie,we,xe]),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),re.success("Link copied to clipboard")},_e=async At=>{if(At.preventDefault(),!d.trim()||!p.trim()||!a)return;const Is=I==="showing";if(Is&&!k){re.error("Please pick a preferred date for your showing");return}q(!0);try{await l.mutateAsync({listingId:a.id,agentId:a.agent_id,firstName:d.trim(),lastName:h.trim(),email:p.trim(),phone:y.trim(),shareToken:c,leadType:Is?"showing_request":"info_request",preferredDate:Is?k:null,preferredTime:Is&&T||null,showingMode:Is?P:null,message:b.trim()||null}),G(!0),re.success(Is?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(jt){console.error("Lead submission error:",jt),re.error(`Failed to submit: ${jt.message||"Please try again"}`)}finally{q(!1)}},Oe=()=>{K!==null&&ee(K===0?De.length-1:K-1)},Ae=()=>{K!==null&&ee(K===De.length-1?0:K+1)};if(i)return e.jsx("div",{className:"min-h-screen bg-neutral-950",children:e.jsx(gn,{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(Yn,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:Xst,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(ia,{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(Yn,{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`,Ue=((Gt=(zt=a.agent)==null?void 0:zt.brokerage)==null?void 0:Gt.name)||((qs=a.agent)==null?void 0:qs.brokerage_name),Ze=a.latitude&&a.longitude?`https://maps.google.com/maps?q=${a.latitude},${a.longitude}&z=15&output=embed`:a.property_address?`https://maps.google.com/maps?q=${encodeURIComponent(`${a.property_address}, ${a.city}, ${a.state}`)}&z=15&output=embed`:null,Qe=a.description||"",Ye=Qe.length>420,nt=ue||!Ye?Qe:Qe.slice(0,420).trimEnd()+"…",rt=a.page_config||{},Fe=At=>{var Is;return(((Is=rt.sections)==null?void 0:Is[At])??!0)!==!1},dt=Array.isArray(rt.addons)?rt.addons:[],Dt=rt.custom_note||"",pt=rt.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(ql,{children:[e.jsxs("title",{children:[Xe," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${bse(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${Qst[a.property_type]} in ${a.city}, ${a.state}. ${Qe.slice(0,140)}`}),e.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${a.slug||a.id}`}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:""}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400;9..144,500;9..144,600&display=swap",rel:"stylesheet"}),e.jsx("meta",{property:"og:title",content:Xe}),e.jsx("meta",{property:"og:description",content:`${bse(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:`${bse(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:Qe,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:De.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 ${Ee?"bg-neutral-950/85 backdrop-blur-xl border-b border-white/10 py-3":"bg-gradient-to-b from-black/60 to-transparent py-4"}`,children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 flex items-center justify-between gap-3",children:[e.jsxs(Yn,{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(_a,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),Ee&&e.jsx("div",{className:"hidden md:flex items-center gap-1 text-sm",children:[["overview","Overview"],["gallery","Gallery"],["story","The Story"],["video","Video"],["map","Location"],["payment","Payment"],["agent","Agent"]].map(([At,Is])=>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:Is},At))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hls,{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(zd,{className:"h-4 w-4 text-white"})}),e.jsx(B,{size:"sm",onClick:()=>le(!0),className:"hidden sm:inline-flex bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4 font-medium",children:"Request Tour"})]})]})}),e.jsxs("section",{ref: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(qe,{className:`${mcs[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:pcs[a.status]}),De.length>0&&e.jsxs("button",{onClick:()=>ee(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(s0,{className:"h-3.5 w-3.5"}),De.length," photos"]})]}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 z-10 px-4 sm:px-8 pb-10 sm:pb-14",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex items-end justify-between gap-6 flex-wrap",children:[e.jsxs("div",{className:"max-w-3xl",children:[a.neighborhood&&e.jsxs("p",{className:"text-white/70 uppercase tracking-[0.25em] text-xs mb-3 font-medium",children:[a.neighborhood," · ",a.city,", ",a.state]}),a.property_address&&e.jsx("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:a.property_address}),!a.property_address&&e.jsxs("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:[a.city,", ",a.state]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx("p",{className:"font-display text-white text-3xl sm:text-4xl md:text-5xl font-medium",children:bse(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:mH(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(Eo,{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}),Ue&&e.jsx("p",{className:"text-xs text-white/60",children:Ue})]}),e.jsx(B,{size:"sm",onClick:()=>le(!0),className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:"Contact"})]})]}),e.jsxs("div",{className:"mt-10 flex items-center gap-2 text-white/50 text-xs uppercase tracking-widest",children:[e.jsx("span",{className:"h-px w-8 bg-white/30"}),"Scroll to explore"]})]})})]}),Fe("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:U_,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:t0,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:H_,label:"Interior",value:`${mH(a.square_footage)} sqft`},a.lot_size&&{icon:j3,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:ra,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:P5,label:"Price / sqft",value:`$${mH(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((At,Is)=>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})]})]},Is))})}),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:[Fe("story")&&Qe&&e.jsxs("section",{id:"story",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-3",children:"The Story"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light mb-6 text-white",children:"A closer look at this home"}),e.jsx("div",{className:"prose prose-invert prose-lg max-w-none",children:e.jsx("p",{className:"text-white/75 leading-relaxed whitespace-pre-wrap",children:nt})}),Ye&&e.jsx("button",{onClick:()=>oe(!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(qe,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(Ni,{className:"h-3 w-3 mr-1.5"}),Qst[a.property_type]]}),a.has_hoa&&e.jsx(qe,{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"]})})]}),(Dt||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(yn,{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:['"',Dt||a.agent_notes,'"']})]})]}),Fe("gallery")&&De.length>1&&e.jsxs("section",{id:"gallery",children:[e.jsxs("div",{className:"flex items-end justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),e.jsxs("button",{onClick:()=>ee(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",De.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:De.slice(0,7).map((At,Is)=>{const jt=["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"],Qs=Is===6&&De.length>7;return e.jsxs("button",{onClick:()=>ee(Is),className:`${jt[Is]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:At.photo_url,alt:`Photo ${Is+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),Qs&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(s0,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",De.length-7," more"]})]})]},At.id)})})]}),Fe("video")&&((As=a.video)==null?void 0:As.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"})})]}),Fe("map")&&Ze&&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:Ze,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(oi,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),Fe("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:["$",mH(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(se,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),e.jsxs("span",{className:"text-white font-medium",children:[ie,"%"]})]}),e.jsx(Qf,{value:[ie],onValueChange:At=>de(At[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",mH(Math.round(a.price*ie/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[we.toFixed(2),"%"]})]}),e.jsx(Qf,{value:[we],onValueChange:At=>je(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(se,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[xe," yr"]})]}),e.jsx(Qf,{value:[xe],onValueChange:At=>fe(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."})]})]}),dt.map(At=>{const Is=At.type,jt=At.data||{};if(Is==="extra_video"&&jt.url){const Qs=String(jt.url).includes("youtu")?`https://www.youtube.com/embed/${String(jt.url).split(/[/=]/).pop()}`:jt.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:jt.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:jt.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:Qs,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:jt.title||"Video"})})]},At.id)}return Is==="3d_tour"&&jt.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:jt.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:jt.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},At.id):Is==="floor_plan"&&jt.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:jt.title||"Layout"}),e.jsx("img",{src:jt.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},At.id):Is==="testimonial"&&jt.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:['"',jt.quote,'"']}),jt.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",jt.author]})]},At.id):Is==="custom_cta"&&jt.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:pt?`${pt}22`:"rgba(255,255,255,0.05)",border:`1px solid ${pt||"rgba(255,255,255,0.1)"}`},children:[jt.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:jt.title}),e.jsx(B,{asChild:!0,size:"lg",style:pt?{background:pt}:void 0,children:e.jsx("a",{href:jt.url||"#agent",children:jt.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(Eo,{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}),Ue&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:Ue})]})]}),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(pa,{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(on,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),a.co_agent_name&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[a.co_agent_photo_url?e.jsx("img",{src:a.co_agent_photo_url,alt:a.co_agent_name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:e.jsx(Eo,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Co-Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.co_agent_name}),a.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:a.co_agent_brokerage})]})]}),(a.co_agent_phone||a.co_agent_email)&&e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.co_agent_phone&&e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.co_agent_phone}`,children:[e.jsx(pa,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.co_agent_email&&e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.co_agent_email}`,children:[e.jsx(on,{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(Jst,{submitted:W,activeTab:I,setActiveTab:O,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:x,phone:y,setPhone:g,message:b,setMessage:v,preferredDate:k,setPreferredDate:C,preferredTime:T,setPreferredTime:M,showingMode:P,setShowingMode:L,isSubmitting:$,onSubmit:_e})})]})]}),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:[((Bt=a.agent)==null?void 0:Bt.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(pa,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs(B,{onClick:()=>le(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(ym,{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:Xst,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(Fs,{open:K!==null,onOpenChange:()=>ee(null),children:e.jsxs(Os,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx($s,{className:"sr-only",children:e.jsx(zs,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>ee(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(dr,{className:"h-5 w-5"})}),K!==null&&De[K]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:De[K].photo_url,alt:`Photo ${K+1}`,className:"w-full max-h-[85vh] object-contain"}),De.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Oe,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(Cc,{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:[K+1," / ",De.length]})]})]})]})}),e.jsx(Fs,{open:J,onOpenChange:le,children:e.jsxs(Os,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx($s,{className:"sr-only",children:e.jsx(zs,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(Jst,{submitted:W,activeTab:I,setActiveTab:O,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:x,phone:y,setPhone:g,message:b,setMessage:v,preferredDate:k,setPreferredDate:C,preferredTime:T,setPreferredTime:M,showingMode:P,setShowingMode:L,isSubmitting:$,onSubmit:_e})})]})})]})]})}function Jst(s){const{submitted:t,activeTab:n,setActiveTab:r,firstName:a,setFirstName:i,lastName:l,setLastName:o,email:c,setEmail:d,phone:u,setPhone:h,message:m,setMessage:p,preferredDate:x,setPreferredDate:y,preferredTime:g,setPreferredTime:b,showingMode:v,setShowingMode:k,isSubmitting:C,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(da,{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(fa,{value:n,onValueChange:M=>r(M),children:[e.jsxs(xa,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(ss,{value:"info",className:"gap-1.5",children:[e.jsx(ro,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(ss,{value:"showing",className:"gap-1.5",children:[e.jsx(ym,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:T,className:"space-y-3",children:[e.jsxs(ns,{value:"showing",className:"mt-0 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(ye,{id:"preferredDate",type:"date",value:x,onChange:M=>y(M.target.value),min:new Date().toISOString().split("T")[0],required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(vs,{value:g,onValueChange:b,children:[e.jsx(gs,{id:"preferredTime",children:e.jsx(bs,{placeholder:"Any time"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(Je,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(Je,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(vs,{value:v,onValueChange:M=>k(M),children:[e.jsx(gs,{id:"showingMode",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(Je,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(Je,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"firstName",children:"First Name *"}),e.jsx(ye,{id:"firstName",value:a,onChange:M=>i(M.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lastName",children:"Last Name"}),e.jsx(ye,{id:"lastName",value:l,onChange:M=>o(M.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email *"}),e.jsx(ye,{id:"email",type:"email",value:c,onChange:M=>d(M.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"phone",children:["Phone ",n==="showing"&&"*"]}),e.jsx(ye,{id:"phone",type:"tel",value:u,onChange:M=>h(M.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Ds,{id:"message",value:m,onChange:M=>p(M.target.value),rows:2})]}),e.jsx(B,{type:"submit",disabled:C,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:C?"Sending…":n==="showing"?"Request Showing":"Get More Info"}),e.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const CNe="/assets/levelup-logo-white-C2RAgAoG.png",fcs="/assets/listings-hero-noir-BHCJrhvU.jpg";var e5t={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(Xf,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(N,f){var _=f[0],S=f[1],E=f[2],D=f[3],z=_*D-E*S;return z?(N[0]=D*(z=1/z),N[1]=-S*z,N[2]=-E*z,N[3]=_*z,N):null}function h(){var N=new d(9);return d!=Float32Array&&(N[1]=0,N[2]=0,N[3]=0,N[5]=0,N[6]=0,N[7]=0),N[0]=1,N[4]=1,N[8]=1,N}function m(N,f){var _=f[0],S=f[1],E=f[2],D=f[3],z=f[4],H=f[5],Y=f[6],te=f[7],he=f[8];return N[0]=z*he-H*te,N[1]=E*te-S*he,N[2]=S*H-E*z,N[3]=H*Y-D*he,N[4]=_*he-E*Y,N[5]=E*D-_*H,N[6]=D*te-z*Y,N[7]=S*Y-_*te,N[8]=_*z-S*D,N}function p(N,f,_){var S=f[0],E=f[1],D=f[2],z=f[3],H=f[4],Y=f[5],te=f[6],he=f[7],ge=f[8],ve=_[0],Te=_[1],Ie=_[2],Ve=_[3],et=_[4],at=_[5],ft=_[6],ut=_[7],Nt=_[8];return N[0]=ve*S+Te*z+Ie*te,N[1]=ve*E+Te*H+Ie*he,N[2]=ve*D+Te*Y+Ie*ge,N[3]=Ve*S+et*z+at*te,N[4]=Ve*E+et*H+at*he,N[5]=Ve*D+et*Y+at*ge,N[6]=ft*S+ut*z+Nt*te,N[7]=ft*E+ut*H+Nt*he,N[8]=ft*D+ut*Y+Nt*ge,N}function x(){var N=new d(16);return d!=Float32Array&&(N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[11]=0,N[12]=0,N[13]=0,N[14]=0),N[0]=1,N[5]=1,N[10]=1,N[15]=1,N}function y(N){var f=new d(16);return f[0]=N[0],f[1]=N[1],f[2]=N[2],f[3]=N[3],f[4]=N[4],f[5]=N[5],f[6]=N[6],f[7]=N[7],f[8]=N[8],f[9]=N[9],f[10]=N[10],f[11]=N[11],f[12]=N[12],f[13]=N[13],f[14]=N[14],f[15]=N[15],f}function g(N){return N[0]=1,N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[5]=1,N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[10]=1,N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,N}function b(N,f){var _=f[0],S=f[1],E=f[2],D=f[3],z=f[4],H=f[5],Y=f[6],te=f[7],he=f[8],ge=f[9],ve=f[10],Te=f[11],Ie=f[12],Ve=f[13],et=f[14],at=f[15],ft=_*H-S*z,ut=_*Y-E*z,Nt=_*te-D*z,Mt=S*Y-E*H,It=S*te-D*H,xs=E*te-D*Y,es=he*Ve-ge*Ie,ps=he*et-ve*Ie,cs=he*at-Te*Ie,ds=ge*et-ve*Ve,mn=ge*at-Te*Ve,xn=ve*at-Te*et,kn=ft*xn-ut*mn+Nt*ds+Mt*cs-It*ps+xs*es;return kn?(N[0]=(H*xn-Y*mn+te*ds)*(kn=1/kn),N[1]=(E*mn-S*xn-D*ds)*kn,N[2]=(Ve*xs-et*It+at*Mt)*kn,N[3]=(ve*It-ge*xs-Te*Mt)*kn,N[4]=(Y*cs-z*xn-te*ps)*kn,N[5]=(_*xn-E*cs+D*ps)*kn,N[6]=(et*Nt-Ie*xs-at*ut)*kn,N[7]=(he*xs-ve*Nt+Te*ut)*kn,N[8]=(z*mn-H*cs+te*es)*kn,N[9]=(S*cs-_*mn-D*es)*kn,N[10]=(Ie*It-Ve*Nt+at*ft)*kn,N[11]=(ge*Nt-he*It-Te*ft)*kn,N[12]=(H*ps-z*ds-Y*es)*kn,N[13]=(_*ds-S*ps+E*es)*kn,N[14]=(Ve*ut-Ie*Mt-et*ft)*kn,N[15]=(he*Mt-ge*ut+ve*ft)*kn,N):null}function v(N,f,_){var S=f[0],E=f[1],D=f[2],z=f[3],H=f[4],Y=f[5],te=f[6],he=f[7],ge=f[8],ve=f[9],Te=f[10],Ie=f[11],Ve=f[12],et=f[13],at=f[14],ft=f[15],ut=_[0],Nt=_[1],Mt=_[2],It=_[3];return N[0]=ut*S+Nt*H+Mt*ge+It*Ve,N[1]=ut*E+Nt*Y+Mt*ve+It*et,N[2]=ut*D+Nt*te+Mt*Te+It*at,N[3]=ut*z+Nt*he+Mt*Ie+It*ft,N[4]=(ut=_[4])*S+(Nt=_[5])*H+(Mt=_[6])*ge+(It=_[7])*Ve,N[5]=ut*E+Nt*Y+Mt*ve+It*et,N[6]=ut*D+Nt*te+Mt*Te+It*at,N[7]=ut*z+Nt*he+Mt*Ie+It*ft,N[8]=(ut=_[8])*S+(Nt=_[9])*H+(Mt=_[10])*ge+(It=_[11])*Ve,N[9]=ut*E+Nt*Y+Mt*ve+It*et,N[10]=ut*D+Nt*te+Mt*Te+It*at,N[11]=ut*z+Nt*he+Mt*Ie+It*ft,N[12]=(ut=_[12])*S+(Nt=_[13])*H+(Mt=_[14])*ge+(It=_[15])*Ve,N[13]=ut*E+Nt*Y+Mt*ve+It*et,N[14]=ut*D+Nt*te+Mt*Te+It*at,N[15]=ut*z+Nt*he+Mt*Ie+It*ft,N}function k(N,f,_){var S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve=_[0],et=_[1],at=_[2];return f===N?(N[12]=f[0]*Ve+f[4]*et+f[8]*at+f[12],N[13]=f[1]*Ve+f[5]*et+f[9]*at+f[13],N[14]=f[2]*Ve+f[6]*et+f[10]*at+f[14],N[15]=f[3]*Ve+f[7]*et+f[11]*at+f[15]):(E=f[1],D=f[2],z=f[3],H=f[4],Y=f[5],te=f[6],he=f[7],ge=f[8],ve=f[9],Te=f[10],Ie=f[11],N[0]=S=f[0],N[1]=E,N[2]=D,N[3]=z,N[4]=H,N[5]=Y,N[6]=te,N[7]=he,N[8]=ge,N[9]=ve,N[10]=Te,N[11]=Ie,N[12]=S*Ve+H*et+ge*at+f[12],N[13]=E*Ve+Y*et+ve*at+f[13],N[14]=D*Ve+te*et+Te*at+f[14],N[15]=z*Ve+he*et+Ie*at+f[15]),N}function C(N,f,_){var S=_[0],E=_[1],D=_[2];return N[0]=f[0]*S,N[1]=f[1]*S,N[2]=f[2]*S,N[3]=f[3]*S,N[4]=f[4]*E,N[5]=f[5]*E,N[6]=f[6]*E,N[7]=f[7]*E,N[8]=f[8]*D,N[9]=f[9]*D,N[10]=f[10]*D,N[11]=f[11]*D,N[12]=f[12],N[13]=f[13],N[14]=f[14],N[15]=f[15],N}function T(N,f,_){var S=Math.sin(_),E=Math.cos(_),D=f[4],z=f[5],H=f[6],Y=f[7],te=f[8],he=f[9],ge=f[10],ve=f[11];return f!==N&&(N[0]=f[0],N[1]=f[1],N[2]=f[2],N[3]=f[3],N[12]=f[12],N[13]=f[13],N[14]=f[14],N[15]=f[15]),N[4]=D*E+te*S,N[5]=z*E+he*S,N[6]=H*E+ge*S,N[7]=Y*E+ve*S,N[8]=te*E-D*S,N[9]=he*E-z*S,N[10]=ge*E-H*S,N[11]=ve*E-Y*S,N}function M(N,f,_){var S=Math.sin(_),E=Math.cos(_),D=f[0],z=f[1],H=f[2],Y=f[3],te=f[8],he=f[9],ge=f[10],ve=f[11];return f!==N&&(N[4]=f[4],N[5]=f[5],N[6]=f[6],N[7]=f[7],N[12]=f[12],N[13]=f[13],N[14]=f[14],N[15]=f[15]),N[0]=D*E-te*S,N[1]=z*E-he*S,N[2]=H*E-ge*S,N[3]=Y*E-ve*S,N[8]=D*S+te*E,N[9]=z*S+he*E,N[10]=H*S+ge*E,N[11]=Y*S+ve*E,N}function P(N,f,_){var S=Math.sin(_),E=Math.cos(_),D=f[0],z=f[1],H=f[2],Y=f[3],te=f[4],he=f[5],ge=f[6],ve=f[7];return f!==N&&(N[8]=f[8],N[9]=f[9],N[10]=f[10],N[11]=f[11],N[12]=f[12],N[13]=f[13],N[14]=f[14],N[15]=f[15]),N[0]=D*E+te*S,N[1]=z*E+he*S,N[2]=H*E+ge*S,N[3]=Y*E+ve*S,N[4]=te*E-D*S,N[5]=he*E-z*S,N[6]=ge*E-H*S,N[7]=ve*E-Y*S,N}function L(N,f){return N[0]=f[0],N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[5]=f[1],N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[10]=f[2],N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,N}function I(N,f,_){var S,E,D,z=_[0],H=_[1],Y=_[2],te=Math.sqrt(z*z+H*H+Y*Y);return te0&&(D=1/Math.sqrt(D)),N[0]=f[0]*D,N[1]=f[1]*D,N[2]=f[2]*D,N}function De(N,f){return N[0]*f[0]+N[1]*f[1]+N[2]*f[2]}function Be(N,f,_){var S=f[0],E=f[1],D=f[2],z=_[0],H=_[1],Y=_[2];return N[0]=E*Y-D*H,N[1]=D*z-S*Y,N[2]=S*H-E*z,N}function Ne(N,f,_,S){var E=f[0],D=f[1],z=f[2];return N[0]=E+S*(_[0]-E),N[1]=D+S*(_[1]-D),N[2]=z+S*(_[2]-z),N}function Ge(N,f,_){var S=f[0],E=f[1],D=f[2],z=_[3]*S+_[7]*E+_[11]*D+_[15];return N[0]=(_[0]*S+_[4]*E+_[8]*D+_[12])/(z=z||1),N[1]=(_[1]*S+_[5]*E+_[9]*D+_[13])/z,N[2]=(_[2]*S+_[6]*E+_[10]*D+_[14])/z,N}function _e(N,f,_){var S=f[0],E=f[1],D=f[2];return N[0]=S*_[0]+E*_[3]+D*_[6],N[1]=S*_[1]+E*_[4]+D*_[7],N[2]=S*_[2]+E*_[5]+D*_[8],N}function Oe(N,f,_){var S=_[0],E=_[1],D=_[2],z=_[3],H=f[0],Y=f[1],te=f[2],he=E*te-D*Y,ge=D*H-S*te,ve=S*Y-E*H;return N[0]=H+z*(he+=he)+E*(ve+=ve)-D*(ge+=ge),N[1]=Y+z*ge+D*he-S*ve,N[2]=te+z*ve+S*ge-E*he,N}function Ae(N){return N[0]=0,N[1]=0,N[2]=0,N}function Xe(N,f){return N[0]===f[0]&&N[1]===f[1]&&N[2]===f[2]}var Ue=ue,Ze=oe,Qe=K;function Ye(){var N=new d(4);return d!=Float32Array&&(N[0]=0,N[1]=0,N[2]=0,N[3]=0),N}function nt(N,f,_){return N[0]=f[0]*_,N[1]=f[1]*_,N[2]=f[2]*_,N[3]=f[3]*_,N}function rt(N,f){var _=f[0],S=f[1],E=f[2],D=f[3],z=_*_+S*S+E*E+D*D;return z>0&&(z=1/Math.sqrt(z)),N[0]=_*z,N[1]=S*z,N[2]=E*z,N[3]=D*z,N}function Fe(N,f){return N[0]*f[0]+N[1]*f[1]+N[2]*f[2]+N[3]*f[3]}function dt(N,f,_){var S=f[0],E=f[1],D=f[2],z=f[3];return N[0]=_[0]*S+_[4]*E+_[8]*D+_[12]*z,N[1]=_[1]*S+_[5]*E+_[9]*D+_[13]*z,N[2]=_[2]*S+_[6]*E+_[10]*D+_[14]*z,N[3]=_[3]*S+_[7]*E+_[11]*D+_[15]*z,N}function Dt(){var N=new d(4);return d!=Float32Array&&(N[0]=0,N[1]=0,N[2]=0),N[3]=1,N}function pt(N){return N[0]=0,N[1]=0,N[2]=0,N[3]=1,N}function zt(N,f,_){_*=.5;var S=f[0],E=f[1],D=f[2],z=f[3],H=Math.sin(_),Y=Math.cos(_);return N[0]=S*Y+z*H,N[1]=E*Y+D*H,N[2]=D*Y-E*H,N[3]=z*Y-S*H,N}function Gt(N,f,_){_*=.5;var S=f[0],E=f[1],D=f[2],z=f[3],H=Math.sin(_),Y=Math.cos(_);return N[0]=S*Y-D*H,N[1]=E*Y+z*H,N[2]=D*Y+S*H,N[3]=z*Y-E*H,N}W(),Ye();var qs,As,Bt,At=rt,Is=(qs=W(),As=ee(1,0,0),Bt=ee(0,1,0),function(N,f,_){var S=De(f,_);return S<-.999999?(Be(qs,As,f),Qe(qs)<1e-6&&Be(qs,Bt,f),Le(qs,qs),function(E,D,z){z*=.5;var H=Math.sin(z);E[0]=H*D[0],E[1]=H*D[1],E[2]=H*D[2],E[3]=Math.cos(z)}(N,qs,Math.PI),N):S>.999999?(N[0]=0,N[1]=0,N[2]=0,N[3]=1,N):(Be(qs,f,_),N[0]=qs[0],N[1]=qs[1],N[2]=qs[2],N[3]=1+S,At(N,N))});function jt(){var N=new d(2);return d!=Float32Array&&(N[0]=0,N[1]=0),N}function Qs(N,f){var _=new d(2);return _[0]=N,_[1]=f,_}function cn(N,f,_){return N[0]=f,N[1]=_,N}function qt(N,f,_){return N[0]=f[0]+_[0],N[1]=f[1]+_[1],N}function Gs(N,f,_){return N[0]=f[0]-_[0],N[1]=f[1]-_[1],N}function Ls(N,f,_){return N[0]=f[0]*_,N[1]=f[1]*_,N}function sn(N){var f=N[0],_=N[1];return Math.sqrt(f*f+_*_)}function Hs(N,f){var _=f[0],S=f[1],E=_*_+S*S;return E>0&&(E=1/Math.sqrt(E)),N[0]=f[0]*E,N[1]=f[1]*E,N}function nn(N,f){return N[0]*f[0]+N[1]*f[1]}Dt(),Dt(),h();var tn,_n,Cn=Gs;function Un(N){return N&&N.__esModule&&Object.prototype.hasOwnProperty.call(N,"default")?N.default:N}jt();var Kr=function(){if(_n)return tn;function N(f,_,S,E){this.cx=3*f,this.bx=3*(S-f)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*_,this.by=3*(E-_)-this.cy,this.ay=1-this.cy-this.by,this.p1x=f,this.p1y=_,this.p2x=S,this.p2y=E}return _n=1,tn=N,N.prototype={sampleCurveX:function(f){return((this.ax*f+this.bx)*f+this.cx)*f},sampleCurveY:function(f){return((this.ay*f+this.by)*f+this.cy)*f},sampleCurveDerivativeX:function(f){return(3*this.ax*f+2*this.bx)*f+this.cx},solveCurveX:function(f,_){if(_===void 0&&(_=1e-6),f<0)return 0;if(f>1)return 1;for(var S=f,E=0;E<8;E++){var D=this.sampleCurveX(S)-f;if(Math.abs(D)<_)return S;var z=this.sampleCurveDerivativeX(S);if(Math.abs(z)<1e-6)break;S-=D/z}var H=0,Y=1;for(S=f,E=0;E<20&&(D=this.sampleCurveX(S),!(Math.abs(D-f)<_));E++)f>D?H=S:Y=S,S=.5*(Y-H)+H;return S},solve:function(f,_){return this.sampleCurveY(this.solveCurveX(f,_))}},tn}(),jr=Un(Kr);function Xs(N,f){this.x=N,this.y=f}function Ba(N,f){if(Array.isArray(N)){if(!Array.isArray(f)||N.length!==f.length)return!1;for(let _=0;_=1)return 1;const f=N*N,_=f*N;return 4*(N<.5?_:3*(N-f)+_-.75)}function _s(N,f,_,S){const E=new jr(N,f,_,S);return function(D){return E.solve(D)}}const We=_s(.25,.1,.25,1);function it(N,f,_){return Math.min(_,Math.max(f,N))}function gt(N,f,_){return(_=it((_-N)/(f-N),0,1))*_*(3-2*_)}function St(N,f,_){const S=_-f,E=((N-f)%S+S)%S+f;return E===f?_:E}function Ht(N,f,_){if(!N.length)return _(null,[]);let S=N.length;const E=new Array(N.length);let D=null;N.forEach((z,H)=>{f(z,(Y,te)=>{Y&&(D=Y),E[H]=te,--S===0&&_(D,E)})})}let ts=1;function Ms(){return ts++}function js(N){return N<=1?1:Math.pow(2,Math.ceil(Math.log2(N)))}function Zs(N,f){N.forEach(_=>{f[_]&&(f[_]=f[_].bind(f))})}function Tn(N,f,_){const S={};for(const E in N)S[E]=f.call(this,N[E],E,N);return S}function vn(N,f,_){const S={};for(const E in N)f.call(this,N[E],E,N)&&(S[E]=N[E]);return S}function _r(N){return Array.isArray(N)?N.map(_r):typeof N=="object"&&N?Tn(N,_r):N}function Jr(N,f){for(let _=0;_=0)return!0;return!1}const ha={};function Mr(N){ha[N]||(typeof console<"u"&&console.warn(N),ha[N]=!0)}function Xr(N,f,_){return(_.y-N.y)*(f.x-N.x)>(f.y-N.y)*(_.x-N.x)}function Qt(N){let f=0;for(let _,S,E=0,D=N.length,z=D-1;E@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(_,S,E,D)=>{const z=E||D;return f[S]=!z||z.toLowerCase(),""}),f["max-age"]){const _=parseInt(f["max-age"],10);isNaN(_)?delete f["max-age"]:f["max-age"]=_}return f}let Na,oa=null;function ur(N,f){return[N[4*f],N[4*f+1],N[4*f+2],N[4*f+3]]}function ao(N,f,_,S){for(;f<_;){const E=f+_>>1;N[E]>1;N[E]<=S?f=E+1:_=E}return f}function Va(N){return N>0?1/(1.001-N):1+N}function So(N){return N>0?1-1/(1.001-N):-N}function $a(N,f,_){return(N-f.min)*(_.max-_.min)/(f.max-f.min)+_.min}const Gr={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(!Gr.API_URL)return null;try{const N=new URL(Gr.API_URL);return N.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":N.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 Qn(){return new URL(Gr.DRACO_URL,Gr.API_URL).href}function qa(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(Na===void 0){if(typeof WebAssembly!="object")return!1;const N=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]);Na=WebAssembly.validate(N)}return Na}()?Gr.MESHOPT_SIMD_URL:Gr.MESHOPT_URL,Gr.API_URL).href}function xo(){return new URL(Gr.BUILDING_GEN_URL,Gr.API_URL).href}function Wo(N){return Gr.API_URL_REGEX.test(N)}function Co(N){return Gr.API_SPRITE_REGEX.test(N)}let Ko,Ud,Mu,Qm,Gc,lh;function qd(){return Ko==null&&(Ko=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Ko}const Wc={now:()=>Qm!==void 0?Qm:performance.now(),setNow(N){Qm=N},restoreNow(){Qm=void 0},frame(N){const f=requestAnimationFrame(N);return{cancel:()=>cancelAnimationFrame(f)}},getImageData(N,f=0){const{width:_,height:S}=N;Gc||(Gc=document.createElement("canvas"));const E=Gc.getContext("2d",{willReadFrequently:!0});if(!E)throw new Error("failed to create canvas 2d context");return(_>Gc.width||S>Gc.height)&&(Gc.width=_,Gc.height=S),E.clearRect(-f,-f,_+2*f,S+2*f),E.drawImage(N,0,0,_,S),E.getImageData(-f,-f,_+2*f,S+2*f)},resolveURL:N=>(Ud||(Ud=document.createElement("a")),Ud.href=N,Ud.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(Mu==null&&(Mu=window.matchMedia("(prefers-reduced-motion: reduce)")),Mu.matches)},hasCanvasFingerprintNoise(){if(lh!==void 0)return lh;if(!qd())return lh=!1,!1;const N=new OffscreenCanvas(85,1),f=N.getContext("2d",{willReadFrequently:!0});let _=0;for(let E=0;E0?`?${D}`:""}`}const Jm="mapbox-tiles";let xy=500,Ef=50;const Mf=["language","worldview","jobid"];let pu;function Px(){try{return caches}catch{}}function Do(){const N=Px();N&&pu==null&&(pu=N.open(Jm))}let go=1/0;const ep={supported:!1,testSupport:function(N){!Ah&&Ix&&(Vl?Cd(N):_m=N)}};let _m,Ix,Ah=!1,Vl=!1;const tp=typeof self<"u"?self:{};function Cd(N){const f=N.createTexture();N.bindTexture(N.TEXTURE_2D,f);try{if(N.texImage2D(N.TEXTURE_2D,0,N.RGBA,N.RGBA,N.UNSIGNED_BYTE,Ix),N.isContextLost())return;ep.supported=!0}catch{}N.deleteTexture(f),Ah=!0}tp.document&&(Ix=tp.document.createElement("img"),Ix.onload=function(){_m&&Cd(_m),_m=null,Vl=!0},Ix.onerror=function(){Ah=!0,_m=null},Ix.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const g0={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(g0);class Bb extends Error{constructor(f,_,S){_===401&&Wo(S)&&(f+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(f),this.status=_,this.url=S}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function sp(N){return typeof N=="object"&&N!==null&&"status"in N&&N.status===404}const ki=aa()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,np=function(N,f){return/^file:/.test(_=N.url)||/^file:/.test(ki())&&!/^\w+:/.test(_)?function(S,E){const D=new XMLHttpRequest;D.open(S.method||"GET",S.url,!0),S.type==="arrayBuffer"&&(D.responseType="arraybuffer");for(const z in S.headers)D.setRequestHeader(z,S.headers[z]);return S.type==="json"&&(D.responseType="text",D.setRequestHeader("Accept","application/json")),D.withCredentials=S.credentials==="include",D.onerror=()=>{E(new Error(D.statusText))},D.onload=()=>{if((D.status>=200&&D.status<300||D.status===0)&&D.response!==null){let z=D.response;if(S.type==="json")try{z=JSON.parse(D.response)}catch(Y){return E(Y)}const H=new Headers;D.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(Y=>{const te=Y.split(": "),he=te.shift(),ge=te.join(": ");H.append(he,ge)}),E(null,z,H)}else E(new Bb(D.statusText,D.status,S.url))},D.send(S.body),{cancel:()=>D.abort()}}(N,f):function(S,E){const D=new AbortController,z=new Request(S.url,{method:S.method||"GET",body:S.body,credentials:S.credentials,headers:S.headers,referrer:ki(),referrerPolicy:S.referrerPolicy,signal:D.signal});let H=!1,Y=!1;const te=(he=z.url).indexOf("sku=")>0&&Wo(he);var he;S.type==="json"&&z.headers.set("Accept","application/json");const ge=(Te,Ie,Ve)=>{if(Y)return;if(Te&&Te.message!=="SecurityError"&&Mr(Te.toString()),Ie&&Ve)return ve(Ie);const et=Date.now();fetch(z).then(at=>{if(at.ok){const ft=te?at.clone():null;return ve(at,ft,et)}return E(new Bb(at.statusText,at.status,S.url))}).catch(at=>{at.name!=="AbortError"&&E(new Error(`${at.message} ${S.url}`))})},ve=(Te,Ie,Ve)=>{(S.type==="arrayBuffer"?Te.arrayBuffer():S.type==="json"?Te.json():Te.text()).then(et=>{Y||(Ie&&Ve&&function(at,ft,ut){if(Do(),pu==null)return;const Nt=zr(ft.headers.get("cache-control")||"");if(Nt["no-store"])return;const Mt={status:ft.status,statusText:ft.statusText,headers:new Headers};ft.headers.forEach((cs,ds)=>Mt.headers.set(ds,cs)),Nt["max-age"]&&Mt.headers.set("Expires",new Date(ut+1e3*Nt["max-age"]).toUTCString());const It=Mt.headers.get("expires");if(!It||new Date(It).getTime()-ut<42e4)return;let xs=zb(at.url,{persistentParams:Mf});if(ft.status===206){const cs=at.headers.get("Range");if(!cs)return;Mt.status=200,xs=Kh(xs,{range:cs})}const es=new Response((ps=ft.status)!==200&&ps!==404&&[101,103,204,205,304].includes(ps)?null:ft.body,Mt);var ps;Do(),pu!=null&&pu.then(cs=>cs.put(xs,es)).catch(cs=>Mr(cs.message))}(z,Ie,Ve),H=!0,E(null,et,Te.headers))}).catch(et=>{Y||E(new Error(et.message))})};return te?function(Te,Ie){if(Do(),pu==null)return Ie(null);pu.then(Ve=>{let et=zb(Te.url,{persistentParams:Mf});const at=Te.headers.get("Range");at&&(et=Kh(et,{range:at})),Ve.match(et).then(ft=>{const ut=function(Nt){if(!Nt)return!1;const Mt=new Date(Nt.headers.get("expires")||0),It=zr(Nt.headers.get("cache-control")||"");return Number(Mt)>Date.now()&&!It["no-cache"]}(ft);Ve.delete(et).catch(Ie),ut&&Ve.put(et,ft.clone()).catch(Ie),Ie(null,ft,ut)}).catch(Ie)}).catch(Ie)}(z,ge):ge(null,null),{cancel:()=>{Y=!0,H||D.abort()}}}(N,f);var _},gy=function(N,f){return np(Object.assign(N,{type:"arrayBuffer"}),f)};function Yh(N){const f=document.createElement("a");return f.href=N,f.protocol===location.protocol&&f.host===location.host}let Hp,rp;Hp=[],rp=0;const wm=function(N,f){if(ep.supported&&(N.headers||(N.headers={}),N.headers.accept="image/webp,*/*"),rp>=Gr.MAX_PARALLEL_IMAGE_REQUESTS){const D={requestParameters:N,callback:f,cancelled:!1,cancel(){this.cancelled=!0}};return Hp.push(D),D}rp++;let _=!1;const S=()=>{if(!_)for(_=!0,rp--;Hp.length&&rp{S(),D?f(D):z&&function(Y,te){const he=new Blob([new Uint8Array(Y)],{type:"image/png"});createImageBitmap(he).then(ge=>{te(null,ge)}).catch(ge=>{te(new Error(`Could not load image because of ${ge.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(z,(Y,te)=>f(Y,te,H))});return{cancel:()=>{E.cancel(),S()}}};var ix,_g,ap,Zh={exports:{}},Gp={exports:{}},Rx={exports:{}},uv=function(){if(ap)return Zh.exports;ap=1;var N=(ix||(ix=1,Gp.exports=function(_,S){var E,D,z,H,Y,te,he,ge;for(D=_.length-(E=3&_.length),z=S,Y=3432918353,te=461845907,ge=0;ge>>16)*Y&65535)<<16)&4294967295)<<15|he>>>17))*te+(((he>>>16)*te&65535)<<16)&4294967295)<<13|z>>>19))+((5*(z>>>16)&65535)<<16)&4294967295))+(((H>>>16)+58964&65535)<<16);switch(he=0,E){case 3:he^=(255&_.charCodeAt(ge+2))<<16;case 2:he^=(255&_.charCodeAt(ge+1))<<8;case 1:z^=he=(65535&(he=(he=(65535&(he^=255&_.charCodeAt(ge)))*Y+(((he>>>16)*Y&65535)<<16)&4294967295)<<15|he>>>17))*te+(((he>>>16)*te&65535)<<16)&4294967295}return z^=_.length,z=2246822507*(65535&(z^=z>>>16))+((2246822507*(z>>>16)&65535)<<16)&4294967295,z=3266489909*(65535&(z^=z>>>13))+((3266489909*(z>>>16)&65535)<<16)&4294967295,(z^=z>>>16)>>>0}),Gp.exports),f=(_g||(_g=1,Rx.exports=function(_,S){for(var E,D=_.length,z=S^D,H=0;D>=4;)E=1540483477*(65535&(E=255&_.charCodeAt(H)|(255&_.charCodeAt(++H))<<8|(255&_.charCodeAt(++H))<<16|(255&_.charCodeAt(++H))<<24))+((1540483477*(E>>>16)&65535)<<16),z=1540483477*(65535&z)+((1540483477*(z>>>16)&65535)<<16)^(E=1540483477*(65535&(E^=E>>>24))+((1540483477*(E>>>16)&65535)<<16)),D-=4,++H;switch(D){case 3:z^=(255&_.charCodeAt(H+2))<<16;case 2:z^=(255&_.charCodeAt(H+1))<<8;case 1:z=1540483477*(65535&(z^=255&_.charCodeAt(H)))+((1540483477*(z>>>16)&65535)<<16)}return z=1540483477*(65535&(z^=z>>>13))+((1540483477*(z>>>16)&65535)<<16),(z^=z>>>15)>>>0}),Rx.exports);return Zh.exports=N,Zh.exports.murmur3=N,Zh.exports.murmur2=f,Zh.exports}(),rd=Un(uv);class Tc{constructor(f,..._){Object.assign(this,_[0]||{}),this.type=f}}class ip extends Tc{constructor(f,_={}){super("error",Object.assign({error:f},_))}}function Vd(N,f,_){_[N]&&_[N].indexOf(f)!==-1||(_[N]=_[N]||[],_[N].push(f))}function op(N,f,_){if(_&&_[N]){const S=_[N].indexOf(f);S!==-1&&_[N].splice(S,1)}}class Xh{on(f,_){return this._listeners=this._listeners||{},Vd(f,_,this._listeners),this}off(f,_){return op(f,_,this._listeners),op(f,_,this._oneTimeListeners),this}once(f,_){return _?(this._oneTimeListeners=this._oneTimeListeners||{},Vd(f,_,this._oneTimeListeners),this):new Promise(S=>{this.once(f,S)})}fire(f,_){const S=typeof f=="string"?new Tc(f,_):f,E=S.type;if(this.listens(E)){S.target=this;const D=this._listeners&&this._listeners[E]?this._listeners[E].slice():[];for(const Y of D)Y.call(this,S);const z=this._oneTimeListeners&&this._oneTimeListeners[E]?this._oneTimeListeners[E].slice():[];for(const Y of z)op(E,Y,this._oneTimeListeners),Y.call(this,S);const H=this._eventedParent;if(H){const Y=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(S,Y),H.fire(S)}}else S instanceof ip&&console.error(S.error);return this}listens(f){return!!(this._listeners&&this._listeners[f]&&this._listeners[f].length>0||this._oneTimeListeners&&this._oneTimeListeners[f]&&this._oneTimeListeners[f].length>0||this._eventedParent&&this._eventedParent.listens(f))}setEventedParent(f,_){return this._eventedParent=f,this._eventedParentData=_,this}}class Zt{constructor(f){typeof f=="string"?this.name=f:(this.name=f.name,this.iconsetId=f.iconsetId)}static from(f){return new Zt(f)}static toString(f){return f.iconsetId?`${f.name}${f.iconsetId}`:f.name}static parse(f){const[_,S]=f.split("");return new Zt({name:_,iconsetId:S})}static isEqual(f,_){return f.name===_.name&&f.iconsetId===_.iconsetId}toString(){return Zt.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var $e,yt={},is=function(){if($e)return yt;$e=1;var N={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function f(D){return(D=Math.round(D))<0?0:D>255?255:D}function _(D){return f(D[D.length-1]==="%"?parseFloat(D)/100*255:parseInt(D))}function S(D){return(z=D[D.length-1]==="%"?parseFloat(D)/100:parseFloat(D))<0?0:z>1?1:z;var z}function E(D,z,H){return H<0?H+=1:H>1&&(H-=1),6*H<1?D+(z-D)*H*6:2*H<1?z:3*H<2?D+(z-D)*(2/3-H)*6:D}try{yt.parseCSSColor=function(D){var z,H=D.replace(/ /g,"").toLowerCase();if(H in N)return N[H].slice();if(H[0]==="#")return H.length===4?(z=parseInt(H.substr(1),16))>=0&&z<=4095?[(3840&z)>>4|(3840&z)>>8,240&z|(240&z)>>4,15&z|(15&z)<<4,1]:null:H.length===7&&(z=parseInt(H.substr(1),16))>=0&&z<=16777215?[(16711680&z)>>16,(65280&z)>>8,255&z,1]:null;var Y=H.indexOf("("),te=H.indexOf(")");if(Y!==-1&&te+1===H.length){var he=H.substr(0,Y),ge=H.substr(Y+1,te-(Y+1)).split(","),ve=1;switch(he){case"rgba":if(ge.length!==4)return null;ve=S(ge.pop());case"rgb":return ge.length!==3?null:[_(ge[0]),_(ge[1]),_(ge[2]),ve];case"hsla":if(ge.length!==4)return null;ve=S(ge.pop());case"hsl":if(ge.length!==3)return null;var Te=(parseFloat(ge[0])%360+360)%360/360,Ie=S(ge[1]),Ve=S(ge[2]),et=Ve<=.5?Ve*(Ie+1):Ve+Ie-Ve*Ie,at=2*Ve-et;return[f(255*E(at,et,Te+1/3)),f(255*E(at,et,Te)),f(255*E(at,et,Te-1/3)),ve];default:return null}}return null}}catch{}return yt}();class us{constructor(f,_,S,E=1){this.r=f,this.g=_,this.b=S,this.a=E}static parse(f){if(!f)return;if(f instanceof us)return f;if(typeof f!="string")return;const _=is.parseCSSColor(f);return _?new us(_[0]/255,_[1]/255,_[2]/255,_[3]):void 0}toString(){const[f,_,S,E]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*f)},${Math.round(255*_)},${Math.round(255*S)},${E})`}toNonPremultipliedRenderColor(f){const{r:_,g:S,b:E,a:D}=this;return new Dn(f,_,S,E,D)}toPremultipliedRenderColor(f){const{r:_,g:S,b:E,a:D}=this;return new er(f,_*D,S*D,E*D,D)}clone(){return new us(this.r,this.g,this.b,this.a)}}class en{constructor(f,_,S,E,D,z=!1){if(this.premultiplied=!1,this.premultiplied=z,f){const H=f.image.height,Y=H*H;this.premultiplied?(_=D===0?0:_/D*(H-1),S=D===0?0:S/D*(H-1),E=D===0?0:E/D*(H-1)):(_*=H-1,S*=H-1,E*=H-1),_=Math.max(0,Math.min(H-1,_)),S=Math.max(0,Math.min(H-1,S)),E=Math.max(0,Math.min(H-1,E));const te=Math.floor(_),he=Math.floor(S),ge=Math.floor(E),ve=Math.ceil(_),Te=Math.ceil(S),Ie=Math.ceil(E),Ve=_-te,et=S-he,at=E-ge,ft=f.image.data,ut=4*(te+he*Y+ge*H),Nt=4*(te+he*Y+Ie*H),Mt=4*(te+Te*Y+ge*H),It=4*(te+Te*Y+Ie*H),xs=4*(ve+he*Y+ge*H),es=4*(ve+he*Y+Ie*H),ps=4*(ve+Te*Y+ge*H),cs=4*(ve+Te*Y+Ie*H);this.r=xr(xr(xr(ft[ut],ft[Nt],at),xr(ft[Mt],ft[It],at),et),xr(xr(ft[xs],ft[es],at),xr(ft[ps],ft[cs],at),et),Ve)/255*(this.premultiplied?D:1),this.g=xr(xr(xr(ft[ut+1],ft[Nt+1],at),xr(ft[Mt+1],ft[It+1],at),et),xr(xr(ft[xs+1],ft[es+1],at),xr(ft[ps+1],ft[cs+1],at),et),Ve)/255*(this.premultiplied?D:1),this.b=xr(xr(xr(ft[ut+2],ft[Nt+2],at),xr(ft[Mt+2],ft[It+2],at),et),xr(xr(ft[xs+2],ft[es+2],at),xr(ft[ps+2],ft[cs+2],at),et),Ve)/255*(this.premultiplied?D:1),this.a=D}else this.r=_,this.g=S,this.b=E,this.a=D}toArray(){const{r:f,g:_,b:S,a:E}=this;return[255*f,255*_,255*S,E]}toHslaArray(){let{r:f,g:_,b:S,a:E}=this;if(this.premultiplied){if(E===0)return[0,0,0,0];const Ie=1/E;f*=Ie,_*=Ie,S*=Ie}const D=Math.min(Math.max(f,0),1),z=Math.min(Math.max(_,0),1),H=Math.min(Math.max(S,0),1),Y=Math.min(D,z,H),te=Math.max(D,z,H),he=te-Y,ge=.5*(Y+te);if(he===0)return[0,0,100*ge,E];const ve=ge>.5?he/(2-te-Y):he/(te+Y);let Te;switch(te){case D:Te=60*((z-H)/he+(zxr(S,f[E],_))}us.black=new us(0,0,0,1),us.white=new us(1,1,1,1),us.transparent=new us(0,0,0,0),us.red=new us(1,0,0,1),us.blue=new us(0,0,1,1);var Zi=Object.freeze({__proto__:null,array:Ha,color:function(N,f,_){return new us(xr(N.r,f.r,_),xr(N.g,f.g,_),xr(N.b,f.b,_),xr(N.a,f.a,_))},number:xr});class Hi extends Error{constructor(f,_){super(_),this.message=_,this.key=f}}class rl{constructor(f,_=[]){this.parent=f,this.bindings={};for(const[S,E]of _)this.bindings[S]=E}concat(f){return new rl(this,f)}get(f){if(this.bindings[f])return this.bindings[f];if(this.parent)return this.parent.get(f);throw new Error(`${f} not found in scope.`)}has(f){return!!this.bindings[f]||!!this.parent&&this.parent.has(f)}}const Dc={kind:"null"},Lr={kind:"number"},ti={kind:"string"},ui={kind:"boolean"},Rl={kind:"color"},bc={kind:"object"},Gi={kind:"value"},Qh={kind:"collator"},wg={kind:"formatted"},jg={kind:"resolvedImage"};function fu(N,f){return{kind:"array",itemType:N,N:f}}function Hl(N){if(N.kind==="array"){const f=Hl(N.itemType);return typeof N.N=="number"?`array<${f}, ${N.N}>`:N.itemType.kind==="value"?"array":`array<${f}>`}return N.kind}const b1=[Dc,Lr,ti,ui,Rl,wg,bc,fu(Gi),jg];function Dx(N,f){if(f.kind==="error")return null;if(N.kind==="array"){if(f.kind==="array"&&(f.N===0&&f.itemType.kind==="value"||!Dx(N.itemType,f.itemType))&&(typeof N.N!="number"||N.N===f.N))return null}else{if(N.kind===f.kind)return null;if(N.kind==="value"){for(const _ of b1)if(!Dx(_,f))return null}}return`Expected ${Hl(N)} but found ${Hl(f)} instead.`}function y0(N,f){return f.some(_=>_.kind===N.kind)}function Hd(N,f){return f.some(_=>_==="null"?N===null:_==="array"?Array.isArray(N):_==="object"?N&&!Array.isArray(N)&&typeof N=="object":_===typeof N)}function lp(N,f){return N.kind==="array"&&f.kind==="array"?N.N===f.N&&lp(N.itemType,f.itemType):N.kind===f.kind}class v0{constructor(f,_,S){this.sensitivity=f?_?"variant":"case":_?"accent":"base",this.locale=S,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(f,_){return this.collator.compare(f,_)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class yy{constructor(f,_,S,E,D){this.text=f.normalize?f.normalize():f,this.image=_,this.scale=S,this.fontStack=E,this.textColor=D}}class ad{constructor(f){this.sections=f}static fromString(f){return new ad([new yy(f,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(f=>f.text.length!==0||!!f.image&&f.image.hasPrimary())}static factory(f){return f instanceof ad?f:ad.fromString(f)}toString(){return this.sections.length===0?"":this.sections.map(f=>f.text).join("")}serialize(){const f=["format"];for(const _ of this.sections){if(_.image){const E=_.image.getPrimary().id.toString();f.push(["image",E]);continue}f.push(_.text);const S={};_.fontStack&&(S["text-font"]=["literal",_.fontStack.split(",")]),_.scale&&(S["font-scale"]=_.scale),_.textColor&&(S["text-color"]=["rgba"].concat(_.textColor.toNonPremultipliedRenderColor(null).toArray())),f.push(S)}return f}}class gd{constructor(f,_={}){this.id=Zt.from(f),this.params=_.params,this.sx=_.sx||1,this.sy=_.sy||1}toString(){return JSON.stringify(this)}static parse(f){let _,S,E,D;try{({id:_,params:S,sx:E,sy:D}=JSON.parse(f)||{})}catch{return null}return _?new gd(_,{params:S,sx:E,sy:D}):null}scaleSelf(f,_=f){return this.sx*=f,this.sy*=_,this}}class Lu{constructor(f,_,S,E,D=!1){this.primaryId=Zt.from(f),this.primaryOptions=_,S&&(this.secondaryId=Zt.from(S)),this.secondaryOptions=E,this.available=D}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new gd(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new gd(this.secondaryId,this.secondaryOptions):null}static from(f){return typeof f=="string"?Lu.build({name:f}):f}static build(f,_,S,E){return!f||typeof f=="object"&&!("name"in f)?null:new Lu(f,S,_,E)}}function jm(N,f,_,S){return typeof N=="number"&&N>=0&&N<=255&&typeof f=="number"&&f>=0&&f<=255&&typeof _=="number"&&_>=0&&_<=255?S===void 0||typeof S=="number"&&S>=0&&S<=1?null:`Invalid rgba value [${[N,f,_,S].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof S=="number"?[N,f,_,S]:[N,f,_]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Lf(N){if(N===null||typeof N=="string"||typeof N=="boolean"||typeof N=="number"||N instanceof us||N instanceof v0||N instanceof ad||N instanceof Lu)return!0;if(Array.isArray(N)){for(const f of N)if(!Lf(f))return!1;return!0}if(typeof N=="object"){for(const f in N)if(!Lf(N[f]))return!1;return!0}return!1}function yl(N){if(N===null)return Dc;if(typeof N=="string")return ti;if(typeof N=="boolean")return ui;if(typeof N=="number")return Lr;if(N instanceof us)return Rl;if(N instanceof v0)return Qh;if(N instanceof ad)return wg;if(N instanceof Lu)return jg;if(Array.isArray(N)){const f=N.length;let _;for(const S of N){const E=yl(S);if(_){if(_===E)continue;_=Gi;break}_=E}return fu(_||Gi,f)}return bc}function ka(N){const f=typeof N;return N===null?"":f==="string"||f==="number"||f==="boolean"?String(N):N instanceof ad||N instanceof Lu||N instanceof us?N.toString():JSON.stringify(N)}class Ir{constructor(f,_){this.type=f,this.value=_}static parse(f,_){if(f.length!==2)return _.error(`'literal' expression requires exactly one argument, but found ${f.length-1} instead.`);if(!Lf(f[1]))return _.error("invalid value");const S=f[1];let E=yl(S);const D=_.expectedType;return E.kind!=="array"||E.N!==0||!D||D.kind!=="array"||typeof D.N=="number"&&D.N!==0||(E=D),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 us?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof ad?this.value.serialize():this.value}}class Fl{constructor(f){this.name="ExpressionEvaluationError",this.message=f}toJSON(){return this.message}}const Sa={string:ti,number:Lr,boolean:ui,object:bc};class Nm{constructor(f,_){this.type=f,this.args=_}static parse(f,_){if(f.length<2)return _.error("Expected at least one argument.");let S,E=1;const D=f[0];if(D==="array"){let H,Y;if(f.length>2){const te=f[1];if(typeof te!="string"||!(te in Sa)||te==="object")return _.error('The item type argument of "array" must be one of string, number, boolean',1);H=Sa[te],E++}else H=Gi;if(f.length>3){if(f[2]!==null&&(typeof f[2]!="number"||f[2]<0||f[2]!==Math.floor(f[2])))return _.error('The length argument to "array" must be a positive integer literal',2);Y=f[2],E++}S=fu(H,Y)}else S=Sa[D];const z=[];for(;Ef.outputDefined())}serialize(){const f=this.type,_=[f.kind];if(f.kind==="array"){const S=f.itemType;if(S.kind==="string"||S.kind==="number"||S.kind==="boolean"){_.push(S.kind);const E=f.N;(typeof E=="number"||this.args.length>1)&&_.push(E)}}return _.concat(this.args.map(S=>S.serialize()))}}class id{constructor(f){this.type=wg,this.sections=f}static parse(f,_){if(f.length<2)return _.error("Expected at least one argument.");const S=f[1];if(!Array.isArray(S)&&typeof S=="object")return _.error("First argument must be an image or text section.");const E=[];let D=!1;for(let z=1;z<=f.length-1;++z){const H=f[z];if(D&&typeof H=="object"&&!Array.isArray(H)){D=!1;let Y=null;if(H["font-scale"]&&(Y=_.parseObjectValue(H["font-scale"],z,"font-scale",Lr),!Y))return null;let te=null;if(H["text-font"]&&(te=_.parseObjectValue(H["text-font"],z,"text-font",fu(ti)),!te))return null;let he=null;if(H["text-color"]&&(he=_.parseObjectValue(H["text-color"],z,"text-color",Rl),!he))return null;const ge=E[E.length-1];ge.scale=Y,ge.font=te,ge.textColor=he}else{const Y=_.parse(f[z],z,Gi);if(!Y)return null;const te=Y.type.kind;if(te!=="string"&&te!=="value"&&te!=="null"&&te!=="resolvedImage")return _.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");D=!0,E.push({content:Y,scale:null,font:null,textColor:null})}}return new id(E)}evaluate(f){return new ad(this.sections.map(_=>{const S=_.content.evaluate(f);return lp(yl(S),jg)?new yy("",S,null,null,null):new yy(ka(S),null,_.scale?_.scale.evaluate(f):null,_.font?_.font.evaluate(f).join(","):null,_.textColor?_.textColor.evaluate(f):null)}))}eachChild(f){for(const _ of this.sections)f(_.content),_.scale&&f(_.scale),_.font&&f(_.font),_.textColor&&f(_.textColor)}outputDefined(){return!1}serialize(){const f=["format"];for(const _ of this.sections){f.push(_.content.serialize());const S={};_.scale&&(S["font-scale"]=_.scale.serialize()),_.font&&(S["text-font"]=_.font.serialize()),_.textColor&&(S["text-color"]=_.textColor.serialize()),f.push(S)}return f}}class la{constructor(f,_,S,E){this._imageWarnHistory={},this.type=jg,this.namePrimary=f,this.nameSecondary=_,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(f,_){if(f.length<2)return _.error("Expected two or more arguments.");let S=1;const E=[];function D(){if(SZt.isEqual(z,D)),E.available){const z=E.getSecondary()?E.getSecondary().id:null;z&&(E.available=f.availableImages.some(H=>Zt.isEqual(H,z)))}}return E}eachChild(f){if(f(this.namePrimary),this.paramsPrimary)for(const _ in this.paramsPrimary)this.paramsPrimary[_]&&f(this.paramsPrimary[_]);if(this.nameSecondary&&(f(this.nameSecondary),this.paramsSecondary))for(const _ in this.paramsSecondary)this.paramsSecondary[_]&&f(this.paramsSecondary[_])}outputDefined(){return!1}serializeOptions(f,_){const S={};if(_&&(S.iconset={id:_}),f){S.params={};for(const E in f)f[E]&&(S.params[E]=f[E].serialize())}return Object.keys(S).length>0?S:void 0}serialize(){const f=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const _=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);_&&f.push(_)}if(this.nameSecondary&&(f.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const _=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);_&&f.push(_)}return f}}function Ox(N){return ox(N)?"string":b0(N)?"number":Pf(N)?"boolean":Array.isArray(N)?"array":N===null?"null":Ng(N)?"object":typeof N}function Ng(N){return N!=null&&!Array.isArray(N)&&typeof N!="function"&&!(N instanceof String||N instanceof Number||N instanceof Boolean)&&typeof N=="object"}function ox(N){return typeof N=="string"||N instanceof String}function b0(N){return typeof N=="number"||N instanceof Number}function Pf(N){return typeof N=="boolean"||N instanceof Boolean}const Oc={"to-boolean":ui,"to-color":Rl,"to-number":Lr,"to-string":ti};class cp{constructor(f,_){this.type=f,this.args=_}static parse(f,_){if(f.length<2)return _.error("Expected at least one argument.");const S=f[0],E=[];let D=Dc;if(S==="to-array"){if(!Array.isArray(f[1]))return null;const z=f[1].length;if(_.expectedType){if(_.expectedType.kind!=="array")return _.error(`Expected ${_.expectedType.kind} but found array.`);D=fu(_.expectedType.itemType,z)}else{if(!(z>0&&Lf(f[1][0])))return null;D=fu(yl(f[1][0]),z)}for(let H=0;H4?`Invalid rbga value ${JSON.stringify(_)}: expected an array containing either three or four numeric values.`:jm(_[0],_[1],_[2],_[3]),!S))return new us(_[0]/255,_[1]/255,_[2]/255,_[3])}throw new Fl(S||`Could not parse color from value '${typeof _=="string"?_:String(JSON.stringify(_))}'`)}if(this.type.kind==="number"){let _=null;for(const S of this.args){if(_=S.evaluate(f),_===null)return 0;const E=Number(_);if(!isNaN(E))return E}throw new Fl(`Could not convert ${JSON.stringify(_)} to number.`)}return this.type.kind==="formatted"?ad.fromString(ka(this.args[0].evaluate(f))):this.type.kind==="resolvedImage"?Lu.build(ka(this.args[0].evaluate(f))):this.type.kind==="array"?this.args.map(_=>_.evaluate(f)):ka(this.args[0].evaluate(f))}eachChild(f){this.args.forEach(f)}outputDefined(){return this.args.every(f=>f.outputDefined())}serialize(){if(this.type.kind==="formatted")return new id([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new la(this.args[0]).serialize();const f=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(_=>{f.push(_.serialize())}),f}}const ch=["Unknown","Point","LineString","Polygon"];class xu{constructor(f,_,S){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=f,this.options=_,this.iconImageUseTheme=S}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?ch[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}measureLight(f){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const f=this.featureDistanceData.center,_=this.featureDistanceData.scale,{x:S,y:E}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(S*_-f[0])+this.featureDistanceData.bearing[1]*(E*_-f[1])}return 0}parseColor(f){let _=this._parseColorCache[f];return _||(_=this._parseColorCache[f]=us.parse(f)),_}getConfig(f){return this.options?this.options.get(f):null}}class Kc{constructor(f,_,S,E,D){this.name=f,this.type=_,this._evaluate=S,this.args=E,this._overloadIndex=D}evaluate(f){if(!this._evaluate){const _=Kc.definitions[this.name];this._evaluate=Array.isArray(_)?_[2]:_.overloads[this._overloadIndex][1]}return this._evaluate(f,this.args)}eachChild(f){this.args.forEach(f)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(f=>f.serialize()))}static parse(f,_){const S=f[0],E=Kc.definitions[S];if(!E)return _.error(`Unknown expression "${S}". If you wanted a literal array, use ["literal", [...]].`,0);const D=Array.isArray(E)?E[0]:E.type,z=Array.isArray(E)?[[E[1],E[2]]]:E.overloads,H=[];let Y=null,te=-1;for(const[he,ge]of z){if(Array.isArray(he)&&he.length!==f.length-1)continue;H.push(he),te++,Y=new a2(_.registry,_.path,null,_.scope,void 0,_._scope,_.options,_.iconImageUseTheme);const ve=[];let Te=!1;for(let Ie=1;Ieve)).map(dp).join(" | "),ge=[];for(let ve=1;ve_;){if(S-_>600){const Y=S-_+1,te=f-_+1,he=Math.log(Y),ge=.5*Math.exp(2*he/3),ve=.5*Math.sqrt(he*ge*(Y-ge)/Y)*(te-Y/2<0?-1:1);mv(N,f,Math.max(_,Math.floor(f-te*ge/Y+ve)),Math.min(S,Math.floor(f+(Y-te)*ge/Y+ve)),E)}const D=N[f];let z=_,H=S;for(_c(N,_,f),E(N[S],D)>0&&_c(N,_,S);z0;)H--}E(N[_],D)===0?_c(N,_,H):(H++,_c(N,H,S)),H<=f&&(_=H+1),f<=H&&(S=H-1)}}function _c(N,f,_){const S=N[f];N[f]=N[_],N[_]=S}function Fx(N,f){return Nf?1:0}function _0(N){let f=0;for(let _,S,E=0,D=N.length,z=D-1;E=f[2]||N[1]<=f[1]||N[3]>=f[3])}function _1(N,f,_){const S=N[0]-f[0],E=N[1]-f[1],D=N[0]-_[0],z=N[1]-_[1];return S*z-D*E===0&&S*D<=0&&E*z<=0}function gu(N,f,_){return f[1]>N[1]!=_[1]>N[1]&&N[0]<(_[0]-f[0])*(N[1]-f[1])/(_[1]-f[1])+f[0]}function zl(N,f,_=!1){let S=!1;for(let E=0,D=f.length;E0&&H<0||z<0&&H>0}function $o(N,f,_,S){return(E=[S[0]-_[0],S[1]-_[1]])[0]*(D=[f[0]-N[0],f[1]-N[1]])[1]-E[1]*D[0]!==0&&!(!Yo(N,f,_,S)||!Yo(_,S,N,f));var E,D}function Gd(N){const f=new Xs(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),_=new Xs(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const S of N[0])f.x>S.x&&(f.x=S.x),f.y>S.y&&(f.y=S.y),_.x_[2]){const E=.5*S;let D=N[0]-_[0]>E?-S:_[0]-N[0]>E?S:0;D===0&&(D=N[0]-_[2]>E?-S:_[2]-N[0]>E?S:0),N[0]+=D}dh(f,N)}function j0(N,f,_,S){const E=Math.pow(2,S.z)*Yc,D=[S.x*Yc,S.y*Yc],z=[];if(!N)return z;for(const H of N)for(const Y of H){const te=[Y.x+D[0],Y.y+D[1]];yu(te,f,_,E),z.push(te)}return z}function pw(N,f,_,S){const E=Math.pow(2,S.z)*Yc,D=[S.x*Yc,S.y*Yc],z=[];if(!N)return z;for(const Y of N){const te=[];for(const he of Y){const ge=[he.x+D[0],he.y+D[1]];dh(f,ge),te.push(ge)}z.push(te)}if(f[2]-f[0]<=E/2){(H=f)[0]=H[1]=1/0,H[2]=H[3]=-1/0;for(const Y of z)for(const te of Y)yu(te,f,_,E)}var H;return z}class N0{constructor(f,_){this.type=ui,this.geojson=f,this.geometries=_}static parse(f,_){if(f.length!==2)return _.error(`'within' expression requires exactly one argument, but found ${f.length-1} instead.`);if(Lf(f[1])){const S=f[1];if(S.type==="FeatureCollection")for(let E=0;E_)return Vb(D,z,(_-(S-H))/H)}return f[f.length-1]}pointToSegmentDistance(f,_,S){let[E,D]=_,z=up(S[0]-E)*this.kx,H=(S[1]-D)*this.ky;if(z!==0||H!==0){const Y=(up(f[0]-E)*this.kx*z+(f[1]-D)*this.ky*H)/(z*z+H*H);Y>1?(E=S[0],D=S[1]):Y>0&&(E+=z/this.kx*Y,D+=H/this.ky*Y)}return z=up(f[0]-E)*this.kx,H=(f[1]-D)*this.ky,Math.sqrt(z*z+H*H)}pointOnLine(f,_){let S=1/0,E=f[0][0],D=f[0][1],z=0,H=0;for(let Y=0;Y1?(te=f[Y+1][0],he=f[Y+1][1]):Te>0&&(te+=ge/this.kx*Te,he+=ve/this.ky*Te)),ge=up(_[0]-te)*this.kx,ve=(_[1]-he)*this.ky;const Ie=ge*ge+ve*ve;IeD.index||E.index===D.index&&E.t>D.t){const te=E;E=D,D=te}const z=[E.point],H=E.index+1,Y=D.index;!s2(S[H],z[0])&&H<=Y&&z.push(S[H]);for(let te=H+1;te<=Y;te++)z.push(S[te]);return s2(S[Y],D.point)||z.push(D.point),z}lineSliceAlong(f,_,S){let E=0;const D=[];for(let z=0;zf&&D.length===0&&D.push(Vb(H,Y,(f-(E-te))/te)),E>=_)return D.push(Vb(H,Y,(_-(E-te))/te)),D;E>f&&D.push(Y)}return D}bufferPoint(f,_){const S=_/this.ky,E=_/this.kx;return[f[0]-E,f[1]-S,f[0]+E,f[1]+S]}bufferBBox(f,_){const S=_/this.ky,E=_/this.kx;return[f[0]-E,f[1]-S,f[2]+E,f[3]+S]}insideBBox(f,_){return up(f[0]-_[0])>=0&&up(f[0]-_[2])<=0&&f[1]>=_[1]&&f[1]<=_[3]}}function s2(N,f){return N[0]===f[0]&&N[1]===f[1]}function Vb(N,f,_){const S=up(f[0]-N[0]);return[N[0]+S*_,N[1]+(f[1]-N[1])*_]}function up(N){for(;N<-180;)N+=360;for(;N>180;)N-=360;return N}class hh{constructor(f=[],_=(S,E)=>SE?1:0){if(this.data=f,this.length=this.data.length,this.compare=_,this.length>0)for(let S=(this.length>>1)-1;S>=0;S--)this._down(S)}push(f){this.data.push(f),this._up(this.length++)}pop(){if(this.length===0)return;const f=this.data[0],_=this.data.pop();return--this.length>0&&(this.data[0]=_,this._down(0)),f}peek(){return this.data[0]}_up(f){const{data:_,compare:S}=this,E=_[f];for(;f>0;){const D=f-1>>1,z=_[D];if(S(E,z)>=0)break;_[f]=z,f=D}_[f]=E}_down(f){const{data:_,compare:S}=this,E=this.length>>1,D=_[f];for(;f=0)break;_[f]=_[z],f=z}_[f]=D}}var nr=8192;function N1(N,f){return f.dist-N.dist}function k1(N){const f=[1/0,1/0,-1/0,-1/0];if(f.length!==N.length)return!1;for(let _=0;_=N[0]&&N[1]N[1])return[null,null];const _=pv(N);if(f){if(_===2)return[N,null];const S=Math.floor(_/2);return[[N[0],N[0]+S],[N[0]+S,N[1]]]}{if(_===1)return[N,null];const S=Math.floor(_/2)-1;return[[N[0],N[0]+S],[N[0]+S+1,N[1]]]}}function k0(N,f){const _=[1/0,1/0,-1/0,-1/0];if(!Wp(f,N.length))return _;for(let S=f[0];S<=f[1];++S)dh(_,N[S]);return _}function Hb(N){const f=[1/0,1/0,-1/0,-1/0];for(let _=0;_f[2]&&(S=N[0]-f[2]),N[1]>f[3]&&(E=N[1]-f[3]),N[3]=S)return S;if(If(E,D)){if(Gb(N,f))return 0}else if(Gb(f,N))return 0;let z=S;for(const H of N)for(let Y=0,te=H.length,he=te-1;Y=D)continue;const he=te.range1;if(pv(he)<=H){if(!Wp(he,N.length))return NaN;if(f){const ge=wc(N,he,_,S);if((D=Math.min(D,ge))===0)return D}else for(let ge=he[0];ge<=he[1];++ge){const ve=iC(N[ge],_,S);if((D=Math.min(D,ve))===0)return D}}else{const ge=vy(he,f);if(ge[0]!==null){const ve=fv(k0(N,ge[0]),Y,S);ve=z)continue;const ge=he.range1,ve=he.range2;if(pv(ge)<=Y&&pv(ve)<=te){if(!Wp(ge,N.length)||!Wp(ve,_.length))return NaN;if(f&&S?z=Math.min(z,E6(N,ge,_,ve,E)):f||S?f&&!S?z=Math.min(z,WN(_,ve,N,ge,E)):!f&&S&&(z=Math.min(z,WN(N,ge,_,ve,E))):z=Math.min(z,jS(N,ge,_,ve,E)),z===0)return z}else{const Te=vy(ge,f),Ie=vy(ve,S);S1(H,z,E,N,_,Te[0],Ie[0]),S1(H,z,E,N,_,Te[0],Ie[1]),S1(H,z,E,N,_,Te[1],Ie[0]),S1(H,z,E,N,_,Te[1],Ie[1])}}return z}function xw(N,f,_,S,E=1/0){let D=E;const z=k0(N,[0,N.length-1]);for(const H of _)if(!(D!==1/0&&fv(z,k0(H,[0,H.length-1]),S)>=D)&&(D=Math.min(D,Sg(N,f,H,!0,S,D)),D===0))return D;return D}function Wb(N,f,_,S,E=1/0){let D=E;const z=k0(N,[0,N.length-1]);for(const H of _){if(D!==1/0&&fv(z,Hb(H),S)>=D)continue;const Y=M6(N,f,H,S,D);if(isNaN(Y))return Y;if((D=Math.min(D,Y))===0)return D}return D}function KN(N){return N==="Point"||N==="MultiPoint"||N==="LineString"||N==="MultiLineString"||N==="Polygon"||N==="MultiPolygon"}class C1{constructor(f,_){this.type=Lr,this.geojson=f,this.geometries=_}static parse(f,_){if(f.length!==2)return _.error(`'distance' expression requires either one argument, but found ' ${f.length-1} instead.`);if(Lf(f[1])){const S=f[1];if(S.type==="FeatureCollection"){for(let E=0;E{f&&!A1(_)&&(f=!1)}),f}function Rf(N){if(N instanceof Kc&&N.name==="feature-state")return!1;let f=!0;return N.eachChild(_=>{f&&!Rf(_)&&(f=!1)}),f}function Xd(N,f){if(N instanceof Kc&&f.indexOf(N.name)>=0)return!1;let _=!0;return N.eachChild(S=>{_&&!Xd(S,f)&&(_=!1)}),_}function Cg(N,f,_){return[N,f,_].filter(Boolean).join("")}function r2(N,f){switch(N){case"string":return ka(f);case"number":return+f;case"boolean":return!!f;case"color":return us.parse(f);case"formatted":return ad.fromString(ka(f));case"resolvedImage":return Lu.build(ka(f))}return f}function kS(N,f,_,S){return S!==void 0&&(N=S*Math.round(N/S)),f!==void 0&&N_&&(N=_),N}class lx{constructor(f,_,S,E=!1){this.type=f,this.key=_,this.scope=S,this.featureConstant=E}static parse(f,_){let S=_.expectedType;if(S==null&&(S=Gi),f.length<2||f.length>3)return _.error("Invalid number of arguments for 'config' expression.");const E=_.parse(f[1],1);if(!(E instanceof Ir))return _.error("Key name of 'config' expression must be a string literal.");let D,z=!0;const H=ka(E.value);if(f.length>=3){const Y=_.parse(f[2],2);if(!(Y instanceof Ir))return _.error("Scope of 'config' expression must be a string literal.");D=ka(Y.value)}if(_.options){const Y=Cg(H,D,_._scope),te=_.options.get(Y);te&&(z=A1(te.value||te.default))}return new lx(S,H,D,z)}evaluate(f){const _=Cg(this.key,this.scope,f.scope),S=f.getConfig(_);if(!S)return null;const{type:E,value:D,values:z,minValue:H,maxValue:Y,stepValue:te}=S,he=S.default.evaluate(f);let ge=he;if(D){const ve=f.scope;f.scope=(ve||"").split("").slice(1).join(""),ge=D.evaluate(f),f.scope=ve}return E&&(ge=r2(E,ge)),ge===void 0||H===void 0&&Y===void 0&&te===void 0||(typeof ge=="number"?ge=kS(ge,H,Y,te):Array.isArray(ge)&&(ge=ge.map(ve=>typeof ve=="number"?kS(ve,H,Y,te):ve))),D!==void 0&&ge!==void 0&&z&&!z.includes(ge)&&(ge=he,E&&(ge=r2(E,ge))),(E&&E!==this.type||ge!==void 0&&!lp(yl(ge),this.type))&&(ge=r2(this.type.kind,ge)),ge}eachChild(){}outputDefined(){return!1}serialize(){const f=["config",this.key];return this.scope&&f.concat(this.scope),f}}class Kp{constructor(f,_){this.type=_.type,this.name=f,this.boundExpression=_}static parse(f,_){if(f.length!==2||typeof f[1]!="string")return _.error("'var' expression requires exactly one string literal argument.");const S=f[1];return _.scope.has(S)?new Kp(S,_.scope.get(S)):_.error(`Unknown variable "${S}". Make sure "${S}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(f){return this.boundExpression.evaluate(f)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class a2{constructor(f,_=[],S,E=new rl,D=[],z,H,Y){this.registry=f,this.path=_,this.key=_.map(te=>typeof te=="string"?`['${te}']`:`[${te}]`).join(""),this.scope=E,this.errors=D,this.expectedType=S,this._scope=z,this.options=H,this.iconImageUseTheme=Y}parse(f,_,S,E,D={}){return _||S?this.concat(_,null,S,E)._parse(f,D):this._parse(f,D)}parseObjectValue(f,_,S,E,D,z={}){return this.concat(_,S,E,D)._parse(f,z)}_parse(f,_){function S(E,D,z){return z==="assert"?new Nm(D,[E]):z==="coerce"?new cp(D,[E]):E}if(f!==null&&typeof f!="string"&&typeof f!="boolean"&&typeof f!="number"||(f=["literal",f]),Array.isArray(f)){if(f.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const E=typeof f[0]=="string"?this.registry[f[0]]:void 0;if(E){let D=E.parse(f,this);if(!D)return null;if(this.expectedType){const z=this.expectedType,H=D.type;if(z.kind!=="string"&&z.kind!=="number"&&z.kind!=="boolean"&&z.kind!=="object"&&z.kind!=="array"||H.kind!=="value")if(z.kind!=="color"&&z.kind!=="formatted"&&z.kind!=="resolvedImage"||H.kind!=="value"&&H.kind!=="string"){if(this.checkSubtype(z,H))return null}else D=S(D,z,_.typeAnnotation||"coerce");else D=S(D,z,_.typeAnnotation||"assert")}if(!(D instanceof Ir)&&D.type.kind!=="resolvedImage"&&YN(D)){const z=new xu(this._scope,this.options,this.iconImageUseTheme);try{D=new Ir(D.type,D.evaluate(z))}catch(H){return this.error(H.message),null}}return D}return cp.parse(["to-array",f],this)}return this.error(f===void 0?"'undefined' value invalid. Use null instead.":typeof f=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof f} instead.`)}concat(f,_,S,E){let D=typeof f=="number"?this.path.concat(f):this.path;D=typeof _=="string"?D.concat(_):D;const z=E?this.scope.concat(E):this.scope;return new a2(this.registry,D,S||null,z,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(f,..._){const S=`${this.key}${_.map(E=>`[${E}]`).join("")}`;this.errors.push(new Hi(S,f))}checkSubtype(f,_){const S=Dx(f,_);return S&&this.error(S),S}}function YN(N){if(N instanceof Kp)return YN(N.boundExpression);if(N instanceof Kc&&N.name==="error"||N instanceof hv||N instanceof N0||N instanceof C1||N instanceof lx)return!1;const f=N instanceof cp||N instanceof Nm;let _=!0;return N.eachChild(S=>{_=f?_&&YN(S):_&&S instanceof Ir}),!!_&&A1(N)&&Xd(N,["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 gw(N,f){const _=N.length-1;let S,E,D=0,z=_,H=0;for(;D<=z;)if(H=Math.floor((D+z)/2),S=N[H],E=N[H+1],S<=f){if(H===_||ff))throw new Fl("Input is not a number.");z=H-1}return 0}class yw{constructor(f,_,S){this.type=f,this.input=_,this.labels=[],this.outputs=[];for(const[E,D]of S)this.labels.push(E),this.outputs.push(D)}static parse(f,_){if(f.length-1<4)return _.error(`Expected at least 4 arguments, but found only ${f.length-1}.`);if((f.length-1)%2!=0)return _.error("Expected an even number of arguments.");const S=_.parse(f[1],1,Lr);if(!S)return null;const E=[];let D=null;_.expectedType&&_.expectedType.kind!=="value"&&(D=_.expectedType);for(let z=1;z=H)return _.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',te);const ge=_.parse(Y,he,D);if(!ge)return null;D=D||ge.type,E.push([H,ge])}return new yw(D,S,E)}evaluate(f){const _=this.labels,S=this.outputs;if(_.length===1)return S[0].evaluate(f);const E=this.input.evaluate(f);if(E<=_[0])return S[0].evaluate(f);const D=_.length;return E>=_[D-1]?S[D-1].evaluate(f):S[gw(_,E)].evaluate(f)}eachChild(f){f(this.input);for(const _ of this.outputs)f(_)}outputDefined(){return this.outputs.every(f=>f.outputDefined())}serialize(){const f=["step",this.input.serialize()];for(let _=0;_0&&f.push(this.labels[_]),f.push(this.outputs[_].serialize());return f}}const Yp=.95047,hp=1.08883,SS=4/29,by=6/29,vw=3*by*by,bw=by*by*by,ZN=Math.PI/180,XN=180/Math.PI;function QN(N){return N>bw?Math.pow(N,1/3):N/vw+SS}function _w(N){return N>by?N*N*N:vw*(N-SS)}function ww(N){return 255*(N<=.0031308?12.92*N:1.055*Math.pow(N,1/2.4)-.055)}function Kb(N){return(N/=255)<=.04045?N/12.92:Math.pow((N+.055)/1.055,2.4)}function i2(N){const f=Kb(N.r),_=Kb(N.g),S=Kb(N.b),E=QN((.4124564*f+.3575761*_+.1804375*S)/Yp),D=QN((.2126729*f+.7151522*_+.072175*S)/1);return{l:116*D-16,a:500*(E-D),b:200*(D-QN((.0193339*f+.119192*_+.9503041*S)/hp)),alpha:N.a}}function JN(N){let f=(N.l+16)/116,_=isNaN(N.a)?f:f+N.a/500,S=isNaN(N.b)?f:f-N.b/200;return f=1*_w(f),_=Yp*_w(_),S=hp*_w(S),new us(ww(3.2404542*_-1.5371385*f-.4985314*S),ww(-.969266*_+1.8760108*f+.041556*S),ww(.0556434*_-.2040259*f+1.0572252*S),N.alpha)}function oC(N,f,_){const S=f-N;return N+_*(S>180||S<-180?S-360*Math.round(S/360):S)}const Yb={forward:i2,reverse:JN,interpolate:function(N,f,_){return{l:xr(N.l,f.l,_),a:xr(N.a,f.a,_),b:xr(N.b,f.b,_),alpha:xr(N.alpha,f.alpha,_)}}},_y={forward:function(N){const{l:f,a:_,b:S}=i2(N),E=Math.atan2(S,_)*XN;return{h:E<0?E+360:E,c:Math.sqrt(_*_+S*S),l:f,alpha:N.a}},reverse:function(N){const f=N.h*ZN,_=N.c;return JN({l:N.l,a:Math.cos(f)*_,b:Math.sin(f)*_,alpha:N.alpha})},interpolate:function(N,f,_){return{h:oC(N.h,f.h,_),c:xr(N.c,f.c,_),l:xr(N.l,f.l,_),alpha:xr(N.alpha,f.alpha,_)}}};var jw=Object.freeze({__proto__:null,hcl:_y,lab:Yb});class Jh{constructor(f,_,S,E,D){this.type=f,this.operator=_,this.interpolation=S,this.input=E,this.labels=[],this.outputs=[];for(const[z,H]of D)this.labels.push(z),this.outputs.push(H)}static interpolationFactor(f,_,S,E){let D=0;if(f.name==="exponential")D=Nw(_,f.base,S,E);else if(f.name==="linear")D=Nw(_,1,S,E);else if(f.name==="cubic-bezier"){const z=f.controlPoints;D=new jr(z[0],z[1],z[2],z[3]).solve(Nw(_,1,S,E))}return D}static parse(f,_){let[S,E,D,...z]=f;if(!Array.isArray(E)||E.length===0)return _.error("Expected an interpolation type expression.",1);if(E[0]==="linear")E={name:"linear"};else if(E[0]==="exponential"){const te=E[1];if(typeof te!="number")return _.error("Exponential interpolation requires a numeric base.",1,1);E={name:"exponential",base:te}}else{if(E[0]!=="cubic-bezier")return _.error(`Unknown interpolation type ${String(E[0])}`,1,0);{const te=E.slice(1);if(te.length!==4||te.some(he=>typeof he!="number"||he<0||he>1))return _.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);E={name:"cubic-bezier",controlPoints:te}}}if(f.length-1<4)return _.error(`Expected at least 4 arguments, but found only ${f.length-1}.`);if(f.length-1>3&&(f.length-1)%2!=0)return _.error("Expected an even number of arguments.");if(D=_.parse(D,2,Lr),!D)return null;const H=[];let Y=null;S==="interpolate-hcl"||S==="interpolate-lab"?Y=Rl:_.expectedType&&_.expectedType.kind!=="value"&&(Y=_.expectedType);for(let te=0;te=he)return _.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',ve);const Ie=_.parse(ge,Te,Y);if(!Ie)return null;Y=Y||Ie.type,H.push([he,Ie])}return Y.kind==="number"||Y.kind==="color"||Y.kind==="array"&&Y.itemType.kind==="number"&&typeof Y.N=="number"?new Jh(Y,S,E,D,H):_.error(`Type ${Hl(Y)} is not interpolatable.`)}evaluate(f){const _=this.labels,S=this.outputs;if(_.length===1)return S[0].evaluate(f);const E=this.input.evaluate(f);if(E<=_[0])return S[0].evaluate(f);const D=_.length;if(E>=_[D-1])return S[D-1].evaluate(f);const z=gw(_,E),H=Jh.interpolationFactor(this.interpolation,E,_[z],_[z+1]),Y=S[z].evaluate(f),te=S[z+1].evaluate(f);return this.operator==="interpolate"?Zi[this.type.kind.toLowerCase()](Y,te,H):this.operator==="interpolate-hcl"?_y.reverse(_y.interpolate(_y.forward(Y),_y.forward(te),H)):Yb.reverse(Yb.interpolate(Yb.forward(Y),Yb.forward(te),H))}eachChild(f){f(this.input);for(const _ of this.outputs)f(_)}outputDefined(){return this.outputs.every(f=>f.outputDefined())}serialize(){let f;f=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const _=[this.operator,f,this.input.serialize()];for(let S=0;SDx(E,H.type));return new Zb(z?Gi:S,D)}evaluate(f){let _,S=null,E=0;for(const D of this.args){if(E++,S=D.evaluate(f),S&&S instanceof Lu&&!S.available&&(_||(_=S),S=null,E===this.args.length))return _;if(S!==null)break}return S}eachChild(f){this.args.forEach(f)}outputDefined(){return this.args.every(f=>f.outputDefined())}serialize(){const f=["coalesce"];return this.eachChild(_=>{f.push(_.serialize())}),f}}class Ce{constructor(f,_){this.type=_.type,this.bindings=[].concat(f),this.result=_}evaluate(f){return this.result.evaluate(f)}eachChild(f){for(const _ of this.bindings)f(_[1]);f(this.result)}static parse(f,_){if(f.length<4)return _.error(`Expected at least 3 arguments, but found ${f.length-1} instead.`);const S=[];for(let D=1;D=S.length)throw new Fl("Array index out of bounds: index exceeds array size");if(_!==Math.floor(_))throw new Fl("Array index must be an integer. Use at-interpolated for fractional indices");return S[_]}eachChild(f){f(this.index),f(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class ht{constructor(f,_,S){this.type=f,this.index=_,this.input=S}static parse(f,_){if(f.length!==3)return _.error(`Expected 2 arguments, but found ${f.length-1} instead.`);const S=_.parse(f[1],1,Lr),E=_.parse(f[2],2,fu(_.expectedType||Gi));return S&&E?new ht(E.type.itemType,S,E):null}evaluate(f){const _=this.index.evaluate(f),S=this.input.evaluate(f);if(_<0)throw new Fl(`Array index out of bounds: ${_} < 0.`);if(_>S.length-1)throw new Fl(`Array index out of bounds: ${_} > ${S.length-1}.`);if(_===Math.floor(_))return S[_];const E=Math.floor(_),D=Math.ceil(_),z=S[E],H=S[D];if(typeof z!="number"||typeof H!="number")throw new Fl(`Cannot interpolate between non-number values at index ${_}.`);const Y=_-E;return z*(1-Y)+H*Y}eachChild(f){f(this.index),f(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class bt{constructor(f,_){this.type=ui,this.needle=f,this.haystack=_}static parse(f,_){if(f.length!==3)return _.error(`Expected 2 arguments, but found ${f.length-1} instead.`),null;const S=_.parse(f[1],1,Gi),E=_.parse(f[2],2,Gi);return S&&E?y0(S.type,[ui,ti,Lr,Dc,Gi])?new bt(S,E):(_.error(`Expected first argument to be of type boolean, string, number or null, but found ${Hl(S.type)} instead`),null):null}evaluate(f){const _=this.needle.evaluate(f),S=this.haystack.evaluate(f);if(S==null)return!1;if(!Hd(_,["boolean","string","number","null"]))throw new Fl(`Expected first argument to be of type boolean, string, number or null, but found ${Hl(yl(_))} instead.`);if(!Hd(S,["string","array"]))throw new Fl(`Expected second argument to be of type array or string, but found ${Hl(yl(S))} instead.`);return S.indexOf(_)>=0}eachChild(f){f(this.needle),f(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class Yt{constructor(f,_,S){this.type=Lr,this.needle=f,this.haystack=_,this.fromIndex=S}static parse(f,_){if(f.length<=2||f.length>=5)return _.error(`Expected 3 or 4 arguments, but found ${f.length-1} instead.`),null;const S=_.parse(f[1],1,Gi),E=_.parse(f[2],2,Gi);if(!S||!E)return null;if(!y0(S.type,[ui,ti,Lr,Dc,Gi]))return _.error(`Expected first argument to be of type boolean, string, number or null, but found ${Hl(S.type)} instead`),null;if(f.length===4){const D=_.parse(f[3],3,Lr);return D?new Yt(S,E,D):null}return new Yt(S,E)}evaluate(f){const _=this.needle.evaluate(f),S=this.haystack.evaluate(f);if(!Hd(_,["boolean","string","number","null"]))throw new Fl(`Expected first argument to be of type boolean, string, number or null, but found ${Hl(yl(_))} instead.`);if(!Hd(S,["string","array"]))throw new Fl(`Expected second argument to be of type array or string, but found ${Hl(yl(S))} instead.`);if(this.fromIndex){const E=this.fromIndex.evaluate(f);return S.indexOf(_,E)}return S.indexOf(_)}eachChild(f){f(this.needle),f(this.haystack),this.fromIndex&&f(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const f=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),f]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class ls{constructor(f,_,S,E,D,z){this.inputType=f,this.type=_,this.input=S,this.cases=E,this.outputs=D,this.otherwise=z}static parse(f,_){if(f.length<5)return _.error(`Expected at least 4 arguments, but found only ${f.length-1}.`);if(f.length%2!=1)return _.error("Expected an even number of arguments.");let S,E;_.expectedType&&_.expectedType.kind!=="value"&&(E=_.expectedType);const D={},z=[];for(let te=2;teNumber.MAX_SAFE_INTEGER)return ve.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof Ie=="number"&&Math.floor(Ie)!==Ie)return ve.error("Numeric branch labels must be integer values.");if(S){if(ve.checkSubtype(S,yl(Ie)))return null}else S=yl(Ie);if(D[String(Ie)]!==void 0)return ve.error("Branch labels must be unique.");D[String(Ie)]=z.length}const Te=_.parse(ge,te,E);if(!Te)return null;E=E||Te.type,z.push(Te)}const H=_.parse(f[1],1,Gi);if(!H)return null;const Y=_.parse(f[f.length-1],f.length-1,E);return Y?H.type.kind!=="value"&&_.concat(1).checkSubtype(S,H.type)?null:new ls(S,E,H,D,z,Y):null}evaluate(f){const _=this.input.evaluate(f);return(lp(yl(_),this.inputType)&&this.outputs[this.cases[_]]||this.otherwise).evaluate(f)}eachChild(f){f(this.input),this.outputs.forEach(f),f(this.otherwise)}outputDefined(){return this.outputs.every(f=>f.outputDefined())&&this.otherwise.outputDefined()}serialize(){const f=["match",this.input.serialize()],_=Object.keys(this.cases).sort(),S=[],E={};for(const z of _){const H=E[this.cases[z]];H===void 0?(E[this.cases[z]]=S.length,S.push([this.cases[z],[z]])):S[H][1].push(z)}const D=z=>this.inputType.kind==="number"?Number(z):z;for(const[z,H]of S)f.push(H.length===1?D(H[0]):H.map(D)),f.push(this.outputs[z].serialize());return f.push(this.otherwise.serialize()),f}}class hs{constructor(f,_,S){this.type=f,this.branches=_,this.otherwise=S}static parse(f,_){if(f.length<4)return _.error(`Expected at least 3 arguments, but found only ${f.length-1}.`),null;if(f.length%2!=0)return _.error("Expected an odd number of arguments."),null;let S;_.expectedType&&_.expectedType.kind!=="value"&&(S=_.expectedType);const E=[];for(let z=1;z_.outputDefined())&&this.otherwise.outputDefined()}serialize(){const f=["case"];return this.eachChild(_=>{f.push(_.serialize())}),f}}class Ss{constructor(f,_,S,E){this.type=f,this.input=_,this.beginIndex=S,this.endIndex=E}static parse(f,_){if(f.length<=2||f.length>=5)return _.error(`Expected 3 or 4 arguments, but found ${f.length-1} instead.`),null;const S=_.parse(f[1],1,Gi),E=_.parse(f[2],2,Lr);if(!S||!E)return null;if(!y0(S.type,[fu(Gi),ti,Gi]))return _.error(`Expected first argument to be of type array or string, but found ${Hl(S.type)} instead`),null;if(f.length===4){const D=_.parse(f[3],3,Lr);return D?new Ss(S.type,S,E,D):null}return new Ss(S.type,S,E)}evaluate(f){const _=this.input.evaluate(f),S=this.beginIndex.evaluate(f);if(!Hd(_,["string","array"]))throw new Fl(`Expected first argument to be of type array or string, but found ${Hl(yl(_))} instead.`);if(this.endIndex){const E=this.endIndex.evaluate(f);return _.slice(S,E)}return _.slice(S)}eachChild(f){f(this.input),f(this.beginIndex),this.endIndex&&f(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const f=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),f]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class Ts{constructor(f,_){this.type=fu(ti),this.str=f,this.delimiter=_}static parse(f,_){if(f.length!==3)return _.error(`Expected 2 arguments, but found ${f.length-1} instead.`);const S=_.parse(f[1],1,ti),E=_.parse(f[2],2,ti);return S&&E?new Ts(S,E):void 0}evaluate(f){const _=this.str.evaluate(f),S=this.delimiter.evaluate(f);return _.split(S)}eachChild(f){f(this.str),f(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function Ws(N,f){return N==="=="||N==="!="?f.kind==="boolean"||f.kind==="string"||f.kind==="number"||f.kind==="null"||f.kind==="value":f.kind==="string"||f.kind==="number"||f.kind==="value"}function Nn(N,f,_,S){return S.compare(f,_)===0}function Vn(N,f,_){const S=N!=="=="&&N!=="!=";return class t5t{constructor(D,z,H){this.type=ui,this.lhs=D,this.rhs=z,this.collator=H,this.hasUntypedArgument=D.type.kind==="value"||z.type.kind==="value"}static parse(D,z){if(D.length!==3&&D.length!==4)return z.error("Expected two or three arguments.");const H=D[0];let Y=z.parse(D[1],1,Gi);if(!Y)return null;if(!Ws(H,Y.type))return z.concat(1).error(`"${H}" comparisons are not supported for type '${Hl(Y.type)}'.`);let te=z.parse(D[2],2,Gi);if(!te)return null;if(!Ws(H,te.type))return z.concat(2).error(`"${H}" comparisons are not supported for type '${Hl(te.type)}'.`);if(Y.type.kind!==te.type.kind&&Y.type.kind!=="value"&&te.type.kind!=="value")return z.error(`Cannot compare types '${Hl(Y.type)}' and '${Hl(te.type)}'.`);S&&(Y.type.kind==="value"&&te.type.kind!=="value"?Y=new Nm(te.type,[Y]):Y.type.kind!=="value"&&te.type.kind==="value"&&(te=new Nm(Y.type,[te])));let he=null;if(D.length===4){if(Y.type.kind!=="string"&&te.type.kind!=="string"&&Y.type.kind!=="value"&&te.type.kind!=="value")return z.error("Cannot use collator to compare non-string types.");if(he=z.parse(D[3],3,Qh),!he)return null}return new t5t(Y,te,he)}evaluate(D){const z=this.lhs.evaluate(D),H=this.rhs.evaluate(D);if(S&&this.hasUntypedArgument){const Y=yl(z),te=yl(H);if(Y.kind!==te.kind||Y.kind!=="string"&&Y.kind!=="number")throw new Fl(`Expected arguments for "${N}" to be (string, string) or (number, number), but found (${Y.kind}, ${te.kind}) instead.`)}if(this.collator&&!S&&this.hasUntypedArgument){const Y=yl(z),te=yl(H);if(Y.kind!=="string"||te.kind!=="string")return f(D,z,H)}return this.collator?_(D,z,H,this.collator.evaluate(D)):f(D,z,H)}eachChild(D){D(this.lhs),D(this.rhs),this.collator&&D(this.collator)}outputDefined(){return!0}serialize(){const D=[N];return this.eachChild(z=>{D.push(z.serialize())}),D}}}const Ks=Vn("==",function(N,f,_){return f===_},Nn),In=Vn("!=",function(N,f,_){return f!==_},function(N,f,_,S){return!Nn(0,f,_,S)}),Xn=Vn("<",function(N,f,_){return f<_},function(N,f,_,S){return S.compare(f,_)<0}),Cr=Vn(">",function(N,f,_){return f>_},function(N,f,_,S){return S.compare(f,_)>0}),hr=Vn("<=",function(N,f,_){return f<=_},function(N,f,_,S){return S.compare(f,_)<=0}),On=Vn(">=",function(N,f,_){return f>=_},function(N,f,_,S){return S.compare(f,_)>=0});class Pr{constructor(f,_,S,E,D,z){this.type=ti,this.number=f,this.locale=_,this.currency=S,this.unit=E,this.minFractionDigits=D,this.maxFractionDigits=z}static parse(f,_){if(f.length!==3)return _.error("Expected two arguments.");const S=_.parse(f[1],1,Lr);if(!S)return null;const E=f[2];if(typeof E!="object"||Array.isArray(E))return _.error("NumberFormat options argument must be an object.");let D=null;if(E.locale&&(D=_.parseObjectValue(E.locale,2,"locale",ti),!D))return null;let z=null;if(E.currency&&(z=_.parseObjectValue(E.currency,2,"currency",ti),!z))return null;let H=null;if(E.unit&&(H=_.parseObjectValue(E.unit,2,"unit",ti),!H))return null;let Y=null;if(E["min-fraction-digits"]&&(Y=_.parseObjectValue(E["min-fraction-digits"],2,"min-fraction-digits",Lr),!Y))return null;let te=null;return E["max-fraction-digits"]&&(te=_.parseObjectValue(E["max-fraction-digits"],2,"max-fraction-digits",Lr),!te)?null:new Pr(S,D,z,H,Y,te)}evaluate(f){return new Intl.NumberFormat(this.locale?this.locale.evaluate(f):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(f):void 0,unit:this.unit?this.unit.evaluate(f):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(f):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(f):void 0}).format(this.number.evaluate(f))}eachChild(f){f(this.number),this.locale&&f(this.locale),this.currency&&f(this.currency),this.unit&&f(this.unit),this.minFractionDigits&&f(this.minFractionDigits),this.maxFractionDigits&&f(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const f={};return this.locale&&(f.locale=this.locale.serialize()),this.currency&&(f.currency=this.currency.serialize()),this.unit&&(f.unit=this.unit.serialize()),this.minFractionDigits&&(f["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(f["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),f]}}class ga{constructor(f){this.type=Lr,this.input=f}static parse(f,_){if(f.length!==2)return _.error(`Expected 1 argument, but found ${f.length-1} instead.`),null;const S=_.parse(f[1],1);return S?S.type.kind!=="array"&&S.type.kind!=="string"&&S.type.kind!=="value"?(_.error(`Expected argument of type string or array, but found ${Hl(S.type)} instead.`),null):new ga(S):null}evaluate(f){const _=this.input.evaluate(f);if(typeof _=="string"||Array.isArray(_))return _.length;throw new Fl(`Expected value to be of type string or array, but found ${Hl(yl(_))} instead.`)}eachChild(f){f(this.input)}outputDefined(){return!1}serialize(){const f=["length"];return this.eachChild(_=>{f.push(_.serialize())}),f}}function ca(N){return function(){N=1831565813+(N|=0)|0;let f=Math.imul(N^N>>>15,1|N);return f=f+Math.imul(f^f>>>7,61|f)^f,((f^f>>>14)>>>0)/4294967296}}const Li={"==":Ks,"!=":In,">":Cr,"<":Xn,">=":On,"<=":hr,array:Nm,at:ze,"at-interpolated":ht,boolean:Nm,case:hs,coalesce:Zb,collator:hv,format:id,image:la,in:bt,"index-of":Yt,interpolate:Jh,"interpolate-hcl":Jh,"interpolate-lab":Jh,length:ga,let:Ce,literal:Ir,match:ls,number:Nm,"number-format":Pr,object:Nm,slice:Ss,step:yw,string:Nm,"to-boolean":cp,"to-color":cp,"to-number":cp,"to-string":cp,var:Kp,within:N0,distance:C1,config:lx,split:Ts};function fi(N,[f,_,S,E]){f=f.evaluate(N),_=_.evaluate(N),S=S.evaluate(N);const D=E?E.evaluate(N):1,z=jm(f,_,S,D);if(z)throw new Fl(z);return new us(f/255,_/255,S/255,D)}function Zo(N,[f,_,S,E]){f=f.evaluate(N),_=_.evaluate(N),S=S.evaluate(N);const D=E?E.evaluate(N):1,z=function(te,he,ge,ve){return typeof te=="number"&&te>=0&&te<=360?typeof he=="number"&&he>=0&&he<=100&&typeof ge=="number"&&ge>=0&&ge<=100?ve===void 0||typeof ve=="number"&&ve>=0&&ve<=1?null:`Invalid hsla value [${[te,he,ge,ve].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof ve=="number"?[te,he,ge,ve]:[te,he,ge]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof ve=="number"?[te,he,ge,ve]:[te,he,ge]).join(", ")}]: 'h' must be between 0 and 360.`}(f,_,S,D);if(z)throw new Fl(z);const H=`hsla(${f}, ${_}%, ${S}%, ${D})`,Y=us.parse(H);if(!Y)throw new Fl(`Failed to parse HSLA color: ${H}`);return Y}function Si(N,f){return N in f}function Tl(N,f){const _=f[N];return _===void 0?null:_}function Ad(N){return{type:N}}function Xo(N){if(N instanceof lx)return new Set([N.key]);let f=new Set;return N.eachChild(_=>{f=new Set([...f,...Xo(_)])}),f}function Ti(N){if(N instanceof Kc&&N.name==="is-active-floor")return!0;let f=!1;return N.eachChild(_=>{!f&&Ti(_)&&(f=!0)}),f}function Ya(N){return{result:"success",value:N}}function el(N){return{result:"error",value:N}}function io(N,f){return!!N&&!!N.parameters&&N.parameters.indexOf(f)>-1}function qo(N){return N["property-type"]==="data-driven"}function yd(N){return io(N.expression,"measure-light")}function Th(N){return io(N.expression,"zoom")}function vd(N){return!!N.expression&&N.expression.interpolated}function Qd(N){return typeof N=="object"&&N!==null&&!Array.isArray(N)}function Wd(N){return N}function Zp(N,f){const _=f.type==="color",S=N.stops&&typeof N.stops[0][0]=="object",E=S||!(S||N.property!==void 0),D=N.type||(vd(f)?"exponential":"interval");if(_&&((N=Object.assign({},N)).stops&&(N.stops=N.stops.map(te=>[te[0],us.parse(te[1])])),N.default=us.parse(N.default?N.default:f.default)),N.colorSpace&&N.colorSpace!=="rgb"&&!jw[N.colorSpace])throw new Error(`Unknown color space: ${N.colorSpace}`);let z,H,Y;if(D==="exponential")z=vu;else if(D==="interval")z=Zc;else if(D==="categorical"){z=uc,H=Object.create(null);for(const te of N.stops)H[te[0]]=te[1];Y=typeof N.stops[0][0]}else{if(D!=="identity")throw new Error(`Unknown function type "${D}"`);z=jc}if(S){const te={},he=[];for(let Te=0;TeTe[0]),evaluate:({zoom:Te},Ie)=>vu({stops:ge,base:N.base},f,Te).evaluate(Te,Ie)}}if(E){const te=D==="exponential"?{name:"exponential",base:N.base!==void 0?N.base:1}:null;return{kind:"camera",interpolationType:te,interpolationFactor:Jh.interpolationFactor.bind(void 0,te),zoomStops:N.stops.map(he=>he[0]),evaluate:({zoom:he})=>z(N,f,he,H,Y)}}return{kind:"source",evaluate(te,he){const ge=he&&he.properties?he.properties[N.property]:void 0;return ge===void 0?od(N.default,f.default):z(N,f,ge,H,Y)}}}function od(N,f,_){return N!==void 0?N:f!==void 0?f:_!==void 0?_:void 0}function uc(N,f,_,S,E){return od(typeof _===E?S[_]:void 0,N.default,f.default)}function Zc(N,f,_){if(!b0(_))return od(N.default,f.default);const S=N.stops.length;if(S===1||_<=N.stops[0][0])return N.stops[0][1];if(_>=N.stops[S-1][0])return N.stops[S-1][1];const E=gw(N.stops.map(D=>D[0]),_);return N.stops[E][1]}function vu(N,f,_){const S=N.base!==void 0?N.base:1;if(!b0(_))return od(N.default,f.default);const E=N.stops.length;if(E===1||_<=N.stops[0][0])return N.stops[0][1];if(_>=N.stops[E-1][0])return N.stops[E-1][1];const D=gw(N.stops.map(he=>he[0]),_),z=function(he,ge,ve,Te){const Ie=Te-ve,Ve=he-ve;return Ie===0?0:ge===1?Ve/Ie:(Math.pow(ge,Ve)-1)/(Math.pow(ge,Ie)-1)}(_,S,N.stops[D][0],N.stops[D+1][0]),H=N.stops[D][1],Y=N.stops[D+1][1];let te=Zi[f.type]||Wd;if(N.colorSpace&&N.colorSpace!=="rgb"){const he=jw[N.colorSpace];te=(ge,ve)=>he.reverse(he.interpolate(he.forward(ge),he.forward(ve),z))}return typeof H.evaluate=="function"?{evaluate(...he){const ge=H.evaluate.apply(void 0,he),ve=Y.evaluate.apply(void 0,he);if(ge!==void 0&&ve!==void 0)return te(ge,ve,z)}}:te(H,Y,z)}function jc(N,f,_){return f.type==="color"?_=us.parse(_):f.type==="formatted"?_=ad.fromString(_.toString()):f.type==="resolvedImage"?_=Lu.build(_.toString()):Ox(_)===f.type||f.type==="enum"&&f.values[_]||(_=void 0),od(_,N.default,f.default)}Kc.register(Li,{error:[{kind:"error"},[ti],(N,[f])=>{throw new Fl(f.evaluate(N))}],typeof:[ti,[Gi],(N,[f])=>Hl(yl(f.evaluate(N)))],"to-rgba":[fu(Lr,4),[Rl],(N,[f])=>f.evaluate(N).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[fu(Lr,4),[Rl],(N,[f])=>f.evaluate(N).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[Rl,[Lr,Lr,Lr],fi],rgba:[Rl,[Lr,Lr,Lr,Lr],fi],hsl:[Rl,[Lr,Lr,Lr],Zo],hsla:[Rl,[Lr,Lr,Lr,Lr],Zo],has:{type:ui,overloads:[[[ti],(N,[f])=>Si(f.evaluate(N),N.properties())],[[ti,bc],(N,[f,_])=>Si(f.evaluate(N),_.evaluate(N))]]},get:{type:Gi,overloads:[[[ti],(N,[f])=>Tl(f.evaluate(N),N.properties())],[[ti,bc],(N,[f,_])=>Tl(f.evaluate(N),_.evaluate(N))]]},"feature-state":[Gi,[ti],(N,[f])=>Tl(f.evaluate(N),N.featureState||{})],properties:[bc,[],N=>N.properties()],"geometry-type":[ti,[],N=>N.geometryType()],worldview:[ti,[],N=>N.globals.worldview||""],"is-active-floor":[ui,Ad(ti),(N,f)=>{if(!(N.globals&&N.globals.activeFloors&&N.globals.activeFloors.size>0))return!1;if(f.length===0)return!0;const _=N.globals.activeFloors;return f.some(S=>{const E=S.evaluate(N);return _.has(E)})}],id:[Gi,[],N=>N.id()],zoom:[Lr,[],N=>N.globals.zoom],pitch:[Lr,[],N=>N.globals.pitch||0],"distance-from-center":[Lr,[],N=>N.distanceFromCenter()],"measure-light":[Lr,[ti],(N,[f])=>N.measureLight(f.evaluate(N))],"heatmap-density":[Lr,[],N=>N.globals.heatmapDensity||0],"line-progress":[Lr,[],N=>N.globals.lineProgress||0],"raster-value":[Lr,[],N=>N.globals.rasterValue||0],"raster-particle-speed":[Lr,[],N=>N.globals.rasterParticleSpeed||0],"sky-radial-progress":[Lr,[],N=>N.globals.skyRadialProgress||0],accumulated:[Gi,[],N=>N.globals.accumulated===void 0?null:N.globals.accumulated],"+":[Lr,Ad(Lr),(N,f)=>{let _=0;for(const S of f)_+=S.evaluate(N);return _}],"*":[Lr,Ad(Lr),(N,f)=>{let _=1;for(const S of f)_*=S.evaluate(N);return _}],"-":{type:Lr,overloads:[[[Lr,Lr],(N,[f,_])=>f.evaluate(N)-_.evaluate(N)],[[Lr],(N,[f])=>-f.evaluate(N)]]},"/":[Lr,[Lr,Lr],(N,[f,_])=>f.evaluate(N)/_.evaluate(N)],"%":[Lr,[Lr,Lr],(N,[f,_])=>f.evaluate(N)%_.evaluate(N)],ln2:[Lr,[],()=>Math.LN2],pi:[Lr,[],()=>Math.PI],e:[Lr,[],()=>Math.E],"^":[Lr,[Lr,Lr],(N,[f,_])=>Math.pow(f.evaluate(N),_.evaluate(N))],sqrt:[Lr,[Lr],(N,[f])=>Math.sqrt(f.evaluate(N))],log10:[Lr,[Lr],(N,[f])=>Math.log(f.evaluate(N))/Math.LN10],ln:[Lr,[Lr],(N,[f])=>Math.log(f.evaluate(N))],log2:[Lr,[Lr],(N,[f])=>Math.log2(f.evaluate(N))],sin:[Lr,[Lr],(N,[f])=>Math.sin(f.evaluate(N))],cos:[Lr,[Lr],(N,[f])=>Math.cos(f.evaluate(N))],tan:[Lr,[Lr],(N,[f])=>Math.tan(f.evaluate(N))],asin:[Lr,[Lr],(N,[f])=>Math.asin(f.evaluate(N))],acos:[Lr,[Lr],(N,[f])=>Math.acos(f.evaluate(N))],atan:[Lr,[Lr],(N,[f])=>Math.atan(f.evaluate(N))],min:[Lr,Ad(Lr),(N,f)=>Math.min(...f.map(_=>_.evaluate(N)))],max:[Lr,Ad(Lr),(N,f)=>Math.max(...f.map(_=>_.evaluate(N)))],abs:[Lr,[Lr],(N,[f])=>Math.abs(f.evaluate(N))],round:[Lr,[Lr],(N,[f])=>{const _=f.evaluate(N);return _<0?-Math.round(-_):Math.round(_)}],floor:[Lr,[Lr],(N,[f])=>Math.floor(f.evaluate(N))],ceil:[Lr,[Lr],(N,[f])=>Math.ceil(f.evaluate(N))],"filter-==":[ui,[ti,Gi],(N,[f,_])=>N.properties()[f.value]===_.value],"filter-id-==":[ui,[Gi],(N,[f])=>N.id()===f.value],"filter-type-==":[ui,[ti],(N,[f])=>N.geometryType()===f.value],"filter-<":[ui,[ti,Gi],(N,[f,_])=>{const S=N.properties()[f.value],E=_.value;return typeof S==typeof E&&S{const _=N.id(),S=f.value;return typeof _==typeof S&&_":[ui,[ti,Gi],(N,[f,_])=>{const S=N.properties()[f.value],E=_.value;return typeof S==typeof E&&S>E}],"filter-id->":[ui,[Gi],(N,[f])=>{const _=N.id(),S=f.value;return typeof _==typeof S&&_>S}],"filter-<=":[ui,[ti,Gi],(N,[f,_])=>{const S=N.properties()[f.value],E=_.value;return typeof S==typeof E&&S<=E}],"filter-id-<=":[ui,[Gi],(N,[f])=>{const _=N.id(),S=f.value;return typeof _==typeof S&&_<=S}],"filter->=":[ui,[ti,Gi],(N,[f,_])=>{const S=N.properties()[f.value],E=_.value;return typeof S==typeof E&&S>=E}],"filter-id->=":[ui,[Gi],(N,[f])=>{const _=N.id(),S=f.value;return typeof _==typeof S&&_>=S}],"filter-has":[ui,[Gi],(N,[f])=>f.value in N.properties()],"filter-has-id":[ui,[],N=>N.id()!==null&&N.id()!==void 0],"filter-type-in":[ui,[fu(ti)],(N,[f])=>f.value.indexOf(N.geometryType())>=0],"filter-id-in":[ui,[fu(Gi)],(N,[f])=>f.value.indexOf(N.id())>=0],"filter-in-small":[ui,[ti,fu(Gi)],(N,[f,_])=>_.value.indexOf(N.properties()[f.value])>=0],"filter-in-large":[ui,[ti,fu(Gi)],(N,[f,_])=>function(S,E,D,z){for(;D<=z;){const H=D+z>>1;if(E[H]===S)return!0;E[H]>S?z=H-1:D=H+1}return!1}(N.properties()[f.value],_.value,0,_.value.length-1)],all:{type:ui,overloads:[[[ui,ui],(N,[f,_])=>f.evaluate(N)&&_.evaluate(N)],[Ad(ui),(N,f)=>{for(const _ of f)if(!_.evaluate(N))return!1;return!0}]]},any:{type:ui,overloads:[[[ui,ui],(N,[f,_])=>f.evaluate(N)||_.evaluate(N)],[Ad(ui),(N,f)=>{for(const _ of f)if(_.evaluate(N))return!0;return!1}]]},"!":[ui,[ui],(N,[f])=>!f.evaluate(N)],"is-supported-script":[ui,[ti],(N,[f])=>{const _=N.globals&&N.globals.isSupportedScript;return!_||_(f.evaluate(N))}],upcase:[ti,[ti],(N,[f])=>f.evaluate(N).toUpperCase()],downcase:[ti,[ti],(N,[f])=>f.evaluate(N).toLowerCase()],concat:[ti,Ad(Gi),(N,f)=>f.map(_=>ka(_.evaluate(N))).join("")],"resolved-locale":[ti,[Qh],(N,[f])=>f.evaluate(N).resolvedLocale()],random:[Lr,[Lr,Lr,Gi],(N,f)=>{const[_,S,E]=f.map(z=>z.evaluate(N));if(_>S||_===S)return _;let D;if(typeof E=="string")D=function(z){let H=0;if(z.length===0)return H;for(let Y=0;YJSON.stringify(ge)).join(", ")}, but found ${JSON.stringify(he)} instead.`);return he}catch(he){const ge=he;return this._warningHistory[ge.message]||(this._warningHistory[ge.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${ge.message}`)),this._defaultValue}}}function km(N){return Array.isArray(N)&&N.length>0&&typeof N[0]=="string"&&N[0]in Li}function Fc(N,f,_,S,E){const D=new a2(Li,[],f?function(H){const Y={color:Rl,string:ti,number:Lr,enum:ti,boolean:ui,formatted:wg,resolvedImage:jg};return H.type==="array"?fu(Y[H.value]||Gi,H.length):Y[H.type]}(f):void 0,void 0,void 0,_,S,E),z=D.parse(N,void 0,void 0,void 0,f&&f.type==="string"?{typeAnnotation:"coerce"}:void 0);return z?Ya(new Pu(z,f,_,S,E)):el(D.errors)}class Xu{constructor(f,_,S,E){this.kind=f,this._styleExpression=_,this.isLightConstant=S,this.isLineProgressConstant=E,this.isStateDependent=f!=="constant"&&!Rf(_.expression),this.configDependencies=Xo(_.expression),this.isIndoorDependent=Ti(_.expression)}evaluateWithoutErrorHandling(f,_,S,E,D,z){return this._styleExpression.evaluateWithoutErrorHandling(f,_,S,E,D,z)}evaluate(f,_,S,E,D,z,H){return this._styleExpression.evaluate(f,_,S,E,D,z,void 0,void 0,H)}}class Bl{constructor(f,_,S,E,D,z){this.kind=f,this.zoomStops=S,this._styleExpression=_,this.isStateDependent=f!=="camera"&&!Rf(_.expression),this.isIndoorDependent=Ti(_.expression),this.isLightConstant=D,this.isLineProgressConstant=z,this.configDependencies=Xo(_.expression),this.interpolationType=E}evaluateWithoutErrorHandling(f,_,S,E,D,z){return this._styleExpression.evaluateWithoutErrorHandling(f,_,S,E,D,z)}evaluate(f,_,S,E,D,z){return this._styleExpression.evaluate(f,_,S,E,D,z)}interpolationFactor(f,_,S){return this.interpolationType?Jh.interpolationFactor(this.interpolationType,f,_,S):0}}function Iu(N,f,_,S,E){if((N=Fc(N,f,_,S,E)).result==="error")return N;const D=N.value.expression,z=A1(D);if(!z&&!qo(f))return el([new Hi("","data expressions not supported")]);const H=Xd(D,["zoom","pitch","distance-from-center"]);if(!H&&!Th(f))return el([new Hi("","zoom expressions not supported")]);const Y=Xd(D,["measure-light"]);if(!Y&&!yd(f))return el([new Hi("","measure-light expression not supported")]);const te=Xd(D,["line-progress"]);if(!te&&!function(ve){return io(ve.expression,"line-progress")}(f))return el([new Hi("","line-progress expression not supported")]);const he=f.expression&&f.expression.relaxZoomRestriction,ge=Td(D);return ge||H||he?ge instanceof Hi?el([ge]):ge instanceof Jh&&!vd(f)?el([new Hi("",'"interpolate" expressions cannot be used with this property')]):Ya(ge?new Bl(z&&te?"camera":"composite",N.value,ge.labels,ge instanceof Jh?ge.interpolation:void 0,Y,te):new Xu(z&&te?"constant":"source",N.value,Y,te)):el([new Hi("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class Sm{constructor(f,_){this._parameters=f,this._specification=_,Object.assign(this,Zp(this._parameters,this._specification))}static deserialize(f){return new Sm(f._parameters,f._specification)}static serialize(f){return{_parameters:f._parameters,_specification:f._specification}}}function Td(N){let f=null;if(N instanceof Ce)f=Td(N.result);else if(N instanceof Zb){for(const _ of N.args)if(f=Td(_),f)break}else(N instanceof yw||N instanceof Jh)&&N.input instanceof Kc&&N.input.name==="zoom"&&(f=N);return f instanceof Hi||N.eachChild(_=>{const S=Td(_);S instanceof Hi?f=S:f&&S&&f!==S&&(f=new Hi("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),f}var Xp,Qp,Cm=function(){if(Qp)return Xp;Qp=1,Xp=f;var N=3;function f(_,S,E){var D=this.cells=[];if(_ instanceof ArrayBuffer){this.arrayBuffer=_;var z=new Int32Array(this.arrayBuffer);_=z[0],this.d=(S=z[1])+2*(E=z[2]);for(var H=0;H=ve[Ve+0]&&D>=ve[Ve+1])?(Y[Ie]=!0,H.push(ge[Ie])):Y[Ie]=!1}}},f.prototype._forEachCell=function(_,S,E,D,z,H,Y,te){for(var he=this._convertToCellCoord(_),ge=this._convertToCellCoord(S),ve=this._convertToCellCoord(E),Te=this._convertToCellCoord(D),Ie=he;Ie<=ve;Ie++)for(var Ve=ge;Ve<=Te;Ve++){var et=this.d*Ve+Ie;if((!te||te(this._convertFromCellCoord(Ie),this._convertFromCellCoord(Ve),this._convertFromCellCoord(Ie+1),this._convertFromCellCoord(Ve+1)))&&z.call(this,_,S,E,D,et,H,Y,te))return}},f.prototype._convertFromCellCoord=function(_){return(_-this.padding)/this.scale},f.prototype._convertToCellCoord=function(_){return Math.max(0,Math.min(this.d-1,Math.floor(_*this.scale)+this.padding))},f.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var _=this.cells,S=N+this.cells.length+1+1,E=0,D=0;D=0||(E[D]=Ec(N[D],f)));N instanceof Error&&(E.message=N.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 N)}function ec(N){if(N==null||typeof N=="boolean"||typeof N=="number"||typeof N=="string"||N instanceof Boolean||N instanceof Number||N instanceof String||N instanceof Date||N instanceof RegExp||yo(N)||N instanceof ImageBitmap||ArrayBuffer.isView(N)||N instanceof ImageData)return N;if(Array.isArray(N))return N.map(ec);if(typeof N=="object"){const f=N.$name||"Object";if(f==="Map"){const E=N.entries||[],D=new Map;for(let z=0;zN>=1536&&N<=1791,em=N=>N>=1872&&N<=1919,S0=N=>N>=2208&&N<=2303,Jd=N=>N>=11904&&N<=12031,mp=N=>N>=12032&&N<=12255,xv=N=>N>=12272&&N<=12287,T1=N=>N>=12288&&N<=12351,gv=N=>N>=12352&&N<=12447,Am=N=>N>=12448&&N<=12543,Jp=N=>N>=12544&&N<=12591,kw=N=>N>=12704&&N<=12735,Ag=N=>N>=12736&&N<=12783,C0=N=>N>=12784&&N<=12799,wy=N=>N>=12800&&N<=13055,Sw=N=>N>=13056&&N<=13311,Cw=N=>N>=13312&&N<=19903,cx=N=>N>=19968&&N<=40959,jy=N=>N>=40960&&N<=42127,dx=N=>N>=42128&&N<=42191,Xb=N=>N>=44032&&N<=55215,E1=N=>N>=63744&&N<=64255,M1=N=>N>=64336&&N<=65023,Aw=N=>N>=65040&&N<=65055,L1=N=>N>=65072&&N<=65103,bu=N=>N>=65104&&N<=65135,A0=N=>N>=65136&&N<=65279,Df=N=>N>=65280&&N<=65519;function ef(N){for(const f of N)if(ek(f.charCodeAt(0)))return!0;return!1}function CS(N){for(const f of N)if(!P1(f.charCodeAt(0)))return!1;return!0}function P1(N){return!(mc(N)||em(N)||S0(N)||M1(N)||A0(N))}function AS(N){return!(N<11904||!(kw(N)||Jp(N)||L1(N)||E1(N)||Sw(N)||Jd(N)||Ag(N)||T1(N)||Cw(N)||cx(N)||wy(N)||Df(N)||gv(N)||xv(N)||mp(N)||C0(N)||Am(N)||Aw(N)||dx(N)||jy(N)))}function ek(N){return!(N!==746&&N!==747&&(N<4352||!(kw(N)||Jp(N)||L1(N)&&!(N>=65097&&N<=65103)||E1(N)||Sw(N)||Jd(N)||Ag(N)||!(!T1(N)||N>=12296&&N<=12305||N>=12308&&N<=12319||N===12336)||Cw(N)||cx(N)||wy(N)||(f=>f>=12592&&f<=12687)(N)||(f=>f>=43360&&f<=43391)(N)||(f=>f>=55216&&f<=55295)(N)||(f=>f>=4352&&f<=4607)(N)||Xb(N)||gv(N)||xv(N)||(f=>f>=12688&&f<=12703)(N)||mp(N)||C0(N)||Am(N)&&N!==12540||!(!Df(N)||N===65288||N===65289||N===65293||N>=65306&&N<=65310||N===65339||N===65341||N===65343||N>=65371&&N<=65503||N===65507||N>=65512&&N<=65519)||!(!bu(N)||N>=65112&&N<=65118||N>=65123&&N<=65126)||(f=>f>=5120&&f<=5759)(N)||(f=>f>=6320&&f<=6399)(N)||Aw(N)||(f=>f>=19904&&f<=19967)(N)||jy(N)||dx(N))))}function yv(N){return N===12312||N===12313||N===12316||N===12540||N===12448}function vv(N){return!(ek(N)||function(f){return!!((_=>_>=128&&_<=255)(f)&&(f===167||f===169||f===174||f===177||f===188||f===189||f===190||f===215||f===247)||(_=>_>=8192&&_<=8303)(f)&&(f===8214||f===8224||f===8225||f===8240||f===8241||f===8251||f===8252||f===8258||f===8263||f===8264||f===8265||f===8273)||(_=>_>=8448&&_<=8527)(f)||(_=>_>=8528&&_<=8591)(f)||(_=>_>=8960&&_<=9215)(f)&&(f>=8960&&f<=8967||f>=8972&&f<=8991||f>=8996&&f<=9e3||f===9003||f>=9085&&f<=9114||f>=9150&&f<=9165||f===9167||f>=9169&&f<=9179||f>=9186&&f<=9215)||(_=>_>=9216&&_<=9279)(f)&&f!==9251||(_=>_>=9280&&_<=9311)(f)||(_=>_>=9312&&_<=9471)(f)||(_=>_>=9632&&_<=9727)(f)||(_=>_>=9728&&_<=9983)(f)&&!(f>=9754&&f<=9759)||(_=>_>=11008&&_<=11263)(f)&&(f>=11026&&f<=11055||f>=11088&&f<=11097||f>=11192&&f<=11243)||T1(f)||Am(f)||(_=>_>=57344&&_<=63743)(f)||L1(f)||bu(f)||Df(f)||f===8734||f===8756||f===8757||f>=9984&&f<=10087||f>=10102&&f<=10131||f===65532||f===65533)}(N))}function TS(N){return mc(N)||em(N)||S0(N)||M1(N)||A0(N)}function bv(N){return N>=1424&&N<=2303||M1(N)||A0(N)}function Tg(N,f){return!(!f&&bv(N)||N>=2304&&N<=3583||N>=3840&&N<=4255||(_=>_>=6016&&_<=6143)(N))}function o2(N){for(const f of N)if(bv(f.charCodeAt(0)))return!0;return!1}const Ru={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let tm=null,Ed=Ru.unavailable,tf=null;const tk=function(N){N&&typeof N=="string"&&N.indexOf("NetworkError")>-1&&(Ed=Ru.error),tm&&tm(N)};function l2(){sk.fire(new Tc("pluginStateChange",{pluginStatus:Ed,pluginURL:tf}))}const sk=new Xh,T0=function(){return Ed},nk=function(){if(Ed!==Ru.deferred||!tf)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Ed=Ru.loading,l2(),tf&&gy({url:tf},N=>{N?tk(N):(Ed=Ru.loaded,l2())})},$x={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Ed===Ru.loaded||$x.applyArabicShaping!=null,isLoading:()=>Ed===Ru.loading,setState(N){Ed=N.pluginStatus,tf=N.pluginURL},isParsing:()=>Ed===Ru.parsing,isParsed:()=>Ed===Ru.parsed,getPluginURL:()=>tf},L6=function(){$x.isLoading()||$x.isLoaded()||T0()!=="deferred"||nk()};class bi{constructor(f,_){this.zoom=f,_?(this.now=_.now,this.fadeDuration=_.fadeDuration,this.transition=_.transition,this.pitch=_.pitch,this.brightness=_.brightness,this.worldview=_.worldview,this.activeFloors=_.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(f){return function(_,S){for(const E of _)if(!Tg(E.charCodeAt(0),S))return!1;return!0}(f,$x.isLoaded())}}class rk{constructor(f,_,S,E,D){this.property=f,this.value=_,this.expression=function(z,H,Y,te,he){if(Qd(z))return new Sm(z,H);if(km(z)||Array.isArray(z)&&z.length>0){const ge=Iu(z,H,Y,te,he);if(ge.result==="error")throw new Error(ge.value.map(ve=>`${ve.key}: ${ve.message}`).join(", "));return ge.value}{let ge=z;return typeof z=="string"&&H.type==="color"&&(ge=us.parse(z)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>ge}}}(_===void 0?f.specification.default:_,f.specification,S,E,D)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(f,_,S,E){return this.property.possiblyEvaluate(this,f,_,S,E)}}class ES{constructor(f,_,S,E){this.property=f,this.value=new rk(f,void 0,_,S,E)}transitioned(f,_){return new ak(this.property,this.value,_,Object.assign({},f.transition,this.transition),f.now)}untransitioned(){return new ak(this.property,this.value,null,{},0)}}class lC{constructor(f,_,S,E){this._properties=f,this._values=Object.create(f.defaultTransitionablePropertyValues),this._scope=_,this._options=S,this._iconImageUseTheme=E,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(f){return _r(this._values[f].value.value)}setValue(f,_){this._values.hasOwnProperty(f)||(this._values[f]=new ES(this._values[f].property,this._scope,this._options,this._iconImageUseTheme)),this._values[f].value=new rk(this._values[f].property,_===null?void 0:_r(_),this._scope,this._options,this._iconImageUseTheme),this._values[f].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[f].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[f].value.isIndoorDependent())}setTransitionOrValue(f,_){_&&(this._options=_);const S=this._properties.properties;if(f)for(const E in f){const D=f[E];if(E.endsWith("-transition")){const z=E.slice(0,-11);S[z]&&this.setTransition(z,D)}else S.hasOwnProperty(E)&&this.setValue(E,D)}}getTransition(f){return _r(this._values[f].transition)}setTransition(f,_){this._values.hasOwnProperty(f)||(this._values[f]=new ES(this._values[f].property)),this._values[f].transition=_r(_)||void 0}serialize(){const f={};for(const _ of Object.keys(this._values)){const S=this.getValue(_);S!==void 0&&(f[_]=S);const E=this.getTransition(_);E!==void 0&&(f[`${_}-transition`]=E)}return f}transitioned(f,_){const S=new cC(this._properties);for(const E of Object.keys(this._values))S._values[E]=this._values[E].transitioned(f,_._values[E]);return S}untransitioned(){const f=new cC(this._properties);for(const _ of Object.keys(this._values))f._values[_]=this._values[_].untransitioned();return f}isIndoorDependent(){return this._isIndoorDependent}}class ak{constructor(f,_,S,E,D){const z=E.delay||0,H=E.duration||0;D=D||0,this.property=f,this.value=_,this.begin=D+z,this.end=this.begin+H,f.specification.transition&&(E.delay||E.duration)&&(this.prior=S)}possiblyEvaluate(f,_,S){const E=f.now||0,D=this.value.possiblyEvaluate(f,_,S),z=this.prior;if(z){if(E>this.end)return this.prior=null,D;if(this.value.isDataDriven())return this.prior=null,D;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 MS(N){return N instanceof Number||N instanceof String||N instanceof Boolean?N.valueOf():N}function ik(N){if(Array.isArray(N))return N.map(ik);if(N instanceof Object&&!(N instanceof Number||N instanceof String||N instanceof Boolean)){const f={};for(const _ in N)f[_]=ik(N[_]);return f}return MS(N)}function LS(N){if(N===!0||N===!1)return!0;if(!Array.isArray(N)||N.length===0)return!1;switch(N[0]){case"has":return N.length>=2&&N[1]!=="$id"&&N[1]!=="$type";case"in":return N.length>=3&&(typeof N[1]!="string"||Array.isArray(N[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return N.length!==3||Array.isArray(N[1])||Array.isArray(N[2]);case"any":case"all":for(const f of N.slice(1))if(!LS(f)&&typeof f!="boolean")return!1;return!0;default:return!0}}function uC(N,f="",_=null,S="fill"){if(N==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};LS(N)||(N=mC(N));const E=N;let D=!0;try{D=function(he){if(!d2(he))return he;let ge=ik(he);return I6(ge),ge=P6(ge),ge}(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 z=null,H=null;if(S!=="background"&&S!=="sky"&&S!=="slot"){H=Rs[`filter_${S}`];const he=Fc(D,H,f,_);if(he.result==="error")throw new Error(he.value.map(ge=>`${ge.key}: ${ge.message}`).join(", "));z=(ge,ve,Te)=>he.value.evaluate(ge,ve,{},Te)}let Y=null,te=null;if(D!==E){const he=Fc(E,H,f,_);if(he.result==="error")throw new Error(he.value.map(ge=>`${ge.key}: ${ge.message}`).join(", "));Y=(ge,ve,Te,Ie,Ve)=>he.value.evaluate(ge,ve,{},Te,void 0,void 0,Ie,Ve),te=!A1(he.value.expression)}return{filter:z,dynamicFilter:Y||void 0,needGeometry:GO(D),needFeature:!!te}}function P6(N){if(!Array.isArray(N))return N;const f=function(_){if(R6.has(_[0])){for(let S=1;S<_.length;S++)if(d2(_[S]))return!0}return _}(N);return f===!0?f:f.map(_=>P6(_))}function I6(N){let f=!1;const _=[];if(N[0]==="case"){for(let S=1;S",">=","<","<=","to-boolean"]);function hC(N,f){return Nf?1:0}function GO(N){if(!Array.isArray(N))return!1;if(N[0]==="within"||N[0]==="distance")return!0;for(let f=1;f"||f==="<="||f===">="?Q(N[1],N[2],f):f==="any"?(_=N.slice(1),["any"].concat(_.map(mC))):f==="all"?["all"].concat(N.slice(1).map(mC)):f==="none"?["all"].concat(N.slice(1).map(mC).map(st)):f==="in"?ne(N[1],N.slice(2)):f==="!in"?st(ne(N[1],N.slice(2))):f==="has"?Pe(N[1]):f!=="!has"||st(Pe(N[1]));var _}function Q(N,f,_){switch(N){case"$type":return[`filter-type-${_}`,f];case"$id":return[`filter-id-${_}`,f];default:return[`filter-${_}`,N,f]}}function ne(N,f){if(f.length===0)return!1;switch(N){case"$type":return["filter-type-in",["literal",f]];case"$id":return["filter-id-in",["literal",f]];default:return f.length>200&&!f.some(_=>typeof _!=typeof f[0])?["filter-in-large",N,["literal",f.sort(hC)]]:["filter-in-small",N,["literal",f]]}}function Pe(N){switch(N){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",N]}}function st(N){return["!",N]}const lt="";function Ct(N,f){return f?`${N}${lt}${f}`:N}function Ps(N){const f=N.indexOf(lt);return f>=0?N.slice(f+1):""}let qn;const Er=()=>qn||(qn=new pc({"icon-size":new tr(Rs.layout_symbol["icon-size"]),"icon-image":new tr(Rs.layout_symbol["icon-image"]),"icon-rotate":new tr(Rs.layout_symbol["icon-rotate"]),"icon-offset":new tr(Rs.layout_symbol["icon-offset"]),"text-size":new tr(Rs.layout_symbol["text-size"]),"text-rotate":new tr(Rs.layout_symbol["text-rotate"]),"text-offset":new tr(Rs.layout_symbol["text-offset"])}));let Ca;const Ei=()=>Ca||(Ca=new pc({"icon-opacity":new tr(Rs.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new tr(Rs.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new tr(Rs.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new tr(Rs.paint_symbol["text-emissive-strength"]),"icon-color":new tr(Rs.paint_symbol["icon-color"]),"icon-halo-color":new tr(Rs.paint_symbol["icon-halo-color"]),"icon-halo-width":new tr(Rs.paint_symbol["icon-halo-width"]),"icon-halo-blur":new tr(Rs.paint_symbol["icon-halo-blur"]),"icon-translate":new tr(Rs.paint_symbol["icon-translate"]),"text-opacity":new tr(Rs.paint_symbol["text-opacity"]),"text-occlusion-opacity":new tr(Rs.paint_symbol["text-occlusion-opacity"]),"text-color":new tr(Rs.paint_symbol["text-color"],{runtimeType:Rl,getOverride:N=>N.textColor,hasOverride:N=>!!N.textColor}),"text-halo-color":new tr(Rs.paint_symbol["text-halo-color"]),"text-halo-width":new tr(Rs.paint_symbol["text-halo-width"]),"text-halo-blur":new tr(Rs.paint_symbol["text-halo-blur"]),"text-translate":new tr(Rs.paint_symbol["text-translate"]),"symbol-z-offset":new tr(Rs.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"})}));class vl{constructor(f,_,S,E,D,z){this._conditionSpec=f,this._propertiesSpec=S;const H=Fc(f,Rs.appearance.condition);if(H.result==="success"&&(this.condition=H.value),this.name=_,S){this.layoutProperties=new Tm(Er()),this.unevaluatedLayout=new dC(Er(),E,D,z),this.paintProperties=new Tm(Ei()),this.unevaluatedPaint=new dC(Ei(),E,D,"");for(const Y in S)Y in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(Y,S[Y]):Y in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(Y,S[Y])}}isActive(f){return!(this.condition||!f.isHidden||this.name!=="hidden")||this.condition.evaluate(f.globals,f.feature,f.featureState,f.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(f){return this.layoutProperties.get(f)}getPaintProperty(f){return this.paintProperties.get(f)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(f){return this.unevaluatedLayout._values[f]}getUnevaluatedPaintProperty(f){return this.unevaluatedPaint._values[f]}recalculate(f,_,S){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(f,void 0,_,S)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(f,void 0,_,""))}serialize(){const f={};f.condition=this.condition.expression.serialize(),this.name&&(f.name=this.name);const _=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},S=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},E=Object.assign({},_,S);return Object.keys(E).length>0&&(f.properties=E),f}hasIconLayoutProperties(){const f=this.hasLayoutProperty("icon-image"),_=this.hasLayoutProperty("icon-size"),S=this.hasLayoutProperty("icon-offset"),E=this.hasLayoutProperty("icon-rotate");return f||_||S||E}hasTextLayoutProperties(){const f=this.hasLayoutProperty("text-size"),_=this.hasLayoutProperty("text-offset"),S=this.hasLayoutProperty("text-rotate");return f||_||S}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(f=>!f.endsWith("-use-theme")).some(f=>(f.startsWith("icon-")||f==="symbol-z-offset")&&this.hasPaintProperty(f))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(f=>!f.endsWith("-use-theme")).some(f=>(f.startsWith("text-")||f==="symbol-z-offset")&&this.hasPaintProperty(f))}hasLayoutProperty(f){return this.unevaluatedLayout&&this.unevaluatedLayout._values[f].value!==void 0}hasPaintProperty(f){return this.unevaluatedPaint&&this.unevaluatedPaint._values[f].value!==void 0}}const hi="-transition",Du=new Set(["fill","line","background","hillshade","raster"]);class bl extends Xh{constructor(f,_,S,E,D,z){if(super(),this.id=f.id,this.fqid=Ct(this.id,S),this.type=f.type,this.scope=S,this.lut=E,this.options=D,this.iconImageUseTheme=z,this.appearances=new Array,this.appearancesVersion=0,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,this.expressionDependencies={isIndoorDependent:!1,configDependencies:new Set},f.type!=="custom"){if(this.metadata=f.metadata,this.minzoom=f.minzoom,this.maxzoom=f.maxzoom,f.type&&f.type!=="background"&&f.type!=="sky"&&f.type!=="slot"){this.source=f.source,this.sourceLayer=f["source-layer"],this.filter=f.filter;const H=Fc(this.filter,Rs[`filter_${f.type}`]);H.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...H.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||H.value.isIndoorDependent)}if(f.slot&&(this.slot=f.slot),f.appearances&&this.setAppearances(f.appearances),_.layout&&(this._unevaluatedLayout=new dC(_.layout,this.scope,D,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),_.paint){this._transitionablePaint=new lC(_.paint,this.scope,D);for(const H in f.paint)this.setPaintProperty(H,f.paint[H]);for(const H in f.layout)this.setLayoutProperty(H,f.layout[H]);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 Tm(_.paint)}}}onAdd(f){}onRemove(f){}isDraped(f){return!this.is3D(!0)&&Du.has(this.type)}getLayoutProperty(f){return f==="visibility"?this.visibility:this._unevaluatedLayout.getValue(f)}setLayoutProperty(f,_){if(this.type==="custom"&&f==="visibility")return void(this.visibility=_);const S=this._unevaluatedLayout;S._properties.properties[f]&&(S.setValue(f,_),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...S.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||S.isIndoorDependent(),f==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(f){this.appearances=[],f.forEach(_=>{this.appearances.push(new vl(_.condition,_.name,_.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(f){return f.endsWith(hi)?this._transitionablePaint.getTransition(f.slice(0,-11)):this._transitionablePaint.getValue(f)}isPaintProperty(f){return!!this._transitionablePaint._properties.properties[f]}setPaintProperty(f,_){const S=this._transitionablePaint,E=S._properties.properties;if(f.endsWith(hi)){const ge=f.slice(0,-11);return E[ge]&&S.setTransition(ge,_||void 0),!1}if(!E[f])return!1;const D=S._values[f],z=D.value.isDataDriven(),H=D.value;S.setValue(f,_),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...S.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||S.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(f);const Y=S._values[f].value,te=Y.isDataDriven(),he=f.endsWith("pattern")||f==="line-dasharray";return te||z||he||this._handleOverridablePaintPropertyUpdate(f,H,Y)}_handleSpecialPaintPropertyUpdate(f){}getProgramIds(){return null}getDefaultProgramParams(f,_,S){return null}_handleOverridablePaintPropertyUpdate(f,_,S){return!1}isHidden(f){return!!(this.minzoom&&f=this.maxzoom)||this.visibility==="none"}updateTransitions(f){this._transitioningPaint=this._transitionablePaint.transitioned(f,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(f,_){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(f,void 0,_,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(f,void 0,_)}serialize(){const f={id:this.id,type:this.type,slot:this.slot,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.appearances.length!==0&&(f.appearances=this.appearances.map(_=>_.serialize())),vn(f,(_,S)=>!(_===void 0||S==="layout"&&!Object.keys(_).length||S==="paint"&&!Object.keys(_).length))}is3D(f){return!1}hasElevation(){return!1}isSky(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}hasShadowPass(){return!1}canCastShadows(){return!1}hasLightBeamPass(){return!1}cutoffRange(){return 0}tileCoverLift(){return 0}resize(){}_clear(){}isStateDependent(){for(const f in this.paint._values){const _=this.paint.get(f);if(_ instanceof c2&&qo(_.property.specification)&&(_.value.kind==="source"||_.value.kind==="composite")&&_.value.isStateDependent)return!0}for(const f of this.appearances)if(!Rf(f.condition.expression))return!0;return!1}compileFilter(f){this._filterCompiled||(this._featureFilter=uC(this.filter,this.scope,f),this._filterCompiled=!0)}invalidateCompiledFilter(){this._filterCompiled=!1}dynamicFilter(){return this._featureFilter.dynamicFilter}dynamicFilterNeedsFeature(){return this._featureFilter.needFeature}dynamicFilterNeedsGeometry(){return this._featureFilter.needGeometry}getLayerRenderingStats(){return this._stats}resetLayerRenderingStats(f){this._stats&&(f.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(f,_,S){return{}}queryRadius(f){}queryIntersectsFeature(f,_,S,E,D,z,H,Y,te,he){}}const Of={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class M0{constructor(f,_){this._structArray=f,this._pos1=_*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const Sr=new ArrayBuffer(0);class wn{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(f,_){return f._trim(),_&&f.arrayBuffer&&_.add(f.arrayBuffer),{length:f.length,arrayBuffer:f.arrayBuffer}}static deserialize(f){const _=Object.create(this.prototype);return _.arrayBuffer=f.arrayBuffer,_.length=f.length,f.arrayBuffer?_.capacity=f.arrayBuffer.byteLength/_.bytesPerElement:(_.capacity=0,_.arrayBuffer=Sr),_._refreshViews(),_}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(f){this.reserve(f),this.length=f}reserve(f){if(f>this.capacity){this._reallocCount++,this.capacity=Math.max(f,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const _=this.uint8;this._refreshViews(),_&&this.uint8.set(_)}}reserveForAdditional(f){this.reserve(this.length+f)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...f){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...f){throw new Error("StructArray#emplaceBack() must be implemented by each concrete StructArray layout")}destroy(){this.int8=this.uint8=this.int16=this.uint16=this.int32=this.uint32=this.float32=null,this.arrayBuffer=null}}function Fn(N,f=1){let _=0,S=0;return{members:N.map(E=>{const D=Of[E.type].BYTES_PER_ELEMENT,z=_=_i(_,Math.max(f,D)),H=E.components||1;return S=Math.max(S,D),_+=D*H,{name:E.name,type:E.type,components:H,offset:z}}),size:_i(_,Math.max(S,f)),alignment:f}}function _i(N,f){return Math.ceil(N/f)*f}class Pi extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_){const S=this.length;return this.resize(S+1),this.emplace(S,f,_)}emplace(f,_,S){const E=2*f;return this.int16[E+0]=_,this.int16[E+1]=S,f}}Pi.prototype.bytesPerElement=4,gr(Pi,"StructArrayLayout2i4");class Uo extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S){const E=this.length;return this.resize(E+1),this.emplace(E,f,_,S)}emplace(f,_,S,E){const D=3*f;return this.int16[D+0]=_,this.int16[D+1]=S,this.int16[D+2]=E,f}}Uo.prototype.bytesPerElement=6,gr(Uo,"StructArrayLayout3i6");class Xi extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_,S,E){const D=this.length;return this.resize(D+1),this.emplace(D,f,_,S,E)}emplace(f,_,S,E,D){const z=4*f;return this.int16[z+0]=_,this.int16[z+1]=S,this.uint16[z+2]=E,this.uint16[z+3]=D,f}}Xi.prototype.bytesPerElement=8,gr(Xi,"StructArrayLayout2i2ui8");class dl extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f){const _=this.length;return this.resize(_+1),this.emplace(_,f)}emplace(f,_){return this.float32[1*f+0]=_,f}}dl.prototype.bytesPerElement=4,gr(dl,"StructArrayLayout1f4");class Em extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S){const E=this.length;return this.resize(E+1),this.emplace(E,f,_,S)}emplace(f,_,S,E){const D=4*f,z=2*f;return this.int16[D+0]=_,this.int16[D+1]=S,this.float32[z+1]=E,f}}Em.prototype.bytesPerElement=8,gr(Em,"StructArrayLayout2i1f8");class Mc extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S){const E=this.length;return this.resize(E+1),this.emplace(E,f,_,S)}emplace(f,_,S,E){const D=4*f;return this.int16[D+0]=_,this.int16[D+1]=S,this.int16[D+2]=E,f}}Mc.prototype.bytesPerElement=8,gr(Mc,"StructArrayLayout3i8");class I1 extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S,E){const D=this.length;return this.resize(D+1),this.emplace(D,f,_,S,E)}emplace(f,_,S,E,D){const z=4*f;return this.int16[z+0]=_,this.int16[z+1]=S,this.int16[z+2]=E,this.int16[z+3]=D,f}}I1.prototype.bytesPerElement=8,gr(I1,"StructArrayLayout4i8");class D6 extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D){const z=this.length;return this.resize(z+1),this.emplace(z,f,_,S,E,D)}emplace(f,_,S,E,D,z){const H=5*f;return this.int16[H+0]=_,this.int16[H+1]=S,this.int16[H+2]=E,this.int16[H+3]=D,this.int16[H+4]=z,f}}D6.prototype.bytesPerElement=10,gr(D6,"StructArrayLayout5i10");class O6 extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z,H){const Y=this.length;return this.resize(Y+1),this.emplace(Y,f,_,S,E,D,z,H)}emplace(f,_,S,E,D,z,H,Y){const te=6*f,he=12*f,ge=3*f;return this.int16[te+0]=_,this.int16[te+1]=S,this.uint8[he+4]=E,this.uint8[he+5]=D,this.uint8[he+6]=z,this.uint8[he+7]=H,this.float32[ge+2]=Y,f}}O6.prototype.bytesPerElement=12,gr(O6,"StructArrayLayout2i4ub1f12");class R1 extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S){const E=this.length;return this.resize(E+1),this.emplace(E,f,_,S)}emplace(f,_,S,E){const D=3*f;return this.float32[D+0]=_,this.float32[D+1]=S,this.float32[D+2]=E,f}}R1.prototype.bytesPerElement=12,gr(R1,"StructArrayLayout3f12");class Tw extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D){const z=this.length;return this.resize(z+1),this.emplace(z,f,_,S,E,D)}emplace(f,_,S,E,D,z){const H=6*f,Y=3*f;return this.uint16[H+0]=_,this.uint16[H+1]=S,this.uint16[H+2]=E,this.uint16[H+3]=D,this.float32[Y+2]=z,f}}Tw.prototype.bytesPerElement=12,gr(Tw,"StructArrayLayout4ui1f12");class pC extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_,S,E){const D=this.length;return this.resize(D+1),this.emplace(D,f,_,S,E)}emplace(f,_,S,E,D){const z=4*f;return this.uint16[z+0]=_,this.uint16[z+1]=S,this.uint16[z+2]=E,this.uint16[z+3]=D,f}}pC.prototype.bytesPerElement=8,gr(pC,"StructArrayLayout4ui8");class WO extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z){const H=this.length;return this.resize(H+1),this.emplace(H,f,_,S,E,D,z)}emplace(f,_,S,E,D,z,H){const Y=6*f;return this.int16[Y+0]=_,this.int16[Y+1]=S,this.int16[Y+2]=E,this.int16[Y+3]=D,this.int16[Y+4]=z,this.int16[Y+5]=H,f}}WO.prototype.bytesPerElement=12,gr(WO,"StructArrayLayout6i12");class Jq extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z,H,Y,te,he,ge,ve){const Te=this.length;return this.resize(Te+1),this.emplace(Te,f,_,S,E,D,z,H,Y,te,he,ge,ve)}emplace(f,_,S,E,D,z,H,Y,te,he,ge,ve,Te){const Ie=12*f;return this.int16[Ie+0]=_,this.int16[Ie+1]=S,this.int16[Ie+2]=E,this.int16[Ie+3]=D,this.uint16[Ie+4]=z,this.uint16[Ie+5]=H,this.uint16[Ie+6]=Y,this.uint16[Ie+7]=te,this.int16[Ie+8]=he,this.int16[Ie+9]=ge,this.int16[Ie+10]=ve,this.int16[Ie+11]=Te,f}}Jq.prototype.bytesPerElement=24,gr(Jq,"StructArrayLayout4i4ui4i24");class eV extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z){const H=this.length;return this.resize(H+1),this.emplace(H,f,_,S,E,D,z)}emplace(f,_,S,E,D,z,H){const Y=10*f,te=5*f;return this.int16[Y+0]=_,this.int16[Y+1]=S,this.int16[Y+2]=E,this.float32[te+2]=D,this.float32[te+3]=z,this.float32[te+4]=H,f}}eV.prototype.bytesPerElement=20,gr(eV,"StructArrayLayout3i3f20");class u2 extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E){const D=this.length;return this.resize(D+1),this.emplace(D,f,_,S,E)}emplace(f,_,S,E,D){const z=4*f;return this.float32[z+0]=_,this.float32[z+1]=S,this.float32[z+2]=E,this.float32[z+3]=D,f}}u2.prototype.bytesPerElement=16,gr(u2,"StructArrayLayout4f16");class F6 extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(f){const _=this.length;return this.resize(_+1),this.emplace(_,f)}emplace(f,_){return this.uint32[1*f+0]=_,f}}F6.prototype.bytesPerElement=4,gr(F6,"StructArrayLayout1ul4");class D1 extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_){const S=this.length;return this.resize(S+1),this.emplace(S,f,_)}emplace(f,_,S){const E=2*f;return this.uint16[E+0]=_,this.uint16[E+1]=S,f}}D1.prototype.bytesPerElement=4,gr(D1,"StructArrayLayout2ui4");class KO extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z,H,Y,te,he,ge,ve,Te){const Ie=this.length;return this.resize(Ie+1),this.emplace(Ie,f,_,S,E,D,z,H,Y,te,he,ge,ve,Te)}emplace(f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie){const Ve=20*f,et=10*f;return this.int16[Ve+0]=_,this.int16[Ve+1]=S,this.int16[Ve+2]=E,this.int16[Ve+3]=D,this.int16[Ve+4]=z,this.float32[et+3]=H,this.float32[et+4]=Y,this.float32[et+5]=te,this.float32[et+6]=he,this.int16[Ve+14]=ge,this.uint32[et+8]=ve,this.uint16[Ve+18]=Te,this.uint16[Ve+19]=Ie,f}}KO.prototype.bytesPerElement=40,gr(KO,"StructArrayLayout5i4f1i1ul2ui40");class z6 extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z,H){const Y=this.length;return this.resize(Y+1),this.emplace(Y,f,_,S,E,D,z,H)}emplace(f,_,S,E,D,z,H,Y){const te=8*f;return this.int16[te+0]=_,this.int16[te+1]=S,this.int16[te+2]=E,this.int16[te+4]=D,this.int16[te+5]=z,this.int16[te+6]=H,this.int16[te+7]=Y,f}}z6.prototype.bytesPerElement=16,gr(z6,"StructArrayLayout3i2i2i16");class tV extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D){const z=this.length;return this.resize(z+1),this.emplace(z,f,_,S,E,D)}emplace(f,_,S,E,D,z){const H=4*f,Y=8*f;return this.float32[H+0]=_,this.float32[H+1]=S,this.float32[H+2]=E,this.int16[Y+6]=D,this.int16[Y+7]=z,f}}tV.prototype.bytesPerElement=16,gr(tV,"StructArrayLayout2f1f2i16");class B6 extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z){const H=this.length;return this.resize(H+1),this.emplace(H,f,_,S,E,D,z)}emplace(f,_,S,E,D,z,H){const Y=20*f,te=5*f;return this.uint8[Y+0]=_,this.uint8[Y+1]=S,this.float32[te+1]=E,this.float32[te+2]=D,this.float32[te+3]=z,this.float32[te+4]=H,f}}B6.prototype.bytesPerElement=20,gr(B6,"StructArrayLayout2ub4f20");class eu extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_,S){const E=this.length;return this.resize(E+1),this.emplace(E,f,_,S)}emplace(f,_,S,E){const D=3*f;return this.uint16[D+0]=_,this.uint16[D+1]=S,this.uint16[D+2]=E,f}}eu.prototype.bytesPerElement=6,gr(eu,"StructArrayLayout3ui6");class YO extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et,at,ft,ut,Nt,Mt){const It=this.length;return this.resize(It+1),this.emplace(It,f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et,at,ft,ut,Nt,Mt)}emplace(f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et,at,ft,ut,Nt,Mt,It){const xs=30*f,es=15*f,ps=60*f;return this.int16[xs+0]=_,this.int16[xs+1]=S,this.int16[xs+2]=E,this.float32[es+2]=D,this.float32[es+3]=z,this.uint16[xs+8]=H,this.uint16[xs+9]=Y,this.uint32[es+5]=te,this.uint32[es+6]=he,this.uint32[es+7]=ge,this.uint16[xs+16]=ve,this.uint16[xs+17]=Te,this.uint16[xs+18]=Ie,this.float32[es+10]=Ve,this.float32[es+11]=et,this.uint8[ps+48]=at,this.uint8[ps+49]=ft,this.uint8[ps+50]=ut,this.uint32[es+13]=Nt,this.int16[xs+28]=Mt,this.uint8[ps+58]=It,f}}YO.prototype.bytesPerElement=60,gr(YO,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class sV extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et,at,ft,ut,Nt,Mt,It,xs,es,ps,cs,ds,mn,xn,kn,En,Sn,Gn){const dn=this.length;return this.resize(dn+1),this.emplace(dn,f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et,at,ft,ut,Nt,Mt,It,xs,es,ps,cs,ds,mn,xn,kn,En,Sn,Gn)}emplace(f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et,at,ft,ut,Nt,Mt,It,xs,es,ps,cs,ds,mn,xn,kn,En,Sn,Gn,dn){const An=20*f,Pn=40*f,Wn=80*f;return this.float32[An+0]=_,this.float32[An+1]=S,this.int16[Pn+4]=E,this.int16[Pn+5]=D,this.int16[Pn+6]=z,this.int16[Pn+7]=H,this.int16[Pn+8]=Y,this.int16[Pn+9]=te,this.int16[Pn+10]=he,this.int16[Pn+11]=ge,this.int16[Pn+12]=ve,this.uint16[Pn+13]=Te,this.uint16[Pn+14]=Ie,this.uint16[Pn+15]=Ve,this.uint16[Pn+16]=et,this.uint16[Pn+17]=at,this.uint16[Pn+18]=ft,this.uint16[Pn+19]=ut,this.uint16[Pn+20]=Nt,this.uint16[Pn+21]=Mt,this.uint16[Pn+22]=It,this.uint16[Pn+23]=xs,this.uint16[Pn+24]=es,this.uint16[Pn+25]=ps,this.uint16[Pn+26]=cs,this.uint16[Pn+27]=ds,this.uint32[An+14]=mn,this.float32[An+15]=xn,this.float32[An+16]=kn,this.float32[An+17]=En,this.float32[An+18]=Sn,this.uint8[Wn+76]=Gn,this.uint16[Pn+39]=dn,f}}sV.prototype.bytesPerElement=80,gr(sV,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class ZO extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z){const H=this.length;return this.resize(H+1),this.emplace(H,f,_,S,E,D,z)}emplace(f,_,S,E,D,z,H){const Y=6*f;return this.float32[Y+0]=_,this.float32[Y+1]=S,this.float32[Y+2]=E,this.float32[Y+3]=D,this.float32[Y+4]=z,this.float32[Y+5]=H,f}}ZO.prototype.bytesPerElement=24,gr(ZO,"StructArrayLayout6f24");class PS extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D){const z=this.length;return this.resize(z+1),this.emplace(z,f,_,S,E,D)}emplace(f,_,S,E,D,z){const H=5*f;return this.float32[H+0]=_,this.float32[H+1]=S,this.float32[H+2]=E,this.float32[H+3]=D,this.float32[H+4]=z,f}}PS.prototype.bytesPerElement=20,gr(PS,"StructArrayLayout5f20");class $6 extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z,H){const Y=this.length;return this.resize(Y+1),this.emplace(Y,f,_,S,E,D,z,H)}emplace(f,_,S,E,D,z,H,Y){const te=7*f;return this.float32[te+0]=_,this.float32[te+1]=S,this.float32[te+2]=E,this.float32[te+3]=D,this.float32[te+4]=z,this.float32[te+5]=H,this.float32[te+6]=Y,f}}$6.prototype.bytesPerElement=28,gr($6,"StructArrayLayout7f28");class nV extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z,H,Y,te,he,ge){const ve=this.length;return this.resize(ve+1),this.emplace(ve,f,_,S,E,D,z,H,Y,te,he,ge)}emplace(f,_,S,E,D,z,H,Y,te,he,ge,ve){const Te=11*f;return this.float32[Te+0]=_,this.float32[Te+1]=S,this.float32[Te+2]=E,this.float32[Te+3]=D,this.float32[Te+4]=z,this.float32[Te+5]=H,this.float32[Te+6]=Y,this.float32[Te+7]=te,this.float32[Te+8]=he,this.float32[Te+9]=ge,this.float32[Te+10]=ve,f}}nV.prototype.bytesPerElement=44,gr(nV,"StructArrayLayout11f44");class rV extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z,H,Y,te){const he=this.length;return this.resize(he+1),this.emplace(he,f,_,S,E,D,z,H,Y,te)}emplace(f,_,S,E,D,z,H,Y,te,he){const ge=9*f;return this.float32[ge+0]=_,this.float32[ge+1]=S,this.float32[ge+2]=E,this.float32[ge+3]=D,this.float32[ge+4]=z,this.float32[ge+5]=H,this.float32[ge+6]=Y,this.float32[ge+7]=te,this.float32[ge+8]=he,f}}rV.prototype.bytesPerElement=36,gr(rV,"StructArrayLayout9f36");class IS extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_){const S=this.length;return this.resize(S+1),this.emplace(S,f,_)}emplace(f,_,S){const E=2*f;return this.float32[E+0]=_,this.float32[E+1]=S,f}}IS.prototype.bytesPerElement=8,gr(IS,"StructArrayLayout2f8");class aV extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,_,S,E){const D=this.length;return this.resize(D+1),this.emplace(D,f,_,S,E)}emplace(f,_,S,E,D){const z=6*f;return this.uint32[3*f+0]=_,this.uint16[z+2]=S,this.uint16[z+3]=E,this.uint16[z+4]=D,f}}aV.prototype.bytesPerElement=12,gr(aV,"StructArrayLayout1ul3ui12");class RS extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f){const _=this.length;return this.resize(_+1),this.emplace(_,f)}emplace(f,_){return this.uint16[1*f+0]=_,f}}RS.prototype.bytesPerElement=2,gr(RS,"StructArrayLayout1ui2");class iV extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et){const at=this.length;return this.resize(at+1),this.emplace(at,f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et)}emplace(f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et,at){const ft=16*f;return this.float32[ft+0]=_,this.float32[ft+1]=S,this.float32[ft+2]=E,this.float32[ft+3]=D,this.float32[ft+4]=z,this.float32[ft+5]=H,this.float32[ft+6]=Y,this.float32[ft+7]=te,this.float32[ft+8]=he,this.float32[ft+9]=ge,this.float32[ft+10]=ve,this.float32[ft+11]=Te,this.float32[ft+12]=Ie,this.float32[ft+13]=Ve,this.float32[ft+14]=et,this.float32[ft+15]=at,f}}iV.prototype.bytesPerElement=64,gr(iV,"StructArrayLayout16f64");class XO extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,_,S,E,D,z,H){const Y=this.length;return this.resize(Y+1),this.emplace(Y,f,_,S,E,D,z,H)}emplace(f,_,S,E,D,z,H,Y){const te=10*f,he=5*f;return this.uint16[te+0]=_,this.uint16[te+1]=S,this.uint16[te+2]=E,this.uint16[te+3]=D,this.float32[he+2]=z,this.float32[he+3]=H,this.float32[he+4]=Y,f}}XO.prototype.bytesPerElement=20,gr(XO,"StructArrayLayout4ui3f20");class QO extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f){const _=this.length;return this.resize(_+1),this.emplace(_,f)}emplace(f,_){return this.int16[1*f+0]=_,f}}QO.prototype.bytesPerElement=2,gr(QO,"StructArrayLayout1i2");class JO extends wn{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(f){const _=this.length;return this.resize(_+1),this.emplace(_,f)}emplace(f,_){return this.uint8[1*f+0]=_,f}}JO.prototype.bytesPerElement=1,gr(JO,"StructArrayLayout1ub1");class Nee extends M0{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]}}Nee.prototype.size=40;class oV extends KO{get(f){return new Nee(this,f)}}gr(oV,"CollisionBoxArray");class kee extends M0{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.float32[this._pos4+2]}get tileAnchorY(){return this._structArray.float32[this._pos4+3]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+8]}get numGlyphs(){return this._structArray.uint16[this._pos2+9]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+5]}get lineStartIndex(){return this._structArray.uint32[this._pos4+6]}get lineLength(){return this._structArray.uint32[this._pos4+7]}get segment(){return this._structArray.uint16[this._pos2+16]}get lowerSize(){return this._structArray.uint16[this._pos2+17]}get upperSize(){return this._structArray.uint16[this._pos2+18]}get lineOffsetX(){return this._structArray.float32[this._pos4+10]}get lineOffsetY(){return this._structArray.float32[this._pos4+11]}get writingMode(){return this._structArray.uint8[this._pos1+48]}get placedOrientation(){return this._structArray.uint8[this._pos1+49]}set placedOrientation(f){this._structArray.uint8[this._pos1+49]=f}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(f){this._structArray.uint8[this._pos1+50]=f}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(f){this._structArray.uint32[this._pos4+13]=f}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(f){this._structArray.uint8[this._pos1+58]=f}}kee.prototype.size=60;class See extends YO{get(f){return new kee(this,f)}}gr(See,"PlacedSymbolArray");class U6 extends M0{get tileAnchorX(){return this._structArray.float32[this._pos4+0]}get tileAnchorY(){return this._structArray.float32[this._pos4+1]}get projectedAnchorX(){return this._structArray.int16[this._pos2+4]}get projectedAnchorY(){return this._structArray.int16[this._pos2+5]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+6]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+7]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+8]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+9]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+10]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+11]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+12]}get key(){return this._structArray.uint16[this._pos2+13]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+14]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+15]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+16]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+17]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+18]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+19]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+20]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+21]}get featureIndex(){return this._structArray.uint16[this._pos2+22]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+23]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+24]}get numIconVertices(){return this._structArray.uint16[this._pos2+25]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+26]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+27]}get crossTileID(){return this._structArray.uint32[this._pos4+14]}set crossTileID(f){this._structArray.uint32[this._pos4+14]=f}get textOffset0(){return this._structArray.float32[this._pos4+15]}get textOffset1(){return this._structArray.float32[this._pos4+16]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+17]}get zOffset(){return this._structArray.float32[this._pos4+18]}set zOffset(f){this._structArray.float32[this._pos4+18]=f}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}U6.prototype.size=80;class Cee extends sV{get(f){return new U6(this,f)}}gr(Cee,"SymbolInstanceArray");class Aee extends dl{getoffsetX(f){return this.float32[1*f+0]}}gr(Aee,"GlyphOffsetArray");class q6 extends Pi{getx(f){return this.int16[2*f+0]}gety(f){return this.int16[2*f+1]}}gr(q6,"SymbolLineVertexArray");class Tee extends M0{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]}}Tee.prototype.size=12;class lV extends aV{get(f){return new Tee(this,f)}}gr(lV,"FeatureIndexArray");class Eee extends D1{geta_centroid_pos0(f){return this.uint16[2*f+0]}geta_centroid_pos1(f){return this.uint16[2*f+1]}}gr(Eee,"FillExtrusionCentroidArray");class cV extends M0{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]}}cV.prototype.size=6;class dV extends Uo{get(f){return new cV(this,f)}}gr(dV,"FillExtrusionWallArray");const Mee=Fn([{name:"a_pos",components:2,type:"Int16"}],4),OTe=Fn([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),FTe=Fn([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Gl{constructor(f=[]){this.segments=f}_prepareSegment(f,_,S,E,D){let z=this.segments[this.segments.length-1];return f>Gl.MAX_VERTEX_ARRAY_LENGTH&&Mr(`Max vertices per segment is ${Gl.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${f}`),(!z||z.vertexLength+f>Gl.MAX_VERTEX_ARRAY_LENGTH||z.sortKey!==E||D!==void 0&&z&&z.batchIndex!==void 0&&z.batchIndex!==D)&&(z={vertexOffset:_,primitiveOffset:S,vertexLength:0,primitiveLength:0},E!==void 0&&(z.sortKey=E),D!==void 0&&(z.batchIndex=D),this.segments.push(z)),z}prepareSegment(f,_,S,E,D){return this._prepareSegment(f,_.length,S.length,E,D)}get(){return this.segments}destroy(){for(const f of this.segments)for(const _ in f.vaos)f.vaos[_].destroy()}static simpleSegment(f,_,S,E){return new Gl([{vertexOffset:f,primitiveOffset:_,vertexLength:S,primitiveLength:E,vaos:{},sortKey:0}])}}function eF(N,f){return 256*(N=it(Math.floor(N),0,255))+it(Math.floor(f),0,255)}Gl.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,gr(Gl,"SegmentVector");const zTe=Fn([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),BTe=Fn([{name:"a_pattern_b",components:4,type:"Uint16"}]),$Te=Fn([{name:"a_dash",components:4,type:"Uint16"}]);class V6{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(f,_,S,E){this.ids.push(uV(f)),this.positions.push(_,S,E)}eachPosition(f,_){const S=uV(f);let E=0,D=this.ids.length-1;for(;E>1;this.ids[z]>=S?D=z:E=z+1}for(;this.ids[E]===S;)_(this.positions[3*E],this.positions[3*E+1],this.positions[3*E+2]),E++}static serialize(f,_){const S=new Float64Array(f.ids),E=new Uint32Array(f.positions);return H6(S,E,0,S.length-1),_&&(_.add(S.buffer),_.add(E.buffer)),{ids:S,positions:E}}static deserialize(f){const _=new V6;let S;_.ids=f.ids,_.positions=f.positions;for(const E of _.ids)E!==S&&_.uniqueIds.push(E),S=E;return _.indexed=!0,_}}function uV(N){const f=+N;return Number.isSafeInteger(f)?f:rd(String(N))}function H6(N,f,_,S){for(;_>1];let D=_-1,z=S+1;for(;;){do D++;while(N[D]E);if(D>=z)break;_v(N,D,z),_v(f,3*D,3*z),_v(f,3*D+1,3*z+1),_v(f,3*D+2,3*z+2)}z-_`u_${D}`),this.type=S,this.context=E}setUniform(f,_,S,E,D){const z=E.constantOr(this.value);_.set(f,D,z instanceof us?z.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):z)}getBinding(f,_){return this.type==="color"?new qTe(f):new Eh(f)}}class pe{constructor(f,_){this.uniformNames=_.map(S=>`u_${S}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(f,_){this.pixelRatio=f.pixelRatio||1,this.pattern=f.tl.concat(f.br),this.patternTransition=_?_.tl.concat(_.br):this.pattern}setUniform(f,_,S,E,D){let z=null;D!=="u_pattern"&&D!=="u_dash"||(z=this.pattern),D==="u_pattern_b"&&(z=this.patternTransition),D==="u_pixel_ratio"&&(z=this.pixelRatio),z&&_.set(f,D,z)}getBinding(f,_){return _==="u_pattern"||_==="u_pattern_b"||_==="u_dash"?new UTe(f):new Eh(f)}}class ke{constructor(f,_,S,E){this.expression=f,this.type=S,this.maxValue=0,this.paintVertexAttributes=_.map(D=>({name:`a_${D}`,type:"Float32",components:S==="color"?2:1,offset:0})),this.paintVertexArray=new E}populatePaintArray(f,_,S,E,D,z,H,Y){const te=this.paintVertexArray.length,he=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new bi(0,{brightness:z,worldview:Y}),_,{},D,E,H):this.expression.kind==="constant"&&this.expression.value,ge=X(this.lutExpression,_,{},E,D,z,H,Y);this.paintVertexArray.resize(f),this._setPaintValue(te,f,he,ge?null:this.context.lut)}updatePaintArray(f,_,S,E,D,z,H,Y){const te=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:H,worldview:Y},S,E,void 0,D):this.expression.kind==="constant"&&this.expression.value,he=X(this.lutExpression,S,E,D,void 0,H,void 0,Y);this._setPaintValue(f,_,te,he?null:this.context.lut)}_setPaintValue(f,_,S,E){if(this.type==="color"){const D=Z(S.toPremultipliedRenderColor(E));for(let z=f;z<_;z++)this.paintVertexArray.emplace(z,D[0],D[1])}else{for(let D=f;D<_;D++)this.paintVertexArray.emplace(D,S);this.maxValue=Math.max(this.maxValue,Math.abs(S))}}upload(f){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=f.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.lutExpression&&this.lutExpression.kind!=="constant"&&(this.lutExpression.isStateDependent||!this.lutExpression.isLightConstant)||this.expression.kind!=="constant"&&(this.expression.isStateDependent||!this.expression.isLightConstant)))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy()}}class Me{constructor(f,_,S,E,D,z){this.expression=f,this.uniformNames=_.map(H=>`u_${H}_t`),this.type=S,this.useIntegerZoom=E,this.context=D,this.maxValue=0,this.paintVertexAttributes=_.map(H=>({name:`a_${H}`,type:"Float32",components:S==="color"?4:2,offset:0})),this.paintVertexArray=new z}populatePaintArray(f,_,S,E,D,z,H,Y){const te=this.expression.evaluate(new bi(this.context.zoom,{brightness:z,worldview:Y}),_,{},D,E,H),he=this.expression.evaluate(new bi(this.context.zoom+1,{brightness:z,worldview:Y}),_,{},D,E,H),ge=X(this.lutExpression,_,{},E,D,z,H,Y),ve=this.paintVertexArray.length;this.paintVertexArray.resize(f),this._setPaintValue(ve,f,te,he,ge?null:this.context.lut)}updatePaintArray(f,_,S,E,D,z,H,Y){const te=this.expression.evaluate({zoom:this.context.zoom,brightness:H,worldview:Y},S,E,void 0,D),he=this.expression.evaluate({zoom:this.context.zoom+1,brightness:H,worldview:Y},S,E,void 0,D),ge=X(this.lutExpression,S,E,D,void 0,H,void 0,Y);this._setPaintValue(f,_,te,he,ge?null:this.context.lut)}_setPaintValue(f,_,S,E,D){if(this.type==="color"){const z=Z(S.toPremultipliedRenderColor(D)),H=Z(E.toPremultipliedRenderColor(D));for(let Y=f;Y<_;Y++)this.paintVertexArray.emplace(Y,z[0],z[1],H[0],H[1])}else{for(let z=f;z<_;z++)this.paintVertexArray.emplace(z,S,E);this.maxValue=Math.max(this.maxValue,Math.abs(S),Math.abs(E))}}upload(f){this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer&&this.paintVertexBuffer.buffer?this.paintVertexBuffer.updateData(this.paintVertexArray):this.paintVertexBuffer=f.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,this.expression.isStateDependent||!this.expression.isLightConstant))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy()}setUniform(f,_,S,E,D){const z=this.useIntegerZoom?Math.floor(S.zoom):S.zoom,H=it(this.expression.interpolationFactor(z,this.context.zoom,this.context.zoom+1),0,1);_.set(f,D,H)}getBinding(f,_){return new Eh(f)}}class Ke{constructor(f,_,S,E,D){this.expression=f,this.layerId=D,this.paintVertexAttributes=(S==="array"?$Te:zTe).members;for(let z=0;z<_.length;++z);this.paintVertexArray=new E,this.paintTransitionVertexArray=new pC}populatePaintArray(f,_,S,E){const D=this.paintVertexArray.length;this.paintVertexArray.resize(f),this._setPaintValues(D,f,_.patterns&&_.patterns[this.layerId],S)}updatePaintArray(f,_,S,E,D,z,H){this._setPaintValues(f,_,S.patterns&&S.patterns[this.layerId],z)}_setPaintValues(f,_,S,E){if(!E||!S)return;const D=E[S[0]],z=E[S[1]];if(D){if(D){const{tl:H,br:Y,pixelRatio:te}=D;for(let he=f;he<_;he++)this.paintVertexArray.emplace(he,H[0],H[1],Y[0],Y[1],te)}if(z){this.paintTransitionVertexArray.resize(this.paintVertexArray.length);const{tl:H,br:Y}=z;for(let te=f;te<_;te++)this.paintTransitionVertexArray.emplace(te,H[0],H[1],Y[0],Y[1])}}}upload(f){const _=this.expression.isStateDependent||!this.expression.isLightConstant;this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer=f.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,_)),this.paintTransitionVertexArray&&this.paintTransitionVertexArray.length&&(this.paintTransitionVertexBuffer=f.createVertexBuffer(this.paintTransitionVertexArray,BTe.members,_))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy(),this.paintTransitionVertexBuffer&&this.paintTransitionVertexBuffer.destroy()}}class He{constructor(f,_,S=()=>!0){this.binders={},this._buffers=[],this.context=_;const E=[],D=f;for(const z in f.paint._values){const H=D.paint.get(z);if(z.endsWith("-use-theme")||!S(z)||!(H instanceof c2&&qo(H.property.specification)))continue;const Y=ot(z,f.type),te=H.value,he=H.property.specification.type,ge=!!H.property.useIntegerZoom,ve=z==="line-dasharray"||z.endsWith("pattern"),Te=D.paint.get(`${z}-use-theme`),Ie=z==="line-dasharray"&&D.layout.get("line-cap").value.kind!=="constant"||Te&&Te.value.kind!=="constant";if(te.kind!=="constant"||Ie)if(te.kind==="source"||Ie||ve){const Ve=Rt(z,he,"source");this.binders[z]=ve?new Ke(te,Y,he,Ve,f.id):new ke(te,Y,he,Ve),E.push(`/a_${z}`)}else{const Ve=Rt(z,he,"composite");this.binders[z]=new Me(te,Y,he,ge,_,Ve),E.push(`/z_${z}`)}else this.binders[z]=ve?new pe(te.value,Y):new ae(te.value,Y,he,_),E.push(`/u_${z}`);Te&&(this.binders[z].lutExpression=Te.value)}this.cacheKey=E.sort().join("")}getMaxValue(f){const _=this.binders[f];return _ instanceof ke||_ instanceof Me?_.maxValue:0}populatePaintArrays(f,_,S,E,D,z,H,Y){for(const te in this.binders){const he=this.binders[te];he.context=this.context,(he instanceof ke||he instanceof Me||he instanceof Ke)&&he.populatePaintArray(f,_,S,E,D,z,H,Y)}}setConstantPatternPositions(f,_){for(const S in this.binders){const E=this.binders[S];E instanceof pe&&E.setConstantPatternPositions(f,_)}}getPatternTransitionVertexBuffer(f){const _=this.binders[f];return _ instanceof Ke?_.paintTransitionVertexBuffer:null}updatePaintArrays(f,_,S,E,D,z,H,Y,te,he){let ge=!1;const ve=Object.keys(f),Te=ve.length!==0&&!Y,Ie=Te?ve:_.uniqueIds;this.context.lut=D.lut;for(const Ve in this.binders){const et=this.binders[Ve];if(et.context=this.context,(et instanceof ke||et instanceof Me||et instanceof Ke)&&et.expression&&et.expression.kind&&et.expression.kind!=="constant"&&(et.expression.isStateDependent===!0||et.expression.isLightConstant===!1)){const at=D.paint.get(Ve);et.expression=at.value;for(const ft of Ie){const ut=f[ft.toString()];_.eachPosition(ft,(Nt,Mt,It)=>{const xs=E.feature(Nt);et.updatePaintArray(Mt,It,xs,ut,z,H,te,he)})}if(!Te)for(const ft of S.uniqueIds){const ut=f[ft.toString()];S.eachPosition(ft,(Nt,Mt,It)=>{const xs=E.feature(Nt);et.updatePaintArray(Mt,It,xs,ut,z,H,te,he)})}ge=!0}}return ge}defines(){const f=[];for(const _ in this.binders){const S=this.binders[_];(S instanceof ae||S instanceof pe)&&f.push(...S.uniformNames.map(E=>`#define HAS_UNIFORM_${E}`))}return f}getPaintVertexBuffers(){return this._buffers}getUniforms(f){const _=[];for(const S in this.binders){const E=this.binders[S];if(E instanceof ae||E instanceof pe||E instanceof Me)for(const D of E.uniformNames)_.push({name:D,property:S,binding:E.getBinding(f,D)})}return _}setUniforms(f,_,S,E,D){for(const{name:z,property:H,binding:Y}of S)this.binders[H].setUniform(f,Y,D,E.get(H),z)}updatePaintBuffers(){this._buffers=[];for(const f in this.binders){const _=this.binders[f];(_ instanceof ke||_ instanceof Me||_ instanceof Ke)&&_.paintVertexBuffer&&this._buffers.push(_.paintVertexBuffer),_ instanceof Ke&&_.paintTransitionVertexBuffer&&this._buffers.push(_.paintTransitionVertexBuffer)}}upload(f){for(const _ in this.binders){const S=this.binders[_];(S instanceof ke||S instanceof Me||S instanceof Ke)&&S.upload(f)}this.updatePaintBuffers()}destroy(){for(const f in this.binders){const _=this.binders[f];(_ instanceof ke||_ instanceof Me||_ instanceof Ke)&&_.destroy()}}}class tt{constructor(f,_,S=()=>!0){this.programConfigurations={};for(const E of f)this.programConfigurations[E.id]=new He(E,_,S);this.needsUpload=!1,this._featureMap=new V6,this._featureMapWithoutIds=new V6,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(f,_,S,E,D,z,H,Y,te){for(const he in this.programConfigurations)this.programConfigurations[he].populatePaintArrays(f,_,E,D,z,H,Y,te);_.id!==void 0?this._featureMap.add(_.id,S,this._bufferOffset,f):(this._featureMapWithoutIds.add(this._idlessCounter,S,this._bufferOffset,f),this._idlessCounter+=1),this._bufferOffset=f,this.needsUpload=!0}updatePaintArrays(f,_,S,E,D,z,H,Y){for(const te of S)this.needsUpload=this.programConfigurations[te.id].updatePaintArrays(f,this._featureMap,this._featureMapWithoutIds,_,te,E,D,z,H||0,Y)||this.needsUpload}get(f){return this.programConfigurations[f]}upload(f){if(this.needsUpload){for(const _ in this.programConfigurations)this.programConfigurations[_].upload(f);this.needsUpload=!1}}destroy(){for(const f in this.programConfigurations)this.programConfigurations[f].destroy()}}const 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(N,f){return ct[N]||[N.replace(`${f}-`,"").replace(/-/g,"_")]}const wt={"line-pattern":{source:Tw,composite:Tw},"fill-pattern":{source:Tw,composite:Tw},"fill-extrusion-pattern":{source:Tw,composite:Tw},"line-dasharray":{source:pC,composite:pC}},_t={color:{source:IS,composite:u2},number:{source:dl,composite:IS}};function Rt(N,f,_){const S=wt[N];return S&&S[_]||_t[f][_]}gr(ae,"ConstantBinder"),gr(pe,"PatternConstantBinder"),gr(ke,"SourceExpressionBinder"),gr(Ke,"PatternCompositeBinder"),gr(Me,"CompositeExpressionBinder"),gr(He,"ProgramConfiguration",{omit:["_buffers"]}),gr(tt,"ProgramConfigurationSet");const $t=nr/Math.PI/2,kt=64,ks=[kt,32,16],Jt=-$t,ws=$t;function Vt(N,f,_,S=$t){return _=pr(_),[N*Math.sin(_)*S,-f*S,N*Math.cos(_)*S]}function Xt(N,f,_){return Vt(Math.cos(pr(N)),Math.sin(pr(N)),f,_)}const ms=63710088e-1,Us=2*Math.PI*ms;class Cs{constructor(f,_){if(isNaN(f)||isNaN(_))throw new Error(`Invalid LngLat object: (${f}, ${_})`);if(this.lng=+f,this.lat=+_,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new Cs(St(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(f){const _=Math.PI/180,S=this.lat*_,E=f.lat*_,D=Math.sin(S)*Math.sin(E)+Math.cos(S)*Math.cos(E)*Math.cos((f.lng-this.lng)*_);return ms*Math.acos(Math.min(D,1))}toBounds(f=0){const _=360*f/40075017,S=_/Math.cos(Math.PI/180*this.lat);return new pn({lng:this.lng-S,lat:this.lat-_},{lng:this.lng+S,lat:this.lat+_})}toEcef(f){return Xt(this.lat,this.lng,$t+f*$t/ms)}static convert(f){if(f instanceof Cs)return f;if(Array.isArray(f)&&(f.length===2||f.length===3))return new Cs(Number(f[0]),Number(f[1]));if(!Array.isArray(f)&&typeof f=="object"&&f!==null)return new Cs(Number("lng"in f?f.lng:f.lon),Number(f.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}class pn{constructor(f,_){f&&(_?this.setSouthWest(f).setNorthEast(_):Array.isArray(f)&&f.length===4?this.setSouthWest([f[0],f[1]]).setNorthEast([f[2],f[3]]):this.setSouthWest(f[0]).setNorthEast(f[1]))}setNorthEast(f){return this._ne=f instanceof Cs?new Cs(f.lng,f.lat):Cs.convert(f),this}setSouthWest(f){return this._sw=f instanceof Cs?new Cs(f.lng,f.lat):Cs.convert(f),this}extend(f){const _=this._sw,S=this._ne;let E,D;if(f instanceof Cs)E=f,D=f;else{if(!(f instanceof pn))return Array.isArray(f)?f.length===4||f.every(Array.isArray)?this.extend(pn.convert(f)):this.extend(Cs.convert(f)):typeof f=="object"&&f!==null&&f.hasOwnProperty("lat")&&(f.hasOwnProperty("lon")||f.hasOwnProperty("lng"))?this.extend(Cs.convert(f)):this;if(E=f._sw,D=f._ne,!E||!D)return this}return _||S?(_.lng=Math.min(E.lng,_.lng),_.lat=Math.min(E.lat,_.lat),S.lng=Math.max(D.lng,S.lng),S.lat=Math.max(D.lat,S.lat)):(this._sw=new Cs(E.lng,E.lat),this._ne=new Cs(D.lng,D.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(f){const{lng:_,lat:S}=Cs.convert(f);let E=this._sw.lng<=_&&_<=this._ne.lng;return this._sw.lng>this._ne.lng&&(E=this._sw.lng>=_&&_>=this._ne.lng),this._sw.lat<=S&&S<=this._ne.lat&&E}static convert(f){if(f)return f instanceof pn?f:new pn(f)}}function an(N){return Us*Math.cos(N*Math.PI/180)}function Ln(N){return(180+N)/360}function $n(N){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+N*Math.PI/360)))/360}function Ys(N,f){return N/an(f)}function Es(N){return 360*N-180}function hn(N){return 360/Math.PI*Math.atan(Math.exp((180-360*N)*Math.PI/180))-90}function fn(N,f){return N*an(hn(f))}const jn=85.051129;function yr(N){return Math.cos(pr(it(N,-85.051129,jn)))}function rr(N,f){const _=it(f,0,25.5),S=Math.pow(2,_);return yr(N)*Us/(512*S)}function ar(N){return 1/Math.cos(N*Math.PI/180)}function zn(N,f=0){const _=Math.exp(Math.PI*(1-(N.y+f/nr)/(1<=Y?(va(N,f,_,te,he,D,ge,H,Y),va(N,te,he,S,E,ge,z,H,Y)):N.push(z)}function Br(N,f,_){let S=N[0],E=S.x,D=S.y;f(S);const z=[S];for(let H=1;HN.x+1||SN.y+1)&&Mr("Geometry exceeds allowed extent, reduce your vector tile buffer size"),N}function Ea(N,f,_){const S=N.loadGeometry(),E=N.extent,D=nr/E;if(f&&_&&_.projection.isReprojectedInTileSpace){const z=1<{const Te=Es((f.x+ve.x/E)/z),Ie=hn((f.y+ve.y/E)/z),Ve=he.project(Te,Ie);ve.x=(Ve.x*H-Y)*E,ve.y=(Ve.y*H-te)*E};for(let ve=0;ve=E||Ie.y<0||Ie.y>=E||(ge(Ie),Te.push(Ie));S[ve]=Te}}for(const z of S)for(const H of z)Ii(H,D);return S}function Ri(N,f){return{type:N.type,id:N.id,properties:N.properties,geometry:f?Ea(N):[]}}class ri{constructor(f,_,S,E,D){this.properties={},this.extent=S,this.type=0,this.id=void 0,this._pbf=f,this._geometry=-1,this._keys=E,this._values=D,f.readFields(Mo,this,_)}loadGeometry(){const f=this._pbf;f.pos=this._geometry;const _=f.readVarint()+f.pos,S=[];let E,D=1,z=0,H=0,Y=0;for(;f.pos<_;){if(z<=0){const te=f.readVarint();D=7&te,z=te>>3}if(z--,D===1||D===2)H+=f.readSVarint(),Y+=f.readSVarint(),D===1&&(E&&S.push(E),E=[]),E&&E.push(new Xs(H,Y));else{if(D!==7)throw new Error(`unknown command ${D}`);E&&E.push(E[0].clone())}}return E&&S.push(E),S}bbox(){const f=this._pbf;f.pos=this._geometry;const _=f.readVarint()+f.pos;let S=1,E=0,D=0,z=0,H=1/0,Y=-1/0,te=1/0,he=-1/0;for(;f.pos<_;){if(E<=0){const ge=f.readVarint();S=7&ge,E=ge>>3}if(E--,S===1||S===2)D+=f.readSVarint(),z+=f.readSVarint(),DY&&(Y=D),zhe&&(he=z);else if(S!==7)throw new Error(`unknown command ${S}`)}return[H,te,Y,he]}toGeoJSON(f,_,S){const E=this.extent*Math.pow(2,S),D=this.extent*f,z=this.extent*_,H=this.loadGeometry();function Y(ve){return[360*(ve.x+D)/E-180,360/Math.PI*Math.atan(Math.exp((1-2*(ve.y+z)/E)*Math.PI))-90]}function te(ve){return ve.map(Y)}let he;if(this.type===1){const ve=[];for(const Ie of H)ve.push(Ie[0]);const Te=te(ve);he=ve.length===1?{type:"Point",coordinates:Te[0]}:{type:"MultiPoint",coordinates:Te}}else if(this.type===2){const ve=H.map(te);he=ve.length===1?{type:"LineString",coordinates:ve[0]}:{type:"MultiLineString",coordinates:ve}}else{if(this.type!==3)throw new Error("unknown feature type");{const ve=function(Ie){const Ve=Ie.length;if(Ve<=1)return[Ie];const et=[];let at,ft;for(let ut=0;ut=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[f];const _=this._pbf.readVarint()+this._pbf.pos;return new ri(this._pbf,_,this.extent,this._keys,this._values)}}function Wl(N,f,_){N===15?f.version=_.readVarint():N===1?f.name=_.readString():N===5?f.extent=_.readVarint():N===2?f._features.push(_.pos):N===3?f._keys.push(_.readString()):N===4&&f._values.push(function(S){let E=null;const D=S.readVarint()+S.pos;for(;S.pos>3;E=z===1?S.readString():z===2?S.readFloat():z===3?S.readDouble():z===4?S.readVarint64():z===5?S.readVarint():z===6?S.readSVarint():z===7?S.readBoolean():null}if(E==null)throw new Error("unknown feature value");return E}(_))}class Vo{constructor(f,_){this.layers=f.readFields(Ci,{},_)}}function Ci(N,f,_){if(N===3){const S=new Xc(_,_.readVarint()+_.pos);S.length&&(f[S.name]=S)}}const Ai="3d_elevation_id",Kl="level";class ld{constructor(){this._valid=!1}reset(f){return this.feature=f,this._valid=!0,this._geometry=f.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(f,_){return this._valid&&f(_(this._geometry)),this}require(f,_,S){return this.get(f,!0,_,S)}optional(f,_,S){return this.get(f,!1,_,S)}success(){return this._valid}get(f,_,S,E){const D=this.feature.properties.hasOwnProperty(f)?+this.feature.properties[f]:void 0;return this._valid&&D!==void 0&&!Number.isNaN(D)?S(E?E(D):D):_&&(this._valid=!1),this}}class Ho{constructor(f,_){this.featureFunc=f,this.vertexFunc=_}parseFeature(f,_,S){return this.featureFunc(f,_,S)}parseVertex(f,_,S){return this.vertexFunc(f,_,S)}}const mi=new Ho((N,f,_)=>N.reset(f).require(Ai,S=>{_.id=S}).optional("fixed_height_relative",S=>{_.constantHeight=S},Ml.decodeRelativeHeight).geometry(S=>{_.bounds=S},Gd).success(),(N,f,_)=>N.reset(f).require(Ai,S=>{_.id=S}).require("elevation_idx",S=>{_.idx=S}).require("extent",S=>{_.extent=S}).require("height_relative",S=>{_.height=S},Ml.decodeRelativeHeight).geometry(S=>{_.position=S},Ml.getPoint).success()),zc=new Ho((N,f,_)=>N.reset(f).require(Ai,S=>{_.id=S}).optional("fixed_height",S=>{_.constantHeight=S},Ml.decodeMetricHeight).geometry(S=>{_.bounds=S},Gd).success(),(N,f,_)=>N.reset(f).require(Ai,S=>{_.id=S}).require("elevation_idx",S=>{_.idx=S}).require("extent",S=>{_.extent=S}).require("height",S=>{_.height=S},Ml.decodeMetricHeight).geometry(S=>{_.position=S},Ml.getPoint).success());class Ml{static getPoint(f){return Qs(f[0][0].x,f[0][0].y)}static decodeRelativeHeight(f){return 1e-4*f*5}static decodeMetricHeight(f){return 1e-4*f}static getVersionSchema(f){return f?f==="1.0.1"?zc:void 0:mi}static parse(f){const _=[],S=[],E=f.length,D=new ld;for(let z=0;z=0);if(D===0)return 0;D!==f.length&&(_=!1)}return _?2:1}function Mh(N,f){for(const _ of N.projections){const S=ph(f,N.points[0],_.axis);if(_.projection[1]S[1])return 0}return 1}function pp(N,f){let _=0;const S=[0,0,0,0];for(let E=0;E=0&&_++;return _}class Ny{constructor(f,_){this.points=f||new Array(8).fill([0,0,0]),this.planes=_||new Array(6).fill([0,0,0,0]),this.bounds=al.fromPoints(this.points),this.projections=[],this.frustumEdges=[Ue([],this.points[2],this.points[3]),Ue([],this.points[0],this.points[3]),Ue([],this.points[4],this.points[0]),Ue([],this.points[5],this.points[1]),Ue([],this.points[6],this.points[2]),Ue([],this.points[7],this.points[3])];for(const S of this.frustumEdges){const E=[0,-S[2],S[1]],D=[S[2],0,-S[0]];this.projections.push({axis:E,projection:ph(this.points,this.points[0],E)}),this.projections.push({axis:D,projection:ph(this.points,this.points[0],D)})}}static fromInvProjectionMatrix(f,_,S,E){const D=Math.pow(2,S),z=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map(te=>{const he=dt([],te,f),ge=1/he[3]/_*D;return(ve=he)[0]=(Te=he)[0]*(Ie=[ge,ge,E?1/he[3]:ge,ge])[0],ve[1]=Te[1]*Ie[1],ve[2]=Te[2]*Ie[2],ve[3]=Te[3]*Ie[3],ve;var ve,Te,Ie}),H=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(te=>{const he=Le([],Be([],Ue([],z[te[0]],z[te[1]]),Ue([],z[te[2]],z[te[1]]))),ge=-De(he,z[te[1]]);return he.concat(ge)}),Y=[];for(let te=0;tete[1]||te[0]>Y[1])return 0}return 1}containsPoint(f){for(const _ of this.planes){const S=_[3];if(De([_[0],_[1],_[2]],f)+S<0)return!1}return!0}}class al{static fromPoints(f){const _=[1/0,1/0,1/0],S=[-1/0,-1/0,-1/0];for(const E of f)ie(_,_,E),de(S,S,E);return new al(_,S)}static fromTileIdAndHeight(f,_,S){const E=1<f.max[_]||f.min[_]>this.max[_])return!1;return!0}intersectsAabbXY(f){return!(this.min[0]>f.max[0]||f.min[0]>this.max[0]||this.min[1]>f.max[1]||f.min[1]>this.max[1])}encapsulate(f){for(let _=0;_<3;_++)this.min[_]=Math.min(this.min[_],f.min[_]),this.max[_]=Math.max(this.max[_],f.max[_])}encapsulatePoint(f){for(let _=0;_<3;_++)this.min[_]=Math.min(this.min[_],f[_]),this.max[_]=Math.max(this.max[_],f[_])}closestPoint(f){return[Math.max(Math.min(this.max[0],f[0]),this.min[0]),Math.max(Math.min(this.max[1],f[1]),this.min[1]),Math.max(Math.min(this.max[2],f[2]),this.min[2])]}}gr(al,"Aabb");class wv{constructor(f,_){this.feature=f,this.metersToTile=_,this.index=0}get(){const f=this.feature.vertices[this.index],_=this.feature.vertexProps[this.index].dir,S=_[1],E=-_[0],D=(f.extent+1)*this.metersToTile;return[new Xs(Math.trunc(f.position[0]+S*D),Math.trunc(f.position[1]+E*D)),new Xs(Math.trunc(f.position[0]-S*D),Math.trunc(f.position[1]-E*D))]}next(){this.index++}valid(){return this.index{return H.a0?we(Y,Y,1/te):J(Y,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(f){if(this.edges.length===0)return;let _=0,S=Number.POSITIVE_INFINITY,E=0;const[D,z,H,Y,te,he,ge]=this._tmpVec2;cn(ge,f.x,f.y);const ve=new Ou(ge,null);for(let Te=0;Te0?nn(Y,H)/Nt:0,It=it(Mt,0,1),xs=Math.abs((Mt-It)*this.edgeProps[Te].len);Gs(te,ge,et),cn(he,Ve[1],-Ve[0]);const es=xs+Math.abs(nn(te,he));es=0;--z){const H=this.edges[z].a,Y=this.edges[z].b,{position:te,height:he,extent:ge}=this.vertices[H],{position:ve,height:Te,extent:Ie}=this.vertices[Y],Ve=this.vertexProps[H].dir,et=this.vertexProps[Y].dir;if(J(_,te[0]/f,te[1]/f,he),J(S,ve[0]/f,ve[1]/f,Te),J(E,Ve[1],-Ve[0],0),we(E,E,ge),J(D,et[1],-et[0],0),we(D,D,Ie),this.distSqLines(ee(_[0]+.5*E[0],_[1]+.5*E[1],_[2]+.5*E[2]),ee(S[0]-.5*D[0],S[1]-.5*D[1],S[2]-.5*D[2]),ee(_[0]-.5*E[0],_[1]-.5*E[1],_[2]-.5*E[2]),ee(S[0]+.5*D[0],S[1]+.5*D[1],S[2]+.5*D[2]))<=.0025000000000000005)continue;const at=this.vertices.length,ft=qt(jt(),te,ve);this.vertices.push({position:Ls(ft,ft,.5),height:.5*(he+Te),extent:.5*(ge+Ie)});const ut=qt(jt(),Ve,et);this.vertexProps.push({dir:Hs(ut,ut)}),this.edges.splice(z,1),this.edgeProps.splice(z,1),this.edges.push({a:H,b:at}),this.edges.push({a:at,b:Y});const Nt=Gs(jt(),this.vertices[at].position,te),Mt=sn(Nt),It={vec:Nt,dir:Ls(jt(),Nt,1/Mt),len:Mt};this.edgeProps.push(It),this.edgeProps.push(It)}}distSqLines(f,_,S,E){const D=ue(W(),_,f),z=ue(W(),E,S),H=ue(W(),f,S),Y=De(D,D),te=De(D,z),he=De(D,H),ge=De(z,z),ve=De(z,H),Te=Y*ge-te*te;if(Te===0)return fe(Ne(D,S,E,De(H,z)/De(z,z)),f);const Ie=(Y*ve-te*he)/Te;return fe(Ne(D,f,_,(te*ve-he*ge)/Te),Ne(z,S,E,Ie))}}class tc{static parseFrom(f,_){const S=Ml.parse(f);if(!S)return[];let{vertices:E,features:D}=S;const z=1/zn(_);D.sort((he,ge)=>he.id-ge.id),E.sort((he,ge)=>he.id-ge.id||he.idx-ge.idx),E=E.filter((he,ge,ve)=>ge===ve.findIndex(Te=>Te.id===he.id&&Te.idx===he.idx));const H=new Array;let Y=0;const te=E.length;for(const he of D){if(he.constantHeight){H.push(new jv(he.id,he.bounds,he.constantHeight));continue}for(;Y!==te&&E[Y].idE.id===S)}}class fc{constructor(f,_){this.zScale=1,this.xOffset=0,this.yOffset=0,f.equals(_)||(this.zScale=Math.pow(2,_.z-f.z),this.xOffset=(f.x*this.zScale-_.x)*nr,this.yOffset=(f.y*this.zScale-_.y)*nr)}constantElevation(f,_){if(f.constantHeight!=null)return this.computeBiasedHeight(f.constantHeight,_)}pointElevation(f,_,S){const E=this.constantElevation(_,S);return E??(f.x=f.x*this.zScale+this.xOffset,f.y=f.y*this.zScale+this.yOffset,this.computeBiasedHeight(_.pointElevation(f),S))}computeBiasedHeight(f,_){return _<=0?f:f+_*gt(0,_,f>=0?f:Math.abs(.5*f))}}gr(jv,"ElevationFeature");class _l{constructor(f){this.zoom=f.zoom,this.overscaling=f.overscaling,this.layers=f.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=f.index,this.hasPattern=!1,this.projection=f.projection,this.layoutVertexArray=new Pi,this.indexArray=new eu,this.segments=new Gl,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.lut}),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new dl),this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,_){}updateAppearances(f,_,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,E){const D=this.layers[0],z=[];let H=null;D.type==="circle"&&(H=D.layout.get("circle-sort-key"));for(const{feature:te,id:he,index:ge,sourceLayerIndex:ve}of f){const Te=this.layers[0]._featureFilter.needGeometry,Ie=Ri(te,Te);if(!this.layers[0]._featureFilter.filter(new bi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),Ie,S))continue;const Ve=H?H.evaluate(Ie,{},S):void 0,et={id:he,properties:te.properties,type:te.type,sourceLayerIndex:ve,index:ge,geometry:Te?Ie.geometry:Ea(te,S,E),patterns:{},sortKey:Ve};z.push(et)}H&&z.sort((te,he)=>te.sortKey-he.sortKey);let Y=null;E.projection.name==="globe"&&(this.globeExtVertexArray=new WO,Y=E.projection);for(const te of z){const{geometry:he,index:ge,sourceLayerIndex:ve}=te,Te=f[ge].feature;this.addFeature(te,he,ge,_.availableImages,S,Y,_.brightness,_.elevationFeatures),_.featureIndex.insert(Te,he,ge,ve,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(f,_,S,E,D,z,H){this.programConfigurations.updatePaintArrays(f,_,D,S,E,z,H,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,Mee.members),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=f.createVertexBuffer(this.globeExtVertexArray,FTe.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=f.createVertexBuffer(this.elevatedLayoutVertexArray,OTe.members))),this.programConfigurations.upload(f),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy())}addFeature(f,_,S,E,D,z,H,Y){let te;this.elevationMode!=="none"&&(te=tc.getElevationFeature(f,Y));for(const he of _)for(const ge of he){const ve=ge.x,Te=ge.y;if(ve<0||ve>=nr||Te<0||Te>=nr)continue;if(z){const et=z.projectTilePoint(ve,Te,D),at=z.upVector(D,ve,Te);this.addGlobeExtVertex(et,at),this.addGlobeExtVertex(et,at),this.addGlobeExtVertex(et,at),this.addGlobeExtVertex(et,at)}const Ie=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,f.sortKey),Ve=Ie.vertexLength;if(this.addCircleVertex(ve,Te,-1,-1),this.addCircleVertex(ve,Te,1,-1),this.addCircleVertex(ve,Te,1,1),this.addCircleVertex(ve,Te,-1,1),this.elevationMode!=="none"){const et=te?te.pointElevation(new Xs(ve,Te)):0;this.hasElevation=this.hasElevation||et!==0;for(let at=0;at<4;at++)this.elevatedLayoutVertexArray.emplaceBack(et)}this.indexArray.emplaceBack(Ve,Ve+1,Ve+2),this.indexArray.emplaceBack(Ve,Ve+2,Ve+3),Ie.vertexLength+=4,Ie.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,f,S,{},E,D,H,void 0,this.worldview)}addCircleVertex(f,_,S,E){this.layoutVertexArray.emplaceBack(2*f+(S+1)/2,2*_+(E+1)/2)}addGlobeExtVertex(f,_){this.globeExtVertexArray.emplaceBack(f.x,f.y,f.z,_[0]*16384,_[1]*16384,_[2]*16384)}}function _u(N,f){for(let _=0;_1){if(ok(N,f))return!0;for(let S=0;S1?_:_.sub(f)._mult(E)._add(f))}function xC(N,f){let _,S,E,D=!1;for(let z=0;zf.y!=E.y>f.y&&f.x<(E.x-S.x)*(f.y-S.y)/(E.y-S.y)+S.x&&(D=!D)}return D}function L0(N,f){let _=!1;for(let S=0,E=N.length-1;Sf.y!=z.y>f.y&&f.x<(z.x-D.x)*(f.y-D.y)/(z.y-D.y)+D.x&&(_=!_)}return _}function lk(N,f,_,S,E){for(const z of N)if(f<=z.x&&_<=z.y&&S>=z.x&&E>=z.y)return!0;const D=[new Xs(f,_),new Xs(f,E),new Xs(S,E),new Xs(S,_)];if(N.length>2){for(const z of D)if(L0(N,z))return!0}for(let z=0;zE.x&&f.x>E.x||N.yE.y&&f.y>E.y)return!1;const D=Xr(N,f,_[0]);return D!==Xr(N,f,_[1])||D!==Xr(N,f,_[2])||D!==Xr(N,f,_[3])}function dk(N,f,_,S,E,D){let z=f.y-N.y,H=N.x-f.x;if(D=D||0){const Y=z*z+H*H;if(Y===0)return!0;const te=Math.sqrt(Y);z/=te,H/=te}return!((_.x-N.x)*z+(_.y-N.y)*H-D<0||(S.x-N.x)*z+(S.y-N.y)*H-D<0||(E.x-N.x)*z+(E.y-N.y)*H-D<0)}function sF(N,f,_,S,E,D,z){return!(dk(N,f,S,E,D,z)||dk(f,_,S,E,D,z)||dk(_,N,S,E,D,z)||dk(S,E,N,f,_,z)||dk(E,D,N,f,_,z)||dk(D,S,N,f,_,z))}function gC(N,f,_){const S=f.paint.get(N).value;return S.kind==="constant"?S.value:_.programConfigurations.get(f.id).getMaxValue(N)}function Lee(N){return Math.sqrt(N[0]*N[0]+N[1]*N[1])}function dZe(N,f,_,S,E){if(!f[0]&&!f[1])return N;const D=Xs.convert(f)._mult(E);_==="viewport"&&D._rotate(-S);const z=[];for(let H=0;H>_&&f.y===this.y>>_}url(f,_){const S=function(D,z,H){const Y=2**H,te=2*Math.PI*6378137,he=te*(D/Y-.5),ge=te*(.5-(z+1)/Y);return`${he},${ge},${he+te/Y},${ge+te/Y}`}(this.x,this.y,this.z),E=function(D,z,H){let Y,te="";for(let he=D;he>0;he--)Y=1<this.canonical.z?new Eg(f,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new Eg(f,this.wrap,f,this.canonical.x>>_,this.canonical.y>>_)}calculateScaledKey(f,_=!0){if(this.overscaledZ===f&&_)return this.key;if(f>this.canonical.z)return nF(this.wrap*+_,f,this.canonical.z,this.canonical.x,this.canonical.y);{const S=this.canonical.z-f;return nF(this.wrap*+_,f,f,this.canonical.x>>S,this.canonical.y>>S)}}isChildOf(f){if(f.wrap!==this.wrap)return!1;const _=this.canonical.z-f.canonical.z;return f.overscaledZ===0||f.overscaledZ>_&&f.canonical.y===this.canonical.y>>_}children(f){if(this.overscaledZ>=f)return[new Eg(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const _=this.canonical.z+1,S=2*this.canonical.x,E=2*this.canonical.y;return[new Eg(_,this.wrap,_,S,E),new Eg(_,this.wrap,_,S+1,E),new Eg(_,this.wrap,_,S,E+1),new Eg(_,this.wrap,_,S+1,E+1)]}isLessThan(f){return this.wrapf.wrap)&&(this.overscaledZf.overscaledZ)&&(this.canonical.xf.canonical.x)&&this.canonical.y{let f=N.canonical.x-1,_=N.wrap;return f<0&&(f=(1<{let f=N.canonical.x+1,_=N.wrap;return f===1<new Eg(N.overscaledZ,N.wrap,N.canonical.z,N.canonical.x,(N.canonical.y===0?1<new Eg(N.overscaledZ,N.wrap,N.canonical.z,N.canonical.x,N.canonical.y===(1<1?null:function(S,E,D,z){const H=Math.sin(D);return S*(Math.sin((1-z)*D)/H)+E*(Math.sin(z*D)/H)}(N.a[f],N.b[f],N.angle,it(_,0,1))+N.center[f]}function uk(N){if(N.z<=1)return aVt[N.z+2*N.y+N.x];const f=HTe(Ree(N));return al.fromPoints(f)}function FS(N,f,_){return we(N,N,1-_),je(N,N,f,_)}function gZe(N,f){const _=zS(f.zoom);if(_===0)return uk(N);const S=Ree(N),E=HTe(S),D=Ln(S.getWest())*f.worldSize,z=Ln(S.getEast())*f.worldSize,H=$n(S.getNorth())*f.worldSize,Y=$n(S.getSouth())*f.worldSize,te=[D,H,0],he=[z,H,0],ge=[D,Y,0],ve=[z,Y,0],Te=b([],f.globeMatrix);return Ge(te,te,Te),Ge(he,he,Te),Ge(ge,ge,Te),Ge(ve,ve,Te),E[0]=FS(E[0],ge,_),E[1]=FS(E[1],ve,_),E[2]=FS(E[2],he,_),E[3]=FS(E[3],te,_),al.fromPoints(E)}function yZe(N,f,_){for(const S of N)Ge(S,S,f),we(S,S,_)}function vZe(N,f,_,S){const E=f/N.worldSize,D=N.globeMatrix;if(_.z<=1){const ps=uk(_).getCorners();return yZe(ps,D,E),al.fromPoints(ps)}const z=Ree(_,S),H=HTe(z,$t+Iee(N._tileCoverLift));yZe(H,D,E);const Y=Number.MAX_VALUE,te=[-Y,-Y,-Y],he=[Y,Y,Y];if(z.contains(N.center)){for(const ds of H)ie(he,he,ds),de(te,te,ds);te[2]=0;const ps=N.point,cs=[ps.x*E,ps.y*E,0];return ie(he,he,cs),de(te,te,cs),new al(he,te)}if(N._tileCoverLift>0){for(const ps of H)ie(he,he,ps),de(te,te,ps);return new al(he,te)}const ge=[D[12]*E,D[13]*E,D[14]*E],ve=z.getCenter(),Te=it(N.center.lat,-85.051129,jn),Ie=it(ve.lat,-85.051129,jn),Ve=Ln(N.center.lng),et=$n(Te);let at=Ve-Ln(ve.lng);const ft=et-$n(Ie);at>.5?at-=1:at<-.5&&(at+=1);let ut=0;Math.abs(at)>Math.abs(ft)?ut=at>=0?1:3:(ut=ft>=0?0:2,je(ge,ge,[D[4]*E,D[5]*E,D[6]*E],-Math.sin(pr(ft>=0?z.getSouth():z.getNorth()))*$t));const Nt=H[ut],Mt=H[(ut+1)%4],It=new iVt(Nt,Mt,ge),xs=[VTe(It,0)||Nt[0],VTe(It,1)||Nt[1],VTe(It,2)||Nt[2]],es=zS(N.zoom);if(es>0){const ps=function({x:ds,y:mn,z:xn},kn,En,Sn,Gn){const dn=1/(1<.5?Ur=-1:wr<-.5&&(Ur=1),An=((An+Ur)*kn-(Sn*=kn))*En+Sn,Pn=((Pn+Ur)*kn-Sn)*En+Sn,Wn=(Wn*kn-(Gn*=kn))*En+Gn,ir=(ir*kn-Gn)*En+Gn,[[An,ir,0],[Pn,ir,0],[Pn,Wn,0],[An,Wn,0]]}(_,f,N._pixelsPerMercatorPixel,Ve,et);for(let ds=0;dsMath.PI/2*1.01}const NZe=pr(85),oVt=Math.cos(NZe),lVt=Math.sin(NZe),cVt=x(),kZe=N=>{const f=[];return N.paint.get("circle-pitch-alignment")==="map"&&f.push("PITCH_WITH_MAP"),N.paint.get("circle-pitch-scale")==="map"&&f.push("SCALE_WITH_MAP"),f};function SZe(N,f,_,S,E,D,z,H,Y){if(D&&N.queryGeometry.isAboveHorizon)return!1;D&&(Y*=N.pixelToTileUnitsFactor);const te=N.tileID.canonical,he=_.projection.upVectorScale(te,_.center.lat,_.worldSize).metersToTile;for(const ge of f)for(const ve of ge){const Te=ve.add(H),Ie=E&&_.elevation?_.elevation.exaggeration()*E.getElevationAt(Te.x,Te.y,!0):0,Ve=_.projection.projectTilePoint(Te.x,Te.y,te);if(Ie>0){const ut=_.projection.upVector(te,Te.x,Te.y);Ve.x+=ut[0]*he*Ie,Ve.y+=ut[1]*he*Ie,Ve.z+=ut[2]*he*Ie}const et=D?Te:dVt(Ve.x,Ve.y,Ve.z,S),at=D?N.tilespaceRays.map(ut=>hVt(ut,Ie)):N.queryGeometry.screenGeometry,ft=dt([],[Ve.x,Ve.y,Ve.z,1],S);if(!z&&D?Y*=ft[3]/_.cameraToCenterDistance:z&&!D&&(Y*=_.cameraToCenterDistance/ft[3]),D){const ut=hn((ve.y/nr+te.y)/(1<N.width||E.height>N.height||_.x>N.width-E.width||_.y>N.height-E.height)throw new RangeError("out of range source coordinates for image copy");if(E.width>f.width||E.height>f.height||S.x>f.width-E.width||S.y>f.height-E.height)throw new RangeError("out of range destination coordinates for image copy");const Y=N.data,te=f.data,he=D===4&&H;for(let ge=0;ge{f[N.evaluationKey]=Y;const te=N.expression.evaluate(f),he=te?te.toNonPremultipliedRenderColor(null):null;he&&(E.data[z+H+0]=Math.floor(255*he.r),E.data[z+H+1]=Math.floor(255*he.g),E.data[z+H+2]=Math.floor(255*he.b),E.data[z+H+3]=Math.floor(255*he.a))};if(N.clips)for(let z=0,H=0;z80*_){H=N[0],Y=N[1];let he=H,ge=Y;for(let ve=_;vehe&&(he=Te),Ie>ge&&(ge=Ie)}te=Math.max(he-H,ge-Y),te=te!==0?32767/te:0}return xV(D,z,_,H,Y,te,0),z}function DZe(N,f,_,S,E){let D;if(E===function(z,H,Y,te){let he=0;for(let ge=H,ve=Y-te;ge0)for(let z=f;z<_;z+=S)D=BZe(z/S|0,N[z],N[z+1],D);else for(let z=_-S;z>=f;z-=S)D=BZe(z/S|0,N[z],N[z+1],D);return D&&aF(D,D.next)&&(vV(D),D=D.next),D}function Y6(N,f){if(!N)return N;f||(f=N);let _,S=N;do if(_=!1,S.steiner||!aF(S,S.next)&&fp(S.prev,S,S.next)!==0)S=S.next;else{if(vV(S),S=f=S.prev,S===S.next)break;_=!0}while(_||S!==f);return f}function xV(N,f,_,S,E,D,z){if(!N)return;!z&&D&&function(Y,te,he,ge){let ve=Y;do ve.z===0&&(ve.z=ZTe(ve.x,ve.y,te,he,ge)),ve.prevZ=ve.prev,ve.nextZ=ve.next,ve=ve.next;while(ve!==Y);ve.prevZ.nextZ=null,ve.prevZ=null,function(Te){let Ie,Ve=1;do{let et,at=Te;Te=null;let ft=null;for(Ie=0;at;){Ie++;let ut=at,Nt=0;for(let It=0;It0||Mt>0&&ut;)Nt!==0&&(Mt===0||!ut||at.z<=ut.z)?(et=at,at=at.nextZ,Nt--):(et=ut,ut=ut.nextZ,Mt--),ft?ft.nextZ=et:Te=et,et.prevZ=ft,ft=et;at=ut}ft.nextZ=null,Ve*=2}while(Ie>1)}(ve)}(N,S,E,D);let H=N;for(;N.prev!==N.next;){const Y=N.prev,te=N.next;if(D?yVt(N,S,E,D):gVt(N))f.push(Y.i,N.i,te.i),vV(N),N=te.next,H=te.next;else if((N=te)===H){z?z===1?xV(N=vVt(Y6(N),f),f,_,S,E,D,2):z===2&&bVt(N,f,_,S,E,D):xV(Y6(N),f,_,S,E,D,1);break}}}function gVt(N){const f=N.prev,_=N,S=N.next;if(fp(f,_,S)>=0)return!1;const E=f.x,D=_.x,z=S.x,H=f.y,Y=_.y,te=S.y,he=Math.min(E,D,z),ge=Math.min(H,Y,te),ve=Math.max(E,D,z),Te=Math.max(H,Y,te);let Ie=S.next;for(;Ie!==f;){if(Ie.x>=he&&Ie.x<=ve&&Ie.y>=ge&&Ie.y<=Te&&gV(E,H,D,Y,z,te,Ie.x,Ie.y)&&fp(Ie.prev,Ie,Ie.next)>=0)return!1;Ie=Ie.next}return!0}function yVt(N,f,_,S){const E=N.prev,D=N,z=N.next;if(fp(E,D,z)>=0)return!1;const H=E.x,Y=D.x,te=z.x,he=E.y,ge=D.y,ve=z.y,Te=Math.min(H,Y,te),Ie=Math.min(he,ge,ve),Ve=Math.max(H,Y,te),et=Math.max(he,ge,ve),at=ZTe(Te,Ie,f,_,S),ft=ZTe(Ve,et,f,_,S);let ut=N.prevZ,Nt=N.nextZ;for(;ut&&ut.z>=at&&Nt&&Nt.z<=ft;){if(ut.x>=Te&&ut.x<=Ve&&ut.y>=Ie&&ut.y<=et&&ut!==E&&ut!==z&&gV(H,he,Y,ge,te,ve,ut.x,ut.y)&&fp(ut.prev,ut,ut.next)>=0||(ut=ut.prevZ,Nt.x>=Te&&Nt.x<=Ve&&Nt.y>=Ie&&Nt.y<=et&&Nt!==E&&Nt!==z&&gV(H,he,Y,ge,te,ve,Nt.x,Nt.y)&&fp(Nt.prev,Nt,Nt.next)>=0))return!1;Nt=Nt.nextZ}for(;ut&&ut.z>=at;){if(ut.x>=Te&&ut.x<=Ve&&ut.y>=Ie&&ut.y<=et&&ut!==E&&ut!==z&&gV(H,he,Y,ge,te,ve,ut.x,ut.y)&&fp(ut.prev,ut,ut.next)>=0)return!1;ut=ut.prevZ}for(;Nt&&Nt.z<=ft;){if(Nt.x>=Te&&Nt.x<=Ve&&Nt.y>=Ie&&Nt.y<=et&&Nt!==E&&Nt!==z&&gV(H,he,Y,ge,te,ve,Nt.x,Nt.y)&&fp(Nt.prev,Nt,Nt.next)>=0)return!1;Nt=Nt.nextZ}return!0}function vVt(N,f){let _=N;do{const S=_.prev,E=_.next.next;!aF(S,E)&&FZe(S,_,_.next,E)&&yV(S,E)&&yV(E,S)&&(f.push(S.i,_.i,E.i),vV(_),vV(_.next),_=N=E),_=_.next}while(_!==N);return Y6(_)}function bVt(N,f,_,S,E,D){let z=N;do{let H=z.next.next;for(;H!==z.prev;){if(z.i!==H.i&&kVt(z,H)){let Y=zZe(z,H);return z=Y6(z,z.next),Y=Y6(Y,Y.next),xV(z,f,_,S,E,D,0),void xV(Y,f,_,S,E,D,0)}H=H.next}z=z.next}while(z!==N)}function _Vt(N,f){let _=N.x-f.x;return _===0&&(_=N.y-f.y,_===0)&&(_=(N.next.y-N.y)/(N.next.x-N.x)-(f.next.y-f.y)/(f.next.x-f.x)),_}function wVt(N,f){const _=function(E,D){let z=D;const H=E.x,Y=E.y;let te,he=-1/0;if(aF(E,z))return z;do{if(aF(E,z.next))return z.next;if(Y<=z.y&&Y>=z.next.y&&z.next.y!==z.y){const Ve=z.x+(Y-z.y)*(z.next.x-z.x)/(z.next.y-z.y);if(Ve<=H&&Ve>he&&(he=Ve,te=z.x=z.x&&z.x>=ve&&H!==z.x&&OZe(Yte.x||z.x===te.x&&jVt(te,z)))&&(te=z,Ie=Ve)}z=z.next}while(z!==ge);return te}(N,f);if(!_)return f;const S=zZe(_,N);return Y6(S,S.next),Y6(_,_.next)}function jVt(N,f){return fp(N.prev,N,f.prev)<0&&fp(f.next,N,N.next)<0}function ZTe(N,f,_,S,E){return(N=1431655765&((N=858993459&((N=252645135&((N=16711935&((N=(N-_)*E|0)|N<<8))|N<<4))|N<<2))|N<<1))|(f=1431655765&((f=858993459&((f=252645135&((f=16711935&((f=(f-S)*E|0)|f<<8))|f<<4))|f<<2))|f<<1))<<1}function NVt(N){let f=N,_=N;do(f.x<_.x||f.x===_.x&&f.y<_.y)&&(_=f),f=f.next;while(f!==N);return _}function OZe(N,f,_,S,E,D,z,H){return(E-z)*(f-H)>=(N-z)*(D-H)&&(N-z)*(S-H)>=(_-z)*(f-H)&&(_-z)*(D-H)>=(E-z)*(S-H)}function gV(N,f,_,S,E,D,z,H){return!(N===z&&f===H)&&OZe(N,f,_,S,E,D,z,H)}function kVt(N,f){return N.next.i!==f.i&&N.prev.i!==f.i&&!function(_,S){let E=_;do{if(E.i!==_.i&&E.next.i!==_.i&&E.i!==S.i&&E.next.i!==S.i&&FZe(E,E.next,_,S))return!0;E=E.next}while(E!==_);return!1}(N,f)&&(yV(N,f)&&yV(f,N)&&function(_,S){let E=_,D=!1;const z=(_.x+S.x)/2,H=(_.y+S.y)/2;do E.y>H!=E.next.y>H&&E.next.y!==E.y&&z<(E.next.x-E.x)*(H-E.y)/(E.next.y-E.y)+E.x&&(D=!D),E=E.next;while(E!==_);return D}(N,f)&&(fp(N.prev,N,f.prev)||fp(N,f.prev,f))||aF(N,f)&&fp(N.prev,N,N.next)>0&&fp(f.prev,f,f.next)>0)}function fp(N,f,_){return(f.y-N.y)*(_.x-f.x)-(f.x-N.x)*(_.y-f.y)}function aF(N,f){return N.x===f.x&&N.y===f.y}function FZe(N,f,_,S){const E=Fee(fp(N,f,_)),D=Fee(fp(N,f,S)),z=Fee(fp(_,S,N)),H=Fee(fp(_,S,f));return E!==D&&z!==H||!(E!==0||!Oee(N,_,f))||!(D!==0||!Oee(N,S,f))||!(z!==0||!Oee(_,N,S))||!(H!==0||!Oee(_,f,S))}function Oee(N,f,_){return f.x<=Math.max(N.x,_.x)&&f.x>=Math.min(N.x,_.x)&&f.y<=Math.max(N.y,_.y)&&f.y>=Math.min(N.y,_.y)}function Fee(N){return N>0?1:N<0?-1:0}function yV(N,f){return fp(N.prev,N,N.next)<0?fp(N,f,N.next)>=0&&fp(N,N.prev,f)>=0:fp(N,f,N.prev)<0||fp(N,N.next,f)<0}function zZe(N,f){const _=XTe(N.i,N.x,N.y),S=XTe(f.i,f.x,f.y),E=N.next,D=f.prev;return N.next=f,f.prev=N,_.next=E,E.prev=_,S.next=_,_.prev=S,D.next=S,S.prev=D,S}function BZe(N,f,_,S){const E=XTe(N,f,_);return S?(E.next=S.next,E.prev=S,S.next.prev=E,S.next=E):(E.prev=E,E.next=E),E}function vV(N){N.next.prev=N.prev,N.prev.next=N.next,N.prevZ&&(N.prevZ.nextZ=N.nextZ),N.nextZ&&(N.nextZ.prevZ=N.prevZ)}function XTe(N,f,_){return{i:N,x:f,y:_,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function bV(N,f){const _=N.length;if(_<=1)return[N];const S=[];let E,D;for(let z=0;z<_;z++){const H=Qt(N[z]);H!==0&&(N[z].area=Math.abs(H),D===void 0&&(D=H<0),D===H<0?(E&&S.push(E),E=[N[z]]):E.push(N[z]))}if(E&&S.push(E),f>1)for(let z=0;z=nr&&_>=nr}static evaluate(f){if(f.length===0)return new BS;let _=[];for(const Y of f)_.push(...Y.portals);if(_.length===0)return new BS;for(const Y of _){const te=Y.va,he=Y.vb;(BS.isOnBorder(te.x,he.x)||BS.isOnBorder(te.y,he.y))&&(Y.type="border")}const S=_.filter(Y=>Y.type!=="unevaluated"),E=_.filter(Y=>Y.type==="unevaluated");if(E.length===0)return new BS;E.sort((Y,te)=>Y.hash===te.hash?Y.isTunnel===te.isTunnel?0:Y.isTunnel?-1:1:Y.hashY.hashD!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new tt(_,{zoom:S,lut:E},D=>D!=="fill-bridge-guard-rail-color")}addVertices(f,_){const S=this.unevalVertices.length;for(let E=0;E=D.min.x&&ge.x<=D.max.x&&ge.y>=D.min.y&&ge.y<=D.max.y||ve.x>=D.min.x&&ve.x<=D.max.x&&ve.y>=D.min.y&&ve.y<=D.max.y||ck(ge,ve,H))||this.isOnBorder(ge.x,ve.x)||this.isOnBorder(ge.y,ve.y))continue;const Te=Nv.computeEdgeHash(this.unevalVertices[te],this.unevalVertices[he]);let Ie,Ve=this.vertexHashLookup.get(Nv.computePosHash(ge));Ve!=null?Ie=Ve.next:(Ve=this.vertexHashLookup.get(Nv.computePosHash(ve)),Ie=Ve!=null?Ve.prev:Te),this.unevalEdges.push({polygonIdx:f,a:te,b:he,hash:Te,portalHash:Ie,isTunnel:E,type:"unevaluated",featureInfo:z})}}addPortalCandidates(f,_,S,E,D){if(_.length!==0){this.vertexHashLookup.clear();for(const z of _){if(z.length===0)continue;const H=z[0];let Y=Nv.computeEdgeHash(H[H.length-2],H[H.length-1]);for(let te=0;te({vertexOffset:0,primitiveOffset:this.indexArray.length}),S=ve=>{ve.primitiveLength=this.indexArray.length-ve.primitiveOffset},E=new CVt(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(f.portals,this.unevalEdges);const D=_(),z=_(),H=_(),Y=(ve,Te)=>{ve.sort((Ve,et)=>Ve.type===Te&&et.type!==Te?-1:Ve.type!==Te&&et.type===Te?1:0);const Ie=ve.findIndex(Ve=>Ve.type!==Te);return Ie>=0?Ie:ve.length};let te=0;this.unevalEdges.length>0&&(te=Y(this.unevalEdges,"none"),this.constructBridgeStructures(E,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:te},this.tileToMeters)),S(H);const he=_(),ge=_();if(this.unevalEdges.length>0){const ve=this.unevalEdges.splice(te),Te=Y(ve,"tunnel")+te;this.unevalEdges.push(...ve),this.constructTunnelStructures(E,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:te},{min:te,max:Te})}S(he),E.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),S(ge),E.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),S(z),E.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),S(D),this.maskSegments=Gl.simpleSegment(0,ge.primitiveOffset,0,ge.primitiveLength),this.depthSegments=Gl.simpleSegment(0,z.primitiveOffset,0,z.primitiveLength),this.renderableBridgeSegments=Gl.simpleSegment(0,H.primitiveOffset,0,H.primitiveLength),this.renderableTunnelSegments=Gl.simpleSegment(0,he.primitiveOffset,0,he.primitiveLength),this.shadowCasterSegments=Gl.simpleSegment(0,D.primitiveOffset,0,D.primitiveLength)}update(f,_,S,E,D,z,H,Y){this.bridgeProgramConfigurations.updatePaintArrays(f,_,D,S,E,z,H,Y),this.tunnelProgramConfigurations.updatePaintArrays(f,_,D,S,E,z,H,Y)}upload(f){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=f.createVertexBuffer(this.vertexPositions,fVt.members),this.vertexBufferNormal=f.createVertexBuffer(this.vertexNormals,xVt.members),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(f),this.tunnelProgramConfigurations.upload(f))}destroy(){this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBufferNormal.destroy(),this.indexBuffer.destroy()),this.maskSegments&&(this.maskSegments.destroy(),this.depthSegments.destroy(),this.renderableBridgeSegments.destroy(),this.renderableTunnelSegments.destroy(),this.shadowCasterSegments.destroy()),this.bridgeProgramConfigurations.destroy(),this.tunnelProgramConfigurations.destroy()}populatePaintArrays(f,_,S,E,D){const z=(H,Y)=>{for(let te=0;teJ(En,_[Sn].x,_[Sn].y,S[Sn]*Y),ge=W(),ve=W(),Te=W(),Ie=W(),Ve=W(),et=(En,Sn)=>{const Gn=H.get(Nv.computePosHash(_[Sn])),dn=Gn.from,An=Gn.to;if(!dn||!An)return;he(ge,dn),he(ve,Sn),he(Te,An),Ae(Ie),Xe(ge,ve)||(Ue(Ve,ve,ge),Le(Ie,Ve)),Xe(Te,ve)||(Ue(Ve,Te,ve),le(Ie,Ie,Le(Ve,Ve)));const Pn=Qe(Ie);return Pn>0?we(En,Ie,1/Pn):void 0};let at=Number.POSITIVE_INFINITY;this.sortSubarray(E,D.min,D.max,(En,Sn)=>En.featureInfo.featureIndex-Sn.featureInfo.featureIndex);const ft=W(),ut=W(),Nt=W(),Mt=W(),It=W(),xs=W(),es=W(),ps=W(),cs=W(),ds=[W(),W(),W(),W()],mn=[W(),W(),W(),W()],xn=[{coord:new Xs(0,0),height:0},{coord:new Xs(0,0),height:0}],kn=(En,Sn)=>En>Sn;for(let En=D.min;Enat.featureInfo.featureIndex-ft.featureInfo.featureIndex;this.sortSubarray(E,D.min,D.max,Y),this.sortSubarray(E,z.min,z.max,Y);const te=at=>Le(at,at),he=[{coord:new Xs(0,0),height:0},{coord:new Xs(0,0),height:0}],ge=(at,ft)=>atH.hash===Y.hash?Y.polygonIdx-H.polygonIdx:Y.hash>H.hash?1:-1);let S=0,E=0,D=0,z=_[S].polygonIdx;do E++,(E===_.length||_[S].hash!==_[E].hash)&&((E-S===1||_[E-1].polygonIdx!==z)&&(Dte.portalHashhe.hash?H++:he.hash>te.portalHash?Y++:(te.type=he.type,H++)}}}isOnBorder(f,_){return f<=0&&_<=0||f>=nr&&_>=nr}addFeatureSection(f,_,S,E){return f!==_&&(_=f,S.push({featureIndex:f,vertexStart:E.getVertexCount()}),E.clearVertexLookup()),_}sortSubarray(f,_,S,E){const D=f.slice(_,S);D.sort(E),f.splice(_,D.length,...D)}static computeEdgeHash(f,_){return(f.y===_.y&&f.x>_.x||f.y>_.y)&&([f,_]=[_,f]),BigInt(Nv.computePosHash(f))<<32n|BigInt(Nv.computePosHash(_))}static computePosHash(f){return((65535&f.x)<<16|65535&f.y)>>>0}}function AVt(N,f){return N>f?1:N0))return _;_=_.left}}return null}contains(f){for(var _=this._root,S=this._compare;_;){var E=S(f,_.key);if(E===0)return!0;_=E<0?_.left:_.right}return!1}remove(f){var _=this.find(f);if(!_)return!1;if(this.splay(_),_.left)if(_.right){var S=this.minNode(_.right);S.parent!==_&&(this.replace(S,S.right),S.right=_.right,S.right.parent=S),this.replace(_,S),S.left=_.left,S.left.parent=S}else this.replace(_,_.left);else this.replace(_,_.right);return this._size--,!0}removeNode(f){if(!f)return!1;if(this.splay(f),f.left)if(f.right){var _=this.minNode(f.right);_.parent!==f&&(this.replace(_,_.right),_.right=f.right,_.right.parent=_),this.replace(f,_),_.left=f.left,_.left.parent=_}else this.replace(f,f.left);else this.replace(f,f.right);return this._size--,!0}erase(f){var _=this.find(f);if(_){this.splay(_);var S=_.left,E=_.right,D=null;S&&(S.parent=null,D=this.maxNode(S),this.splay(D),this._root=D),E&&(S?D.right=E:this._root=E,E.parent=D),this._size--}}pop(){var f=this._root,_=null;if(f){for(;f.left;)f=f.left;_={key:f.key,data:f.data},this.remove(f.key)}return _}next(f){var _=f;if(_)if(_.right)for(_=_.right;_&&_.left;)_=_.left;else for(_=f.parent;_&&_.right===f;)f=_,_=_.parent;return _}prev(f){var _=f;if(_)if(_.left)for(_=_.left;_&&_.right;)_=_.right;else for(_=f.parent;_&&_.left===f;)f=_,_=_.parent;return _}forEach(f){for(var _=this._root,S=[],E=!1,D=0;!E;)_?(S.push(_),_=_.left):S.length>0?(f(_=S.pop(),D++),_=_.right):E=!0;return this}range(f,_,S,E){const D=[],z=this._compare;let H,Y=this._root;for(;D.length!==0||Y;)if(Y)D.push(Y),Y=Y.left;else{if(Y=D.pop(),H=z(Y.key,_),H>0)break;if(z(Y.key,f)>=0&&S.call(E,Y))return this;Y=Y.right}return this}keys(){for(var f=this._root,_=[],S=[],E=!1;!E;)f?(_.push(f),f=f.left):_.length>0?(f=_.pop(),S.push(f.key),f=f.right):E=!0;return S}values(){for(var f=this._root,_=[],S=[],E=!1;!E;)f?(_.push(f),f=f.left):_.length>0?(f=_.pop(),S.push(f.data),f=f.right):E=!0;return S}at(f){for(var _=this._root,S=[],E=!1,D=0;!E;)if(_)S.push(_),_=_.left;else if(S.length>0){if(_=S.pop(),D===f)return _;D++,_=_.right}else E=!0;return null}load(f=[],_=[],S=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const E=f.length;return S&&sEe(f,_,0,E-1,this._compare),this._root=tEe(null,f,_,0,E),this._size=E,this}min(){var f=this.minNode(this._root);return f?f.key:null}max(){var f=this.maxNode(this._root);return f?f.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(f,_,S,E,D){return new eEe(S,D).load(f,_,E)}}function tEe(N,f,_,S,E){const D=E-S;if(D>0){const z=S+Math.floor(D/2),H={key:f[z],data:_[z],parent:N};return H.left=tEe(H,f,_,S,z),H.right=tEe(H,f,_,z+1,E),H}return null}function sEe(N,f,_,S,E){if(_>=S)return;const D=N[_+S>>1];let z=_-1,H=S+1;for(;;){do z++;while(E(N[z],D)<0);do H--;while(E(N[H],D)>0);if(z>=H)break;let Y=N[z];N[z]=N[H],N[H]=Y,Y=f[z],f[z]=f[H],f[H]=Y}sEe(N,f,_,H,E),sEe(N,f,H+1,S,E)}const UZe=11102230246251565e-32,Sy=134217729,TVt=(3+8*UZe)*UZe;function nEe(N,f,_,S,E){let D,z,H,Y,te=f[0],he=S[0],ge=0,ve=0;he>te==he>-te?(D=te,te=f[++ge]):(D=he,he=S[++ve]);let Te=0;if(gete==he>-te?(z=te+D,H=D-(z-te),te=f[++ge]):(z=he+D,H=D-(z-he),he=S[++ve]),D=z,H!==0&&(E[Te++]=H);gete==he>-te?(z=D+te,Y=z-D,H=D-(z-Y)+(te-Y),te=f[++ge]):(z=D+he,Y=z-D,H=D-(z-Y)+(he-Y),he=S[++ve]),D=z,H!==0&&(E[Te++]=H);for(;ge0:(S[0]-f[0])*(_[1]-f[1])-(_[0]-f[0])*(S[1]-f[1])>0}isAbove(f){return!this.isBelow(f)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const f=new oF(this.point,this.left,this.otherEvent,this.isSubject,this.type);return f.contourId=this.contourId,f.resultTransition=this.resultTransition,f.prevInResult=this.prevInResult,f.isExteriorRing=this.isExteriorRing,f.inOut=this.inOut,f.otherInOut=this.otherInOut,f}}function hk(N,f){return N[0]===f[0]&&N[1]===f[1]}function rEe(N,f,_){const S=function(E,D,z,H,Y,te){const he=(D-te)*(z-Y),ge=(E-Y)*(H-te),ve=he-ge;if(he===0||ge===0||he>0!=ge>0)return ve;const Te=Math.abs(he+ge);return Math.abs(ve)>=33306690738754716e-32*Te?ve:-function(Ie,Ve,et,at,ft,ut,Nt){let Mt,It,xs,es,ps,cs,ds,mn,xn,kn,En,Sn,Gn,dn,An,Pn,Wn,ir;const Ur=Ie-ft,wr=et-ft,vr=Ve-ut,or=at-ut;dn=Ur*or,cs=Sy*Ur,ds=cs-(cs-Ur),mn=Ur-ds,cs=Sy*or,xn=cs-(cs-or),kn=or-xn,An=mn*kn-(dn-ds*xn-mn*xn-ds*kn),Pn=vr*wr,cs=Sy*vr,ds=cs-(cs-vr),mn=vr-ds,cs=Sy*wr,xn=cs-(cs-wr),kn=wr-xn,Wn=mn*kn-(Pn-ds*xn-mn*xn-ds*kn),En=An-Wn,ps=An-En,iF[0]=An-(En+ps)+(ps-Wn),Sn=dn+En,ps=Sn-dn,Gn=dn-(Sn-ps)+(En-ps),En=Gn-Pn,ps=Gn-En,iF[1]=Gn-(En+ps)+(ps-Pn),ir=Sn+En,ps=ir-Sn,iF[2]=Sn-(ir-ps)+(En-ps),iF[3]=ir;let Or=function(jo,gi){let Ao=gi[0];for(let Di=1;Di<4;Di++)Ao+=gi[Di];return Ao}(0,iF),sa=22204460492503146e-32*Nt;if(Or>=sa||-Or>=sa||(ps=Ie-Ur,Mt=Ie-(Ur+ps)+(ps-ft),ps=et-wr,xs=et-(wr+ps)+(ps-ft),ps=Ve-vr,It=Ve-(vr+ps)+(ps-ut),ps=at-or,es=at-(or+ps)+(ps-ut),Mt===0&&It===0&&xs===0&&es===0)||(sa=11093356479670487e-47*Nt+TVt*Math.abs(Or),Or+=Ur*es+or*Mt-(vr*xs+wr*It),Or>=sa||-Or>=sa))return Or;dn=Mt*or,cs=Sy*Mt,ds=cs-(cs-Mt),mn=Mt-ds,cs=Sy*or,xn=cs-(cs-or),kn=or-xn,An=mn*kn-(dn-ds*xn-mn*xn-ds*kn),Pn=It*wr,cs=Sy*It,ds=cs-(cs-It),mn=It-ds,cs=Sy*wr,xn=cs-(cs-wr),kn=wr-xn,Wn=mn*kn-(Pn-ds*xn-mn*xn-ds*kn),En=An-Wn,ps=An-En,kv[0]=An-(En+ps)+(ps-Wn),Sn=dn+En,ps=Sn-dn,Gn=dn-(Sn-ps)+(En-ps),En=Gn-Pn,ps=Gn-En,kv[1]=Gn-(En+ps)+(ps-Pn),ir=Sn+En,ps=ir-Sn,kv[2]=Sn-(ir-ps)+(En-ps),kv[3]=ir;const Ta=nEe(4,iF,4,kv,qZe);dn=Ur*es,cs=Sy*Ur,ds=cs-(cs-Ur),mn=Ur-ds,cs=Sy*es,xn=cs-(cs-es),kn=es-xn,An=mn*kn-(dn-ds*xn-mn*xn-ds*kn),Pn=vr*xs,cs=Sy*vr,ds=cs-(cs-vr),mn=vr-ds,cs=Sy*xs,xn=cs-(cs-xs),kn=xs-xn,Wn=mn*kn-(Pn-ds*xn-mn*xn-ds*kn),En=An-Wn,ps=An-En,kv[0]=An-(En+ps)+(ps-Wn),Sn=dn+En,ps=Sn-dn,Gn=dn-(Sn-ps)+(En-ps),En=Gn-Pn,ps=Gn-En,kv[1]=Gn-(En+ps)+(ps-Pn),ir=Sn+En,ps=ir-Sn,kv[2]=Sn-(ir-ps)+(En-ps),kv[3]=ir;const ya=nEe(Ta,qZe,4,kv,VZe);dn=Mt*es,cs=Sy*Mt,ds=cs-(cs-Mt),mn=Mt-ds,cs=Sy*es,xn=cs-(cs-es),kn=es-xn,An=mn*kn-(dn-ds*xn-mn*xn-ds*kn),Pn=It*xs,cs=Sy*It,ds=cs-(cs-It),mn=It-ds,cs=Sy*xs,xn=cs-(cs-xs),kn=xs-xn,Wn=mn*kn-(Pn-ds*xn-mn*xn-ds*kn),En=An-Wn,ps=An-En,kv[0]=An-(En+ps)+(ps-Wn),Sn=dn+En,ps=Sn-dn,Gn=dn-(Sn-ps)+(En-ps),En=Gn-Pn,ps=Gn-En,kv[1]=Gn-(En+ps)+(ps-Pn),ir=Sn+En,ps=ir-Sn,kv[2]=Sn-(ir-ps)+(En-ps),kv[3]=ir;const xi=nEe(ya,VZe,4,kv,HZe);return HZe[xi-1]}(E,D,z,H,Y,te,Te)}(N[0],N[1],f[0],f[1],_[0],_[1]);return S>0?-1:S<0?1:0}function vC(N,f){const _=N.point,S=f.point;return _[0]>S[0]?1:_[0]S[1]?1:-1:function(E,D,z){return E.left!==D.left?E.left?1:-1:rEe(z,E.otherEvent.point,D.otherEvent.point)!==0?E.isBelow(D.otherEvent.point)?-1:1:!E.isSubject&&D.isSubject?1:-1}(N,f,_)}function bC(N,f,_){const S=new oF(f,!1,N,N.isSubject),E=new oF(f,!0,N.otherEvent,N.isSubject);return hk(N.point,N.otherEvent.point)&&console.warn("what is that, a collapsed segment?",N),S.contourId=E.contourId=N.contourId,vC(E,N.otherEvent)>0&&(N.otherEvent.left=!0,E.left=!1),N.otherEvent.otherEvent=E,N.otherEvent=S,_.push(E),_.push(S),_}function zee(N,f){return N[0]*f[1]-N[1]*f[0]}function aEe(N,f){return N[0]*f[0]+N[1]*f[1]}function iEe(N,f,_){const S=function(Y,te,he,ge){const ve=[te[0]-Y[0],te[1]-Y[1]],Te=[ge[0]-he[0],ge[1]-he[1]];function Ie(xs,es,ps){return[xs[0]+es*ps[0],xs[1]+es*ps[1]]}const Ve=[he[0]-Y[0],he[1]-Y[1]];let et=zee(ve,Te),at=et*et;const ft=aEe(ve,ve);if(at>0){const xs=zee(Ve,Te)/et;if(xs<0||xs>1)return null;const es=zee(Ve,ve)/et;return es<0||es>1?null:xs===0||xs===1?[Ie(Y,xs,ve)]:es===0||es===1?[Ie(he,es,Te)]:[Ie(Y,xs,ve)]}if(et=zee(Ve,ve),at=et*et,at>0)return null;const ut=aEe(ve,Ve)/ft,Nt=ut+aEe(ve,Te)/ft,Mt=Math.min(ut,Nt),It=Math.max(ut,Nt);return Mt<=1&&It>=0?Mt===1?[Ie(Y,Mt>0?Mt:0,ve)]:It===0?[Ie(Y,It<1?It:1,ve)]:[Ie(Y,Mt>0?Mt:0,ve),Ie(Y,It<1?It:1,ve)]:null}(N.point,N.otherEvent.point,f.point,f.otherEvent.point),E=S?S.length:0;if(E===0||E===1&&(hk(N.point,f.point)||hk(N.otherEvent.point,f.otherEvent.point))||E===2&&N.isSubject===f.isSubject)return 0;if(E===1)return!hk(N.point,S[0])&&!hk(N.otherEvent.point,S[0])&&bC(N,S[0],_),!hk(f.point,S[0])&&!hk(f.otherEvent.point,S[0])&&bC(f,S[0],_),1;const D=[];let z=!1,H=!1;return hk(N.point,f.point)?z=!0:vC(N,f)===1?D.push(f,N):D.push(N,f),hk(N.otherEvent.point,f.otherEvent.point)?H=!0:vC(N.otherEvent,f.otherEvent)===1?D.push(f.otherEvent,N.otherEvent):D.push(N.otherEvent,f.otherEvent),z&&H||z?(f.type=1,N.type=f.inOut===N.inOut?2:3,z&&!H&&bC(D[1].otherEvent,D[0].point,_),2):H?(bC(D[0],D[1].point,_),3):D[0]!==D[3].otherEvent?(bC(D[0],D[1].point,_),bC(D[1],D[2].point,_),3):(bC(D[0],D[1].point,_),bC(D[3].otherEvent,D[2].point,_),3)}function EVt(N,f){if(N===f)return 0;if(rEe(N.point,N.otherEvent.point,f.point)!==0||rEe(N.point,N.otherEvent.point,f.otherEvent.point)!==0)return hk(N.point,f.point)?N.isBelow(f.otherEvent.point)?-1:1:N.point[0]===f.point[0]?N.point[1](f.contourId??0)?1:-1}return vC(N,f)===1?1:-1}class MVt{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function LVt(N,f,_,S){let E,D=N+1,z=f[N].point;const H=f.length;for(DS;)D--;return D}function PVt(N,f,_){const S=new MVt;if(N.prevInResult!=null){const E=N.prevInResult,D=E.outputContourId;if(E.resultTransition>0){const z=f[D];if(z.holeOf!=null){const H=z.holeOf;f[H].holeIds.push(_),S.holeOf=H,S.depth=f[D].depth}else f[D].holeIds.push(_),S.holeOf=D,S.depth=f[D].depth+1}else S.holeOf=null,S.depth=f[D].depth}else S.holeOf=null,S.depth=0;return S}const WZe=Math.max,KZe=Math.min;let Bee=0;function YZe(N,f,_,S,E,D){let z,H,Y,te,he,ge;for(z=0,H=N.length-1;z0?ge.left=!0:he.left=!0;const ve=Y[0],Te=Y[1];E[0]=KZe(E[0],ve),E[1]=KZe(E[1],Te),E[2]=WZe(E[2],ve),E[3]=WZe(E[3],Te),S.push(he),S.push(ge)}}const $ee=[];function ZZe(N,f,_){let S=N,E=f;typeof N[0][0][0]=="number"&&(S=[N]),typeof f[0][0][0]=="number"&&(E=[f]);let D=function(ve,Te,Ie){let Ve=null;return ve.length*Te.length===0&&(Ie===0?Ve=$ee:Ie===2?Ve=ve:(Ie===1||Ie===3)&&(Ve=ve.length===0?Te:ve)),Ve}(S,E,_);if(D)return D===$ee?null:D;const z=[1/0,1/0,-1/0,-1/0],H=[1/0,1/0,-1/0,-1/0],Y=function(ve,Te,Ie,Ve,et){const at=new hh(void 0,vC);let ft,ut,Nt,Mt,It,xs;for(Nt=0,Mt=ve.length;NtVe[2]||Ve[0]>Ie[2]||Ie[1]>Ve[3]||Ve[1]>Ie[3])&&(et===0?at=$ee:et===2?at=ve:(et===1||et===3)&&(at=ve.concat(Te))),at}(S,E,z,H,_),D)return D===$ee?null:D;const te=function(ve,Te,Ie,Ve,et,at){const ft=new eEe(EVt),ut=[],Nt=Math.min(Ve[2],et[2]);let Mt,It,xs;for(;ve.length!==0;){let es=ve.pop();if(ut.push(es),at===0&&es.point[0]>Nt||at===2&&es.point[0]>Ve[2])break;if(es.left){It=Mt=ft.insert(es),xs=ft.minNode(),Mt=Mt!==xs?ft.prev(Mt):null,It=ft.next(It);const ps=Mt?Mt.key:null;let cs;if(wV(es,ps,at),It&&iEe(es,It.key,ve)===2&&(wV(es,ps,at),wV(It.key,es,at)),Mt&&iEe(Mt.key,es,ve)===2){let ds=Mt;ds=ds!==xs?ft.prev(ds):null,cs=ds?ds.key:null,wV(ps,cs,at),wV(es,ps,at)}}else es=es.otherEvent,It=Mt=ft.find(es),Mt&&It&&(Mt=Mt!==xs?ft.prev(Mt):null,It=ft.next(It),ft.remove(es),It&&Mt&&iEe(Mt.key,It.key,ve))}return ut}(Y,0,0,z,H,_),he=function(ve){let Te,Ie;const Ve=function(ft){let ut,Nt,Mt,It,xs;const es=[];for(Nt=0,Mt=ft.length;Nt{et[xs]=!0,xs=Ve.length)&&Ve[Mt];);at.push(ut)}return at}(te),ge=[];for(let ve=0;ve{z.push(new Xs(ge,Y+(ge-H)/(te-H)*(he-Y)))}:(z,H,Y,te,he,ge)=>{z.push(new Xs(H+(ge-Y)/(he-Y)*(te-H),ge))};for(const z of N){const H=[];for(const Y of z){if(Y.length<=2)continue;const te=[];for(let ve=0;vef&&D(te,Te,Ie,Ve,et,f):at>_?ft<_&&D(te,Te,Ie,Ve,et,_):te.push(Y[ve]),ft=f&&D(te,Te,Ie,Ve,et,f),ft>_&&at<=_&&D(te,Te,Ie,Ve,et,_)}let he=Y[Y.length-1];const ge=S===0?he.x:he.y;ge>=f&&ge<=_&&te.push(he),te.length&&(he=te[te.length-1],te[0].x===he.x&&te[0].y===he.y||te.push(te[0]),H.push(te))}H.length&&E.push(H)}return E}function IVt(N,f){const _=ZZe(oEe(N),oEe([f]),0);return _==null?[]:XZe(_)}function RVt(N,f,_=0){let E=oEe(N,65536);const D=[];for(;f.valid();f.next()){const[z,H]=f.get();let Y=z.x*65536,te=z.y*65536,he=H.x*65536,ge=H.y*65536;const ve=he-Y,Te=ge-te,Ie=Math.hypot(ve,Te);if(Ie===0)continue;Y-=ve*_,te-=Te*_,he+=ve*_,ge+=Te*_;const Ve=Math.trunc(Te/Ie*3),et=-Math.trunc(ve/Ie*3);D.push([[[Y,te],[he,ge],[he+Ve,ge+et],[Y+Ve,te+et],[Y,te]]])}return D.length>0&&(E=ZZe(E,D,2)),XZe(E,1/65536,128)}function oEe(N,f=1){return[N.map(_=>_.map(S=>[S.x*f,S.y*f]))]}function XZe(N,f=1,_){return N.map(S=>S.map((E,D)=>{const z=E.map(H=>{let Y=H[0],te=H[1];return _&&(Y=Math.round(Y/_)*_,te=Math.round(te/_)*_),new Xs(Y*f,te*f)._round()});return D>0&&z.reverse(),z}))}class lEe{constructor(f,_){this.layoutVertexArray=new Pi,this.indexArray=new eu,this.lineIndexArray=new D1,this.triangleSegments=new Gl,this.lineSegments=new Gl,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.lut}),this.uploaded=!1,_&&(this.elevatedLayoutVertexArray=new dl)}update(f,_,S,E,D,z,H,Y){this.programConfigurations.updatePaintArrays(f,_,D,S,E,z,H,Y)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,mVt.members),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.lineIndexBuffer=f.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=f.createVertexBuffer(this.elevatedLayoutVertexArray,pVt.members))),this.programConfigurations.upload(f),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(f,_,S,E,D,z,H){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,f,_,S,E,D,z,void 0,H)}}class qee{constructor(f){this.zoom=f.zoom,this.pixelRatio=f.pixelRatio,this.overscaling=f.overscaling,this.layers=f.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=f.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=f.lut,this.bufferData=new lEe(f,!1),this.elevationBufferData=new lEe(f,!0),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.projection=f.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=f.sourceLayerIndex,this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,_){}updateAppearances(f,_,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,E){this.hasPattern=QTe("fill",this.layers,this.pixelRatio,_);const D=this.layers[0].layout.get("fill-sort-key"),z=[];for(const{feature:H,id:Y,index:te,sourceLayerIndex:he}of f){const ge=this.layers[0]._featureFilter.needGeometry,ve=Ri(H,ge);if(!this.layers[0]._featureFilter.filter(new bi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),ve,S))continue;const Te=D?D.evaluate(ve,{},S,_.availableImages):void 0,Ie={id:Y,properties:H.properties,type:H.type,sourceLayerIndex:he,index:te,geometry:ge?ve.geometry:Ea(H,S,E),patterns:{},sortKey:Te};z.push(Ie)}D&&z.sort((H,Y)=>H.sortKey-Y.sortKey);for(const H of z){const{geometry:Y,index:te,sourceLayerIndex:he}=H;if(this.hasPattern){const ge=JTe("fill",this.layers,H,this.zoom,this.pixelRatio,_);this.patternFeatures.push(ge)}else this.addFeature(H,Y,te,S,{},_.availableImages,_.brightness,_.elevationFeatures);_.featureIndex.insert(f[te].feature,Y,te,he,this.index)}}update(f,_,S,E,D,z,H){this.bufferData.update(f,_,S,E,D,z,H,this.worldview),this.elevationBufferData.update(f,_,S,E,D,z,H,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(f,_,S,E,D,z,H,this.worldview)}addFeatures(f,_,S,E,D,z){for(const H of this.patternFeatures)this.addFeature(H,H.geometry,H.index,_,S,E,z,f.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(f){this.bufferData.upload(f),this.elevationBufferData.upload(f),this.elevatedStructures&&this.elevatedStructures.upload(f)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(f,_,S,E,D,z=[],H,Y){const te=bV(_,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(f,te,E,S,Y):this.addGeometry(te,this.bufferData),this.bufferData.populatePaintArrays(f,S,D,z,E,H,this.worldview),this.elevationBufferData.populatePaintArrays(f,S,D,z,E,H,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(f,_,S,E,D){this.elevatedStructures&&(this.elevatedStructures.construct(f),this.elevatedStructures.populatePaintArrays(_,S,E,D,this.worldview))}addElevatedRoadFeature(f,_,S,E,D){const z=new Array,H=tc.getElevationFeature(f,D);if(!H)return void this.addGeometry(_,this.bufferData);{const te=this.clipPolygonsToTile(_,1);te.length>0&&z.push({polygons:te,elevationFeature:H,elevationTileID:S})}const Y={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(f,{},S),featureIndex:E};for(const te of z)if(te.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new Nv(te.elevationTileID,this.layers,this.zoom,this.lut));const ge=te.elevationFeature.isTunnel();let ve=0;f.properties.hasOwnProperty(Kl)&&(ve=+f.properties[Kl]),this.elevatedStructures.addPortalCandidates(te.elevationFeature.id,te.polygons,ge,te.elevationFeature,ve)}te.elevationFeature.constantHeight==null&&(te.polygons=this.prepareElevatedPolygons(te.polygons,te.elevationFeature,te.elevationTileID));const he=new fc(S,te.elevationTileID);this.addElevatedGeometry(te.polygons,he,te.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,E,Y)}}addElevatedGeometry(f,_,S,E,D,z){const H={elevation:S,elevationSampler:_,bias:E,index:D,featureInfo:z},[Y,te]=this.addGeometry(f,this.elevationBufferData,H);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:Y,max:te}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,Y),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,te))}addGeometry(f,_,S){let E=Number.POSITIVE_INFINITY,D=Number.NEGATIVE_INFINITY,z=null;S&&(z=S.elevationSampler.constantElevation(S.elevation,S.bias),z!=null&&(E=z,D=z));const H=(Y,te,he)=>{if(S!=null)if(te.push(Y),z!=null)_.elevatedLayoutVertexArray.emplaceBack(z),he.push(z);else{const ge=S.elevationSampler.pointElevation(Y,S.elevation,S.bias);_.elevatedLayoutVertexArray.emplaceBack(ge),he.push(ge),E=Math.min(E,ge),D=Math.max(D,ge)}};for(const Y of f){let te=0;for(const ut of Y)te+=ut.length;const he=_.triangleSegments.prepareSegment(te,_.layoutVertexArray,_.indexArray),ge=he.vertexLength,ve=[],Te=[],Ie=[],Ve=[],et=[],at=_.layoutVertexArray.length;for(const ut of Y){if(ut.length===0)continue;ut!==Y[0]&&Te.push(ve.length/2);const Nt=_.lineSegments.prepareSegment(ut.length,_.layoutVertexArray,_.lineIndexArray),Mt=Nt.vertexLength;S&&et.push(_.layoutVertexArray.length-at),H(ut[0],Ie,Ve),_.layoutVertexArray.emplaceBack(ut[0].x,ut[0].y),_.lineIndexArray.emplaceBack(Mt+ut.length-1,Mt),ve.push(ut[0].x),ve.push(ut[0].y);for(let It=1;It0&&S&&this.elevationMode==="hd-road-base"){const ut=S.elevation.isTunnel(),Nt=S.elevation.safeArea,Mt=this.elevatedStructures.addVertices(Ie,Ve);this.elevatedStructures.addTriangles(ft,Mt,ut);const It=et.length;if(It>0){for(let xs=0;xs=S&&Te.max.x<=D&&Te.min.y>=E&&Te.max.y<=z?Y:te).push(ve)}if(Y.length===f.length)return f;const he=[new Xs(S,E),new Xs(D,E),new Xs(D,z),new Xs(S,z),new Xs(S,E)],ge=Y;for(const ve of te)ge.push(...IVt(ve,he));return ge}}let QZe,JZe,eXe,tXe;gr(qee,"FillBucket",{omit:["layers","patternFeatures"]}),gr(lEe,"FillBufferData"),gr(Nv,"ElevatedStructures");class Vee{constructor(f,_,S,E){if(this.triangleCount=_.length/3,this.min=new Xs(0,0),this.max=new Xs(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||f.length===0)return;const[D,z]=[f[0].clone(),f[0].clone()];for(let ge=1;gege.cellIdx-ve.cellIdx||ge.triIdx-ve.triIdx);let he=0;for(;hethis.max.x||this.min.x>f.x||f.y>this.max.y||this.min.y>f.y)return;const S=mk(f.x-this.min.x,this.xScale,this.cellsX),E=mk(f.y-this.min.y,this.yScale,this.cellsY),D=this.cells[E*this.cellsX+S];if(D){this._lazyInitLookup();for(let z=0;zthis.max.x||this.min.x>_.x||f.y>this.max.y||this.min.y>_.y)return;this._lazyInitLookup();const E=mk(f.x-this.min.x,this.xScale,this.cellsX),D=mk(_.x-this.min.x,this.xScale,this.cellsX),z=mk(f.y-this.min.y,this.yScale,this.cellsY),H=mk(_.y-this.min.y,this.yScale,this.cellsY);for(let Y=z;Y<=H;Y++)for(let te=E;te<=D;te++){const he=this.cells[Y*this.cellsX+te];if(he)for(let ge=0;ge_.fqid),this.index=f.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.footprints=[],this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,_){for(const S of this.footprints)_.push({footprint:S,id:f})}updateAppearances(f,_,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,E){const D=[];for(const{feature:z,id:H,index:Y,sourceLayerIndex:te}of f){const he=this.layers[0]._featureFilter.needGeometry,ge=Ri(z,he);if(!this.layers[0]._featureFilter.filter(new bi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),ge,S))continue;const ve={id:H,properties:z.properties,type:z.type,sourceLayerIndex:te,index:Y,geometry:he?ge.geometry:Ea(z,S,E),patterns:{}};D.push(ve)}for(const z of D){const{geometry:H,index:Y,sourceLayerIndex:te}=z;this.addFeature(z,H,Y,S,{},_.availableImages,_.brightness),_.featureIndex.insert(f[Y].feature,H,Y,te,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(f){}update(f,_,S,E,D,z,H){}destroy(){}addFeature(f,_,S,E,D,z=[],H){for(const Y of bV(_,2)){const te=[],he=[],ge=[],ve=new Xs(1/0,1/0),Te=new Xs(-1/0,-1/0);for(const et of Y)if(et.length!==0){et!==Y[0]&&ge.push(he.length/2);for(let at=0;atf.max.x||N.max.xf.max.y||N.max.ynew Xs((Y.x+D.x*nr)*H-z.x*nr,(Y.y+D.y*nr)*H-z.y*nr))}return dEe(_,E,N.indices,0,N.indices.length,0,0)}function oXe(N,f,_,S){const E=Math.pow(2,S.z-_.z);return new Xs((N+_.x*nr)*E-S.x*nr,(f+_.y*nr)*E-S.y*nr)}function lXe(N,f){const _=[];f.grid.queryPoint(N,_);const S=f.indices,E=f.vertices;for(let D=0;D<_.length;D++){const z=_[D];if(L0([E[S[3*z+0]],E[S[3*z+1]],E[S[3*z+2]]],N))return!0}return!1}const Wee={None:0,Model:1,Symbol:2,FillExtrusion:4},uEe=[new Xs(0,0),new Xs(nr,0),new Xs(nr,nr),new Xs(0,nr)];function cXe(N,f){const _=[];let S=[];if(!f||N.length<2)return[N];if(N.length===2)return ck(N[0],N[1],uEe)?[N]:[];for(let E=0;E0&&(S.length>1&&_.push(S),S=[])}return S.length>1&&_.push(S),_}const hEe=ri.types,GVt=["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"],WVt=["fill-extrusion-flood-light-ground-radius"],KVt=Math.pow(2,13),YVt=Math.pow(2,15)-1,Kee=new Xs(0,1),$S=2147483648,Yee=1073741824;function NV(N,f,_,S,E,D,z,H){N.emplaceBack((f<<1)+z,(_<<1)+D,(Math.floor(S*KVt)<<1)+E,Math.round(H))}function kV(N,f,_){N.emplaceBack(f.x*nr,f.y*nr,_?1:0)}function Zee(N,f,_,S,E,D){N.emplaceBack(f.x,f.y,(_.x<<1)+S,(_.y<<1)+E,D)}function SV(N,f,_){N.emplaceBack(f.x,f.y,f.z,_[0]*16384,_[1]*16384,_[2]*16384)}class dXe{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class mEe{constructor(){this.centroidXY=new Xs(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 Xs(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Xs(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new Xs(0,0)}span(){return new Xs(this.max.x-this.min.x,this.max.y-this.min.y)}}class pEe{constructor(){this.acc=new Xs(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(f,_){f.min.x===Number.MAX_VALUE&&(f.min.x=f.max.x=_.x,f.min.y=f.max.y=_.y)}appendEdge(f,_,S){this.accCount++,this.acc._add(_);let E=!!this.borders;_.xf.max.x&&(f.max.x=_.x,E=!0),_.yf.max.y&&(f.max.y=_.y,E=!0),((_.x===0||_.x===nr)&&_.x===S.x)!=((_.y===0||_.y===nr)&&_.y===S.y)&&this.processBorderOverlap(_,S),E&&this.checkBorderIntersection(_,S)}checkBorderIntersection(f,_){_.x<0!=f.x<0&&this.addBorderIntersection(0,xr(_.y,f.y,(0-_.x)/(f.x-_.x))),_.x>nr!=f.x>nr&&this.addBorderIntersection(1,xr(_.y,f.y,(nr-_.x)/(f.x-_.x))),_.y<0!=f.y<0&&this.addBorderIntersection(2,xr(_.x,f.x,(0-_.y)/(f.y-_.y))),_.y>nr!=f.y>nr&&this.addBorderIntersection(3,xr(_.x,f.x,(nr-_.y)/(f.y-_.y)))}addBorderIntersection(f,_){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const S=this.borders[f];_S[1]&&(S[1]=_)}processBorderOverlap(f,_){if(f.x===_.x){if(f.y===_.y)return;const S=f.x===0?0:1;this.addBorderIntersection(S,_.y),this.addBorderIntersection(S,f.y)}else{const S=f.y===0?2:3;this.addBorderIntersection(S,_.x),this.addBorderIntersection(S,f.x)}}centroid(){return this.accCount===0?new Xs(0,0):new Xs(Math.floor(Math.max(0,this.acc.x)/this.accCount),Math.floor(Math.max(0,this.acc.y)/this.accCount))}intersectsCount(){return this.borders?this.borders.reduce((f,_)=>f+ +(_[0]!==Number.MAX_VALUE),0):0}}function uXe(N,f){const _=N.add(f)._unit(),S=it(N.x*_.x+N.y*_.y,-1,1);var E,D,z;return z=Math.acos(S),Math.min(4,Math.max(-4,Math.tan(z)))/4*YVt*((E=N).x*(D=f).y-E.y*D.x<0?-1:1)}const ZVt=[N=>N.x<0,N=>N.x>nr,N=>N.y<0,N=>N.y>nr];function XVt(N,f,_,S){const E=[4];if(S===0)return E;_._mult(S);const D=N.sub(_),z=f.sub(_),H=[N,f,D,z];for(let Y=0;Y<4;Y++)for(const te of H)if(ZVt[Y](te)){E.push(Y);break}return E}class fEe{constructor(f){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new D6,this.indexArray=new eu,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.lut},_=>WVt.includes(_)),this._segments=new Gl,this.hiddenByLandmarkVertexArray=new JO,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Gl}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(f,_,S,E=!1){const D=f.length;if(D>2){let z=Math.max(0,this._segments.get().length-1);const H=this._segments._prepareSegment(4*D,this.vertexArray.length,2*this._segmentToGroundQuads[z].length);let Y;z!==this._segments.get().length-1&&(z++,this._segmentToGroundQuads[z]=[],this._segmentToRegionTriCounts[z]=[0,0,0,0,0]);{const te=f[0],he=f[1];Y=uXe(te.sub(f[D-1])._perp()._unit(),he.sub(te)._perp()._unit())}for(let te=0;teE.region-D.region);for(let S=0;S<_;S++){const E=this._segmentToGroundQuads[S],D=f[S],z=this._segmentToRegionTriCounts[S];z.reduce((Y,te)=>Y+te,0);let H=0;for(let Y=0;Y<=4;Y++){const te=z[Y];if(te!==0){let he=this.regionSegments[Y];he||(he=this.regionSegments[Y]=new Gl);const ge={vertexOffset:D.vertexOffset,primitiveOffset:D.primitiveOffset+H,vertexLength:D.vertexLength,primitiveLength:te};he.get().push(ge)}H+=te}for(let Y=0;Y0?this.hiddenByLandmarkVertexBuffer=f.createVertexBuffer(this.hiddenByLandmarkVertexArray,$Vt.members,!0):this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.updateData(this.hiddenByLandmarkVertexArray),this._needsHiddenByLandmarkUpdate=!1)}destroy(){if(this.vertexBuffer){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.destroy(),this.groundRadiusBuffer&&this.groundRadiusBuffer.destroy(),this._segments&&this._segments.destroy(),this.programConfigurations.destroy();for(let f=0;f<=4;f++){const _=this.regionSegments[f];_&&_.destroy()}}}}class Xee{constructor(f){this.zoom=f.zoom,this.canonical=f.canonical,this.overscaling=f.overscaling,this.layers=f.layers,this.pixelRatio=f.pixelRatio,this.layerIds=this.layers.map(_=>_.fqid),this.index=f.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=f.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new eu,this.footprintVertices=new Pi,this.footprintSegments=[],this.layoutVertexArray=new I1,this.centroidVertexArray=new Eee,this.wallVertexArray=new dV,this.indexArray=new eu,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.lut},_=>GVt.includes(_)),this.segments=new Gl,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.groundEffect=new fEe(f),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,_){}updateAppearances(f,_,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,E){this.features=[],this.hasPattern=QTe("fill-extrusion",this.layers,this.pixelRatio,_),this.featuresOnBorder=[],this.borderFeatureIndices=[[],[],[],[]],this.borderDoneWithNeighborZ=[-1,-1,-1,-1],this.selfDEMTileTimestamp=Number.MAX_VALUE,this.borderDEMTileTimestamp=[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],this.tileToMeter=zn(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:D,id:z,index:H,sourceLayerIndex:Y}of f){const te=this.layers[0]._featureFilter.needGeometry,he=Ri(D,te);if(!this.layers[0]._featureFilter.filter(new bi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),he,S))continue;const ge={id:z,sourceLayerIndex:Y,index:H,geometry:te?he.geometry:Ea(D,S,E),properties:D.properties,type:D.type,patterns:{}},ve=this.layoutVertexArray.length,Te=hEe[ge.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:D.id,feature:JTe("fill-extrusion",this.layers,ge,this.zoom,this.pixelRatio,_)});else if(this.wallMode)for(const Ie of ge.geometry)for(const Ve of cXe(Ie,Te))this.addFeature(D.id,ge,[Ve],H,S,{},_.availableImages,E,_.brightness);else this.addFeature(D.id,ge,ge.geometry,H,S,{},_.availableImages,E,_.brightness);_.featureIndex.insert(D,ge.geometry,H,Y,this.index,ve)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(f,_,S,E,D,z){for(const{featureId:H,feature:Y}of this.features){const te=hEe[Y.type]==="Polygon",{geometry:he}=Y;if(this.wallMode)for(const ge of he)for(const ve of cXe(ge,te))this.addFeature(H,Y,[ve],Y.index,_,S,E,D,z);else this.addFeature(H,Y,he,Y.index,_,S,E,D,z)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(f,_,S,E,D,z,H){this.programConfigurations.updatePaintArrays(f,_,D,S,E,z,H,this.worldview),this.groundEffect.update(f,_,D,S,E,z,H,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,qVt),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.wallVertexBuffer=f.createVertexBuffer(this.wallVertexArray,BVt.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=f.createVertexBuffer(this.layoutVertexExtArray,UVt.members,!0)),this.groundEffect.upload(f)),this.groundEffect.uploadPaintProperties(f),this.programConfigurations.upload(f),this.uploaded=!0}uploadCentroid(f){this.groundEffect.uploadHiddenByLandmark(f),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=f.createVertexBuffer(this.centroidVertexArray,zVt.members,!0):this.centroidVertexBuffer&&this.centroidVertexBuffer.updateData(this.centroidVertexArray),this.needsCentroidUpdate=!1)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.centroidVertexBuffer&&this.centroidVertexBuffer.destroy(),this.layoutVertexExtBuffer&&this.layoutVertexExtBuffer.destroy(),this.groundEffect.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(f,_,S,E,D,z,H,Y,te){const he=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(_,{})/this.tileToMeter,ge=[new Xs(0,0),new Xs(nr,nr)],ve=Y.projection,Te=ve.name==="globe",Ie=this.wallMode||hEe[_.type]==="Polygon",Ve=new pEe;Ve.centroidDataIndex=this.centroidData.length;const et=new mEe;et.buildingId=f,_.properties&&_.properties.hasOwnProperty("building_id")&&(et.buildingId=Number(_.properties.building_id)),Ve.buildingId=et.buildingId;const at=this.layers[0].paint.get("fill-extrusion-base").evaluate(_,{},D)<=0,ft=this.layers[0].paint.get("fill-extrusion-height").evaluate(_,{},D);let ut;if(et.height=ft,et.vertexArrayOffset=this.layoutVertexArray.length,et.groundVertexArrayOffset=this.groundEffect.vertexArray.length,Te&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new WO),this.wallMode){if(Te)return void Mr("Non zero fill-extrusion-line-width is not yet supported on globe.");if(S.length!==1)return;ut=function(cs){const ds=cs[0].x===cs[cs.length-1].x&&cs[0].y===cs[cs.length-1].y;(function(vr){let or=0;const Or=vr.length;for(let sa=0;sa=0})(cs)||(cs=cs.reverse());const xn={geometry:[],joinNormals:[],indices:[]},kn=[],En=[],Sn=[];let Gn=cs.length;for(;Gn>=2&&cs[Gn-1].equals(cs[Gn-2]);)Gn--;if(Gn<(ds?3:2))return xn;let dn,An,Pn,Wn,ir,Ur=0;for(;Ur0;let ya="miter";const xi=2;ya==="miter"&&sa>xi&&(ya="bevel"),ya==="bevel"&&(sa>100&&(ya="flipbevel"),sa{const tl=new Xs(gi.x,gi.y),Oo=new Xs(gi.x,gi.y);tl.x+=Ao.x*Ld,tl.y+=Ao.y*Ld,Oo.x-=Ao.x*Math.max(Di,1),Oo.y-=Ao.y*Math.max(Di,1),Sn.push(Ao),kn.push(tl),En.push(Oo)};if(ya==="miter")or._mult(sa),jo(dn,or,0,0);else if(ya==="flipbevel")or=ir.mult(-1),jo(dn,or,0,0),jo(dn,or.mult(-1),0,0);else{const gi=-Math.sqrt(sa*sa-1),Ao=Ta?gi:0,Di=Ta?0:gi;An&&jo(dn,Wn,Ao,Di),Pn&&jo(dn,ir,Ao,Di)}}xn.geometry=[...kn,...En.reverse(),kn[0]],xn.joinNormals=[...Sn,...Sn.reverse(),Sn[Sn.length-1]];const wr=xn.geometry.length-1;for(let vr=0;vrcs<(ds.length-1)/2||cs===ds.length-1,Mt=this.wallMode?[S]:bV(S,500);for(let cs=Mt.length-1;cs>=0;cs--){const ds=Mt[cs];(ds.length===0||JVt(ds[0]))&&Mt.splice(cs,1)}let It;if(Te)It=yXe(Mt,ge,D);else{It=[];for(const cs of Mt)It.push({polygon:cs,bounds:ge})}const xs=Ie?this.edgeRadius:0,es=xs>0&&this.zoom<17,ps=(cs,ds)=>{if(cs.length===0)return!1;const mn=cs[cs.length-1];return ds.x===mn.x&&ds.y===mn.y};for(const{polygon:cs,bounds:ds}of It){let mn=0,xn=0;for(const Gn of cs)Ie&&!Gn[0].equals(Gn[Gn.length-1])&&Gn.push(Gn[0]),xn+=Ie?Gn.length-1:Gn.length;const kn=this.segments.prepareSegment((Ie?5:4)*xn,this.layoutVertexArray,this.indexArray);et.footprintSegIdx<0&&(et.footprintSegIdx=this.footprintSegments.length),et.polygonSegIdx<0&&(et.polygonSegIdx=this.polygonSegments.length);const En={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},Sn=new dXe;if(Sn.vertexOffset=this.footprintVertices.length,Sn.indexOffset=3*this.footprintIndices.length,Sn.ringIndices=[],Ie){const Gn=[],dn=[];mn=kn.vertexLength;for(let Pn=0;Pn4&&fXe(dn[dn.length-2],dn[0],dn[1]),Pn=xs?QVt(dn[dn.length-2],dn[0],dn[1],xs):0;const Wn=[];let ir,Ur,wr;Ur=dn[1].sub(dn[0])._perp()._unit();let vr=!0;for(let or=1,Or=0;or0?1:0,Ao=sa.dist(Ta);if(Or+Ao>32768&&(Or=0),xs){wr=ya.sub(Ta)._perp()._unit();let Oo=mXe(sa,Ta,ya,hXe(Ur,wr),xs);isNaN(Oo)&&(Oo=0);const Yl=Ta.sub(sa)._unit();sa=sa.add(Yl.mult(Pn))._round(),Ta=Ta.add(Yl.mult(-Oo))._round(),Pn=Oo,Ur=wr,at&&this.zoom>=17&&(ps(Wn,sa)||Wn.push(sa),ps(Wn,Ta)||Wn.push(Ta))}const Di=kn.vertexLength,Ld=dn.length>4&&fXe(sa,Ta,ya);let tl=xXe(Or,An,vr);if(NV(this.layoutVertexArray,sa.x,sa.y,jo,gi,0,0,tl),NV(this.layoutVertexArray,sa.x,sa.y,jo,gi,0,1,tl),this.wallMode){const Oo=Nt(or-1,dn),Yl=ut.joinNormals[or-1];kV(this.wallVertexArray,Yl,Oo),kV(this.wallVertexArray,Yl,Oo)}if(Or+=Ao,tl=xXe(Or,Ld,!vr),An=Ld,NV(this.layoutVertexArray,Ta.x,Ta.y,jo,gi,0,0,tl),NV(this.layoutVertexArray,Ta.x,Ta.y,jo,gi,0,1,tl),this.wallMode){const Oo=Nt(or,dn),Yl=ut.joinNormals[or];kV(this.wallVertexArray,Yl,Oo),kV(this.wallVertexArray,Yl,Oo)}if(kn.vertexLength+=4,this.indexArray.emplaceBack(Di+0,Di+1,Di+2),this.indexArray.emplaceBack(Di+1,Di+3,Di+2),kn.primitiveLength+=2,xs){const Oo=mn+(or===1?dn.length-2:or-2),Yl=or===1?mn:Oo+1;if(this.indexArray.emplaceBack(Di+1,Oo,Di+3),this.indexArray.emplaceBack(Oo,Yl,Di+3),kn.primitiveLength+=2,ir===void 0&&(ir=Di),!xEe(ya,dn[or],ds)){const bd=or===dn.length-1?ir:kn.vertexLength;this.indexArray.emplaceBack(Di+2,Di+3,bd),this.indexArray.emplaceBack(Di+3,bd+1,bd),this.indexArray.emplaceBack(Di+3,Yl,bd+1),kn.primitiveLength+=3}vr=!vr}if(Te){const Oo=this.layoutVertexExtArray,Yl=ve.projectTilePoint(sa.x,sa.y,D),bd=ve.projectTilePoint(Ta.x,Ta.y,D),Lm=ve.upVector(D,sa.x,sa.y),_d=ve.upVector(D,Ta.x,Ta.y);SV(Oo,Yl,Lm),SV(Oo,Yl,Lm),SV(Oo,bd,_d),SV(Oo,bd,_d)}}Ie&&(mn+=dn.length-1),at&&xs&&this.zoom>=17&&(Wn.length!==0&&ps(Wn,Wn[0])&&Wn.pop(),this.groundEffect.addData(Wn,ds,he,xs>0))}this.footprintSegments.push(Sn),En.triangleCount=this.indexArray.length-En.triangleArrayOffset,this.polygonSegments.push(En),++et.footprintSegLen,++et.polygonSegLen}if(et.vertexCount=this.layoutVertexArray.length-et.vertexArrayOffset,et.groundVertexCount=this.groundEffect.vertexArray.length-et.groundVertexArrayOffset,et.vertexCount!==0){if(et.centroidXY=Ve.borders?Kee:this.encodeCentroid(Ve,et),_.properties&&_.properties.hasOwnProperty("building_id")){const cs=et.buildingId;let ds=this.buildingGroups.get(cs);ds||(ds={accX:0,accY:0,accCount:0,mergedMin:new Xs(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Xs(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(cs,ds)),ds.accX+=Ve.acc.x,ds.accY+=Ve.acc.y,ds.accCount+=Ve.accCount,ds.mergedMin.x=Math.min(ds.mergedMin.x,et.min.x),ds.mergedMin.y=Math.min(ds.mergedMin.y,et.min.y),ds.mergedMax.x=Math.max(ds.mergedMax.x,et.max.x),ds.mergedMax.y=Math.max(ds.mergedMax.y,et.max.y),ds.partIndices.push(this.centroidData.length)}if(this.centroidData.push(et),Ve.borders){this.featuresOnBorder.push(Ve);const cs=this.featuresOnBorder.length-1;for(let ds=0;dsthis.featuresOnBorder[_].borders[f][0]-this.featuresOnBorder[S].borders[f][0])}splitToSubtiles(){const f=[];for(let H=0;Hnr),he=2*te+(+(Y.min.x+Y.max.x>nr)^te);for(let ge=0;geH.triangleSegmentIdx===Y.triangleSegmentIdx?H.subtile-Y.subtile:H.triangleSegmentIdx-Y.triangleSegmentIdx);let S=0,E=0,D=0;for(const H of f){if(H.triangleSegmentIdx!==S)break;D++}const z=f.length;for(;E!==f.length;){S=f[E].triangleSegmentIdx;let H=0,Y=E,te=E;for(let he=Y;he0&&this.triangleSubSegments.push({segment:Te,min:ge,max:ve}),Y=te;for(let Ie=Y;Ie[Ve[0]*(1-at[0])+et[0]*at[0],Ve[1]*(1-at[1])+et[1]*at[1]],Te=[],Ie=[];for(const Ve of this.triangleSubSegments){Te[0]=Ve.min.x/nr,Te[1]=Ve.min.y/nr,Ie[0]=Ve.max.x/nr,Ie[1]=Ve.max.y/nr;const et=ve(he,ge,Te),at=ve(he,ge,Ie);if(new al([et[0],et[1],D],[at[0],at[1],z]).intersectsPrecise(S)===0){te&&(E.segments.push(te),te=void 0);continue}const ft=Ve.segment;te&&te.vertexOffset!==ft.vertexOffset&&(E.segments.push(te),te=void 0),te?(te.vertexLength+=ft.vertexLength,te.primitiveLength+=ft.primitiveLength):te={vertexOffset:ft.vertexOffset,primitiveLength:ft.primitiveLength,vertexLength:ft.vertexLength,primitiveOffset:ft.primitiveOffset,sortKey:void 0,vaos:{}}}return te&&E.segments.push(te),E}encodeCentroid(f,_){const S=f.centroid(),E=_.span(),D=Math.min(7,Math.round(E.x*this.tileToMeter/10)),z=Math.min(6,Math.round(E.y*this.tileToMeter/10));return new Xs(it(S.x,1,8191)<<3|D,it(S.y,1,8191)<<3|z)}encodeBorderCentroid(f){if(!f.borders)return new Xs(0,0);const _=f.borders,S=Number.MAX_VALUE;if(_[0][0]!==S||_[1][0]!==S){const E=_[0][0]!==S?0:1;return new Xs(6|(_[0][0]!==S?0:65528),(_[E][0]+_[E][1])/2<<3|6)}{const E=_[2][0]!==S?2:3;return new Xs((_[E][0]+_[E][1])/2<<3|6,6|(_[2][0]!==S?0:65528))}}showCentroid(f){const _=this.centroidData[f.centroidDataIndex];if(_.flags&=$S,_.groupCentroidPos.x!==0||_.groupCentroidPos.y!==0){const S=_.span(),E=Math.min(7,Math.round(S.x*this.tileToMeter/10)),D=Math.min(6,Math.round(S.y*this.tileToMeter/10));_.centroidXY=new Xs(it(_.groupCentroidPos.x,1,8191)<<3|E,it(_.groupCentroidPos.y,1,8191)<<3|D)}else _.centroidXY=new Xs(0,0);this.writeCentroidToBuffer(_)}writeCentroidToBuffer(f){this.groundEffect.updateHiddenByLandmark(f);const _=f.vertexArrayOffset,S=f.vertexCount+f.vertexArrayOffset,E=-1073741824&f.flags?Kee:f.centroidXY,D=this.centroidVertexArray.geta_centroid_pos0(_);if(this.centroidVertexArray.geta_centroid_pos1(_)!==E.y||D!==E.x){for(let z=_;zY.max.x||Y.min.x>z.max.x||z.min.y>Y.max.y||Y.min.y>z.max.y||z.footprint.buildingIds.has(Y.buildingId)&&(Y.flags|=z.clipMask!==Wee.None?-1073741824:$S);else for(const Y of this.centroidData)if(!(Y.flags&$S||Y.flags&Yee||z.min.x>Y.max.x||Y.min.x>z.max.x||z.min.y>Y.max.y||Y.min.y>z.max.y))for(let te=0;te_!=Te>_&&f<(this.footprintVertices.int16[2*(he+z.vertexOffset)+0]-ge)*(_-ve)/(Te-ve)+ge&&(E=!E)}H=Y}}return E}getHeightAtTileCoord(f,_){let S=Number.NEGATIVE_INFINITY,E=!0;const D=4*(f+nr)*nr+(_+nr);if(this.partLookup.hasOwnProperty(D)){const z=this.partLookup[D];return z?{height:z.height,hidden:!!(z.flags&$S)}:void 0}for(const z of this.centroidData)f>z.max.x||z.min.x>f||_>z.max.y||z.min.y>_||z.height<=S||this.footprintContainsPoint(f,_,z)&&(S=z.height,this.partLookup[D]=z,E=!!(z.flags&$S));if(S!==Number.NEGATIVE_INFINITY)return{height:S,hidden:E};this.partLookup[D]=void 0}}function hXe(N,f){const _=N.add(f)._unit();return N.x*_.x+N.y*_.y}function QVt(N,f,_,S){const E=f.sub(N)._perp()._unit(),D=_.sub(f)._perp()._unit();return mXe(N,f,_,hXe(E,D),S)}function mXe(N,f,_,S,E){const D=Math.sqrt(1-S*S);return Math.min(N.dist(f)/3,f.dist(_)/3,E*D/S)}function xEe(N,f,_){return N.x<_[0].x&&f.x<_[0].x||N.x>_[1].x&&f.x>_[1].x||N.y<_[0].y&&f.y<_[0].y||N.y>_[1].y&&f.y>_[1].y}function pXe(N,f){return N.xf[1].x||N.yf[1].y}function JVt(N){return N.every(f=>f.x<=0)||N.every(f=>f.x>=nr)||N.every(f=>f.y<=0)||N.every(f=>f.y>=nr)}function fXe(N,f,_){if(N.x<0||N.x>=nr||f.x<0||f.x>=nr||_.x<0||_.x>=nr)return!1;const S=_.sub(f),E=S.perp(),D=N.sub(f);return(S.x*D.x+S.y*D.y)/Math.sqrt((S.x*S.x+S.y*S.y)*(D.x*D.x+D.y*D.y))>-.866&&E.x*D.x+E.y*D.y<0}function xXe(N,f,_){const S=f?2|N:-3&N;return _?1|S:-2&S}function gXe(){const N=Math.PI/32,f=Math.tan(N),_=ms;return _*Math.sqrt(1+2*f*f)-_}function yXe(N,f,_){const S=1<<_.z,E=Es(_.x/S),D=Es((_.x+1)/S),z=hn(_.y/S),H=hn((_.y+1)/S);return function(Y,te,he,ge,ve=0,Te){const Ie=[];if(!Y.length||!he||!ge)return Ie;const Ve=(It,xs)=>{for(const es of It)Ie.push({polygon:es,bounds:xs})},et=Math.ceil(Math.log2(he)),at=Math.ceil(Math.log2(ge)),ft=et-at,ut=[];for(let It=0;It0?0:1);for(let It=0;Itxs+1?Mt.push({polygons:kn,bounds:Sn,depth:xs+1}):Ve(kn,Sn)}if(En.length){const Sn=[new Xs(es===0?xn:ps.x,es===1?xn:ps.y),cs];ut.length>xs+1?Mt.push({polygons:En,bounds:Sn,depth:xs+1}):Ve(En,Sn)}}return Ie}(N,f,Math.ceil((D-E)/11.25),Math.ceil((z-H)/11.25),1,(Y,te,he)=>{if(Y===0)return .5*(te+he);{const ge=hn((_.y+te/nr)/S);return($n(.5*(hn((_.y+he/nr)/S)+ge))*S-_.y)*nr}})}function eHt(N,f,_,S,E,D){const z=Math.pow(2,S.z-E.z);for(let H=0;H<_;H++){let Y=N.int16[2*(H+f)+0],te=N.int16[2*(H+f)+1];Y=(Y+E.x*nr)*z-S.x*nr,te=(te+E.y*nr)*z-S.y*nr,D.push(new Xs(Y,te))}}let vXe,bXe;gr(Xee,"FillExtrusionBucket",{omit:["layers","features"]}),gr(mEe,"PartData"),gr(dXe,"FootprintSegment"),gr(pEe,"BorderCentroidData"),gr(fEe,"GroundEffect");class Z6 extends Xs{constructor(f,_,S){super(f,_),this.z=S}}class _Xe extends Z6{constructor(f,_,S,E){super(f,_,S),this.w=E}}function wXe(N,f,_,S){const E=_==="x"?"y":"x",D=(S-N[_])/(f[_]-N[_]);N[E]=Math.round(N[E]+(f[E]-N[E])*D),N[_]=S,N.hasOwnProperty("z")&&(N.z=xr(N.z,f.z,D)),N.hasOwnProperty("w")&&(N.w=xr(N.w,f.w,D))}function jXe(N,f,_,S){const E=_,D=S;for(const z of["x","y"]){let H=N,Y=f;H[z]>=Y[z]&&(H=f,Y=N),H[z]E&&wXe(H,Y,z,E),H[z]D&&wXe(Y,H,z,D)}}function Qee(N,f,_,S,E,D){const z=[];for(let H=0;H=S&&Ie.x>=S||(Te.x>=S?Te=new Xs(S,Te.y+(S-Te.x)/(Ie.x-Te.x)*(Ie.y-Te.y))._round():Ie.x>=S&&(Ie=new Xs(S,Te.y+(S-Te.x)/(Ie.x-Te.x)*(Ie.y-Te.y))._round()),Te.y>=E&&Ie.y>=E||(Te.y>=E?Te=new Xs(Te.x+(E-Te.y)/(Ie.y-Te.y)*(Ie.x-Te.x),E)._round():Ie.y>=E&&(Ie=new Xs(Te.x+(E-Te.y)/(Ie.y-Te.y)*(Ie.x-Te.x),E)._round()),te&&Te.equals(te[te.length-1])||(te=[Te],z.push(te),D&&D.push({progress:{min:et+NXe(at,ft,Te)*Ve,max:1},parentIndex:H,prevPoint:at,nextPoint:ft})),te.push(Ie),D&&(D[D.length-1].progress.max=et+NXe(at,ft,Ie)*Ve,D[D.length-1].nextPoint=ft)))))}if(D&&ge>0)for(let ve=he;vete.t-he.t);let z=0,H=0,Y=[];for(S.push(Y);z!==N.length;){if(H===D.length){for(;z!==N.length;)Y.length!==0&&Y[Y.length-1].equals(N[z])||Y.push(N[z]),z++;break}D[H].t<=z?(Y.length!==0&&Y[Y.length-1].equals(D[H].point)||Y.push(D[H].point),Math.trunc(D[H].t),H++):(Y.length!==0&&Y[Y.length-1].equals(N[z])||Y.push(N[z]),z++)}}function NXe(N,f,_){return N.x!==f.x?(_.x-N.x)/(f.x-N.x):N.y!==f.y?(_.y-N.y)/(f.y-N.y):0}function CV(N,f){return N.x*f.x+N.y*f.y}function kXe(N,f){if(N.length===1){let _=0;const S=f[_++];let E;for(;!E||S.equals(E);)if(E=f[_++],!E)return 1/0;for(;_{xn[0]=kn,xn[1]=En,xn[2]=Sn,xn[3]=1},mn=gXe();Te>0&&(Te+=mn),Ie+=mn;for(const xn of ve){const kn=[],En=[];for(const Sn of xn){const Gn=Sn.x+Ve.x,dn=Sn.y+Ve.y,An=ge.projection.projectTilePoint(Gn,dn,Mt),Pn=ge.projection.upVector(Mt,Sn.x,Sn.y);let Wn=Te,ir=Ie;if(at){const Ur=AXe(Gn,dn,Te,Ie,at,ft,ut,Nt);Wn+=Ur.base,ir+=Ur.top}Te!==0?ds(ps,An.x+Pn[0]*es*Wn,An.y+Pn[1]*es*Wn,An.z+Pn[2]*es*Wn):ds(ps,An.x,An.y,An.z),ds(cs,An.x+Pn[0]*es*ir,An.y+Pn[1]*es*ir,An.z+Pn[2]*es*ir),Ge(ps,ps,et),Ge(cs,cs,et),kn.push(new Z6(ps[0],ps[1],ps[2])),En.push(new Z6(cs[0],cs[1],cs[2]))}It.push(kn),xs.push(En)}return[It,xs]}(N,f,_,S,E,D,z,H,Y,te,he):z?function(ge,ve,Te,Ie,Ve,et,at,ft,ut){const Nt=[],Mt=[],It=[0,0,0,1];for(const xs of ge){const es=[],ps=[];for(const cs of xs){const ds=cs.x+Ie.x,mn=cs.y+Ie.y,xn=AXe(ds,mn,ve,Te,et,at,ft,ut);It[0]=ds,It[1]=mn,It[2]=xn.base,It[3]=1,dt(It,It,Ve),It[3]=Math.max(It[3],1e-5);const kn=new Z6(It[0]/It[3],It[1]/It[3],It[2]/It[3]);It[0]=ds,It[1]=mn,It[2]=xn.top,It[3]=1,dt(It,It,Ve),It[3]=Math.max(It[3],1e-5);const En=new Z6(It[0]/It[3],It[1]/It[3],It[2]/It[3]);es.push(kn),ps.push(En)}Nt.push(es),Mt.push(ps)}return[Nt,Mt]}(f,_,S,E,D,z,H,Y,te):function(ge,ve,Te,Ie,Ve){const et=[],at=[],ft=Ve[8]*ve,ut=Ve[9]*ve,Nt=Ve[10]*ve,Mt=Ve[11]*ve,It=Ve[8]*Te,xs=Ve[9]*Te,es=Ve[10]*Te,ps=Ve[11]*Te;for(const cs of ge){const ds=[],mn=[];for(const xn of cs){const kn=xn.x+Ie.x,En=xn.y+Ie.y,Sn=Ve[0]*kn+Ve[4]*En+Ve[12],Gn=Ve[1]*kn+Ve[5]*En+Ve[13],dn=Ve[2]*kn+Ve[6]*En+Ve[14],An=Ve[3]*kn+Ve[7]*En+Ve[15],Pn=Sn+ft,Wn=Gn+ut,ir=dn+Nt,Ur=Math.max(An+Mt,1e-5),wr=Sn+It,vr=Gn+xs,or=dn+es,Or=Math.max(An+ps,1e-5);ds.push(new Z6(Pn/Ur,Wn/Ur,ir/Ur)),mn.push(new Z6(wr/Or,vr/Or,or/Or))}et.push(ds),at.push(mn)}return[et,at]}(f,_,S,E,D)}function AXe(N,f,_,S,E,D,z,H){const Y=z*E.getElevationAt(N,f,!0,!0),te=D[0]!==0,he=te?D[1]===0?z*(D[0]/7-450):z*function(ge,ve,Te){const Ie=Math.floor(ve[0]/8),Ve=Math.floor(ve[1]/8),et=10*(ve[0]-8*Ie),at=10*(ve[1]-8*Ve),ft=ge.getElevationAt(Ie,Ve,!0,!0),ut=ge.getMeterToDEM(Te),Nt=Math.floor(.5*(et*ut-1)),Mt=Math.floor(.5*(at*ut-1)),It=ge.tileCoordToPixel(Ie,Ve),xs=2*Nt+1,es=2*Mt+1,ps=function(En,Sn,Gn,dn,An){return[En.getElevationAtPixel(Sn,Gn,!0),En.getElevationAtPixel(Sn+An,Gn,!0),En.getElevationAtPixel(Sn,Gn+An,!0),En.getElevationAtPixel(Sn+dn,Gn+An,!0)]}(ge,It.x-Nt,It.y-Mt,xs,es),cs=Math.abs(ps[0]-ps[1]),ds=Math.abs(ps[2]-ps[3]),mn=Math.abs(ps[0]-ps[2])+Math.abs(ps[1]-ps[3]),xn=Math.min(.25,.5*ut*(cs+ds)/xs),kn=Math.min(.25,.5*ut*mn/es);return ft+Math.max(xn*et,kn*at)}(E,D,H):Y;return{base:Y+(_===0?-1:_),top:te?Math.max(he+S,Y+_+2):Y+S}}const gEe=4096;class sHt{constructor(f){this.module=f,this.memoryStack=this.module.malloc(gEe),this.memoryStackNextFree=this.memoryStack}createIntArray(f){const _=this.memoryStackNextFree;return this.memoryStackNextFree+=f.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>gEe?-1:(new Int32Array(this.module.heap32.buffer,_,f.length).set(f),_)}createFloatArray(f){const _=this.memoryStackNextFree;return this.memoryStackNextFree+=f.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>gEe?-1:(new Float32Array(this.module.heapF32.buffer,_,f.length).set(f),_)}readStringBuffer(f){let _="";for(;this.module.heapU8[f]!==0;)_+=String.fromCharCode(this.module.heapU8[f]),++f;return _}setStyle(f){const _=f.normalScale;this.module.setStyle(_[0],_[1],_[2],f.tileToMeters)}setAOOptions(f,_){this.module.setAOOptions(f?1:0,_)}setMetricOptions(f,_){this.module.setMetricOptions(f?1:0,_)}setStructuralOptions(f){this.module.setStructuralOptions(f?1:0)}setFacadeOptions(f,_){this.module.setFacadeOptions(f,_?1:0)}setFauxFacadeOptions(f,_,S){this.module.setFauxFacadeOptions(f?1:0,_?1:0,S)}setFacadeClassifierOptions(f){this.module.setFacadeClassifierOptions(f)}generateMesh(f,_){this.memoryStackNextFree=this.memoryStack;for(const H of f){const Y=this.createIntArray(H.ringIndices),te=this.createFloatArray(H.coordinates);if(Y===-1||te===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(H.id,H.sourceId,H.minHeight,H.height,H.roofType,te,Y,H.ringIndices.length-1)}for(const H of _){let Y;Y=H.entrances?JSON.parse(H.entrances):[];const te=this.createFloatArray(Y),he=this.createFloatArray(H.coordinates);if(te===-1||he===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(H.sourceId,H.crossPerc,H.distanceToRoad,te,Y.length,he,H.coordinates.length)}if(!this.module.generateMesh()){const H=this.module.getLastError();return this.readStringBuffer(H)}const S=this.module.getMeshCount(),E=new Array(S);for(let H=0;H>2)-3,et=Te[Ie++]>>2;if(Ie++,E.json=JSON.parse(FXe.decode(Te.subarray(Ie,Ie+et))),Ie+=et,Ie>>0,Math.ceil(1.2*Nt)),It=Math.ceil((Mt-Nt)/65536);try{return Ve.grow(It),et(),!0}catch{return!1}},b:at}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(Te,ft):Te.then(ut=>ut.arrayBuffer()).then(ut=>WebAssembly.instantiate(ut,ft))).then(ut=>{const{Rb:Nt,Qb:Mt,P:It,T:xs,X:es,Ja:ps,La:cs,Qa:ds,Va:mn,Wa:xn,eb:kn,jb:En,f:Sn,e:Gn,yb:dn,zb:An,Ab:Pn,Bb:Wn,Db:ir,Gb:Ur}=ut.instance.exports;Ve=Gn;const wr=(()=>{let vr=0,or=0,Or=0,sa=0;return Ta=>{Or&&(Nt(sa),Nt(vr),or+=Or,Or=vr=0),vr||(or+=128,vr=Mt(or));const ya=Ta.length+7&-8;let xi=vr;ya>=or&&(Or=ya,xi=sa=Mt(ya));for(let jo=0;jo{m2=Te,AV=void 0}))}()),ve&&he.push(function(){if(yEe)return;const Te=function(Ie){let Ve;const et=WebAssembly.instantiateStreaming(Ie,{}).then(ut=>{Ve=ut.instance,Ve.exports.__wasm_call_ctors()}),at={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},ft={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:et,supported:!0,decodeGltfBuffer(ut,Nt,Mt,It,xs,es){(function(ps,cs,ds,mn,xn,kn,En){const Sn=ps.exports.sbrk,Gn=mn+3&-4,dn=Sn(Gn*xn),An=Sn(kn.length),Pn=new Uint8Array(ps.exports.memory.buffer);Pn.set(kn,An);const Wn=cs(dn,mn,xn,An,kn.length);if(Wn===0&&En&&En(dn,Gn,xn),ds.set(Pn.subarray(dn,dn+mn*xn)),Sn(dn-Sn(0)),Wn!==0)throw new Error(`Malformed buffer data: ${Wn}`)})(Ve,Ve.exports[ft[xs]],ut,Nt,Mt,It,Ve.exports[at[es]])}}}(fetch(qa()));return Te.ready.then(()=>{yEe=Te})}()),z)for(let Te=0;Te{const H=np(S,(Y,te)=>{Y?z(Y):D(te)});E&&E.addEventListener("abort",()=>{H.cancel(),z(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:N,type:"arrayBuffer"},f);return $Xe(_,0,N,f)}function bEe(N){switch(N){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 _Ee(N){switch(N){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 pk{constructor(f,_,S,E){this.context=f,this.format=S,this.useMipmap=E&&E.useMipmap,this.texture=f.gl.createTexture(),this.update(_,{premultiply:E&&E.premultiply})}update(f,_){const S=f&&f instanceof HTMLVideoElement&&f.width===0?f.videoWidth:f.width,E=f&&f instanceof HTMLVideoElement&&f.height===0?f.videoHeight:f.height,{context:D}=this,{gl:z}=D,{x:H,y:Y}=_&&_.position?_.position:{x:0,y:0},te=H+S,he=Y+E;this.size&&(this.size[0]!==te||this.size[1]!==he)&&(!_||_.recreateWhenResize===void 0||_.recreateWhenResize)&&(z.bindTexture(z.TEXTURE_2D,null),z.deleteTexture(this.texture),this.texture=z.createTexture(),this.size=null),z.bindTexture(z.TEXTURE_2D,this.texture),D.pixelStoreUnpackFlipY.set(!1),D.pixelStoreUnpack.set(1),D.pixelStoreUnpackPremultiplyAlpha.set(this.format===z.RGBA8&&(!_||_.premultiply!==!1));const ge=f instanceof HTMLImageElement||f instanceof HTMLCanvasElement||f instanceof HTMLVideoElement||f instanceof ImageData||ImageBitmap&&f instanceof ImageBitmap;if(!this.size&&te>0&&he>0){const ve=this.useMipmap?Math.floor(Math.log2(Math.max(te,he)))+1:1;z.texStorage2D(z.TEXTURE_2D,ve,this.format,te,he),this.size=[te,he]}this.size&&(ge?z.texSubImage2D(z.TEXTURE_2D,0,H,Y,bEe(this.format),_Ee(this.format),f):"data"in f&&f.data&&z.texSubImage2D(z.TEXTURE_2D,0,H,Y,S,E,bEe(this.format),_Ee(this.format),f.data)),this.useMipmap&&z.generateMipmap(z.TEXTURE_2D)}bind(f,_,S=!1){const{context:E}=this,{gl:D}=E;D.bindTexture(D.TEXTURE_2D,this.texture),f!==this.minFilter&&(D.texParameteri(D.TEXTURE_2D,D.TEXTURE_MAG_FILTER,f),D.texParameteri(D.TEXTURE_2D,D.TEXTURE_MIN_FILTER,this.useMipmap&&!S?f===D.NEAREST?D.NEAREST_MIPMAP_NEAREST:D.LINEAR_MIPMAP_LINEAR:f),this.minFilter=f),_!==this.wrapS&&(D.texParameteri(D.TEXTURE_2D,D.TEXTURE_WRAP_S,_),D.texParameteri(D.TEXTURE_2D,D.TEXTURE_WRAP_T,_),this.wrapS=_)}bindExtraParam(f,_,S,E,D){const{context:z}=this,{gl:H}=z;H.bindTexture(H.TEXTURE_2D,this.texture),_!==this.magFilter&&(H.texParameteri(H.TEXTURE_2D,H.TEXTURE_MAG_FILTER,_),this.magFilter=_),f!==this.minFilter&&(H.texParameteri(H.TEXTURE_2D,H.TEXTURE_MIN_FILTER,this.useMipmap?f===H.NEAREST?H.NEAREST_MIPMAP_NEAREST:H.LINEAR_MIPMAP_LINEAR:f),this.minFilter=f),S!==this.wrapS&&(H.texParameteri(H.TEXTURE_2D,H.TEXTURE_WRAP_S,S),this.wrapS=S),E!==this.wrapT&&(H.texParameteri(H.TEXTURE_2D,H.TEXTURE_WRAP_T,E),this.wrapT=E),D!==this.compareMode&&(D?(H.texParameteri(H.TEXTURE_2D,H.TEXTURE_COMPARE_MODE,H.COMPARE_REF_TO_TEXTURE),H.texParameteri(H.TEXTURE_2D,H.TEXTURE_COMPARE_FUNC,D)):H.texParameteri(H.TEXTURE_2D,H.TEXTURE_COMPARE_MODE,H.NONE),this.compareMode=D)}destroy(){const{gl:f}=this.context;f.deleteTexture(this.texture),this.texture=null}}class EV{constructor(f,_){this.context=f,this.texture=_}bind(f,_){const{context:S}=this,{gl:E}=S;E.bindTexture(E.TEXTURE_2D,this.texture),f!==this.minFilter&&(E.texParameteri(E.TEXTURE_2D,E.TEXTURE_MAG_FILTER,f),E.texParameteri(E.TEXTURE_2D,E.TEXTURE_MIN_FILTER,f),this.minFilter=f),_!==this.wrapS&&(E.texParameteri(E.TEXTURE_2D,E.TEXTURE_WRAP_S,_),E.texParameteri(E.TEXTURE_2D,E.TEXTURE_WRAP_T,_),this.wrapS=_)}}const cHt=Fn([{name:"a_pos_3f",components:3,type:"Float32"}]),dHt=Fn([{name:"a_color_3f",components:3,type:"Float32"}]),uHt=Fn([{name:"a_color_4f",components:4,type:"Float32"}]),hHt=Fn([{name:"a_uv_2f",components:2,type:"Float32"}]),mHt=Fn([{name:"a_normal_3f",components:3,type:"Float32"}]),pHt=Fn([{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"}]),fHt=Fn([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function qXe(N,f){const _=ste(N.projection,N.zoom,N.width,N.height),S=function(D,z,H,Y,te){const he=new Cs(H.lng-180*_C,H.lat),ge=new Cs(H.lng+180*_C,H.lat),ve=D.project(he.lng,he.lat),Te=D.project(ge.lng,ge.lat),Ie=-Math.atan2(Te.y-ve.y,Te.x-ve.x),Ve=ta.fromLngLat(H);Ve.y=it(Ve.y,-1+_C,1-_C);const et=Ve.toLngLat(),at=D.project(et.lng,et.lat),ft=ta.fromLngLat(et);ft.x+=_C;const ut=ft.toLngLat(),Nt=D.project(ut.lng,ut.lat),Mt=HXe(Nt.x-at.x,Nt.y-at.y,Ie),It=ta.fromLngLat(et);It.y+=_C;const xs=It.toLngLat(),es=D.project(xs.lng,xs.lat),ps=HXe(es.x-at.x,es.y-at.y,Ie),cs=Math.abs(Mt.x)/Math.abs(ps.y),ds=g([]);P(ds,ds,-Ie*(1-(te?0:Y)));const mn=g([]);return C(mn,mn,[1,1-(1-cs)*Y,1]),mn[4]=-ps.x/ps.y*Y,P(mn,mn,Ie),v(mn,ds,mn),mn}(N.projection,0,N.center,_,f),E=VXe(N);return C(S,S,[E,E,1]),S}function VXe(N){const f=N.projection,_=ste(N.projection,N.zoom,N.width,N.height),S=wEe(f,N.center),E=wEe(f,Cs.convert(f.center));return Math.pow(2,S*_+(1-_)*E)}function ste(N,f,_,S,E=1/0){const D=N.range;if(!D)return 0;const z=Math.min(E,Math.max(_,S)),H=Math.log2(z/1024);return gt(D[0]+H,D[1]+H,f)}const _C=1/4e4;function wEe(N,f){const _=it(f.lat,-85.051129,jn),S=new Cs(f.lng-180*_C,_),E=new Cs(f.lng+180*_C,_),D=N.project(S.lng,_),z=N.project(E.lng,_),H=ta.fromLngLat(S),Y=ta.fromLngLat(E),te=z.x-D.x,he=z.y-D.y,ge=Y.x-H.x,ve=Y.y-H.y,Te=Math.sqrt((ge*ge+ve*ve)/(te*te+he*he));return Math.log2(Te)}function HXe(N,f,_){const S=Math.cos(_),E=Math.sin(_);return{x:N*S-f*E,y:N*E+f*S}}function GXe(N,f,_){g(N),P(N,N,pr(f[2])),T(N,N,pr(f[0])),M(N,N,pr(f[1])),C(N,N,_),v(N,N,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function nte(N,f,_,S,E,D,z,H){const Y=[_[0]-f[0],_[1]-f[1],0],te=[S[0]-f[0],S[1]-f[1],0];if(K(Y)<1e-12||K(te)<1e-12)return pt(N);const he=Be([],Y,te);Le(he,he),ue(te,S,f),Y[2]=(D-E)*H,te[2]=(z-E)*H;const ge=Y;return Be(ge,Y,te),Le(ge,ge),Is(N,he,ge)}function rte(N,f,_=!1){const S=zS(f.zoom),E=function(D,z,H){const Y=z.worldSize,te=[D[12],D[13],D[14]],he=hn(te[1]/Y),ge=Es(te[0]/Y),ve=g([]),Te=Ys(1,he)*Y,Ie=Ys(1,0)*Y*rr(he,z.zoom),Ve=1/WTe(Y);let et=Ie*Ve;if(H){const Nt=ste(z.projection,z.zoom,z.width,z.height,1024);et=Ve*z.projection.pixelSpaceConversion(z.center.lat,Y,Nt)}const at=Xt(he,ge);le(at,at,we([],Le([],at),Te*et*te[2]));const ft=function(Nt){const Mt=[Nt[0],Nt[1],Nt[2]];let It=[0,1,0];const xs=Be([],It,Mt);return Be(It,Mt,xs),Se(It)===0&&(It=[0,1,0],Be(xs,Mt,It)),Le(xs,xs),Le(It,It),Le(Mt,Mt),[xs[0],xs[1],xs[2],0,It[0],It[1],It[2],0,Mt[0],Mt[1],Mt[2],0,Nt[0],Nt[1],Nt[2],1]}(at);C(ve,ve,[et,et,et*Te]),k(ve,ve,[-te[0],-te[1],-te[2]]);const ut=v([],z.globeMatrix,ft);return v(ut,ut,ve),v(ut,ut,D),ut}(N,f,_);if(S>0){const D=function(z,H){const Y=H.worldSize,te=Ys(1,0)*Y*rr(H.center.lat,H.zoom)/WTe(Y),he=Ys(1,H.center.lat)*Y,ge=g([]);M(ge,ge,pr(H.center.lng)),T(ge,ge,pr(H.center.lat)),k(ge,ge,[0,0,$t]),C(ge,ge,[te,te,te*he]);const ve=H.point;return k(ge,ge,[-ve.x,-ve.y,0]),v(ge,ge,z),v(ge,H.globeMatrix,ge)}(N,f);return function(z,H,Y){const te=(Ie,Ve,et)=>{const at=K(Ie),ft=K(Ve),ut=FS(Ie,Ve,et);return we(ut,ut,1/K(ut)*xr(at,ft,et))},he=te([z[0],z[1],z[2]],[H[0],H[1],H[2]],Y),ge=te([z[4],z[5],z[6]],[H[4],H[5],H[6]],Y),ve=te([z[8],z[9],z[10]],[H[8],H[9],H[10]],Y),Te=FS([z[12],z[13],z[14]],[H[12],H[13],H[14]],Y);return[he[0],he[1],he[2],0,ge[0],ge[1],ge[2],0,ve[0],ve[1],ve[2],0,Te[0],Te[1],Te[2],1]}(E,D,S)}return E}function jEe(N,f,_,S){const E=al.projectAabbCorners(S,_);let D=Number.MAX_VALUE;for(let H=0;H0||et===0&&Ie[0]*Ve[0]+Ie[1]*Ve[1]>=0&&Ie[0]*Ie[0]+Ie[1]*Ie[1]>Ve[0]*Ve[0]+Ve[1]*Ve[1])&&(he=Te)}ge=he}while(ge!==te);return Y.length>0&&Y.push(Y[0]),Y}(E);if(_u(N,z))return D}const X6=64,cF={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function ate(N,f,_,S,E,D,z,H,Y,te=!1){const he=_.zoom,ge=_.project(S),ve=rr(S.lat,he),Te=1/ve;g(N),k(N,N,[ge.x+z[0]*Te,ge.y+z[1]*Te,z[2]]);let Ie=1,Ve=1;const et=_.worldSize;if(te){if(_.projection.name==="mercator"){let Nt=0;_.elevation&&(Nt=_.elevation.getAtPointOrZero(new ta(ge.x/et,ge.y/et),0));const Mt=dt([],[ge.x,ge.y,Nt,1],_.projMatrix)[3]/_.cameraToCenterDistance;Ie=Mt,Ve=Mt*rr(_.center.lat,he)}else if(_.projection.name==="globe"){const Nt=rte(N,_),Mt=[0,0,0,1];dt(Mt,Mt,v([],_.projMatrix,Nt));const It=Mt[3]/_.cameraToCenterDistance,xs=zS(he),es=_.projection.pixelsPerMeter(S.lat,et)*rr(S.lat,he),ps=_.projection.pixelsPerMeter(_.center.lat,et)*rr(_.center.lat,he);Ie=It/xr(es,yr(_.center.lat),xs),Ve=It*ve/es,Ie*=ps,Ve*=ps}}else Ie=Te;C(N,N,[Ie,Ie,Ve]);const at=[...N],ft=f.orientation,ut=[];if(GXe(ut,[ft[0]+(E?E[0]:0),ft[1]+(E?E[1]:0),ft[2]+(E?E[2]:0)],D),v(N,at,ut),H&&_.elevation){let Nt=0;const Mt=[];if(Y&&_.elevation){Nt=function(xs,es,ps,cs,ds){const mn=es.elevation;if(!mn)return 0;const xn=al.projectAabbCorners(ps,cs),kn=Ys(1,ds.lat)*es.worldSize,En=function(or,Or){const sa=[0,0,1],Ta=[{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 ya of Ta){const xi=or[ya.corners[0]],jo=or[ya.corners[1]],gi=or[ya.corners[2]],Ao=[jo[0]-xi[0],jo[1]-xi[1],Or*(jo[2]-xi[2])],Di=Be(Ao,Ao,[gi[0]-xi[0],gi[1]-xi[1],Or*(gi[2]-xi[2])]);Le(Di,Di),ya.dotProductWithUp=De(Di,sa)}return Ta.sort((ya,xi)=>ya.dotProductWithUp-xi.dotProductWithUp),Ta[0].corners}(xn,kn),Sn=xn[En[0]],Gn=xn[En[1]],dn=xn[En[2]],An=xn[En[3]],Pn=mn.getAtPointOrZero(new ta(Sn[0]/es.worldSize,Sn[1]/es.worldSize),0),Wn=mn.getAtPointOrZero(new ta(Gn[0]/es.worldSize,Gn[1]/es.worldSize),0),ir=mn.getAtPointOrZero(new ta(dn[0]/es.worldSize,dn[1]/es.worldSize),0),Ur=mn.getAtPointOrZero(new ta(An[0]/es.worldSize,An[1]/es.worldSize),0),wr=(Pn+Ur)/2,vr=(Wn+ir)/2;return wr>vr?Wn=f.gl.NEAREST_MIPMAP_NEAREST}),N.uploaded=!0,N.image=null)}function xHt(N,f,_){N.indexBuffer=f.createIndexBuffer(N.indexArray,!1,!0),N.vertexBuffer=f.createVertexBuffer(N.vertexArray,cHt.members,!1,!0),N.normalArray&&(N.normalBuffer=f.createVertexBuffer(N.normalArray,mHt.members,!1,!0)),N.texcoordArray&&(N.texcoordBuffer=f.createVertexBuffer(N.texcoordArray,hHt.members,!1,!0)),N.colorArray&&(N.colorBuffer=f.createVertexBuffer(N.colorArray,(N.colorArray.bytesPerElement===12?dHt:uHt).members,!1,!0)),N.featureArray&&(N.pbrBuffer=f.createVertexBuffer(N.featureArray,fHt.members,!0)),N.segments=Gl.simpleSegment(0,0,N.vertexArray.length,N.indexArray.length);const S=N.material;S.pbrMetallicRoughness.baseColorTexture&&MV(S.pbrMetallicRoughness.baseColorTexture,f),S.pbrMetallicRoughness.metallicRoughnessTexture&&MV(S.pbrMetallicRoughness.metallicRoughnessTexture,f),S.normalTexture&&MV(S.normalTexture,f),S.occlusionTexture&&MV(S.occlusionTexture,f,_),S.emissionTexture&&MV(S.emissionTexture,f)}function NEe(N,f,_){if(N.meshes)for(const S of N.meshes)xHt(S,f,_);if(N.children)for(const S of N.children)NEe(S,f,_)}function ite(N){if(N.meshes)for(const f of N.meshes)f.indexArray.destroy(),f.vertexArray.destroy(),f.colorArray&&f.colorArray.destroy(),f.normalArray&&f.normalArray.destroy(),f.texcoordArray&&f.texcoordArray.destroy(),f.featureArray&&f.featureArray.destroy();if(N.children)for(const f of N.children)ite(f)}function gHt(N){N.pbrMetallicRoughness.baseColorTexture&&N.pbrMetallicRoughness.baseColorTexture.gfxTexture&&N.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),N.pbrMetallicRoughness.metallicRoughnessTexture&&N.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&N.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),N.normalTexture&&N.normalTexture.gfxTexture&&N.normalTexture.gfxTexture.destroy(),N.emissionTexture&&N.emissionTexture.gfxTexture&&N.emissionTexture.gfxTexture.destroy(),N.occlusionTexture&&N.occlusionTexture.gfxTexture&&N.occlusionTexture.gfxTexture.destroy()}function kEe(N){if(N.meshes)for(const f of N.meshes)f.vertexBuffer&&(f.vertexBuffer.destroy(),f.indexBuffer.destroy(),f.normalBuffer&&f.normalBuffer.destroy(),f.texcoordBuffer&&f.texcoordBuffer.destroy(),f.colorBuffer&&f.colorBuffer.destroy(),f.pbrBuffer&&f.pbrBuffer.destroy(),f.segments.destroy(),f.material&&gHt(f.material));if(N.footprintDebugMesh&&(N.footprintDebugMesh.vertexBuffer.destroy(),N.footprintDebugMesh.indexBuffer.destroy(),N.footprintDebugMesh.segments.destroy()),N.children)for(const f of N.children)kEe(f)}function Q6(N,f){const _=N.json.bufferViews[f.bufferView],S=ete[f.componentType];return new S(N.buffers[_.buffer],(f.byteOffset||0)+(_.byteOffset||0),f.count*(_.byteStride&&_.byteStride!==TV[f.type]*S.BYTES_PER_ELEMENT?_.byteStride/S.BYTES_PER_ELEMENT:TV[f.type]))}function SEe(N,f,_,S){const E=ete[f.componentType],D=function(he){switch(he){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(E),z=N.json.bufferViews[f.bufferView],H=z.byteStride?z.byteStride/E.BYTES_PER_ELEMENT:TV[f.type],Y=_.float32,te=Y.length/_.capacity;for(let he=0,ge=0;he0){for(let et=0;et0){D.texcoordArray=new IS;const ve=f.json.accessors[E.TEXCOORD_0];D.texcoordArray.resize(ve.count);const Te=Q6(f,ve);SEe(f,ve,D.texcoordArray,Te)}if(E._FEATURE_ID_RGBA4444!==void 0){const ve=f.json.accessors[E._FEATURE_ID_RGBA4444];f.json.extensionsUsed&&f.json.extensionsUsed.includes("EXT_meshopt_compression")&&(D.featureData=Q6(f,ve))}E._FEATURE_RGBA4444!==void 0&&(D.featureData=new Uint32Array(Q6(f,f.json.accessors[E._FEATURE_RGBA4444]).buffer));const ge=N.material;return D.material=function(ve,Te){const{emissiveFactor:Ie=[0,0,0],alphaMode:Ve="OPAQUE",alphaCutoff:et=.5,normalTexture:at,occlusionTexture:ft,emissiveTexture:ut,doubleSided:Nt,name:Mt}=ve,{baseColorFactor:It=[1,1,1,1],metallicFactor:xs=1,roughnessFactor:es=1,baseColorTexture:ps,metallicRoughnessTexture:cs}=ve.pbrMetallicRoughness||{},ds=ft?Te[ft.index]:void 0;if(ft&&ft.extensions&&ft.extensions.KHR_texture_transform&&ds){const mn=ft.extensions.KHR_texture_transform;ds.offsetScale=[mn.offset[0],mn.offset[1],mn.scale[0],mn.scale[1]]}return{name:Mt,pbrMetallicRoughness:{baseColorFactor:new us(...It),metallicFactor:xs,roughnessFactor:es,baseColorTexture:ps?Te[ps.index]:void 0,metallicRoughnessTexture:cs?Te[cs.index]:void 0},doubleSided:Nt,emissiveFactor:new us(...Ie),alphaMode:Ve,alphaCutoff:et,normalTexture:at?Te[at.index]:void 0,occlusionTexture:ds,emissionTexture:ut?Te[ut.index]:void 0,defined:ve.defined===void 0}}(ge!==void 0?f.json.materials[ge]:{defined:!1},_),D}function KXe(N,f,_){const{matrix:S,rotation:E,translation:D,scale:z,mesh:H,extras:Y,children:te,name:he}=N,ge={};if(ge.name=he,ge.localMatrix=S||function(ve,Te,Ie,Ve){var et=Te[0],at=Te[1],ft=Te[2],ut=Te[3],Nt=et+et,Mt=at+at,It=ft+ft,xs=et*Nt,es=et*Mt,ps=et*It,cs=at*Mt,ds=at*It,mn=ft*It,xn=ut*Nt,kn=ut*Mt,En=ut*It,Sn=Ve[0],Gn=Ve[1],dn=Ve[2];return ve[0]=(1-(cs+mn))*Sn,ve[1]=(es+En)*Sn,ve[2]=(ps-kn)*Sn,ve[3]=0,ve[4]=(es-En)*Gn,ve[5]=(1-(xs+mn))*Gn,ve[6]=(ds+xn)*Gn,ve[7]=0,ve[8]=(ps+kn)*dn,ve[9]=(ds-xn)*dn,ve[10]=(1-(xs+cs))*dn,ve[11]=0,ve[12]=Ie[0],ve[13]=Ie[1],ve[14]=Ie[2],ve[15]=1,ve}([],E||[0,0,0,1],D||[0,0,0],z||[1,1,1]),ge.globalMatrix=y(ge.localMatrix),H!==void 0){ge.meshes=_[H];const ve=ge.anchor=[0,0];for(const Te of ge.meshes){const{min:Ie,max:Ve}=Te.aabb;ve[0]+=Ie[0]+Ve[0],ve[1]+=Ie[1]+Ve[1]}ve[0]=Math.floor(ve[0]/ge.meshes.length/2),ve[1]=Math.floor(ve[1]/ge.meshes.length/2)}if(Y&&(Y.id&&(ge.id=Y.id),Y.lights&&(ge.lights=function(ve){if(!ve.length)return[];const Te=function(ft){const ut=atob(ft),Nt=new Uint8Array(ut.length);for(let Mt=0;Mt1&&S[S.length-1].equals(S[0])&&S.pop();let E=0;for(let z=0;z0&&S.reverse();const D=rF(S.flatMap(z=>[z.x,z.y]),[]);return D.length===0?null:{vertices:S,indices:D}}function _Ht(N,f){const _=[],S=[];let E=0;const D=[];for(const z of N){E=_.length;const H=z.vertexArray.float32,Y=z.indexArray.uint16;for(let te=0;te0&&([S[z+1],S[z+2]]=[S[z+2],S[z+1]])}return{vertices:_,indices:S}}function CEe(N){const f=function(Y,te){const he=[],ge=WebGL2RenderingContext;if(Y.json.textures)for(const ve of Y.json.textures){const Te={magFilter:ge.LINEAR,minFilter:ge.NEAREST,wrapS:ge.REPEAT,wrapT:ge.REPEAT};ve.sampler!==void 0&&Object.assign(Te,Y.json.samplers[ve.sampler]),he.push({image:te[ve.source],sampler:Te,uploaded:!1})}return he}(N,N.images),_=function(Y,te){const he=[];for(const ge of Y.json.meshes){const ve=[];for(const Te of ge.primitives)ve.push(yHt(Te,Y,te));he.push(ve)}return he}(N,f),{scenes:S,scene:E,nodes:D}=N.json,z=S?S[E||0].nodes:[...D.keys()],H=[];for(const Y of z)H.push(KXe(D[Y],N,_));return function(Y,te,he){const ge={},ve=new Set;for(let Te=0;Te0){const Te=Array.from(ve.values()).sort((Ie,Ve)=>Ie-Ve);for(let Ie=Te.length-1;Ie>=0;Ie--)Y.splice(Te[Ie],1)}}(H,z,N.json.nodes),H}function wHt(N){N.heightmap=new Float32Array(4096),N.heightmap.fill(-1);const f=N.vertexArray.float32,_=N.aabb.min[0]-1,S=N.aabb.min[1]-1,E=X6/(N.aabb.max[0]-_+2),D=X6/(N.aabb.max[1]-S+2);for(let z=0;zN.heightmap[te*X6+Y]&&(N.heightmap[te*X6+Y]=H)}}function YXe(N,f,_,S,E){_.reserve(_.length+4*N.length),S.reserve(S.length+10*N.length),E.reserve(E.length+10*N.length);let D=S.length;for(const z of N){const H=Math.min(10,Math.max(4,1.3*z.height))*f,Y=[-z.normal[1],z.normal[0],0],te=Math.min(.29,.1*z.width/z.depth),he=z.width-2*z.depth*f*(te+.01),ge=je([],z.pos,Y,he/2),ve=je([],z.pos,Y,-he/2),Te=[ge[0],ge[1],ge[2]+z.height],Ie=[ve[0],ve[1],ve[2]+z.height],Ve=je([],z.normal,Y,te);we(Ve,Ve,H);const et=je([],z.normal,Y,-te);we(et,et,H),le(Ve,ge,Ve),le(et,ve,et),ge[2]+=.1,ve[2]+=.1,S.emplaceBack(Ve[0],Ve[1],Ve[2]),S.emplaceBack(et[0],et[1],et[2]),S.emplaceBack(ge[0],ge[1],ge[2]),S.emplaceBack(ve[0],ve[1],ve[2]),S.emplaceBack(Te[0],Te[1],Te[2]),S.emplaceBack(Ie[0],Ie[1],Ie[2]),S.emplaceBack(ge[0],ge[1],ge[2]),S.emplaceBack(ve[0],ve[1],ve[2]),S.emplaceBack(Ve[0],Ve[1],Ve[2]),S.emplaceBack(et[0],et[1],et[2]);const at=he/H/2;E.emplaceBack(-at-te,-1,at,.8),E.emplaceBack(at+te,-1,at,.8),E.emplaceBack(-at,0,at,1.3),E.emplaceBack(at,0,at,1.3),E.emplaceBack(at+te,-.8,at,.7),E.emplaceBack(at+te,-.8,at,.7),E.emplaceBack(0,0,at,1.3),E.emplaceBack(0,0,at,1.3),E.emplaceBack(at+te,-1.2,at,.8),E.emplaceBack(at+te,-1.2,at,.8),_.emplaceBack(6+D,4+D,8+D),_.emplaceBack(7+D,9+D,5+D),_.emplaceBack(0+D,1+D,2+D),_.emplaceBack(1+D,3+D,2+D),D+=10}}function jHt(N,f){const _={};_.indexArray=new eu,_.vertexArray=new R1,_.colorArray=new u2,YXe(N,f,_.indexArray,_.vertexArray,_.colorArray);const S={defined:!0};S.emissiveFactor=us.black;const E={};return E.baseColorFactor=us.white,S.pbrMetallicRoughness=E,_.material=S,_.aabb=new al([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),_}const ZXe=Fn([{name:"a_pos_3f",components:3,type:"Float32"}]),NHt=Fn([{name:"a_normal_3",components:3,type:"Int16"}]),kHt=Fn([{name:"a_centroid_3",components:3,type:"Int16"}]),XXe=Fn([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),SHt=Fn([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),CHt=Fn([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),AHt=Fn([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),THt=Fn([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),EHt=Fn([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),QXe=ri.types,ote=32767;function MHt(N,f){const _=nr+f;for(const S of N)for(const E of S)if(E.x<-f||E.x>_||E.y<-f||E.y>_)return!1;return!0}function LHt(N){switch(N){case"flat":return 3;case"hipped":return 1;case"gabled":return 2;case"parapet":return 0;case"mansard":return 4;case"skillion":return 5;case"pyramidal":return 6;default:throw new Error(`Unknown roof shape: ${N}`)}}class AEe{constructor(){this.layoutVertexArray=new R1,this.layoutAttenuationArray=new u2,this.layoutColorArray=new D1,this.indexArray=new eu,this.indexArrayForConflation=new eu,this.segmentsBucket=new Gl}}class TEe{constructor(f){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Gl,this.entranceBloom=new AEe;const _=66560;this.layoutVertexArray=new R1,this.layoutVertexArray.reserve(_),this.layoutNormalArray=new Uo,this.layoutNormalArray.reserve(_),this.layoutCentroidArray=new Uo,this.layoutCentroidArray.reserve(_),this.layoutColorArray=new D1,this.layoutColorArray.reserve(_),this.layoutFloodLightDataArray=new QO,this.layoutFloodLightDataArray.reserve(_),this.layoutAOArray=new JO,this.layoutAOArray.reserve(_),this.indexArray=new eu,this.indexArray.reserve(66560),this.indexArrayForConflation=new eu,this.segmentsBucket=new Gl,this.entranceBloom=new AEe,f&&(this.layoutFacadePaintArray=new D1,this.layoutFacadeDataArray=new pC,this.layoutFacadeVerticalRangeArray=new D1)}reserve(f,_,S){this.layoutVertexArray.reserveForAdditional(f),this.layoutCentroidArray.reserveForAdditional(f),this.layoutFloodLightDataArray.reserveForAdditional(f),this.layoutNormalArray.reserveForAdditional(f),this.layoutAOArray.reserveForAdditional(f),this.layoutColorArray.reserveForAdditional(f),this.indexArray.reserveForAdditional(_),S&&(this.layoutFacadePaintArray.reserveForAdditional(f),this.layoutFacadeDataArray.reserveForAdditional(f),this.layoutFacadeVerticalRangeArray.reserveForAdditional(f))}}class JXe{constructor(f){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new IS,this.footprintsIndices=new RS,this.footprintsMin=new Xs(1/0,1/0),this.footprintsMax=new Xs(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new TEe(!1),this.buildingWithFacade=new TEe(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=f.zoom,this.canonical=f.canonical,this.layers=f.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=f.index,this.hasPattern=!1,this.worldview=f.worldview,this.lut=f.lut,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.lut}),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.projection=f.projection,this.groundEffect=new fEe(f),this.groundEffect.groundRadiusArray=new dl,this.hasAppearances=null}updateFootprints(f,_){const S=new Vee([],[],1),E={vertices:[],indices:new Uint32Array(0),grid:S,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};_.push({footprint:E,id:f})}updateAppearances(f,_,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(Jee!=null||TXe!=null)return null;if(lF!=null)return lF;const f=fetch(xo());return lF=function(_){let S,E,D,z,H;function Y(){S=new Uint8Array(H.buffer),E=new Int16Array(H.buffer),D=new Int32Array(H.buffer),z=new Float32Array(H.buffer)}function te(){throw new Error("Unexpected BuildingGen error.")}const he=()=>{},ge={a:{a:te,f:function(ve){const Te=S.length,Ie=Math.max(ve>>>0,Math.ceil(1.2*Te)),Ve=Math.ceil((Ie-Te)/65536);try{return H.grow(Ve),Y(),!0}catch{return!1}},g:te,b:he,c:he,d:he,e:he}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(_,ge):_.then(ve=>ve.arrayBuffer()).then(ve=>WebAssembly.instantiate(ve,ge))).then(ve=>{const Te=ve.instance.exports;return(0,Te.g)(),H=Te.f,Y(),new sHt({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:D,heapF32:z})})}(f).then(_=>(lF=null,Jee=_,Jee)).catch(_=>{Mr("Could not load building-gen"),lF=null,TXe=_ instanceof Error?_:new Error("Unknown error")}),lF}()}populate(f,_,S,E){const D=nHt();if(!D)return;const z=zn(S);this.tileToMeter=z,this.brightness=_.brightness,D.setStyle({normalScale:[1,-1,z],tileToMeters:z}),D.setAOOptions(!1,.3),D.setMetricOptions(!1,16),D.setStructuralOptions(!0),D.setFacadeClassifierOptions(3);const H=new Map,Y=new Map;let te=0;for(const{feature:at}of f){if(QXe[at.type]!=="LineString"){H.set(at.id,at.properties.source_id);continue}const ft=this.layers[0]._featureFilter.needGeometry;if(ft&&!this.layers[0]._featureFilter.filter(new bi(this.zoom),at,S))continue;const ut=Ri(at,ft);if(!ft&&!this.layers[0]._featureFilter.filter(new bi(this.zoom),ut,S))continue;const Nt=ft?ut.geometry:Ea(at,S,E),Mt=[];for(const ps of Nt)for(const cs of ps)Mt.push(cs.x),Mt.push(cs.y);const It={coordinates:Mt,crossPerc:at.properties.cross_perc,distanceToRoad:at.properties.distance_to_road,entrances:at.properties.entrances,sourceId:0},xs=at.properties.source_id;let es=Y.get(xs);es||(es=[],Y.set(xs,es)),es.push(It),++te}this.maxHeight=0;const he=new Array,ge=new Set,ve=at=>{at!=null&&ge.add(at)},Te=(at,ft)=>{at!=null&&he.push({buildingId:at,footprintIndex:ft})},Ie=64*(f.length-te),Ve=Ie/2;this.buildingWithFacade.reserve(Ie,Ve,!0),this.buildingWithoutFacade.reserve(2*Ie,2*Ve,!1),this.footprintsIndices.reserve(16*(f.length-te)),this.footprintsVertices.reserve(8*(f.length-te));for(const{feature:at,id:ft,index:ut,sourceLayerIndex:Nt}of f){if(QXe[at.type]==="LineString")continue;const Mt=this.layers[0]._featureFilter.needGeometry;if(Mt&&!this.layers[0]._featureFilter.filter(new bi(this.zoom),at,S))continue;let It=null;if(at.properties&&at.properties.hasOwnProperty("building_id")&&(It=Number(at.properties.building_id),ge.has(It)))continue;const xs=Ri(at,Mt);if(!Mt&&!this.layers[0]._featureFilter.filter(new bi(this.zoom),xs,S))continue;const es=Mt?xs.geometry:Ea(at,S,E),ps=bV(es,500);let cs=!1;for(const Qi of ps)if(Qi.length!==1){cs=!0;break}if(cs){ve(It);continue}if(!MHt(es,163)){ve(It);continue}const ds=this.layers[0],mn=LHt(ds.layout.get("building-roof-shape").evaluate(at,{},S)),xn=ds.layout.get("building-base").evaluate(at,{},S),kn=ds.layout.get("building-height").evaluate(at,{},S),En=ds.layout.get("building-flood-light-ground-radius").evaluate(at,{},S),Sn=ds.paint.get("building-ambient-occlusion-intensity"),Gn=En/this.tileToMeter;at.properties["building-part"]="roof";const dn=ds.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),An=ds.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);at.properties["building-part"]="wall";const Pn=ds.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),Wn=ds.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);at.properties["building-part"]="window";const ir=ds.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),Ur=ds.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);at.properties["building-part"]="door";const wr=ds.paint.get("building-color").evaluate(at,{},this.canonical).toPremultipliedRenderColor(this.lut),vr=ds.paint.get("building-emissive-strength").evaluate(at,{},this.canonical);let or=ds.layout.get("building-flood-light-wall-radius").evaluate(at,{},S);or=it(or,0,2048);const Or=or/2048*ote,sa=H.get(ft),Ta=Y.get(sa)||[],ya=Ta.length!==0&&ds.layout.get("building-facade").evaluate(at,{},S);D.setFacadeOptions(4,!0),D.setFauxFacadeOptions(ya,!1,1);let xi=0,jo=0,gi=0,Ao=0,Di=0,Ld=0,tl=0,Oo=0,Yl=0,bd=0,Lm=0;if(ya){let Qi=Math.round(ds.layout.get("building-facade-floors").evaluate(at,{},S));if(xn===0){Qi=Math.max(1,Qi-(Ta.length>0?1:0));let nu=4;if(kn>100){const nm=[10,13,15];nu=nm[at.id?at.id%nm.length:0]}else kn<=10&&(nu=3);D.setFacadeOptions(nu,!0),Di=(kn<15?1.3:1.61803)*nu/z}else Di=xn/z;Ld=kn/z,Di=Math.min(Di,Ld),gi=ds.layout.get("building-facade-unit-width").evaluate(at,{},S)/z,Ao=(Ld-Di)/Qi,D.setFauxFacadeOptions(!0,!0,gi);const yp=ds.layout.get("building-facade-window").evaluate(at,{},S);xi=yp[0],jo=yp[1],tl=Math.floor(65535*Math.min(1,Di/nr)),Oo=Math.floor(65535*Math.min(1,Ld/nr)),Yl=Math.floor(255*xi)<<8|Math.floor(255*jo),bd=Math.floor(65535*Math.min(1,gi/nr)),Lm=Math.floor(65535*Math.min(1,Ao/nr))}const _d=Array(ps.length),tu={x:1/0,y:1/0},Qu={x:-1/0,y:-1/0},su={x:0,y:0};let zf=0;for(let Qi=0;Qi0){const nu=[],nm=Array(yp.length+1);nm[0]=0;for(let t_=0;t_nr||tu.y<0||Qu.y>nr)&&this.featuresOnBorder.push({featureId:at.id,footprintIndex:this.footprints.length});{const Qi=rF(HS,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+Qi.length),this.footprintsIndices.uint16.set(Qi,wF),this.buildingIds.add(It??at.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,Jb.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,Jb.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,e_.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,e_.y);const yp={footprintVertexOffset:VS,footprintVertexLength:this.footprintsVertices.length-VS,footprintIndexOffset:wF,footprintIndexLength:this.footprintsIndices.length-wF,min:Jb,max:e_,hiddenFlags:0,indicesOffset:Dte,indicesLength:v6e,bloomIndicesOffset:Bf,bloomIndicesLength:Pd,groundEffectVertexOffset:aM,groundEffectVertexLength:jF,hasFauxFacade:ya,height:_F,promoteId:ft,feature:xs,parts:xp,buildingBloom:Lg},nu=this.footprints.length;at.id!==void 0&&this.featureFootprintLookup.set(at.id,nu),Te(It,nu),this.footprints.push(yp)}this.programConfigurations.populatePaintArrays(Ui.layoutVertexArray.length,at,ut,{},_.availableImages,S,_.brightness),this.groundEffect.addPaintPropertiesData(at,ut,{},_.availableImages,S,_.brightness),_.featureIndex.insert(at,es,ut,Nt,this.index,Ux)}he.forEach(({buildingId:at,footprintIndex:ft})=>{ge.has(at)&&(this.footprints[ft].hiddenFlags|=4)});const et=new Set;this.buildingIds.forEach((at,ft,ut)=>{ge.has(at)||et.add(at)}),this.buildingIds=et,this.groundEffect.prepareBorderSegments()}update(f,_,S,E,D,z,H){this.programConfigurations.updatePaintArrays(f,_,D,S,E,z,H),this.groundEffect.update(f,_,D,S,E,z,H),this.evaluate(this.layers[0],f),this.colorBufferUploaded=!1}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(f){const _=S=>{S.layoutVertexBuffer=f.createVertexBuffer(S.layoutVertexArray,ZXe.members),S.layoutNormalBuffer=f.createVertexBuffer(S.layoutNormalArray,NHt.members),S.layoutCentroidBuffer=f.createVertexBuffer(S.layoutCentroidArray,kHt.members),S.layoutFloodLightDataBuffer=f.createVertexBuffer(S.layoutFloodLightDataArray,EHt.members),S.layoutFacadeDataArray&&S.layoutFacadeDataArray.length&&(S.layoutFacadeDataBuffer=f.createVertexBuffer(S.layoutFacadeDataArray,CHt.members)),S.layoutFacadeVerticalRangeArray&&S.layoutFacadeVerticalRangeArray.length&&(S.layoutFacadeVerticalRangeBuffer=f.createVertexBuffer(S.layoutFacadeVerticalRangeArray,AHt.members)),S.entranceBloom.layoutVertexArray.length&&(S.entranceBloom.layoutVertexBuffer=f.createVertexBuffer(S.entranceBloom.layoutVertexArray,ZXe.members),S.entranceBloom.layoutAttenuationBuffer=f.createVertexBuffer(S.entranceBloom.layoutAttenuationArray,THt.members)),this.uploadUpdatedColorBuffer(f),this.uploadUpdatedIndexBuffer(f)};this.uploaded||(_(this.buildingWithoutFacade),_(this.buildingWithFacade),this.groundEffect.upload(f)),this.groundEffect.uploadPaintProperties(f),this.programConfigurations.upload(f),this.uploaded=!0}destroy(){const f=_=>{_.layoutVertexBuffer&&(_.layoutVertexBuffer.destroy(),_.layoutNormalBuffer.destroy(),_.layoutColorBuffer.destroy(),_.segmentsBucket.destroy(),_.indexBuffer&&_.indexBuffer.destroy(),_.entranceBloom.layoutVertexBuffer&&(_.entranceBloom.layoutVertexBuffer.destroy(),_.entranceBloom.layoutColorBuffer.destroy(),_.entranceBloom.layoutAttenuationBuffer.destroy(),_.entranceBloom.indexBuffer.destroy(),_.entranceBloom.segmentsBucket.destroy()))};f(this.buildingWithoutFacade),f(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(f,_,S=!0){let E=!1;const D=S?_:0,z=0|(S?-1:~_);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const H of f){const Y=this.footprints[H],te=Y.hiddenFlags&z|D;Y.hiddenFlags!==te&&(Y.hiddenFlags=te,E=!0,this.groundEffect.updateHiddenByLandmarkRange(Y.groundEffectVertexOffset,Y.groundEffectVertexLength,Y.hiddenFlags!==0))}return E&&(this.indexArrayForConflationUploaded=!1),E}uploadUpdatedIndexBuffer(f){if(this.groundEffect.uploadHiddenByLandmark(f),this.indexArrayForConflationUploaded)return;const _=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))};_(this.buildingWithoutFacade),_(this.buildingWithFacade);for(const E of this.footprints){const D=E.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,z=E.indicesOffset+E.indicesLength;if(E.hiddenFlags!==0){for(let Y=E.indicesOffset;Y{E.indexArray.length!==0&&(E.indexBuffer?E.indexBuffer.updateData(E.indexArrayForConflation):E.indexBuffer=f.createIndexBuffer(E.indexArrayForConflation,!0),E.entranceBloom.indexBuffer?E.entranceBloom.indexBuffer.updateData(E.entranceBloom.indexArrayForConflation):E.entranceBloom.indexBuffer=f.createIndexBuffer(E.entranceBloom.indexArrayForConflation,!0))};S(this.buildingWithoutFacade),S(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(f){const _=S=>{S.layoutColorBuffer?S.layoutColorBuffer.updateData(S.layoutColorArray):S.layoutColorBuffer=f.createVertexBuffer(S.layoutColorArray,XXe.members,!0),S.layoutFacadePaintArray&&(S.layoutFacadePaintBuffer?S.layoutFacadePaintBuffer.updateData(S.layoutFacadePaintArray):S.layoutFacadePaintBuffer=f.createVertexBuffer(S.layoutFacadePaintArray,SHt.members,!0)),S.entranceBloom.layoutColorBuffer?S.entranceBloom.layoutColorBuffer.updateData(S.entranceBloom.layoutColorArray):S.entranceBloom.layoutColorBuffer=f.createVertexBuffer(S.entranceBloom.layoutColorArray,XXe.members,!0)};_(this.buildingWithoutFacade),_(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(f,_){const S=f.paint.get("building-ambient-occlusion-intensity");for(const E of this.footprints){if(4&E.hiddenFlags)continue;const D=_[E.promoteId],z=E.feature;z.properties["building-part"]="roof";const H=f.paint.get("building-color").evaluate(z,D,this.canonical).toPremultipliedRenderColor(this.lut),Y=f.paint.get("building-emissive-strength").evaluate(z,D,this.canonical);z.properties["building-part"]="wall";const te=f.paint.get("building-color").evaluate(z,D,this.canonical).toPremultipliedRenderColor(this.lut),he=f.paint.get("building-emissive-strength").evaluate(z,D,this.canonical);z.properties["building-part"]="window";const ge=f.paint.get("building-color").evaluate(z,D,this.canonical).toPremultipliedRenderColor(this.lut),ve=f.paint.get("building-emissive-strength").evaluate(z,D,this.canonical);z.properties["building-part"]="door";const Te=f.paint.get("building-color").evaluate(z,D,this.canonical).toPremultipliedRenderColor(this.lut),Ie=f.paint.get("building-emissive-strength").evaluate(z,D,this.canonical),Ve=E.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const at of E.parts){let ft,ut=H;at.part===1?(ut=H,ft=Y):at.part===0?(ut=te,ft=he):at.part===2?(ut=ge,ft=ve):at.part===3&&(ut=Te,ft=Ie),ft=it(ft,0,1);for(let Nt=0;Ntz.max.x||Y.max.xz.max.y||Y.max.yH.max.x||H.min.x>f||_>H.max.y||H.min.y>_||H.height<=S||PHt(z,this.footprintsVertices.float32.subarray(2*H.footprintVertexOffset,2*(H.footprintVertexOffset+H.footprintVertexLength)),this.footprintsIndices.uint16.subarray(H.footprintIndexOffset,H.footprintIndexOffset+H.footprintIndexLength))&&(S=H.height,this.footprintLookup[D]=H,E=H.hiddenFlags!==0);if(S!==Number.NEGATIVE_INFINITY)return{height:S,hidden:E};this.footprintLookup[D]=void 0}}function PHt(N,f,_){for(let S=0;S<_.length;S+=3){const E=_[S],D=_[S+1],z=_[S+2],H=f[2*E+0],Y=f[2*E+1],te=f[2*D+0],he=f[2*D+1],ge=f[2*z+0],ve=f[2*z+1],Te=(H-ge)*(N.y-ve)-(Y-ve)*(N.x-ge),Ie=(te-H)*(N.y-Y)-(he-Y)*(N.x-H);if(Te<0!=Ie<0&&Te!==0&&Ie!==0)continue;const Ve=(ge-te)*(N.y-he)-(ve-he)*(N.x-te);if(Ve===0||Ve<0==Te+Ie<=0)return!0}return!1}function IHt(N,f,_,S,E,D){const z=Math.pow(2,S.z-E.z);for(let H=0;H<_;H++){let Y=N.float32[2*(H+f)+0],te=N.float32[2*(H+f)+1];Y=(Y+E.x*nr)*z-S.x*nr,te=(te+E.y*nr)*z-S.y*nr,D.push(new Xs(Y,te))}}let eQe,tQe;gr(JXe,"BuildingBucket",{omit:["layers"]}),gr(TEe,"BuildingGeometry"),gr(AEe,"BuildingBloomGeometry");const RHt=Fn([{name:"a_pos_normal",components:2,type:"Int16"},{name:"a_data",components:4,type:"Uint8"},{name:"a_linesofar",components:1,type:"Float32"}],4),DHt=Fn([{name:"a_z_offset_width",components:3,type:"Float32"}],4),OHt=Fn([{name:"a_elevation_ground_scale",components:1,type:"Float32"}],4),{members:FHt}=RHt,zHt=Fn([{name:"a_packed",components:3,type:"Float32"}]),{members:BHt}=zHt,$Ht=Fn([{name:"a_pattern_data",components:3,type:"Float32"}]),{members:UHt}=$Ht;class sQe{constructor(f,_){this.width=f,this.height=_,this.nextRow=0,this.image=new yC({width:f,height:_}),this.positions={},this.uploaded=!1}getDash(f,_){const S=this.getKey(f,_);return this.positions[S]}trim(){const f=this.width,_=this.height=js(this.nextRow);this.image.resize({width:f,height:_})}getKey(f,_){return f.join(",")+_}getDashRanges(f,_,S){const E=[];let D=f.length%2==1?-f[f.length-1]*S:0,z=f[0]*S,H=!0;E.push({left:D,right:z,isDash:H,zeroLength:f[0]===0});let Y=f[0];for(let te=1;te1&&(Y=f[++H]);const he=Math.abs(te-Y.left),ge=Math.abs(te-Y.right),ve=Math.min(he,ge);let Te;const Ie=D/S*(E+1);if(Y.isDash){const Ve=E-Math.abs(Ie);Te=Math.sqrt(ve*ve+Ve*Ve)}else Te=E-Math.sqrt(ve*ve+Ie*Ie);this.image.data[z+te]=Math.max(0,Math.min(255,Te+128))}}}addRegularDash(f,_){for(let Y=f.length-1;Y>=0;--Y){const te=f[Y],he=f[Y+1];te.zeroLength?f.splice(Y,1):he&&he.isDash===te.isDash&&(he.left=te.left,f.splice(Y,1))}const S=f[0],E=f[f.length-1];S.isDash===E.isDash&&(S.left=E.left-this.width,E.right=S.right+this.width);const D=this.width*this.nextRow;let z=0,H=f[z];for(let Y=0;Y1&&(H=f[++z]);const te=Math.abs(Y-H.left),he=Math.abs(Y-H.right),ge=Math.min(te,he);this.image.data[D+Y]=Math.max(0,Math.min(255,(H.isDash?ge:-ge)+_+128))}}addDash(f,_){const S=this.getKey(f,_);if(this.positions[S])return this.positions[S];const E=_==="round",D=E?7:0,z=2*D+1;if(this.nextRow+z>this.height)return Mr("LineAtlas out of space"),null;f.length===0&&f.push(1);let H=0;for(let ge=0;ge_.fqid),this.index=f.index,this.projection=f.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(_=>{this.gradients[_.id]={}}),this.layoutVertexArray=new O6,this.layoutVertexArray2=new R1,this.patternVertexArray=new R1,this.indexArray=new eu,this.programConfigurations=new tt(f.layers,{zoom:f.zoom,lut:f.lut}),this.segments=new Gl,this.maxLineLength=0,this.zOffsetVertexArray=new R1,this.elevationGroundScaleVertexArray=new dl,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.tessellationStep=f.tessellationStep?f.tessellationStep:128,this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,_){}updateAppearances(f,_,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,E){this.hasPattern=QTe("line",this.layers,this.pixelRatio,_);const D=this.layers[0].layout.get("line-sort-key");this.tileToMeter=zn(S);const z=this.layers[0].layout.get("line-elevation-reference");if(z==="hd-road-markup")this.elevationType="road";else{const ve=this.layers[0].layout.get("line-z-offset"),Te=ve.isConstant()&&!ve.constantOr(0);this.elevationType=z!=="sea"&&z!=="ground"&&Te?"none":"offset",this.elevationType==="offset"&&z==="none"&&Mr(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=z==="sea"}const H=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&H!==void 0;const Y=[];for(const{feature:ve,id:Te,index:Ie,sourceLayerIndex:Ve}of f){const et=this.layers[0]._featureFilter.needGeometry,at=Ri(ve,et);if(!this.layers[0]._featureFilter.filter(new bi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),at,S))continue;const ft=D?D.evaluate(at,{},S):void 0,ut={id:Te,properties:ve.properties,type:ve.type,sourceLayerIndex:Ve,index:Ie,geometry:et?at.geometry:Ea(ve,S,E),patterns:{},sortKey:ft};Y.push(ut)}D&&Y.sort((ve,Te)=>ve.sortKey-Te.sortKey);const{lineAtlas:te,featureIndex:he}=_,ge=this.addConstantDashes(te);for(const ve of Y){const{geometry:Te,index:Ie,sourceLayerIndex:Ve}=ve;if(ge&&this.addFeatureDashes(ve,te),this.hasPattern){const et=JTe("line",this.layers,ve,this.zoom,this.pixelRatio,_);this.patternFeatures.push(et)}else this.addFeature(ve,Te,Ie,S,te.positions,_.availableImages,_.brightness,_.elevationFeatures);he.insert(f[Ie].feature,Te,Ie,Ve,this.index)}}addConstantDashes(f){let _=!1;for(const S of this.layers){const E=S.paint.get("line-dasharray").value,D=S.layout.get("line-cap").value;if(E.kind!=="constant"||D.kind!=="constant")_=!0;else{const z=D.value,H=E.value;if(!H)continue;f.addDash(H,z)}}return _}addFeatureDashes(f,_){const S=this.zoom;for(const E of this.layers){const D=E.paint.get("line-dasharray").value,z=E.layout.get("line-cap").value;if(D.kind==="constant"&&z.kind==="constant")continue;let H,Y;if(D.kind==="constant"){if(H=D.value,!H)continue}else H=D.evaluate({zoom:S},f);Y=z.kind==="constant"?z.value:z.evaluate({zoom:S},f),_.addDash(H,Y),f.patterns[E.id]=[_.getKey(H,Y)]}}update(f,_,S,E,D,z,H,Y,te){this.programConfigurations.updatePaintArrays(f,_,D,S,E,z,H,te)}addFeatures(f,_,S,E,D,z){for(const H of this.patternFeatures)this.addFeature(H,H.geometry,H.index,_,S,E,z,f.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=f.createVertexBuffer(this.layoutVertexArray2,BHt)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=f.createVertexBuffer(this.patternVertexArray,UHt)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=f.createVertexBuffer(this.zOffsetVertexArray,DHt.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=f.createVertexBuffer(this.elevationGroundScaleVertexArray,OHt.members,!0)),this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,FHt),this.indexBuffer=f.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(f),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(f,_){let S,E;if(_&&_>0?(S=`mapbox_clip_start_${_}`,E=`mapbox_clip_end_${_}`):(S="mapbox_clip_start",E="mapbox_clip_end"),f.properties&&f.properties.hasOwnProperty(S)&&f.properties.hasOwnProperty(E))return{start:+f.properties[S],end:+f.properties[E]}}addFeature(f,_,S,E,D,z,H,Y){const te=this.layers[0].layout,he=te.get("line-join").evaluate(f,{}),ge=te.get("line-cap").evaluate(f,{}),ve=te.get("line-miter-limit"),Te=te.get("line-round-limit");this.lineClips=this.lineFeatureClips(f),this.lineFeature=f;const Ie=!(!f.properties||!f.properties.hasOwnProperty("mapbox_line_metrics"))&&f.properties.mapbox_line_metrics;this.zOffsetValue=te.get("line-z-offset").value;const Ve=this.layers[0].paint.get("line-width").value;if(Ve.kind!=="constant"&&Ve.isLineProgressConstant===!1&&(this.variableWidthValue=Ve),this.isSeaLevelReference){const et=te.get("line-elevation-ground-scale").value;et.kind==="constant"&&et.value===0||(this.elevationGroundScaleValue=et)}if(this.elevationType==="road"){const et=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(f,_,E,Y,he,ge,ve,Te)){const[at,ft]=this.clipRuntimeLinesToTile(_,1);for(let ut=0;ut0?Mt.parentIndex:null)}this.fillNonElevatedRoadSegment(et)}}else for(let et=0;et<_.length;et++)this.addLine(_[et],f,E,he,ge,ve,Te,void 0,Ie&&et>0?et:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,f,S,D,z,E,H,void 0,this.worldview)}computeSegNextDir(f,_){return f.nextPoint.sub(_.at(-2)).unit()}computeSegPrevDir(f,_){return _[1].sub(f.prevPoint).unit()}clipLinesToTile(f,_){return Qee(f,-_,-_,nr+_,nr+_)}clipRuntimeLinesToTile(f,_){const S=[];return[Qee(f,-_,-_,nr+_,nr+_,S),S]}addElevatedRoadFeature(f,_,S,E,D,z,H,Y){const te=[],he=tc.getElevationFeature(f,E);if(he){const ge=this.clipLinesToTile(_,1),ve=this.prepareElevatedLines(ge,he,S);for(const Te of ve)te.push({geometry:Te,elevation:he,elevationTileID:S,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(te.length===0)return!1;for(const ge of te){const ve=this.layoutVertexArray.length;this.addLine(ge.geometry,f,S,D,z,H,Y);const Te=new fc(S,ge.elevationTileID);if(ge.elevation)for(let Ie=ve;Ie>1,this.layoutVertexArray.int16[6*Ie+1]>>1),et=Te.pointElevation(Ve,ge.elevation,.05);this.updateHeightRange(et),this.zOffsetVertexArray.emplaceBack(et,0,0)}else this.fillNonElevatedRoadSegment(ve)}return!0}prepareElevatedLines(f,_,S){if(_.constantHeight!=null)return f;const E=[],D=1/zn(S);for(const z of f)tHt(z,new wv(_,D),0,E);return E}fillNonElevatedRoadSegment(f){for(let _=f;_0,ve=Y&&Y.progress.max<1;if(this.lineClips){let ps={min:this.lineClips.start,max:this.lineClips.end},cs=1;if(Y){const xn=this.lineClips.end-this.lineClips.start;ps=function(kn,En,Sn){return{min:$a(kn.min,En,Sn),max:$a(kn.max,En,Sn)}}(Y.progress,{min:0,max:1},ps),xn>0&&(cs=(ps.max-ps.min)/xn)}const ds=+_.properties.mapbox_clip_feature_len,mn=+_.properties.mapbox_clip_seg_len;if(Number.isNaN(ds)||Number.isNaN(mn)){for(let kn=0;kn=2&&f[Ie-1].equals(f[Ie-2]);)Ie--;let Ve=0;for(;Ve0,An=this.overscaling<=16?122880/(512*this.overscaling):0;if(cs&&ds==="round"){if(Enz&&(ds="bevel"),ds==="bevel"&&(En>2&&(ds="flipbevel"),En2*An){const ir=at.sub(at.sub(ft)._mult(An/Pn)._round());this.updateDistance(ft,ir),this.addCurrentVertex(ir,Nt,0,0,et,es),ft=ir}this.updateDistance(ft,at),xn._mult(En),this.addCurrentVertex(at,xn,0,0,et,es);const Wn=at.dist(ut);if(Wn>2*An){const ir=at.add(ut.sub(at)._mult(An/Wn)._round());this.updateDistance(at,ir),this.addCurrentVertex(ir,Mt,0,0,et,es),at=ir}}else xn._mult(En),this.addCurrentVertex(at,xn,0,0,et,es);else if(ds==="flipbevel"){if(En>100)xn=Mt.mult(-1);else{const Pn=En*Nt.add(Mt).mag()/Nt.sub(Mt).mag();xn._perp()._mult(Pn*(dn?-1:1))}this.addCurrentVertex(at,xn,0,0,et,es),this.addCurrentVertex(at,xn.mult(-1),0,0,et,es)}else if(ds==="bevel"||ds==="fakeround"){const Pn=at.dist(ft);let Wn=1;if(this.elevationType==="offset"&&ds==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&es!=null&&ft&&ut){const Or=4*An;Pn1){this.lineSoFar=f.w;const Ve=(_.x-f.x)/ge,et=(_.y-f.y)/ge,at=(_.z-f.z)/ge,ft=(_.w-f.w)/ge,ut=_.x-f.x,Nt=_.y-f.y,Mt=Math.sqrt(ut*ut+Nt*Nt);if(Mt===0)return;const It=-Nt/Mt,xs=ut/Mt,es=It,ps=xs,cs=-It,ds=-xs;for(let mn=1;mn=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,he),Y.primitiveLength++),z?this.e2=he:this.e1=he,te!=null&&this.zOffsetVertexArray.emplaceBack(te.zOffset,te.variableWidth,te.variableWidth),this.elevationGroundScaleValue){const ge=te?te.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(ge)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(f,_){this.prevDistance=this.distance,this.distance+=f.dist(_),this.updateScaledDistance()}}function EEe(N,f,_){return N.x_||N.y_}let nQe,rQe;function aQe(N,f,_){return f*(nr/(N.tileSize*Math.pow(2,_-N.tileID.overscaledZ)))}gr(lte,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const iQe=(N,f,_)=>(1-_)*N+_*f;function oQe(N,f){return 1/aQe(N,1,f.tileZoom)}function lQe(N,f,_,S){return N.translatePosMatrix(S||f.tileID.projMatrix,f,_.paint.get("line-translate"),_.paint.get("line-translate-anchor"))}const cQe=N=>{const f=[];dQe(N)&&f.push("RENDER_LINE_DASH"),N.paint.get("line-gradient")&&f.push("RENDER_LINE_GRADIENT"),N.paint.get("line-blend-mode")==="multiply"&&f.push("LINE_BLEND_MULTIPLY");const _=N.paint.get("line-trim-offset");_[0]===0&&_[1]===0||f.push("RENDER_LINE_TRIM_OFFSET"),N.paint.get("line-border-width").constantOr(1)!==0&&f.push("RENDER_LINE_BORDER");const S=N.layout.get("line-join").constantOr("miter")==="none",E=!!N.paint.get("line-pattern").constantOr(1);return S&&E&&f.push("LINE_JOIN_NONE"),f};function dQe(N){const f=N.paint.get("line-dasharray").value;return f.kind!=="constant"||f.value}let MEe;const uQe=()=>MEe||(MEe={layout:nQe||(nQe=new pc({"line-cap":new tr(Rs.layout_line["line-cap"]),"line-join":new tr(Rs.layout_line["line-join"]),"line-miter-limit":new sr(Rs.layout_line["line-miter-limit"]),"line-round-limit":new sr(Rs.layout_line["line-round-limit"]),"line-sort-key":new tr(Rs.layout_line["line-sort-key"]),"line-z-offset":new tr(Rs.layout_line["line-z-offset"]),"line-elevation-reference":new sr(Rs.layout_line["line-elevation-reference"]),"line-cross-slope":new sr(Rs.layout_line["line-cross-slope"]),visibility:new sr(Rs.layout_line.visibility),"line-width-unit":new sr(Rs.layout_line["line-width-unit"]),"line-elevation-ground-scale":new tr(Rs.layout_line["line-elevation-ground-scale"])})),paint:rQe||(rQe=new pc({"line-opacity":new tr(Rs.paint_line["line-opacity"]),"line-color":new tr(Rs.paint_line["line-color"]),"line-translate":new sr(Rs.paint_line["line-translate"]),"line-translate-anchor":new sr(Rs.paint_line["line-translate-anchor"]),"line-width":new tr(Rs.paint_line["line-width"]),"line-gap-width":new tr(Rs.paint_line["line-gap-width"]),"line-offset":new tr(Rs.paint_line["line-offset"]),"line-blur":new tr(Rs.paint_line["line-blur"]),"line-dasharray":new tr(Rs.paint_line["line-dasharray"]),"line-pattern":new tr(Rs.paint_line["line-pattern"]),"line-pattern-cross-fade":new sr(Rs.paint_line["line-pattern-cross-fade"]),"line-gradient":new E0(Rs.paint_line["line-gradient"]),"line-trim-offset":new sr(Rs.paint_line["line-trim-offset"]),"line-trim-fade-range":new sr(Rs.paint_line["line-trim-fade-range"]),"line-trim-color":new sr(Rs.paint_line["line-trim-color"]),"line-emissive-strength":new tr(Rs.paint_line["line-emissive-strength"]),"line-border-width":new tr(Rs.paint_line["line-border-width"]),"line-border-color":new tr(Rs.paint_line["line-border-color"]),"line-occlusion-opacity":new sr(Rs.paint_line["line-occlusion-opacity"]),"line-blend-mode":new sr(Rs.paint_line["line-blend-mode"]),"line-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"})}))},MEe);class GHt extends tr{possiblyEvaluate(f,_){return _=new bi(Math.floor(_.zoom),{now:_.now,fadeDuration:_.fadeDuration,transition:_.transition,worldview:_.worldview}),super.possiblyEvaluate(f,_)}evaluate(f,_,S,E){return _=Object.assign({},_,{zoom:Math.floor(_.zoom)}),super.evaluate(f,_,S,E)}}let LV;function hQe(N,f){return f>0?f+2*N:N}const WHt=Fn([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),KHt=Fn([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),YHt=Fn([{name:"a_projected_pos",components:4,type:"Float32"}],4);Fn([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const ZHt=Fn([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),XHt=Fn([{name:"a_feature_index",components:1,type:"Float32"}],4),QHt=Fn([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),JHt=Fn([{name:"a_texb",components:2,type:"Uint16"}]),eGt=Fn([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),tGt=Fn([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);Fn([{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 mQe=Fn([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),sGt=Fn([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);Fn([{name:"triangle",components:3,type:"Uint16"}]),Fn([{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"}]),Fn([{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"}]),Fn([{type:"Float32",name:"offsetX"}]),Fn([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const LEe=class hje{constructor(f=null,_=0,S=4096){this.batchIndex=_,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=f||null,this.propsDwords=S,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(hje.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let E=0;Ef.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${f.maxUniformBlockSize}`);if(this.headerBuffer=_.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(_.bindBuffer(_.UNIFORM_BUFFER,this.headerBuffer),_.bufferData(_.UNIFORM_BUFFER,hje.HEADER_BYTES,_.DYNAMIC_DRAW),this.propertiesBuffer=_.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(_.bindBuffer(_.UNIFORM_BUFFER,this.propertiesBuffer),_.bufferData(_.UNIFORM_BUFFER,this.totalBytes,_.DYNAMIC_DRAW),this.blockIndicesBuffer=_.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");_.bindBuffer(_.UNIFORM_BUFFER,this.blockIndicesBuffer),_.bufferData(_.UNIFORM_BUFFER,this.totalBytes,_.DYNAMIC_DRAW),_.bindBuffer(_.UNIFORM_BUFFER,null)}writeHeader(f){const _=this.headerData;_[0]=f.dataDrivenMask,_[1]=f.zoomDependentMask,_[2]=f.dataDrivenBlockSizeVec4,_[3]=f.offsets[0],_[4]=f.offsets[1],_[5]=f.offsets[2],_[6]=f.offsets[3],_[7]=f.offsets[4],_[8]=f.offsets[5],_[9]=f.offsets[6],_[10]=f.offsets[7],_[11]=f.offsets[8]}writeDataDrivenBlock(f,_,S){const E=4*S.dataDrivenBlockSizeVec4;if(E===0)return;const D=_*E;if(D+E>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${_} exceeds propertiesData capacity`);for(let z=0;z<9;z++)S.dataDrivenMask&1<{if(!H)return;const te=S.getUniformBlockIndex(_,z);te!==S.INVALID_INDEX&&(S.uniformBlockBinding(_,te,Y),S.bindBufferBase(S.UNIFORM_BUFFER,Y,H))},D=3*this.batchIndex;E("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,D),E("SymbolPaintPropertiesUniform",this.propertiesBuffer,D+1),E("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,D+2)}destroy(){if(this.context){const f=this.context.gl;this.headerBuffer&&(f.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(f.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(f.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};LEe.HEADER_DWORDS=12,LEe.HEADER_BYTES=48;let PEe=LEe;function IEe(N,f,_,S){return[eF(255*N,255*f),eF(255*_,255*S)]}function pQe(N,f,_,S,E,D,z,H){return!!N&&(N.kind==="constant"?N.value==="none":N.kind==="composite"||N.kind==="source"?N.evaluate({zoom:0,brightness:D,worldview:H},f,_,E,S,z)==="none":typeof N=="string"&&N==="none")}gr(PEe,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class REe{constructor(f,_,S,E,D="",z,H){this.layer=f,this.zoom=_,this.lut=S,this.isText=E,this.propDefs=this._getPropDefs(),this.worldview=D,this.maxUniformBufferBindings=z||24,this.uboSizeDwords=H||4096,this.featureVertexRangesFromId=new Map,this.allFeatures=[],this.ubos=[],this.featureCount=0,this.cachedHeader=null,this.maxFeaturesPerBatch=0,this.propertyHashToUBOIndex=new Map,this.canDeduplicate=this._checkIfAllPropertiesAreConstant(f,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 f=this.isText?"text":"icon";return[{name:`${f}-color`,useThemeName:`${f}-color-use-theme`,isColor:!0},{name:`${f}-halo-color`,useThemeName:`${f}-halo-color-use-theme`,isColor:!0},{name:`${f}-opacity`,useThemeName:null,isColor:!1},{name:`${f}-halo-width`,useThemeName:null,isColor:!1},{name:`${f}-halo-blur`,useThemeName:null,isColor:!1},{name:`${f}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${f}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${f}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const f=this.layer.paint,_=this.propDefs;let S=0,E=0,D=0,z=0;const H=[0,0,0,0,0,0,0,0,0];for(let Y=0;Y<9;Y++){const{name:te,isColor:he,isVec2:ge}=_[Y],ve=f.get(te),Te=!(!ve||typeof ve.isConstant!="function"||ve.isConstant()),Ie=this._appearancesHavePaintProperties(te),Ve=Te||Ie,et=!(!ve||!ve.value||ve.value.kind!=="composite"),at=this.layer._transitionablePaint._values[te],ft=!Ve&&(at&&at.value&&at.value.expression&&at.value.expression.kind)==="camera";Ve?(S|=1<_.hasPaintProperty(f):this.isText?_=>_.hasTextPaintProperties():_=>_.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(f,_){const S=f.paint,E=_?"text":"icon",D=[`${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 z of D){const H=S.get(z);if(H&&typeof H=="object"&&"isConstant"in H&&!H.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(f,_){if(_.dataDrivenMask===0)return"";const S=[];for(let E=0;E<9;E++){if(!(_.dataDrivenMask&1<=Ie){Mr(`Too many symbol features: batch ${ve} requires binding points up to ${3*ve+2}, device limit ${Ie}. Some features will render incorrectly.`);const et={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:_,featureId:Y};return this.allFeatures.push(et),Y!=null&&(this.featureVertexRangesFromId.has(Y)||this.featureVertexRangesFromId.set(Y,[]),this.featureVertexRangesFromId.get(Y).push(et)),0}this.ubos[ve]||(this.ubos[ve]=new PEe(H,ve,this.uboSizeDwords),this.ubos[ve].writeHeader(te)),this.ubos[ve].writeDataDrivenBlock(he,Te,te);const Ve={batchIndex:ve,localFeatureIndex:Te,vtFeatureIndex:_,featureId:Y};return this.allFeatures.push(Ve),Y!=null&&(this.featureVertexRangesFromId.has(Y)||this.featureVertexRangesFromId.set(Y,[]),this.featureVertexRangesFromId.get(Y).push(Ve)),Te}updateFeatures(f,_,S,E,D,z,H){if(this.layer=_,this.cachedConstantUniforms=null,!this.cachedHeader)return;const Y=this.cachedHeader;for(const te of f){const he=this.featureVertexRangesFromId.get(te);if(!he)continue;const ge=z[te]||{};for(const ve of he){if(!S)continue;const Te=S.feature(ve.vtFeatureIndex);if(!Te)continue;const Ie={type:Te.type,id:te,properties:Te.properties||{},geometry:[]},Ve=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(ve.vtFeatureIndex):void 0,et=this.evaluateAllProperties(Ie,ge,E,D,H,void 0,Ve);this.ubos[ve.batchIndex]&&this.ubos[ve.batchIndex].writeDataDrivenBlock(et,ve.localFeatureIndex,Y)}}}updateDynamicExpressions(f,_,S,E,D,z){if(this.layer=f,this.cachedConstantUniforms=null,!this.cachedHeader)return;const H=this.cachedHeader;for(const Y of this.allFeatures){if(!_)continue;const te=_.feature(Y.vtFeatureIndex);if(!te)continue;const he=Y.featureId!=null&&D[Y.featureId]||{},ge={type:te.type,id:Y.featureId,properties:te.properties||{},geometry:[]},ve=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(Y.vtFeatureIndex):void 0,Te=this.evaluateAllProperties(ge,he,S,E,z,void 0,ve);this.ubos[Y.batchIndex]&&this.ubos[Y.batchIndex].writeDataDrivenBlock(Te,Y.localFeatureIndex,H)}}updateFeaturePaintForAppearance(f,_,S,E,D,z,H){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(f,H||null),!this.cachedHeader))return!1;const Y=this.cachedHeader;if(Y.dataDrivenMask===0)return!1;let te=!1;for(const he of this.allFeatures){if(he.vtFeatureIndex!==f)continue;const ge=this.evaluateAllProperties(_,S,E,D,z,void 0,H);this.ubos[he.batchIndex]&&(this.ubos[he.batchIndex].writeDataDrivenBlock(ge,he.localFeatureIndex,Y),te=!0)}return te}getConstantUniformValues(f,_){const S=this.cachedHeader,E=!(!S||!S.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===_&&(!E||this.cachedConstantRenderZoom===f))return this.cachedConstantUniforms;const D=this.layer.paint,z=this.propDefs,H=E?new bi(f,{brightness:_,worldview:this.worldview}):null,Y={type:1,id:void 0,properties:{},geometry:[]},te=ve=>{const Te=z[ve],Ie=D.get(Te.name);if(!Ie)return[0,0,0,1];const Ve=Te.useThemeName?D.get(Te.useThemeName):void 0,et=pQe(Ve&&typeof Ve!="string"?Ve.value:void 0,Y,{},[],void 0,_,void 0,this.worldview)?null:this.lut;let at;at=S&&S.cameraMask&1<{const Ie=D.get(z[ve].name);if(!Ie)return Te;if(S&&S.cameraMask&1<{S.text=function(E,D,z){const H=D.layout.get("text-transform").evaluate(z,{});return H==="uppercase"?E=E.toLocaleUpperCase():H==="lowercase"&&(E=E.toLocaleLowerCase()),$x.applyArabicShaping&&(E=$x.applyArabicShaping(E)),E}(S.text,f,_)}),N}const PV={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function rGt(N){return N==="︶"||N==="﹈"||N==="︸"||N==="﹄"||N==="﹂"||N==="︾"||N==="︼"||N==="︺"||N==="︘"||N==="﹀"||N==="︐"||N==="︓"||N==="︔"||N==="`"||N===" ̄"||N==="︑"||N==="︒"}function aGt(N){return N==="︵"||N==="﹇"||N==="︷"||N==="﹃"||N==="﹁"||N==="︽"||N==="︻"||N==="︹"||N==="︗"||N==="︿"}const DEe=4294967296,fQe=1/DEe,xQe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let cte=class{constructor(N=new Uint8Array(16)){this.buf=ArrayBuffer.isView(N)?N:new Uint8Array(N),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(N,f,_=this.length){for(;this.pos<_;){const S=this.readVarint(),E=S>>3,D=this.pos;this.type=7&S,N(E,f,this),this.pos===D&&this.skip(S)}return f}readMessage(N,f){return this.readFields(N,f,this.readVarint()+this.pos)}readFixed32(){const N=this.dataView.getUint32(this.pos,!0);return this.pos+=4,N}readSFixed32(){const N=this.dataView.getInt32(this.pos,!0);return this.pos+=4,N}readFixed64(){const N=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*DEe;return this.pos+=8,N}readSFixed64(){const N=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*DEe;return this.pos+=8,N}readFloat(){const N=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,N}readDouble(){const N=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,N}readVarint(N){const f=this.buf;let _,S;return S=f[this.pos++],_=127&S,S<128?_:(S=f[this.pos++],_|=(127&S)<<7,S<128?_:(S=f[this.pos++],_|=(127&S)<<14,S<128?_:(S=f[this.pos++],_|=(127&S)<<21,S<128?_:(S=f[this.pos],_|=(15&S)<<28,function(E,D,z){const H=z.buf;let Y,te;if(te=H[z.pos++],Y=(112&te)>>4,te<128||(te=H[z.pos++],Y|=(127&te)<<3,te<128)||(te=H[z.pos++],Y|=(127&te)<<10,te<128)||(te=H[z.pos++],Y|=(127&te)<<17,te<128)||(te=H[z.pos++],Y|=(127&te)<<24,te<128)||(te=H[z.pos++],Y|=(1&te)<<31,te<128))return dF(E,Y,D);throw new Error("Expected varint not more than 10 bytes")}(_,N,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const N=this.readVarint();return N%2==1?(N+1)/-2:N/2}readBoolean(){return!!this.readVarint()}readString(){const N=this.readVarint()+this.pos,f=this.pos;return this.pos=N,N-f>=12&&xQe?xQe.decode(this.buf.subarray(f,N)):function(_,S,E){let D="",z=S;for(;z239?4:H>223?3:H>191?2:1;if(z+ve>E)break;ve===1?H<128&&(ge=H):ve===2?(Y=_[z+1],(192&Y)==128&&(ge=(31&H)<<6|63&Y,ge<=127&&(ge=null))):ve===3?(Y=_[z+1],te=_[z+2],(192&Y)==128&&(192&te)==128&&(ge=(15&H)<<12|(63&Y)<<6|63&te,(ge<=2047||ge>=55296&&ge<=57343)&&(ge=null))):ve===4&&(Y=_[z+1],te=_[z+2],he=_[z+3],(192&Y)==128&&(192&te)==128&&(192&he)==128&&(ge=(15&H)<<18|(63&Y)<<12|(63&te)<<6|63&he,(ge<=65535||ge>=1114112)&&(ge=null))),ge===null?(ge=65533,ve=1):ge>65535&&(ge-=65536,D+=String.fromCharCode(ge>>>10&1023|55296),ge=56320|1023&ge),D+=String.fromCharCode(ge),z+=ve}return D}(this.buf,f,N)}readBytes(){const N=this.readVarint()+this.pos,f=this.buf.subarray(this.pos,N);return this.pos=N,f}readPackedVarint(N=[],f){const _=this.readPackedEnd();for(;this.pos<_;)N.push(this.readVarint(f));return N}readPackedSVarint(N=[]){const f=this.readPackedEnd();for(;this.pos127;);else if(f===2)this.pos=this.readVarint()+this.pos;else if(f===5)this.pos+=4;else{if(f!==1)throw new Error(`Unimplemented type: ${f}`);this.pos+=8}}writeTag(N,f){this.writeVarint(N<<3|f)}realloc(N){let f=this.length||16;for(;f268435455||N<0?function(f,_){let S,E;if(f>=0?(S=f%4294967296|0,E=f/4294967296|0):(S=~(-f%4294967296),E=~(-f/4294967296),4294967295^S?S=S+1|0:(S=0,E=E+1|0)),f>=18446744073709552e3||f<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");_.realloc(10),function(D,z,H){H.buf[H.pos++]=127&D|128,D>>>=7,H.buf[H.pos++]=127&D|128,D>>>=7,H.buf[H.pos++]=127&D|128,D>>>=7,H.buf[H.pos++]=127&D|128,H.buf[H.pos]=127&(D>>>=7)}(S,0,_),function(D,z){const H=(7&D)<<4;z.buf[z.pos++]|=H|((D>>>=3)?128:0),D&&(z.buf[z.pos++]=127&D|((D>>>=7)?128:0),D&&(z.buf[z.pos++]=127&D|((D>>>=7)?128:0),D&&(z.buf[z.pos++]=127&D|((D>>>=7)?128:0),D&&(z.buf[z.pos++]=127&D|((D>>>=7)?128:0),D&&(z.buf[z.pos++]=127&D)))))}(E,_)}(N,this):(this.realloc(4),this.buf[this.pos++]=127&N|(N>127?128:0),N<=127||(this.buf[this.pos++]=127&(N>>>=7)|(N>127?128:0),N<=127||(this.buf[this.pos++]=127&(N>>>=7)|(N>127?128:0),N<=127||(this.buf[this.pos++]=N>>>7&127))))}writeSVarint(N){this.writeVarint(N<0?2*-N-1:2*N)}writeBoolean(N){this.writeVarint(+N)}writeString(N){N=String(N),this.realloc(4*N.length),this.pos++;const f=this.pos;this.pos=function(S,E,D){for(let z,H,Y=0;Y55295&&z<57344){if(!H){z>56319||Y+1===E.length?(S[D++]=239,S[D++]=191,S[D++]=189):H=z;continue}if(z<56320){S[D++]=239,S[D++]=191,S[D++]=189,H=z;continue}z=H-55296<<10|z-56320|65536,H=null}else H&&(S[D++]=239,S[D++]=191,S[D++]=189,H=null);z<128?S[D++]=z:(z<2048?S[D++]=z>>6|192:(z<65536?S[D++]=z>>12|224:(S[D++]=z>>18|240,S[D++]=z>>12&63|128),S[D++]=z>>6&63|128),S[D++]=63&z|128)}return D}(this.buf,N,this.pos);const _=this.pos-f;_>=128&&gQe(f,_,this),this.pos=f-1,this.writeVarint(_),this.pos+=_}writeFloat(N){this.realloc(4),this.dataView.setFloat32(this.pos,N,!0),this.pos+=4}writeDouble(N){this.realloc(8),this.dataView.setFloat64(this.pos,N,!0),this.pos+=8}writeBytes(N){const f=N.length;this.writeVarint(f),this.realloc(f);for(let _=0;_=128&&gQe(_,S,this),this.pos=_-1,this.writeVarint(S),this.pos+=S}writeMessage(N,f,_){this.writeTag(N,2),this.writeRawMessage(f,_)}writePackedVarint(N,f){f.length&&this.writeMessage(N,iGt,f)}writePackedSVarint(N,f){f.length&&this.writeMessage(N,oGt,f)}writePackedBoolean(N,f){f.length&&this.writeMessage(N,dGt,f)}writePackedFloat(N,f){f.length&&this.writeMessage(N,lGt,f)}writePackedDouble(N,f){f.length&&this.writeMessage(N,cGt,f)}writePackedFixed32(N,f){f.length&&this.writeMessage(N,uGt,f)}writePackedSFixed32(N,f){f.length&&this.writeMessage(N,hGt,f)}writePackedFixed64(N,f){f.length&&this.writeMessage(N,mGt,f)}writePackedSFixed64(N,f){f.length&&this.writeMessage(N,pGt,f)}writeBytesField(N,f){this.writeTag(N,2),this.writeBytes(f)}writeFixed32Field(N,f){this.writeTag(N,5),this.writeFixed32(f)}writeSFixed32Field(N,f){this.writeTag(N,5),this.writeSFixed32(f)}writeFixed64Field(N,f){this.writeTag(N,1),this.writeFixed64(f)}writeSFixed64Field(N,f){this.writeTag(N,1),this.writeSFixed64(f)}writeVarintField(N,f){this.writeTag(N,0),this.writeVarint(f)}writeSVarintField(N,f){this.writeTag(N,0),this.writeSVarint(f)}writeStringField(N,f){this.writeTag(N,2),this.writeString(f)}writeFloatField(N,f){this.writeTag(N,5),this.writeFloat(f)}writeDoubleField(N,f){this.writeTag(N,1),this.writeDouble(f)}writeBooleanField(N,f){this.writeVarintField(N,+f)}};function dF(N,f,_){return _?4294967296*f+(N>>>0):4294967296*(f>>>0)+(N>>>0)}function gQe(N,f,_){const S=f<=16383?1:f<=2097151?2:f<=268435455?3:Math.floor(Math.log(f)/(7*Math.LN2));_.realloc(S);for(let E=_.pos-1;E>=N;E--)_.buf[E+S]=_.buf[E]}function iGt(N,f){for(let _=0;_=0&&S>=f&&dte[this.text.charCodeAt(S)];S--)_--;this.text=this.text.substring(f,_),this.sectionIndex=this.sectionIndex.slice(f,_)}substring(f,_){const S=new uF;return S.text=this.text.substring(f,_),S.sectionIndex=this.sectionIndex.slice(f,_),S.sections=this.sections,S}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((f,_)=>Math.max(f,this.sections[_].scale),0)}addTextSection(f,_){this.text+=f.text,this.sections.push(IV.forText(f.scale,f.fontStack||_));const S=this.sections.length-1;for(let E=0;E=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function OEe(N,f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve=1,et=1){const at=uF.fromFeature(N,E,Ve,et);ge===Sv.vertical&&at.verticalizePunctuation(ve);let ft=[];const ut=function(es,ps,cs,ds,mn,xn,kn=1){if(!es)return[];const En=[],Sn=function(An,Pn,Wn,ir,Ur,wr,vr=1){let or=0;for(let Or=0;Or=0;let dn=0;for(let An=0;An0&&Ux>Di&&(Di=Ux)}else{const xp=cs[bd.fontStack];if(!xp)continue;xp[_d]&&(su=xp[_d]);const Lg=ps[bd.fontStack];if(!Lg)continue;const Bf=Lg.glyphs[_d];if(!Bf)continue;if(Qu=Bf.metrics,Pm=_d!==8203?Mm:0,vr){const Pd=Lg.ascender!==void 0?Math.abs(Lg.ascender):0,Ux=Lg.descender!==void 0?Math.abs(Lg.descender):0,gp=(Pd+Ux)*tu;Ld-_/2;){if(z--,z<0)return!1;H-=N[z].dist(D),D=N[z]}H+=N[z].dist(N[z+1]),z++;const Y=[];let te=0;for(;H<_/2;){const he=N[z],ge=N[z+1];if(!ge)return!1;let ve=N[z-1].angleTo(he)-he.angleTo(ge);for(ve=Math.abs((ve+3*Math.PI)%(2*Math.PI)-Math.PI),Y.push({distance:H,angleDelta:ve}),te+=ve;H-Y[0].distance>S;)te-=Y.shift().angleDelta;if(te>E)return!1;z++,H+=he.dist(ge)}return!0}function CQe(N){let f=0;for(let _=0;_te){const Ie=(te-Y)/Te,Ve=xr(ge.x,ve.x,Ie),et=xr(ge.y,ve.y,Ie),at=new qS(Ve,et,0,ve.angleTo(ge),he);return!z||SQe(N,at,H,z,f)?at:void 0}Y+=Te}}function _Gt(N,f,_,S,E,D,z,H,Y){const te=AQe(S,D,z),he=TQe(S,E),ge=he*z,ve=N[0].x===0||N[0].x===Y||N[0].y===0||N[0].y===Y;return f-ge=0&&Nt=0&&Mt=0&&ve+te<=he){const It=new qS(Nt,Mt,0,ft,Ie);S&&!SQe(N,It,D,S,E)||Te.push(It)}}ge+=at}return H||Te.length||z||(Te=EQe(N,ge/2,_,S,E,D,z,!0,Y)),Te}function MQe(N){let f=0,_=0;for(const z of N)f+=z.w*z.h,_=Math.max(_,z.w);N.sort((z,H)=>H.h-z.h);const S=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(f/.95)),_),h:1/0}];let E=0,D=0;for(const z of N)for(let H=S.length-1;H>=0;H--){const Y=S[H];if(!(z.w>Y.w||z.h>Y.h)){if(z.x=Y.x,z.y=Y.y,D=Math.max(D,z.y+z.h),E=Math.max(E,z.x+z.w),z.w===Y.w&&z.h===Y.h){const te=S.pop();te&&Hf.id?1:N.versionf.version?1:N.sxf.sx?1:N.syf.sy?1:0}function UEe(N){let f=0;for(let _=0;_0,LQe(f,S,this.iconDescriptors,D),LQe(_,S,this.patternDescriptors,D),this.iconDescriptors.sort(hte),this.patternDescriptors.sort(hte);let z=0;const H=E?E.data:"";H&&(z=p2(z,UEe(H))),z=p2(z,1);for(const Y of this.iconDescriptors)z=p2(z,UEe(Y.id)),z=p2(z,Y.version),z=p2(z,Y.sx),z=p2(z,Y.sy);z=p2(z,1);for(const Y of this.patternDescriptors)z=p2(z,UEe(Y.id)),z=p2(z,Y.version),z=p2(z,Y.sx),z=p2(z,Y.sy);this.hash=z}subsetOf(f){return this.isSubsetArray(this.iconDescriptors,f.iconDescriptors,hte)&&this.isSubsetArray(this.patternDescriptors,f.patternDescriptors,hte)}isSubsetArray(f,_,S){let E=0,D=0;if(f.length>_.length)return!1;for(;E{const z=E.variant.id.toString().localeCompare(D.variant.id.toString());return z!==0?z:E.variant.sx!==D.variant.sx?E.variant.sx-D.variant.sx:E.variant.sy!==D.variant.sy?E.variant.sy-D.variant.sy:0});const S=new Map;for(const E of _)S.set(E.key,E.value);return S}class PQe{constructor(f){this.sourceAtlasHash=f}}class IQe{constructor(f,_,S,E){const D=new Map,z=new Map;this.haveRenderCallbacks=[];const H=[],Y=E!==void 0,te=Y?new Map:void 0,he=Y?HEe(f,te):f,ge=Y?HEe(_,te):_;this.addImages(he,D,1,H),this.addImages(ge,z,2,H);const{w:ve,h:Te}=MQe(H),Ie=new hx({width:ve||1,height:Te||1});for(const[Ve,et]of he.entries()){const at=D.get(Ve).paddedRect;hx.copy(et.data,Ie,{x:0,y:0},{x:at.x+1,y:at.y+1},et.data,null,et.sdf)}for(const[Ve,et]of ge.entries()){const at=z.get(Ve),ft=at.paddedRect;let ut=at.padding;const Nt=ft.x+ut,Mt=ft.y+ut,It=et.data.width,xs=et.data.height;ut=ut>1?ut-1:ut,hx.copy(et.data,Ie,{x:0,y:0},{x:Nt,y:Mt},et.data,S),hx.copy(et.data,Ie,{x:0,y:xs-ut},{x:Nt,y:Mt-ut},{width:It,height:ut},S),hx.copy(et.data,Ie,{x:0,y:0},{x:Nt,y:Mt+xs},{width:It,height:ut},S),hx.copy(et.data,Ie,{x:It-ut,y:0},{x:Nt-ut,y:Mt},{width:ut,height:xs},S),hx.copy(et.data,Ie,{x:0,y:0},{x:Nt+It,y:Mt},{width:ut,height:xs},S),hx.copy(et.data,Ie,{x:It-ut,y:xs-ut},{x:Nt-ut,y:Mt-ut},{width:ut,height:ut},S),hx.copy(et.data,Ie,{x:0,y:xs-ut},{x:Nt+It,y:Mt-ut},{width:ut,height:ut},S),hx.copy(et.data,Ie,{x:0,y:0},{x:Nt+It,y:Mt+xs},{width:ut,height:ut},S),hx.copy(et.data,Ie,{x:It-ut,y:0},{x:Nt-ut,y:Mt+xs},{width:ut,height:ut},S)}this.lut=S,this.image=Ie,this.iconPositions=D,this.patternPositions=z,Y&&(this.contentDescriptor=new qEe(he,ge,E,S,te))}addImages(f,_,S,E){for(const[D,z]of f.entries()){const{bin:H,imagePosition:Y,imageVariant:te}=VEe(D,z,S);_.set(D,Y),E.push(H),z.hasRenderCallback&&this.haveRenderCallbacks.push(te.id)}}patchUpdatedImages(f,_,S,E){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(D=>f.hasImage(D,S)),f.dispatchRenderCallbacks(this.haveRenderCallbacks,S);for(const D of f.getUpdatedImages(S)){for(const z of this.iconPositions.keys()){const H=gd.parse(z);if(Zt.isEqual(H.id,D)){const Y=f.getImage(D,S);this.patchUpdatedImage(this.iconPositions.get(z),Y,_,null)}}for(const z of this.patternPositions.keys()){const H=gd.parse(z);if(Zt.isEqual(H.id,D)){const Y=f.getImage(D,S);this.patchUpdatedImage(this.patternPositions.get(z),Y,_,E||this.lut)}}}}patchUpdatedImage(f,_,S,E=null){if(!f||!_||f.version===_.version)return;f.version=_.version;const[D,z]=f.tl,H=f.sdf;if(this.lut||H){const Y={width:_.data.width,height:_.data.height},te=new hx(Y);hx.copy(_.data,te,{x:0,y:0},{x:0,y:0},Y,E,H),S.update(te,{position:{x:D,y:z},recreateWhenResize:!1})}else S.update(_.data,{position:{x:D,y:z},recreateWhenResize:!1})}}gr(RV,"ImagePosition"),gr(IQe,"ImageAtlas",{omit:["lut"]}),gr(PQe,"ImageAtlasReference");class DV{constructor(f){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!f||f.useServerFontComposition===void 0||f.useServerFontComposition}loadGlyphRange(f,_,S,E,D){if(this.useServerFontComposition)return void DV.loadGlyphRange(f,_,S,E,D);const z=f.split(",").map(H=>H.trim()).filter(H=>H.length>0);z.length!==0?z.length!==1?this._loadMultipleFonts(z,_,S,E,D):this._loadFont(z[0],_,S,E,D):D(new Error("Empty fontstack"))}_loadMultipleFonts(f,_,S,E,D){const z=f.map(()=>null),H={completed:0,firstError:null,callbackCalled:!1},Y=(te,he,ge)=>{if(!H.callbackCalled&&(he&&!H.firstError&&(H.firstError=he),ge&&(z[te]=ge),H.completed++,H.completed===f.length)){H.callbackCalled=!0;const ve=z.filter(Ie=>Ie!==null);if(ve.length===0)return void D(H.firstError||new Error("All fonts failed to load"));const Te=this._composeGlyphs(ve);D(null,Te)}};for(let te=0;te{Y(te,he,ge)})}_loadFont(f,_,S,E,D){const z=`${f}:${_}`;if(this.cachedRanges.has(z)){const Y=this.cachedRanges.get(z);return void Wc.frame(()=>D(null,Y))}const H=this.pendingRequests.get(z);H?H.push(D):(this.pendingRequests.set(z,[D]),DV.loadGlyphRange(f,_,S,E,(Y,te)=>{Y||this.cachedRanges.set(z,te||null);const he=this.pendingRequests.get(z);if(this.pendingRequests.delete(z),he)for(const ge of he)ge(Y,te)}))}_composeGlyphs(f){const _={};let S,E;for(const D of f)if(S===void 0&&D.ascender!==void 0&&(S=D.ascender),E===void 0&&D.descender!==void 0&&(E=D.descender),D.glyphs)for(const z in D.glyphs)_[z]===void 0&&(_[z]=D.glyphs[z]);return{glyphs:_,ascender:S,descender:E}}}DV.loadGlyphRange=function(N,f,_,S,E){const D=256*f,z=D+255,H=S.transformRequest(S.normalizeGlyphsURL(_).replace("{fontstack}",N).replace("{range}",`${D}-${z}`),g0.Glyphs);gy(H,(Y,te)=>{if(Y)E(Y);else if(te){const he={},ge=function(ve){return new cte(ve).readFields(fGt,{})}(te);for(const ve of ge.glyphs)he[ve.id]=ve;E(null,{glyphs:he,ascender:ge.ascender,descender:ge.descender})}})};const OV=1e20;function RQe(N,f,_,S,E,D,z,H,Y){for(let te=f;te-1);Y++,D[Y]=H,z[Y]=te,z[Y+1]=OV}for(let H=0,Y=0;H{if(z){E.ascender=z.ascender,E.descender=z.descender;for(const H in z.glyphs)this._doesCharSupportLocalGlyph(+H)||(E.glyphs[+H]=z.glyphs[+H]);E.ranges[_]=!0}for(const H of E.requests[_]||[])H(D,z);delete E.requests[_]}))}getGlyphs(f,_){const S=[],E=this.url||Gr.GLYPHS_URL;for(const D in f)for(const z of f[D])S.push({stack:D,id:z});Ht(S,({stack:D,id:z},H)=>{let Y=this.entries[D];Y||(Y=this.entries[D]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let te=Y.glyphs[z];if(te!==void 0)return void H(null,{stack:D,id:z,glyph:te});if(te=this._tinySDF(Y,D,z),te)return Y.glyphs[z]=te,void H(null,{stack:D,id:z,glyph:te});const he=Math.floor(z/256);if(256*he>65535)return Mr("glyphs > 65535 not supported"),void H(null,{stack:D,id:z,glyph:te});if(Y.ranges[he])return void H(null,{stack:D,id:z,glyph:te});let ge=Y.requests[he];ge||(ge=Y.requests[he]=[],this.glyphLoader.loadGlyphRange(D,he,E,this.requestManager,(ve,Te)=>{if(Te){Y.ascender=Te.ascender,Y.descender=Te.descender;for(const Ie in Te.glyphs)this._doesCharSupportLocalGlyph(+Ie)||(Y.glyphs[+Ie]=Te.glyphs[+Ie]);Y.ranges[he]=!0}for(const Ie of ge)Ie(ve,Te);delete Y.requests[he]})),ge.push((ve,Te)=>{ve?H(ve):Te&&H(null,{stack:D,id:z,glyph:Te.glyphs[z]||null})})},(D,z)=>{if(D)_(D);else if(z){const H={};for(const{stack:Y,id:te,glyph:he}of z)H[Y]===void 0&&(H[Y]={}),H[Y].glyphs===void 0&&(H[Y].glyphs={}),H[Y].glyphs[te]=he&&{id:he.id,bitmap:he.bitmap.clone(),metrics:he.metrics},H[Y].ascender=this.entries[Y].ascender,H[Y].descender=this.entries[Y].descender;_(null,H)}})}_doesCharSupportLocalGlyph(f){return this.localGlyphMode!==GEe.none&&(this.localGlyphMode===GEe.all?!!this.localFontFamily:!!this.localFontFamily&&(cx(f)||Xb(f)||gv(f)||Am(f)||T1(f)||Cw(f)||(_=f)>=131072&&_<=173791||(S=>S>=66736&&S<=66815)(f)));var _}_tinySDF(f,_,S){const E=this.localFontFamily;if(!E||!this._doesCharSupportLocalGlyph(S))return;let D=f.tinySDF;if(!D){let et="400";/bold/i.test(_)?et="900":/medium/i.test(_)?et="500":/light/i.test(_)&&(et="200"),D=f.tinySDF=new mte.TinySDF({fontFamily:E,fontWeight:et,fontSize:48,buffer:6,radius:16}),D.fontWeight=et}const z=D.fontWeight;if(this.localGlyphs[z][S])return this.localGlyphs[z][S];const H=String.fromCodePoint(S),{data:Y,width:te,height:he,glyphWidth:ge,glyphHeight:ve,glyphLeft:Te,glyphTop:Ie,glyphAdvance:Ve}=D.draw(H);return this.localGlyphs[z][S]={id:S,bitmap:new yC({width:te,height:he},Y),metrics:{width:ge/2,height:ve/2,left:Te/2,top:Ie/2-27,advance:Ve/2,localGlyph:!0}}}}function OQe(N,f){return N+f[1]-f[0]}function WEe(N,f,_,S,E=1){const D=[],z=N.imagePrimary,H=z.pixelRatio,Y=z.paddedRect.w-2,te=z.paddedRect.h-2,he=(N.right-N.left)*E,ge=(N.bottom-N.top)*E,ve=z.stretchX||[[0,Y]],Te=z.stretchY||[[0,te]],Ie=ve.reduce(OQe,0),Ve=Te.reduce(OQe,0),et=Y-Ie,at=te-Ve;let ft=0,ut=Ie,Nt=0,Mt=Ve,It=0,xs=et,es=0,ps=at;if(z.content&&S){const ds=z.content;ft=pte(ve,0,ds[0]),Nt=pte(Te,0,ds[1]),ut=pte(ve,ds[0],ds[2]),Mt=pte(Te,ds[1],ds[3]),It=ds[0]-ft,es=ds[1]-Nt,xs=ds[2]-ds[0]-ut,ps=ds[3]-ds[1]-Mt}const cs=(ds,mn,xn,kn)=>{const En=fte(ds.stretch-ft,ut,he,N.left*E),Sn=xte(ds.fixed-It,xs,ds.stretch,Ie),Gn=fte(mn.stretch-Nt,Mt,ge,N.top*E),dn=xte(mn.fixed-es,ps,mn.stretch,Ve),An=fte(xn.stretch-ft,ut,he,N.left*E),Pn=xte(xn.fixed-It,xs,xn.stretch,Ie),Wn=fte(kn.stretch-Nt,Mt,ge,N.top*E),ir=xte(kn.fixed-es,ps,kn.stretch,Ve),Ur=new Xs(En,Gn),wr=new Xs(An,Gn),vr=new Xs(An,Wn),or=new Xs(En,Wn),Or=new Xs(Sn/H,dn/H),sa=new Xs(Pn/H,ir/H),Ta=f*Math.PI/180;if(Ta){const Di=Math.sin(Ta),Ld=Math.cos(Ta),tl=[Ld,-Di,Di,Ld];Ur._matMult(tl),wr._matMult(tl),or._matMult(tl),vr._matMult(tl)}const ya=ds.stretch+ds.fixed,xi=xn.stretch+xn.fixed,jo=mn.stretch+mn.fixed,gi=kn.stretch+kn.fixed,Ao=N.imageSecondary;return{tl:Ur,tr:wr,bl:or,br:vr,texPrimary:{x:z.paddedRect.x+1+ya,y:z.paddedRect.y+1+jo,w:xi-ya,h:gi-jo},texSecondary:Ao?{x:Ao.paddedRect.x+1+ya,y:Ao.paddedRect.y+1+jo,w:xi-ya,h:gi-jo}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Or,pixelOffsetBR:sa,minFontScaleX:xs/H/he,minFontScaleY:ps/H/ge,isSDF:_}};if(z.stretchX||z.stretchY){const ds=FQe(ve,et,Ie),mn=FQe(Te,at,Ve);for(let xn=0;xn0?[ft,-ut]:Nt<0?[-ft,ut]:ft===0?[ut,ft]:[ut,-ft]}(_);let Te=Math.abs(f.top-f.bottom);for(const at of f.positionedLines)Te-=at.lineOffset;const Ie=f.positionedLines.length,Ve=Te/Ie;let et=f.top-_[1];for(let at=0;atD)&&(D=Ie.x),(!Te||Ie.y>z)&&(z=Ie.y)}const Y=Math.min(D-S,z-E);let te=Y/2;const he=new hh([],kGt);if(Y===0)return new Xs(S,E);for(let Te=S;Tege.d||!ge.d)&&(ge=Te,_&&console.log("found best %d after %d probes",Math.round(1e4*Te.d)/1e4,ve)),Te.max-ge.d<=f||(te=Te.h/2,he.push(new mF(Te.p.x-te,Te.p.y-te,te,N)),he.push(new mF(Te.p.x+te,Te.p.y-te,te,N)),he.push(new mF(Te.p.x-te,Te.p.y+te,te,N)),he.push(new mF(Te.p.x+te,Te.p.y+te,te,N)),ve+=4)}return _&&(console.log(`num probes: ${ve}`),console.log(`best distance: ${ge.d}`)),ge.p}function kGt(N,f){return f.max-N.max}mte.TinySDF=class{constructor({fontSize:N=24,buffer:f=3,radius:_=8,cutoff:S=.25,fontFamily:E="sans-serif",fontWeight:D="normal",fontStyle:z="normal",lang:H=null}={}){this.buffer=f,this.cutoff=S,this.radius=_,this.lang=H;const Y=this.size=N+4*f,te=this._createCanvas(Y),he=this.ctx=te.getContext("2d",{willReadFrequently:!0});he.font=`${z} ${D} ${N}px ${E}`,he.textBaseline="alphabetic",he.textAlign="left",he.fillStyle="black",this.gridOuter=new Float64Array(Y*Y),this.gridInner=new Float64Array(Y*Y),this.f=new Float64Array(Y),this.z=new Float64Array(Y+1),this.v=new Uint16Array(Y)}_createCanvas(N){const f=document.createElement("canvas");return f.width=f.height=N,f}draw(N){const{width:f,actualBoundingBoxAscent:_,actualBoundingBoxDescent:S,actualBoundingBoxLeft:E,actualBoundingBoxRight:D}=this.ctx.measureText(N),z=Math.ceil(_),H=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(D-E))),Y=Math.min(this.size-this.buffer,z+Math.ceil(S)),te=H+2*this.buffer,he=Y+2*this.buffer,ge=Math.max(te*he,0),ve=new Uint8ClampedArray(ge),Te={data:ve,width:te,height:he,glyphWidth:H,glyphHeight:Y,glyphTop:z,glyphLeft:0,glyphAdvance:f};if(H===0||Y===0)return Te;const{ctx:Ie,buffer:Ve,gridInner:et,gridOuter:at}=this;this.lang&&(Ie.lang=this.lang),Ie.clearRect(Ve,Ve,H,Y),Ie.fillText(N,Ve,Ve+z);const ft=Ie.getImageData(Ve,Ve,H,Y);at.fill(OV,0,ge),et.fill(0,0,ge);for(let ut=0;ut0?xs*xs:0,et[It]=xs<0?xs*xs:0}}RQe(at,0,0,te,he,te,this.f,this.v,this.z),RQe(et,Ve,Ve,H,Y,te,this.f,this.v,this.z);for(let ut=0;utD.y!=Ve.y>D.y&&D.x<(Ve.x-Ie.x)*(D.y-Ie.y)/(Ve.y-Ie.y)+Ie.x&&(H=!H),Y=Math.min(Y,Ew(D,Ie,Ve))}}return(H?1:-1)*Math.sqrt(Y)}(this.p,E),this.max=this.d+this.h*Math.SQRT2}}const SGt=Object.keys,KEe=Number.POSITIVE_INFINITY,CGt=Math.sqrt(2);function wC(N,f,_,S,E,D){const z=zEe(N)&&N.collisionPadding?N.collisionPadding:[0,0,0,0],H={top:N.top-z[1],bottom:N.bottom+z[3],left:N.left-z[0],right:N.right+z[2],scaled:!1};return S!==void 0&&function(Y,te){Y.top*=te,Y.bottom*=te,Y.left*=te,Y.right*=te,Y.scaled=!0}(H,S),D&&(H.left+=D[0],H.right+=D[0],H.top+=D[1],H.bottom+=D[1]),_&&function(Y,te,he){if(!te)return;const ge=pr(te),ve=new Xs(he?he[0]:0,he?he[1]:0),Te=new Xs(Y.left,Y.top),Ie=new Xs(Y.right,Y.top),Ve=new Xs(Y.left,Y.bottom),et=new Xs(Y.right,Y.bottom);Te._rotateAround(ge,ve),Ie._rotateAround(ge,ve),Ve._rotateAround(ge,ve),et._rotateAround(ge,ve),Y.left=Math.min(Te.x,Ie.x,Ve.x,et.x),Y.right=Math.max(Te.x,Ie.x,Ve.x,et.x),Y.top=Math.min(Te.y,Ie.y,Ve.y,et.y),Y.bottom=Math.max(Te.y,Ie.y,Ve.y,et.y)}(H,_,E),f?{top:Math.min(f.top,H.top),bottom:Math.max(f.bottom,H.bottom),left:Math.min(f.left,H.left),right:Math.max(f.right,H.right),scaled:f.scaled||H.scaled}:H}function $Qe(N,[f,_]){let S=0,E=0;if(_===KEe){f<0&&(f=0);const D=f/CGt;switch(N){case"top-right":case"top-left":E=D-7;break;case"bottom-right":case"bottom-left":E=7-D;break;case"bottom":E=7-f;break;case"top":E=f-7}switch(N){case"top-right":case"bottom-right":S=-D;break;case"top-left":case"bottom-left":S=D;break;case"left":S=f;break;case"right":S=-f}}else{switch(f=Math.abs(f),_=Math.abs(_),N){case"top-right":case"top-left":case"top":E=_-7;break;case"bottom-right":case"bottom-left":case"bottom":E=7-_}switch(N){case"top-right":case"bottom-right":case"right":S=-f;break;case"top-left":case"bottom-left":case"left":S=f}}return[S,E]}function AGt(N,f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie){const Ve=N.layers[0],et=Ve.appearances;if(et.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const at={iconBBox:null,iconVerticalBBox:null},ft={textBBox:null,textVerticalBBox:null},{baseIconRotate:ut,baseTextRotate:Nt,iconScaleFactor:Mt}=function(xs,es,ps){const cs=xs.get("icon-rotate").evaluate(es,{},ps),ds=xs.get("text-rotate").evaluate(es,{},ps),[mn,xn]=xs.get("icon-size-scale-range");return{baseIconRotate:cs,baseTextRotate:ds,iconScaleFactor:it(1,mn,xn)}}(S,E,D);f&&(at.iconBBox=wC(f,at.iconBBox,ut),_)&&(at.iconVerticalBBox=wC(_,at.iconVerticalBBox,ut+90));const It=yte(ge.horizontal);It&&(ft.textBBox=wC(It,ft.textBBox,Nt,1,Te)),ge.vertical&&(ft.textVerticalBBox=wC(ge.vertical,ft.textVerticalBBox,Nt+90,1,Te));for(const xs of et)xs.hasIconLayoutProperties()&&TGt(at,N,Ve,xs,E,D,H,ut,z,Y,f,te,Mt,he,Ie),xs.hasTextLayoutProperties()&&EGt(ft,Ve,xs,E,D,Te,Nt,ve,It,ge.vertical);return{iconBBox:at.iconBBox,iconVerticalBBox:at.iconVerticalBBox,textBBox:ft.textBBox,textVerticalBBox:ft.textVerticalBBox}}function TGt(N,f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie){const{appearanceIconOffset:Ve,appearanceIconRotate:et,appearanceIconSize:at}=UQe(S,_,E,D,z,H,Y,te.iconScaleFactor);let ft=null,ut=null,Nt=null;S.hasLayoutProperty("icon-image")?Nt=function(It,xs,es,ps,cs,ds,mn,xn){let kn=null;const En=xs.getAppearanceValueAndResolveTokens(es,"icon-image",ps,cs,xn);if(En){const Sn=It.getResolvedImageFromTokens(En),Gn=es.hasLayoutProperty("icon-size")?es.getUnevaluatedLayoutProperty("icon-size"):xs._unevaluatedLayout._values["icon-size"],dn=FV(Sn,J6(It.zoom,Gn,It.worldview,xn),Gn,cs,It.zoom,ps,It.pixelRatio,mn,It.worldview,xn);kn=ds.get(dn.iconPrimary.toString())}return kn}(f,_,S,E,D,ge,ve,Ie):he&&(Nt=he.imagePrimary),Nt&&(ft=ute(Nt,null,Ve,Te),f.allowVerticalPlacement&&(ut=ute(Nt,null,Ve,Te)));const Mt=Y>0?at/Y:1;ft&&(N.iconBBox=wC(ft,N.iconBBox,et,Mt!==1?Mt:void 0)),ut&&(N.iconVerticalBBox=wC(ut,N.iconVerticalBBox,et+90,Mt!==1?Mt:void 0))}function UQe(N,f,_,S,E,D,z,H){const Y=N.hasLayoutProperty("icon-offset")?f.getAppearanceValueAndResolveTokens(N,"icon-offset",_,S,[]):null,te=Y&&Array.isArray(Y)?Y:E,he=N.hasLayoutProperty("icon-rotate")?f.getAppearanceValueAndResolveTokens(N,"icon-rotate",_,S,[]):null,ge=typeof he=="number"?he:D,ve=N.hasLayoutProperty("icon-size")?f.getAppearanceValueAndResolveTokens(N,"icon-size",_,S,[]):null;return{appearanceIconOffset:te,appearanceIconRotate:ge,appearanceIconSize:typeof ve=="number"?ve*H:z}}function EGt(N,f,_,S,E,D,z,H,Y,te){const{appearanceTextOffset:he,appearanceTextRotate:ge,appearanceTextSize:ve}=qQe(_,f,S,E,D,z,H),Te=ve/H,Ie=[(he[0]-D[0])*Te,(he[1]-D[1])*Te],Ve=Ie[0]!==0||Ie[1]!==0;Y&&(N.textBBox=wC(Y,N.textBBox,ge,Te,he,Ve?Ie:void 0)),te&&(N.textVerticalBBox=wC(te,N.textVerticalBBox,ge+90,Te,he,Ve?Ie:void 0))}function qQe(N,f,_,S,E,D,z){const H=N.hasLayoutProperty("text-offset")?f.getAppearanceValueAndResolveTokens(N,"text-offset",_,S,[]):null,Y=H&&Array.isArray(H)?[H[0]*Mm,H[1]*Mm]:E,te=N.hasLayoutProperty("text-rotate")?f.getAppearanceValueAndResolveTokens(N,"text-rotate",_,S,[]):null,he=typeof te=="number"?te:D,ge=N.hasLayoutProperty("text-size")?f.getAppearanceValueAndResolveTokens(N,"text-size",_,S,[]):null;return{appearanceTextOffset:Y,appearanceTextRotate:he,appearanceTextSize:typeof ge=="number"?ge:z}}function gte(N,f,_,S,E,D,z,H,Y){if(!f||!f.usvg)return;const te=kQe(S),he=kQe(E),ge=D!=="both"&&D!=="width"||!jQe(S)?1:he.width/te.width,ve=D!=="both"&&D!=="height"||!NQe(S)?1:he.height/te.height;_.scaleSelf(ge,ve);const Te=_.toString();z.set(Te,_),H.set(Te,f);const{imagePosition:Ie}=VEe(Te,f,1);Y.set(Te,Ie)}function VQe(N,f,_,S,E,D,z,H,Y,te){if(!N)return;const he=function(ge,ve,Te,Ie,Ve,et,at){if(ge.kind==="camera")return ge.maxSize;if(ge.kind==="composite"){const ft=ve.possiblyEvaluate(new bi(ge.maxZoom,{worldview:et}),Te,at).evaluate(Ve,{},Te,at),ut=ve.possiblyEvaluate(new bi(ge.minZoom,{worldview:et}),Te,at).evaluate(Ve,{},Te,at);return Math.max(ft,ut)}return ve.possiblyEvaluate(new bi(Ie,{worldview:et}),Te,at).evaluate(Ve,{},Te,at)}(f,_,S,E,D,Y,te);return N.scaleSelf(he*H*z)}function FV(N,f,_,S,E,D,z,H,Y,te){return{iconPrimary:VQe(N.getPrimary(),f,_,S,E,D,z,H,Y,te),iconSecondary:VQe(N.getSecondary(),f,_,S,E,D,z,H,Y,te)}}function MGt(N,f,_){if(!f)return;const S=_.get(N.toString()),E=_.get(f.toString());S&&E&&(S.paddedRect.w===E.paddedRect.w&&S.paddedRect.h===E.paddedRect.h||Mr(`Mismatch in icon variant sizes: ${N.toString()} and ${f.toString()}`),S.usvg!==E.usvg&&Mr(`Mismatch in icon variant image types: ${N.id} and ${f.id}`))}function HQe(N,f,_,S){if(!N)return;const E=f.get(_.toString());if(E&&(N.imagePrimary=E),S){const D=f.get(S.toString());N.imageSecondary=D}}function LGt(N,f){for(const _ in N.horizontal)GQe(N.horizontal[_],f);GQe(N.vertical,f)}function GQe(N,f){if(N){for(const _ of N.positionedLines)for(const S of _.positionedGlyphs)if(S.image!==null){const E=S.image.toString();S.rect=f.get(E).paddedRect}}}function YEe(N){switch(N){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function PGt(N,f,_,S,E,D,z,H,Y){const te=yte(D.horizontal)||D.vertical,he=_.get("icon-text-fit-padding").evaluate(S,{},E);let ge,ve=f;return f&&Y!=="none"&&(N.allowVerticalPlacement&&D.vertical&&(ge=BEe(f,D.vertical,Y,he,H,z)),te&&(ve=BEe(f,te,Y,he,H,z))),{defaultShapedIcon:ve,verticallyShapedIcon:ge}}function WQe(N,f){return N*f/24}function IGt(N,f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et,at,ft,ut,Nt,Mt,It,xs){let es=z.textMaxSize.evaluate(f,{},ve);es===void 0?es=H*z.textScaleFactor:es*=z.textScaleFactor;const ps=N.layers[0].layout,cs=WQe(H,z.textScaleFactor),ds=yte(_.horizontal)||_.vertical,mn=N.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),xn=N.getAppearanceFeatureData(f.index);(et!=="none"||mn)&&xn&&(xn.textShaping=ds,xn.iconTextFitPadding=ps.get("icon-text-fit-padding").evaluate(f,{},ve),xn.fontScale=cs,xn.textScaleFactor=z.textScaleFactor);const kn=Te.name==="globe",En=N.tilePixelRatio*es/24,Sn=(ir=N.overscaling,N.zoom>18&&ir>2&&(ir>>=1),Math.max(nr/(512*ir),1)*ps.get("symbol-spacing")),Gn=ps.get("text-padding")*N.tilePixelRatio,dn=ps.get("icon-padding")*N.tilePixelRatio,An=pr(ps.get("text-max-angle")),Pn=ps.get("icon-rotation-alignment")==="map"&&ut!=="point",Wn=Sn/2;var ir;N.hasAnyIconTextFit===!1&&et!=="none"&&(N.hasAnyIconTextFit=!0);const Ur=f.properties?+f.properties[Ai]:null,wr=Ur&&N.elevationFeatureIdToIndex?N.elevationFeatureIdToIndex.get(Ur):65535,vr=(or,Or,sa)=>{if(Or.x<0||Or.x>=nr||Or.y<0||Or.y>=nr)return;let Ta=null;if(kn){const{x:ya,y:xi,z:jo}=Te.projectTilePoint(Or.x,Or.y,sa);Ta={anchor:new qS(ya,xi,jo,0,void 0),up:Te.upVector(sa,Or.x,Or.y)}}(function(ya,xi,jo,gi,Ao,Di,Ld,tl,Oo,Yl,bd,Lm,_d,tu,Qu,su,zf,Pm,Ui,Mg,wu,xp,Lg,Bf,Pd,Ux,gp,Dte,_F,P0,v6e,wF){const VS=ya.addToLineVertexArray(xi,gi);let HS,Jb,e_,aM,jF,Qi,yp,nu=0,nm=0,t_=0,Cv=0,Av=-1,Tv=-1;const Pw={};let Ote=rd("");const y2=jo?jo.anchor:xi,NF=Dte!=="none";let kF=0,Lh=0;if(Oo._unevaluatedLayout.getValue("text-radial-offset")===void 0){const ju=Oo.layout.get("text-offset").evaluate(wu,{},Pd);kF=ju[0]*Mm,Lh=ju[1]*Mm}else kF=Oo.layout.get("text-radial-offset").evaluate(wu,{},Pd)*Mm,Lh=KEe;if(ya.allowVerticalPlacement&&Ao.vertical){const ju=Ao.vertical;if(Qu)Qi=QEe(ju),tl&&(yp=QEe(tl));else{const Pg=Oo.layout.get("text-rotate").evaluate(wu,{},Pd)+90;e_=vte(Yl,y2,xi,bd,Lm,_d,ju,tu,Pg,su,wF),tl&&(aM=vte(Yl,y2,xi,bd,Lm,_d,tl,Pm,Pg,null,v6e))}}if(Di){const ju=Oo.layout.get("icon-rotate").evaluate(wu,{},Pd),Pg=WEe(Di,ju,Lg,NF,xp.iconScaleFactor),I0=tl?WEe(tl,ju,Lg,NF,xp.iconScaleFactor):void 0;Jb=vte(Yl,y2,xi,bd,Lm,_d,Di,Pm,ju,null,P0);const Rw=function(v2,JV,SF,YWt,ZWt,fet,xet,XWt,Vzn,_6e){const get=v2.layers[0],yet=get.appearances;let CF=JV.length;if(SF&&(CF=Math.max(CF,SF.length)),yet.length===0)return CF;const[QWt,JWt]=YWt.get("icon-size-scale-range"),eKt=it(1,QWt,JWt);for(const $te of yet)if($te.hasLayoutProperty("icon-image")){const vet=get.getAppearanceValueAndResolveTokens($te,"icon-image",fet,xet,_6e);if(vet){const bet=v2.getResolvedImageFromTokens(vet);if(bet){const _et=$te.hasLayoutProperty("icon-size")?$te.getUnevaluatedLayoutProperty("icon-size"):ZWt._values["icon-size"],tKt=FV(bet,J6(v2.zoom,_et,v2.worldview,_6e),_et,xet,v2.zoom,fet,v2.pixelRatio,eKt,v2.worldview,_6e),wet=XWt.get(tKt.iconPrimary.toString());wet&&(CF=Math.max(CF,wGt(wet)))}}}return CF}(ya,Pg,I0,Oo.layout,Oo._unevaluatedLayout,wu,Pd,ya.iconAtlasPositions,0,Bf);nu=4*Rw;const Fte=Oo.layout.get("icon-size").evaluate(wu,{},Pd,Bf),zte=xp.compositeIconSizes?xp.compositeIconSizes[0].evaluate(wu,{},Pd,Bf):0,b6e=xp.compositeIconSizes?xp.compositeIconSizes[1].evaluate(wu,{},Pd,Bf):0,Bte=XEe(ya.layerIds[0],ya.iconSizeData,Fte,xp.iconScaleFactor,zte,b6e);ya.addSymbols(ya.icon,Pg,Bte,Mg,Ui,wu,void 0,jo,xi,VS.lineStartIndex,VS.lineLength,-1,Bf,Pd,Ux,gp,ya.symbolInstances.length,Rw),Av=ya.icon.placedSymbolArray.length-1,I0&&(nm=4*Rw,ya.addSymbols(ya.icon,I0,Bte,Mg,Ui,wu,Sv.vertical,jo,xi,VS.lineStartIndex,VS.lineLength,-1,Bf,Pd,Ux,gp,ya.symbolInstances.length,Rw),Tv=ya.icon.placedSymbolArray.length-1)}for(const ju in Ao.horizontal){const Pg=ju,I0=Ao.horizontal[Pg];HS||(Ote=rd(I0.text),Qu?jF=QEe(I0):HS=vte(Yl,y2,xi,bd,Lm,_d,I0,tu,Oo.layout.get("text-rotate").evaluate(wu,{},Pd),su,wF));const Rw=I0.positionedLines.length===1;if(t_+=KQe(ya,jo,xi,I0,Ld,Oo,Qu,wu,su,VS,Ao.vertical?Sv.horizontal:Sv.horizontalOnly,Rw?SGt(Ao.horizontal):[Pg],Pw,Av,xp,Bf,Pd,ya.symbolInstances.length,Ux),Rw)break}Ao.vertical&&(Cv+=KQe(ya,jo,xi,Ao.vertical,Ld,Oo,Qu,wu,su,VS,Sv.vertical,["vertical"],Pw,Tv,xp,Bf,Pd,ya.symbolInstances.length,Ux));let fh=-1;const rm=(ju,Pg)=>ju?Math.max(ju,Pg):Pg;fh=rm(jF,fh),fh=rm(Qi,fh),fh=rm(yp,fh);const Iw=fh>-1?1:0;ya.glyphOffsetArray.length>=65535&&Mr("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),wu.sortKey!==void 0&&ya.addToSortKeyRanges(ya.symbolInstances.length,wu.sortKey),ya.symbolInstances.emplaceBack(xi.x,xi.y,y2.x,y2.y,y2.z,Pw.right>=0?Pw.right:-1,Pw.center>=0?Pw.center:-1,Pw.left>=0?Pw.left:-1,Pw.vertical>=0?Pw.vertical:-1,Av,Tv,Ote,HS!==void 0?HS:ya.collisionBoxArray.length,HS!==void 0?HS+1:ya.collisionBoxArray.length,e_!==void 0?e_:ya.collisionBoxArray.length,e_!==void 0?e_+1:ya.collisionBoxArray.length,Jb!==void 0?Jb:ya.collisionBoxArray.length,Jb!==void 0?Jb+1:ya.collisionBoxArray.length,aM||ya.collisionBoxArray.length,aM?aM+1:ya.collisionBoxArray.length,bd,t_,Cv,nu,nm,Iw,0,kF,Lh,fh,0,NF?1:0,_F)})(N,Or,Ta,or,_,S,D,E,N.layers[0],N.collisionBoxArray,f.index,f.sourceLayerIndex,N.index,Gn,ft,te,0,dn,Pn,at,f,z,he,ge,ve,Ie,Ve,et,wr,Nt,Mt,It)};if(ut==="line")for(const or of Qee(f.geometry,0,0,nr,nr)){const Or=_Gt(or,Sn,An,_.vertical||ds,S,24,En,N.overscaling,nr);for(const sa of Or)ds&&RGt(N,ds.text,Wn,sa)||vr(or,sa,ve)}else if(ut==="line-center"){for(const or of f.geometry)if(or.length>1){const Or=bGt(or,An,_.vertical||ds,S,24,En);Or&&vr(or,Or,ve)}}else if(f.type==="Polygon")for(const or of bV(f.geometry,0)){const Or=NGt(or,16);vr(or[0],new qS(Or.x,Or.y,0,0,void 0),ve)}else if(f.type==="LineString")for(const or of f.geometry)vr(or,new qS(or[0].x,or[0].y,0,0,void 0),ve);else if(f.type==="Point")for(const or of f.geometry)for(const Or of or)vr([Or],new qS(Or.x,Or.y,0,0,void 0),ve)}const ZEe=255,eM=ZEe*US;function KQe(N,f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et,at,ft){const ut=BQe(0,S,Y,D,z,H,E,N.allowVerticalPlacement,void 0,Ie.textScaleFactor),Nt=D.layout.get("text-size").evaluate(H,{},et),Mt=Ie.compositeTextSizes?Ie.compositeTextSizes[0].evaluate(H,{},et):0,It=Ie.compositeTextSizes?Ie.compositeTextSizes[1].evaluate(H,{},et):0,xs=XEe(N.layerIds[0],N.textSizeData,Nt,Ie.textScaleFactor,Mt,It);N.addSymbols(N.text,ut,xs,Y,z,H,he,f,_,te.lineStartIndex,te.lineLength,Te,Ve,et,ft,!1,at,ut.length);for(const es of ge)ve[es]=N.text.placedSymbolArray.length-1;return 4*ut.length}function XEe(N,f,_,S,E,D){const z=f;let H=null;return z.kind==="source"?(H=[US*_*S],H[0]>eM&&Mr(`${N}: Value for "text-size" is >= ${ZEe}. Reduce your "text-size".`)):z.kind==="composite"&&(H=[US*E*S,US*D*S],(H[0]>eM||H[1]>eM)&&Mr(`${N}: Value for "text-size" is >= ${ZEe}. Reduce your "text-size".`)),H}function yte(N){for(const f in N)return N[f];return null}function vte(N,f,_,S,E,D,z,H,Y,te,he){let ge,ve,Te,Ie;if(ge=he?he.top:z.top,ve=he?he.bottom:z.bottom,Te=he?he.left:z.left,Ie=he?he.right:z.right,zEe(z)&&z.collisionPadding){const Ve=z.collisionPadding;Te-=Ve[0],ge-=Ve[1],Ie+=Ve[2],ve+=Ve[3]}if(Y){const Ve=new Xs(Te,ge),et=new Xs(Ie,ge),at=new Xs(Te,ve),ft=new Xs(Ie,ve),ut=pr(Y);let Nt=new Xs(0,0);te&&(Nt=new Xs(te[0],te[1])),Ve._rotateAround(ut,Nt),et._rotateAround(ut,Nt),at._rotateAround(ut,Nt),ft._rotateAround(ut,Nt),Te=Math.min(Ve.x,et.x,at.x,ft.x),Ie=Math.max(Ve.x,et.x,at.x,ft.x),ge=Math.min(Ve.y,et.y,at.y,ft.y),ve=Math.max(Ve.y,et.y,at.y,ft.y)}return N.emplaceBack(f.x,f.y,f.z,_.x,_.y,Te,ge,Ie,ve,H,S,E,D),N.length-1}function QEe(N){zEe(N)&&N.collisionPadding&&(N.top-=N.collisionPadding[1],N.bottom+=N.collisionPadding[3]);const f=N.bottom-N.top;return f>0?Math.max(10,f):null}function RGt(N,f,_,S){const E=N.compareText;if(f in E){const D=E[f];for(let z=D.length-1;z>=0;z--)if(S.dist(D[z])<_)return!0}else E[f]=[];return E[f].push(S),!1}function YQe(N,f){const _=N.fovAboveCenter,S=N.elevation?N.elevation.getMinElevationBelowMSL()*f:0,E=Math.min(S,N.isOrthographic?-10*f:0),D=(N._camera.position[2]*N.worldSize-E)/Math.cos(N._pitch),z=Math.sin(_)*D/Math.sin(Math.max(Math.PI/2-N._pitch-_,.01));let H=Math.sin(N._pitch)*z+D;const Y=D*(1/N._horizonShift);if(!N.elevation||N.elevation.exaggeration()===0){let te=Math.max(N.zoom-17,0);N.isOrthographic&&(te/=10),H*=1+te}return Math.min(1.01*H,Y)}function tM(N,f){if(!f.isReprojectedInTileSpace)return{scale:1<ut&&(Nt(It,kn,es,ps,mn,xn),Nt(kn,xs,mn,xn,cs,ds))}Nt(ge,ve,S,D,E,D),Nt(ve,Te,E,D,E,z),Nt(Te,Ie,E,z,S,z),Nt(Ie,ge,S,z,S,D),Ve-=ut,et-=ut,at+=ut,ft+=ut;const Mt=1/Math.max(at-Ve,ft-et);return{scale:Mt,x:Ve*Mt,y:et*Mt,x2:at*Mt,y2:ft*Mt,projection:f}}function ZQe(N,{x:f,y:_},S=0){return new Xs(((f-S)*N.scale-N.x)*nr,(_*N.scale-N.y)*nr)}const DGt=g(new Float32Array(16));class jC{constructor(f){this.spec=f,this.name=f.name,this.wrap=!1,this.requiresDraping=!1,this.supportsWorldCopies=!1,this.supportsTerrain=!1,this.supportsFog=!1,this.supportsFreeCamera=!1,this.zAxisUnit="meters",this.isReprojectedInTileSpace=!0,this.unsupportedLayers=["custom"],this.center=[0,0],this.range=[3.5,7]}project(f,_){return{x:0,y:0,z:0}}unproject(f,_){return new Cs(0,0)}projectTilePoint(f,_,S){return{x:f,y:_,z:0}}locationPoint(f,_,S,E=!0){return f._coordinatePoint(f.locationCoordinate(_,S),E)}pixelsPerMeter(f,_){return Ys(1,f)*_}pixelSpaceConversion(f,_,S){return 1}farthestPixelDistance(f){return YQe(f,f.pixelsPerMeter)}pointCoordinate(f,_,S,E){const D=f.horizonLineFromTop(!1),z=new Xs(_,Math.max(D,S));return f.rayIntersectionCoordinate(f.pointRayIntersection(z,E))}pointCoordinate3D(f,_,S){const E=new Xs(_,S);if(f.elevation)return f.elevation.pointCoordinate(E);{const D=this.pointCoordinate(f,E.x,E.y,0);return[D.x,D.y,D.z]}}isPointAboveHorizon(f,_){if(f.elevation&&f.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(f,_.x,_.y);const S=f.horizonLineFromTop();return _.y0?_<-pF+S&&(_=-pF+S):_>pF-S&&(_=pF-S);const z=D/Math.pow(_te(_),E);let H=z*Math.sin(E*f),Y=D-z*Math.cos(E*f);return H=.5*(H/Math.PI+.5),Y=.5*(Y/Math.PI+.5),{x:H,y:this.southernCenter?Y:1-Y,z:0}}unproject(f,_){f=(2*f-.5)*Math.PI,this.southernCenter&&(_=1-_),_=(2*(1-_)-.5)*Math.PI;const{n:S,f:E}=this,D=E-_,z=Math.sign(D),H=Math.sign(S)*Math.sqrt(f*f+D*D);let Y=Math.atan2(f,Math.abs(D))*z;D*S<0&&(Y-=Math.PI*Math.sign(f)*z);const te=it(rn(Y/S)+this.center[0],-180,180),he=it(rn(2*Math.atan(Math.pow(E/H,1/S))-pF),-85.051129,jn);return new Cs(te,this.southernCenter?-he:he)}}class XQe extends jC{constructor(f){super(f),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(f,_){return{x:Ln(f),y:$n(_),z:0}}unproject(f,_){const S=Es(f),E=hn(_);return new Cs(S,E)}}const QQe=pr(jn);class $Gt extends jC{project(f,_){const S=(_=pr(_))*_,E=S*S;return{x:.5*((f=pr(f))*(.8707-.131979*S+E*(E*(.003971*S-.001529*E)-.013791))/Math.PI+.5),y:1-.5*(_*(1.007226+S*(.015085+E*(.028874*S-.044475-.005916*E)))/Math.PI+1),z:0}}unproject(f,_){f=(2*f-.5)*Math.PI;let S=_=(2*(1-_)-1)*Math.PI,E=25,D=0,z=S*S;do{z=S*S;const te=z*z;D=(S*(1.007226+z*(.015085+te*(.028874*z-.044475-.005916*te)))-_)/(1.007226+z*(.045255+te*(.259866*z-.311325-.005916*11*te))),S=it(S-D,-QQe,QQe)}while(Math.abs(D)>1e-6&&--E>0);z=S*S;const H=it(rn(f/(.8707+z*(z*(z*z*z*(.003971-.001529*z)-.013791)-.131979))),-180,180),Y=rn(S);return new Cs(H,Y)}}const JQe=pr(jn);class UGt extends jC{project(f,_){_=pr(_),f=pr(f);const S=Math.cos(_),E=2/Math.PI,D=Math.acos(S*Math.cos(f/2)),z=Math.sin(D)/D,H=.5*(f*E+2*S*Math.sin(f/2)/z)||0,Y=.5*(_+Math.sin(_)/z)||0;return{x:.5*(H/Math.PI+.5),y:1-.5*(Y/Math.PI+1),z:0}}unproject(f,_){let S=f=(2*f-.5)*Math.PI,E=_=(2*(1-_)-1)*Math.PI,D=25;const z=1e-6;let H=0,Y=0;do{const te=Math.cos(E),he=Math.sin(E),ge=2*he*te,ve=he*he,Te=te*te,Ie=Math.cos(S/2),Ve=Math.sin(S/2),et=2*Ie*Ve,at=Ve*Ve,ft=1-Te*Ie*Ie,ut=ft?1/ft:0,Nt=ft?Math.acos(te*Ie)*Math.sqrt(1/ft):0,Mt=.5*(2*Nt*te*Ve+2*S/Math.PI)-f,It=.5*(Nt*he+E)-_,xs=.5*ut*(Te*at+Nt*te*Ie*ve)+1/Math.PI,es=ut*(et*ge/4-Nt*he*Ve),ps=.125*ut*(ge*Ve-Nt*he*Te*et),cs=.5*ut*(ve*Ie+Nt*at*te)+.5,ds=es*ps-cs*xs;H=(It*es-Mt*cs)/ds,Y=(Mt*ps-It*xs)/ds,S=it(S-H,-Math.PI,Math.PI),E=it(E-Y,-JQe,JQe)}while((Math.abs(H)>z||Math.abs(Y)>z)&&--D>0);return new Cs(rn(S),rn(E))}}class eJe extends jC{constructor(f){super(f),this.center=f.center||[0,0],this.parallels=f.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(pr(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(f,_){const{scale:S,cosPhi:E}=this;return{x:pr(f)*E*S+.5,y:-Math.sin(pr(_))/E*S+.5,z:0}}unproject(f,_){const{scale:S,cosPhi:E}=this,D=-(_-.5)/S,z=it(rn((f-.5)/S)/E,-180,180),H=Math.asin(it(D*E,-1,1)),Y=it(rn(H),-85.051129,jn);return new Cs(z,Y)}}class qGt extends XQe{constructor(f){super(f),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(f,_,S){const E=mV(f,_,S);return Ge(E,E,pV(uk(S))),{x:E[0],y:E[1],z:E[2]}}locationPoint(f,_,S){const E=Xt(_.lat,_.lng),D=Le([],E),z=S?f._centerAltitude+S:f.elevation?f.elevation.getAtPointOrZero(f.locationCoordinate(_),f._centerAltitude):f._centerAltitude;je(E,E,D,Ys(1,0)*nr*z);const H=g(new Float64Array(16));return v(H,f.pixelMatrix,f.globeMatrix),Ge(E,E,H),new Xs(E[0],E[1])}pixelsPerMeter(f,_){return Ys(1,0)*_}pixelSpaceConversion(f,_,S){const E=Ys(1,f)*_,D=xr(Ys(1,45)*_,E,S);return this.pixelsPerMeter(f,_)/D}createTileMatrix(f,_,S){const E=GTe(uk(S.canonical));return v(new Float64Array(16),f.globeMatrix,E)}createInversionMatrix(f,_){const{center:S}=f,E=pV(uk(_));return M(E,E,pr(S.lng)),T(E,E,pr(S.lat)),C(E,E,[f._pixelsPerMercatorPixel,f._pixelsPerMercatorPixel,1]),Float32Array.from(E)}pointCoordinate(f,_,S,E){return xZe(f,_,S,!0)||new ta(0,0)}pointCoordinate3D(f,_,S){const E=this.pointCoordinate(f,_,S,0);return[E.x,E.y,E.z]}isPointAboveHorizon(f,_){return!xZe(f,_.x,_.y,!1)}farthestPixelDistance(f){const _=function(E,D){const z=E.cameraToCenterDistance,H=E._centerAltitude*D,Y=E._camera,te=E._camera.forward(),he=le([],we([],te,-z),[0,0,H]),ge=E.worldSize/(2*Math.PI),ve=[0,0,-ge],Te=E.width/E.height,Ie=Math.tan(E.fovAboveCenter),Ve=we([],Y.up(),Ie),et=we([],Y.right(),Ie*Te),at=Le([],le([],le([],te,Ve),et)),ft=[];let ut;if(new Ji(he,at).closestPointOnSphere(ve,ge,ft)){const Nt=le([],ft,ve),Mt=Ue([],Nt,he);ut=Math.cos(E.fovAboveCenter)*K(Mt)}else{const Nt=Ue([],he,ve),Mt=Ue([],ve,he);Le(Mt,Mt);const It=K(Nt)-ge;ut=Math.sqrt(It*(It+2*ge));const xs=Math.acos(ut/(ge+It))-Math.acos(De(te,Mt));ut*=Math.cos(xs)}return 1.01*ut}(f,this.pixelsPerMeter(f.center.lat,f.worldSize)),S=zS(f.zoom);if(S>0){const E=YQe(f,Ys(1,f.center.lat)*f.worldSize),D=f.worldSize/(2*Math.PI),z=Math.max(f.width,f.height)/f.worldSize*Math.PI;return xr(_,E+D*(1-Math.cos(z)),Math.pow(S,10))}return _}upVector(f,_,S){return mV(_,S,f,1)}upVectorScale(f){return{metersToTile:Iee(Dee(uk(f)))}}}function tJe(N){const f=N.parallels,_=!!f&&Math.abs(f[0]+f[1])<.01;switch(N.name){case"mercator":return new XQe(N);case"equirectangular":return new zGt(N);case"naturalEarth":return new $Gt(N);case"equalEarth":return new FGt(N);case"winkelTripel":return new UGt(N);case"albers":return _?new eJe(N):new OGt(N);case"lambertConformalConic":return _?new eJe(N):new BGt(N);case"globe":return new qGt(N)}throw new Error(`Invalid projection name: ${N.name}`)}class VGt{constructor(f,_){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=_,this.appearances=f;const S=f.map(E=>function(D){if(!D.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const z=D.condition.expression;return{featureDependent:!A1(z),stateDependent:!Rf(z),zoomDependent:!Xd(z,["zoom"]),pitchDependent:!Xd(z,["pitch"]),brightnessDependent:!Xd(z,["brightness","measure-light"]),worldviewDependent:!Xd(z,["worldview"])}}(E));this.anyFeatureDependent=S.some(E=>E.featureDependent),this.anyStateDependent=S.some(E=>E.stateDependent)}update(f,_){const S=this.lastParams,E=!S||S.zoom!==f.zoom||S.pitch!==(f.pitch||0)||S.brightness!==(f.brightness||0)||S.worldview!==f.worldview;this.lastParams={zoom:f.zoom,pitch:f.pitch||0,brightness:f.brightness||0,worldview:f.worldview};const D=_&&this.anyStateDependent;if(!E&&!D&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!D){const z=this.evaluateAllFeatures(f);return z===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=z,{kind:"all-features",appearanceIndex:z})}return{kind:"per-feature"}}evaluateAllFeatures(f){for(let _=0;_{for(let E=0;Ez-H),D=new Map;for(const z of E){const H=S.get(z);D.set(z,new Gl(H))}return _&&(this.cachedBatchIndices=E,this.cachedBatchSegments=D),{batchIndices:E,batchSegments:D}}snapshotSymbolVertexData(f,_){const S=f*xF;return this.layoutVertexArray.uint16.slice(S,S+_*xF)}restoreSymbolVertexData(f,_){this.layoutVertexArray.uint16.set(_,f*xF)}updateSymbolVertexData(f,_,S,E,D,z,H,Y,te,he,ge,ve,Te){const Ie=this.layoutVertexArray.uint16,Ve=f*xF;Ie[Ve]=_,Ie[Ve+1]=S,Ie[Ve+2]=E,Ie[Ve+3]=D,Ie[Ve+4]=z,Ie[Ve+5]=H,Ie[Ve+6]=Y,Ie[Ve+7]=te,Ie[Ve+8]=he,Ie[Ve+9]=ge,Ie[Ve+10]=ve,Ie[Ve+11]=Te}upload(f,_,S,E,D,z){this.isEmpty()||(S&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,WHt.members,!!z),this.indexBuffer=f.createIndexBuffer(this.indexArray,_),this.dynamicLayoutVertexBuffer=f.createVertexBuffer(this.dynamicLayoutVertexArray,YHt.members,!0),this.opacityVertexBuffer=f.createVertexBuffer(this.opacityVertexArray,GGt,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=f.createVertexBuffer(this.iconTransitioningVertexArray,JHt.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=f.createVertexBuffer(this.globeExtVertexArray,KHt.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||D)&&(this.zOffsetVertexBuffer=f.createVertexBuffer(this.zOffsetVertexArray,ZHt.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=f.createVertexBuffer(this.orientationVertexArray,QHt.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=f.createVertexBuffer(this.featureIdArray,XHt.members,!1))),(S||E)&&(this.programConfigurations.upload(f),this.uboBinder&&this.uboBinder.upload(f)))}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy(),this.iconTransitioningVertexBuffer&&this.iconTransitioningVertexBuffer.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.orientationVertexBuffer&&this.orientationVertexBuffer.destroy(),this.featureIdBuffer&&this.featureIdBuffer.destroy(),this.uboBinder&&this.uboBinder.destroy())}}gr(JEe,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class e6e{constructor(f,_,S){this.layoutVertexArray=new f,this.layoutAttributes=_,this.indexArray=new S,this.segments=new Gl,this.collisionVertexArray=new B6,this.collisionVertexArrayExt=new u2}upload(f){this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=f.createVertexBuffer(this.collisionVertexArray,eGt.members,!0),this.collisionVertexBufferExt=f.createVertexBuffer(this.collisionVertexArrayExt,tGt.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}gr(e6e,"CollisionBuffers");class f2{constructor(f){this.collisionBoxArray=f.collisionBoxArray,this.zoom=f.zoom,this.overscaling=f.overscaling,this.layers=f.layers,this.layerIds=this.layers.map(z=>z.fqid),this.index=f.index,this.pixelRatio=f.pixelRatio,this.sourceLayerIndex=f.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=g([]),this.placementViewportMatrix=g([]);const _=this.layers[0]._unevaluatedLayout._values;this.worldview=f.worldview,this.localizable=f.localizable,this.maxUniformBufferBindings=f.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=f.maxUniformBlockSizeDwords,this.disableSymbolUBO=f.disableSymbolUBO,this.textSizeData=J6(this.zoom,_["text-size"],this.worldview,f.availableImages),this.iconSizeData=J6(this.zoom,_["icon-size"],this.worldview,f.availableImages);const S=this.layers[0].layout,E=S.get("symbol-sort-key"),D=S.get("symbol-z-order");this.lut=f.lut,this.canOverlap=S.get("text-allow-overlap")||S.get("icon-allow-overlap")||S.get("text-ignore-placement")||S.get("icon-ignore-placement"),this.sortFeaturesByKey=D!=="viewport-y"&&E.constantOr(1)!==void 0,this.sortFeaturesByY=(D==="viewport-y"||D==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=S.get("text-writing-mode").map(z=>Sv[z]),this.stateDependentLayerIds=this.layers.filter(z=>z.isStateDependent()).map(z=>z.id),this.sourceID=f.sourceID,this.projection=f.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.elevationStateComplete=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(f){const _=this.layers[0].getAppearances();if(!_||_.length===0)return!1;const S=Array.isArray(f)?f:[f];return _.some(E=>S.some(D=>E.hasLayoutProperty(D)))}getAppearanceFeatureData(f){return this.featureAppearanceData.get(f)}createArrays(){this.text=new JEe(new tt(this.layers,{zoom:this.zoom,lut:this.lut},f=>f.startsWith("text")||f.startsWith("symbol"))),this.icon=new JEe(new tt(this.layers,{zoom:this.zoom,lut:this.lut},f=>f.startsWith("icon")||f.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new REe(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new REe(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new Aee,this.lineVertexArray=new q6,this.symbolInstances=new Cee}calculateGlyphDependencies(f,_,S,E,D){for(const z of f){const H=z.codePointAt(0);if(H===void 0)break;if(_[H]=!0,E&&D&&H<=65535){const Y=PV[z];Y&&(_[Y.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(f,_,S,E,D,z,H){if(!f.hasLayoutProperty("icon-size"))return H*z;let Y=1;const te=f.getUnevaluatedLayoutProperty("icon-size"),he=J6(this.zoom,te,this.worldview,D),ge=hF(he,_);if(he.kind!=="constant"&&he.kind!=="camera"||(Y=ge.uSize),he.kind==="composite"){const{minZoom:ve,maxZoom:Te}=he,Ie=te.possiblyEvaluate(new bi(ve,{worldview:this.worldview}),E),Ve=te.possiblyEvaluate(new bi(Te,{worldview:this.worldview}),E),et=Ie.evaluate(S,{},E,D);Y=et+(Ve.evaluate(S,{},E,D)-et)*ge.uSizeT}return he.kind==="source"&&(Y=te.possiblyEvaluate(new bi(this.zoom,{worldview:this.worldview}),E).evaluate(S,{},E,D)),Y*z}updateFootprints(f,_){}updateReplacement(f,_){if(_.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=_.updateTime;const S=_.getReplacementRegionsForTile(f.toUnwrapped(),!0);return!Gee(this.activeReplacements,S)&&(this.activeReplacements=S,!0)}getResolvedImageFromTokens(f){return typeof f=="string"?Lu.build(f):f}populate(f,_,S,E){const D=this.layers[0],z=D.layout,H=this.projection.name==="globe",Y=z.get("text-font"),te=z.get("text-field"),he=z.get("icon-image"),[ge,ve]=z.get("icon-size-scale-range"),Te=it(_.scaleFactor||1,ge,ve),[Ie,Ve]=z.get("text-size-scale-range"),et=it(_.scaleFactor||1,Ie,Ve),at=(te.value.kind!=="constant"||te.value.value instanceof ad&&!te.value.value.isEmpty()||te.value.value.toString().length>0)&&(Y.value.kind!=="constant"||Y.value.value.length>0),ft=he.value.kind!=="constant"||!!he.value.value||Object.keys(he.parameters).length>0,ut=this.hasAnyAppearanceLayoutProperty("icon-image"),Nt=z.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!at&&!ft&&!ut)return;const Mt=_.iconDependencies,It=_.glyphDependencies,xs=_.availableImages,es=new bi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),ps=cs=>{const ds=cs.id.toString();Mt.has(ds)?Mt.get(ds).push(cs):Mt.set(ds,[cs])};for(const cs of f){const{feature:ds,id:mn,index:xn,sourceLayerIndex:kn}=cs,En=D._featureFilter.needGeometry,Sn=Ri(ds,En);if(!D._featureFilter.filter(es,Sn,S))continue;if(En||(Sn.geometry=Ea(ds,S,E)),H&&ds.type!==1&&S.z<=5){const wr=Sn.geometry,vr=.98078528056,or=(Or,sa)=>De(mV(Or.x,Or.y,S,1),mV(sa.x,sa.y,S,1)){if(!wr.getLayoutProperty("icon-image"))return;const vr=this.getCombinedIconPrimary(wr,An,Sn,S,xs,ir,Te);vr&&ps(vr)}),Gn){const wr=Y.evaluate(Sn,{},S).join(","),vr=z.get("text-rotation-alignment")==="map"&&z.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(Sv.vertical)>=0;for(const or of Gn.sections)if(or.image){const Or=or.image.getPrimary().scaleSelf(this.pixelRatio*et),sa=Or.id.toString(),Ta=Mt.get(sa)||[];Ta.push(Or),Mt.set(sa,Ta)}else{const Or=ef(Gn.toString()),sa=or.fontStack||wr,Ta=It[sa]=It[sa]||{};this.calculateGlyphDependencies(or.text,Ta,vr,this.allowVerticalPlacement,Or)}}}if(z.get("symbol-placement")==="line"&&(this.features=function(cs){const ds={},mn={},xn=[];let kn=0;function En(An){xn.push(cs[An]),kn++}function Sn(An,Pn,Wn){const ir=mn[An];return delete mn[An],mn[Pn]=ir,xn[ir].geometry[0].pop(),xn[ir].geometry[0]=xn[ir].geometry[0].concat(Wn[0]),ir}function Gn(An,Pn,Wn){const ir=ds[Pn];return delete ds[Pn],ds[An]=ir,xn[ir].geometry[0].shift(),xn[ir].geometry[0]=Wn[0].concat(xn[ir].geometry[0]),ir}function dn(An,Pn,Wn){const ir=Wn?Pn[0][Pn[0].length-1]:Pn[0][0];return`${An}:${ir.x}:${ir.y}`}for(let An=0;AnAn.geometry)}(this.features)),z.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",_.elevationFeatures){!this.elevationFeatures&&_.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const cs of _.elevationFeatures)this.elevationFeatureIdToIndex.set(cs.id,this.elevationFeatures.length),this.elevationFeatures.push(cs)}}else z.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((cs,ds)=>cs.sortKey-ds.sortKey)}getCombinedIconPrimary(f,_,S,E,D,z,H){let Y,te;if(f.hasLayoutProperty("icon-image")){const he=_.getAppearanceValueAndResolveTokens(f,"icon-image",S,E,D);Y=this.getResolvedImageFromTokens(he)}else{const he=_.getValueAndResolveTokens("icon-image",S,E,D);Y=this.getResolvedImageFromTokens(he)}if(Y){const he=f.hasLayoutProperty("icon-size")?f.getUnevaluatedLayoutProperty("icon-size"):_._unevaluatedLayout._values["icon-size"];te=FV(Y,J6(this.zoom,he,this.worldview,D),he,E,this.zoom,z,this.pixelRatio,H,this.worldview,D).iconPrimary}return te}updateSymbolInstanceIconVertices(f,_,S,E,D,z){const{canonical:H,availableImages:Y,globalProperties:te,layer:he,iconScaleFactor:ge,featureState:ve,layoutIconOffset:Te,layoutIconSize:Ie,layoutIconRotate:Ve}=z;if(f.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(_.activeAppearanceIndex===S)return{vertexOffsetDelta:f.numIconVertices,hasChanges:!1};const et=S>=0?he.appearances[S]:null;if(et){const at=this.getCombinedIconPrimary(et,he,E,H,Y,{sortKey:void 0,text:void 0,icon:null,index:f.featureIndex,sourceLayerIndex:f.featureIndex,geometry:[],properties:_.properties,type:"Point",id:_.id},ge);if(!at)return{vertexOffsetDelta:0,hasChanges:!1};const ft=at.toString(),ut=this.iconAtlasPositions&&this.iconAtlasPositions.get(ft);if(ut){const{appearanceIconOffset:Nt,appearanceIconRotate:Mt}=UQe(et,he,E,H,Te,Ve,Ie,ge);let It=ute(ut,void 0,Nt,he.layout.get("icon-anchor").evaluate(E,ve,H));const xs=ut.sdf,es=he.layout.get("icon-text-fit").constantOr("none");es!=="none"&&_.textShaping&&_.iconTextFitPadding&&_.fontScale&&(It=BEe(It,_.textShaping,es,_.iconTextFitPadding,Nt,_.fontScale));const ps=this.calculateEffectiveAppearanceIconSize(et,te.zoom,E,H,Y,ge,Ie),cs=0,ds=1+(Math.min(eM,Math.round(ps*US))<<1),mn=WEe(It,Mt,xs,es!=="none",ge);_.isUsingAppearanceIconVertexData||(_.isUsingAppearanceIconVertexData=!0,_.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(D,f.numIconVertices));const xn=Math.floor(f.numIconVertices/4),kn=Math.min(mn.length,xn);let En=D;for(let Gn=0;Gn0||f.numVerticalGlyphVertices>0;if(!Nt)return{vertexOffsetDelta:Nt?f.numHorizontalGlyphVertices+f.numVerticalGlyphVertices:0,hasChanges:!1};if(_.activeAppearanceIndex===S)return{vertexOffsetDelta:f.numHorizontalGlyphVertices+f.numVerticalGlyphVertices,hasChanges:!1};const Mt=S>=0?Y.appearances[S]:null;if(Mt&&_.textShaping){const{appearanceTextOffset:It,appearanceTextRotate:xs,appearanceTextSize:es}=qQe(Mt,Y,E,H,ve,Ie,Te);_.fontScale=WQe(es,_.textScaleFactor);const ps=Mt.getUnevaluatedLayoutProperty("text-size");let cs=this.textSizeData,ds=at,mn=ft;Mt.hasLayoutProperty("text-size")&&(cs=J6(this.zoom,ps,this.worldview,ut),ds=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,mn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const xn=_.textShaping.bottom-ve[1],kn=_.textShaping.left-ve[0],En=_.textShaping.right-ve[0];_.textShaping.top=It[1]+(_.textShaping.top-ve[1]),_.textShaping.bottom=It[1]+xn,_.textShaping.left=It[0]+kn,_.textShaping.right=It[0]+En;const Sn=BQe(0,_.textShaping,It,Y,!1,E,he,this.allowVerticalPlacement,xs),Gn=es&&cs.kind==="composite"?ps.possiblyEvaluate(new bi(ds,{}),H).evaluate(E,ge,H):Ve,dn=es&&cs.kind==="composite"?ps.possiblyEvaluate(new bi(mn,{}),H).evaluate(E,ge,H):et,An=XEe(Mt.name,cs,es,te,Gn,dn),Pn=Array.isArray(An)?An[1]:es,Wn=0,ir=1+(Math.min(eM,Math.round(Pn*US))<<1);_.isUsingAppearanceTextVertexData||(_.isUsingAppearanceTextVertexData=!0,_.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(D,f.numHorizontalGlyphVertices+f.numVerticalGlyphVertices));for(let Ur=0;Ur0){const te=new Set(Object.keys(f).map(he=>{const ge=Number(he);return!isNaN(ge)&&Number.isSafeInteger(ge)&&String(ge)===he?ge:he}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(te,D[0],_,Y,S,f,H),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(te,D[0],_,Y,S,f,H)}}}updateRoadElevation(f){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let _=!1;const S=zn(f),E=1/S;let D=!1,z=!1;for(let H=0;H0||ve>0,et=Te>0,at=this.elevationFeatures[Y.elevationFeatureIndex];if(at){const ft=new Xs(Y.tileAnchorX,Y.tileAnchorY),ut=.075+at.pointElevation(ft);Y.zOffset!==ut&&(_=!0,Y.zOffset=ut),ut!==0&&(this.hasAnyZOffset=!0);const Nt=at.computeSlopeNormal(ft,E),Mt=Is(Dt(),ee(0,0,1),Nt);Oe(te,te,Mt),Oe(he,he,Mt),te[2]*=S,he[2]*=S,te[0]===1&&te[1]===0&&te[2]===0&&he[0]===0&&he[1]===1&&he[2]===0||(D=D||Ve,z=z||et)}if(Ve&&(wte(this.text.orientationVertexArray,ge,te,he),wte(this.text.orientationVertexArray,ve,te,he)),et){const{placedIconSymbolIndex:ft,verticalPlacedIconSymbolIndex:ut}=Y;ft>=0&&wte(this.icon.orientationVertexArray,Te,te,he),ut>=0&&wte(this.icon.orientationVertexArray,Ie,te,he)}}D||(this.text.orientationVertexArray=void 0),z||(this.icon.orientationVertexArray=void 0),_&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const f=(D,z,H)=>{S+=z,S>D.length&&D.resize(S);for(let Y=-z;Y<0;Y++)D.emplace(Y+S,H)},_=(D,z,H)=>{E+=z,E>D.length&&D.resize(E);for(let Y=-z;Y<0;Y++)D.emplace(Y+E,H)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let S=0,E=0;for(let D=0;D0;if((H>0||Y>0)&&(f(this.text.zOffsetVertexArray,H,he),f(this.text.zOffsetVertexArray,Y,he)),ge){const{placedIconSymbolIndex:ve,verticalPlacedIconSymbolIndex:Te}=z;ve>=0&&_(this.icon.zOffsetVertexArray,te,he),Te>=0&&_(this.icon.zOffsetVertexArray,z.numVerticalIconVertices,he)}}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(f,_,S,E,D){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(f),this.iconCollisionBox.upload(f)),this.text.upload(f,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(z=>z.appearances&&z.appearances.length>0)),this.icon.upload(f,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(f,_,S,E,D,z=!1){const H={hasLayoutChanges:!1,hasUboChanges:!1};if(!f||!S||!this.featureAppearanceData)return H;const Y=_||{},te=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,he=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!te&&!he)return H;const ge=this.layers[0],ve=ge.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===ge.appearancesVersion||(this.featureAppearances=new VGt(ge.appearances,ge.appearancesVersion));const Te=this.featureAppearances.update(E,z);if(Te.kind==="no-changes")return H;let Ie=1,Ve=0,et=!1,at=!1;if(te){const[It,xs]=ve.get("icon-size-scale-range");Ie=it(1,It,xs)}let ft=1,ut=0,Nt=!1;if(he){const[It,xs]=ve.get("text-size-scale-range");ft=it(1,It,xs)}const Mt=new Map;if(D&&S)for(const It of S){const xs=D.getImage(It,ge.scope);if(xs){const es=new gd(It.toString());Mt.set(es.toString(),xs)}}for(let It=0;ItEn.isActive({globals:E,feature:ds,canonical:f,featureState:cs})):-1;mn=kn>=0?kn:-1}const xn=es.activeAppearanceIndex!==mn;if(he){const kn=ve.get("text-size"),En=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Sn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Gn={canonical:f,layer:ge,featureState:cs,availableImages:S,textScaleFactor:ft,imageMap:Mt,layoutTextOffset:ve.get("text-offset").evaluate(ds,cs,f).map(An=>An*Mm),layoutTextSize:kn.evaluate(ds,cs,f),layoutTextRotate:ve.get("text-rotate").evaluate(ds,cs,f),layoutMinZoomSize:kn.evaluate(ds,{zoom:En},f),layoutMaxZoomSize:kn.evaluate(ds,{zoom:Sn},f),layoutTextSizeMinZoom:En,layoutTextSizeMaxZoom:Sn},dn=this.updateSymbolInstanceTextVertices(xs,es,mn,ds,ut,Gn);ut+=dn.vertexOffsetDelta,Nt=Nt||dn.hasChanges}if(te){const kn={canonical:f,layer:ge,featureState:cs,availableImages:S,globalProperties:E,iconScaleFactor:Ie,layoutIconOffset:ve.get("icon-offset").evaluate(ds,cs,f),layoutIconSize:ve.get("icon-size").evaluate(ds,cs,f,S),layoutIconRotate:ve.get("icon-rotate").evaluate(ds,cs,f)},En=this.updateSymbolInstanceIconVertices(xs,es,mn,ds,Ve,kn);Ve+=En.vertexOffsetDelta,et=et||En.hasChanges}if(xn){const kn=xs.featureIndex,En=E?E.brightness:null,Sn=cs||{},Gn=mn>=0?ge.appearances[mn]:null;this.text.uboBinder&&(this.text.uboBinder.layer=ge,at=this.text.uboBinder.updateFeaturePaintForAppearance(kn,ds,Sn,f,S,En,Gn)||at),this.icon.uboBinder&&(this.icon.uboBinder.layer=ge,at=this.icon.uboBinder.updateFeaturePaintForAppearance(kn,ds,Sn,f,S,En,Gn)||at)}es.activeAppearanceIndex=mn}return et&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),Nt&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:et||Nt,hasUboChanges:at}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=tJe(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(f,_){const S=this.lineVertexArray.length;if(f.segment!==void 0)for(const{x:E,y:D}of _)this.lineVertexArray.emplaceBack(E,D);return{lineStartIndex:S,lineLength:this.lineVertexArray.length-S}}addSymbols(f,_,S,E,D,z,H,Y,te,he,ge,ve,Te,Ie,Ve,et,at,ft){const ut=f.indexArray,Nt=f.layoutVertexArray,Mt=f.globeExtVertexArray,It=ft,xs=f.uboBinder?f.uboBinder.getCurrentBatchIndex():void 0,es=f.segments.prepareSegment(4*It,Nt,ut,this.canOverlap?z.sortKey:void 0,xs),ps=this.glyphOffsetArray.length,cs=es.vertexLength,ds=this.allowVerticalPlacement&&H===Sv.vertical?Math.PI/2:0,mn=z.text&&z.text.sections;let xn=Nt.length,kn=-1;for(let Gn=0;Gn<_.length;Gn++){const{tl:dn,tr:An,bl:Pn,br:Wn,texPrimary:ir,texSecondary:Ur,pixelOffsetTL:wr,pixelOffsetBR:vr,minFontScaleX:or,minFontScaleY:Or,glyphOffset:sa,isSDF:Ta,sectionIndex:ya}=_[Gn],xi=es.vertexLength,jo=sa[1];if(qV(Nt,te.x,te.y,dn.x,jo+dn.y,ir.x,ir.y,S,Ta,wr.x,wr.y,or,Or),qV(Nt,te.x,te.y,An.x,jo+An.y,ir.x+ir.w,ir.y,S,Ta,vr.x,wr.y,or,Or),qV(Nt,te.x,te.y,Pn.x,jo+Pn.y,ir.x,ir.y+ir.h,S,Ta,wr.x,vr.y,or,Or),qV(Nt,te.x,te.y,Wn.x,jo+Wn.y,ir.x+ir.w,ir.y+ir.h,S,Ta,vr.x,vr.y,or,Or),Y){const{x:gi,y:Ao,z:Di}=Y.anchor,[Ld,tl,Oo]=Y.up;HV(Mt,gi,Ao,Di,Ld,tl,Oo),HV(Mt,gi,Ao,Di,Ld,tl,Oo),HV(Mt,gi,Ao,Di,Ld,tl,Oo),HV(Mt,gi,Ao,Di,Ld,tl,Oo),fF(f.dynamicLayoutVertexArray,gi,Ao,Di,ds)}else fF(f.dynamicLayoutVertexArray,te.x,te.y,te.z,ds);if(et){const gi=Ur||ir;VV(f.iconTransitioningVertexArray,gi.x,gi.y),VV(f.iconTransitioningVertexArray,gi.x+gi.w,gi.y),VV(f.iconTransitioningVertexArray,gi.x,gi.y+gi.h),VV(f.iconTransitioningVertexArray,gi.x+gi.w,gi.y+gi.h)}if(ut.emplaceBack(xi,xi+1,xi+2),ut.emplaceBack(xi+1,xi+2,xi+3),es.vertexLength+=4,es.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(sa[0]),(Gn===_.length-1||ya!==_[Gn+1].sectionIndex)&&(f.programConfigurations.populatePaintArrays(Nt.length,z,z.index,{},Te,Ie,Ve,mn&&mn[ya],this.worldview),f.uboBinder&&f.featureIdArray)){const gi=f.uboBinder.populateUBO(z,z.index,Ie,Te,Ve,mn&&mn[ya],void 0);kn=gi;const Ao=Nt.length-xn;for(let Di=0;Di=0)){const Gn=4*En;for(let dn=0;dn=0?_.rightJustifiedTextSymbolIndex:_.centerJustifiedTextSymbolIndex>=0?_.centerJustifiedTextSymbolIndex:_.leftJustifiedTextSymbolIndex>=0?_.leftJustifiedTextSymbolIndex:_.verticalPlacedTextSymbolIndex>=0?_.verticalPlacedTextSymbolIndex:E),z=$Ee(this.textSizeData,f,D)/Mm;return this.tilePixelRatio*z}getSymbolInstanceIconSize(f,_,S){const E=this.icon.placedSymbolArray.get(S),D=$Ee(this.iconSizeData,f,E);return this.tilePixelRatio*D}_commitDebugCollisionVertexUpdate(f,_,S,E){f.emplaceBack(_,-S,-S,E),f.emplaceBack(_,S,-S,E),f.emplaceBack(_,S,S,E),f.emplaceBack(_,-S,S,E)}_updateTextDebugCollisionBoxes(f,_,S,E,D,z,H){for(let Y=E;Y0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(f,_){const S=f.placedSymbolArray.get(_),E=S.vertexStartIndex+4*S.numGlyphs;for(let D=S.vertexStartIndex;DE[H]-E[Y]||D[Y]-D[H]),z}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let f=0;fthis.symbolInstances.get(_).zOffset-this.symbolInstances.get(f).zOffset)}addToSortKeyRanges(f,_){const S=this.sortKeyRanges[this.sortKeyRanges.length-1];S&&S.sortKey===_?S.symbolInstanceEnd=f+1:this.sortKeyRanges.push({sortKey:_,symbolInstanceStart:f,symbolInstanceEnd:f+1})}sortFeatures(f){if(this.sortFeaturesByY&&this.sortedAngle!==f)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(f),this.sortedAngle=f,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const _ of this.symbolInstanceIndexes){const S=this.symbolInstances.get(_);this.featureSortOrder.push(S.featureIndex);const{rightJustifiedTextSymbolIndex:E,centerJustifiedTextSymbolIndex:D,leftJustifiedTextSymbolIndex:z,verticalPlacedTextSymbolIndex:H,placedIconSymbolIndex:Y,verticalPlacedIconSymbolIndex:te}=S;E>=0&&this.addIndicesForPlacedSymbol(this.text,E),D>=0&&D!==E&&this.addIndicesForPlacedSymbol(this.text,D),z>=0&&z!==D&&z!==E&&this.addIndicesForPlacedSymbol(this.text,z),H>=0&&this.addIndicesForPlacedSymbol(this.text,H),Y>=0&&this.addIndicesForPlacedSymbol(this.icon,Y),te>=0&&this.addIndicesForPlacedSymbol(this.icon,te)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(f,_){const S=(this.text.uboBinder&&this.text.uboBinder.maxFeaturesPerBatch>0?this.text.uboBinder:this.icon.uboBinder&&this.icon.uboBinder.maxFeaturesPerBatch>0?this.icon.uboBinder:null).maxFeaturesPerBatch;if(this.symbolsByBatch)for(const E of this.symbolsByBatch.values())for(const D of E){const z=this.symbolInstances.get(D.index);D.rotatedY=0|Math.round(f*z.tileAnchorX+_*z.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let E=0;ED.rotatedY-z.rotatedY||z.featureIndex-D.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(f,_){for(const S of f){const E=S.batchIndex;if(E===void 0)continue;const D=_.get(E);if(!D){S.primitiveOffset=this.text.indexArray.length,S.primitiveLength=0;continue}S.primitiveOffset=this.text.indexArray.length;const z=this.text.indexArray.length;for(const{index:H}of D){const Y=this.symbolInstances.get(H),{rightJustifiedTextSymbolIndex:te,centerJustifiedTextSymbolIndex:he,leftJustifiedTextSymbolIndex:ge,verticalPlacedTextSymbolIndex:ve}=Y;te>=0&&this.addIndicesForPlacedSymbol(this.text,te),he>=0&&he!==te&&this.addIndicesForPlacedSymbol(this.text,he),ge>=0&&ge!==he&&ge!==te&&this.addIndicesForPlacedSymbol(this.text,ge),ve>=0&&this.addIndicesForPlacedSymbol(this.text,ve)}S.primitiveLength=this.text.indexArray.length-z}}rebuildIconSegmentIndices(f,_){for(const S of f){const E=S.batchIndex;if(E===void 0)continue;const D=_.get(E);if(!D){S.primitiveOffset=this.icon.indexArray.length,S.primitiveLength=0;continue}S.primitiveOffset=this.icon.indexArray.length;const z=this.icon.indexArray.length;for(const{index:H}of D){const Y=this.symbolInstances.get(H),{placedIconSymbolIndex:te,verticalPlacedIconSymbolIndex:he}=Y;te>=0&&this.addIndicesForPlacedSymbol(this.icon,te),he>=0&&this.addIndicesForPlacedSymbol(this.icon,he)}S.primitiveLength=this.icon.indexArray.length-z}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const f=Math.sin(this.sortedAngle),_=Math.cos(this.sortedAngle),S=this.getOrCreateSortedSymbolsByBatch(f,_),E=Array.from(S.keys()).sort((D,z)=>D-z);for(const D of E){const z=S.get(D);for(const{index:H}of z){const Y=this.symbolInstances.get(H);this.featureSortOrder.push(Y.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),S),this.rebuildIconSegmentIndices(this.icon.segments.get(),S),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(f){const _=this.symbolInstances.get(this.text.symbolInstanceIndices[f]).elevationFeatureIndex;let S;return this.elevationFeatures&&_S in N?String(N[S]):"")}let nJe,rJe,t6e;gr(f2,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),f2.addDynamicAttributes=fF;class aJe{constructor(f){this.type=f.property.overrides?f.property.overrides.runtimeType:Dc,this.defaultValue=f}evaluate(f){if(f.formattedSection){const _=this.defaultValue.property.overrides;if(_&&_.hasOverride(f.formattedSection))return _.getOverride(f.formattedSection)}return f.feature&&f.featureState?this.defaultValue.evaluate(f.feature,f.featureState):this.defaultValue.property.specification.default}eachChild(f){this.defaultValue.isConstant()||f(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}gr(aJe,"FormatSectionOverride",{omit:["defaultValue"]});const s6e=()=>t6e||(t6e={layout:nJe||(nJe=new pc({"symbol-placement":new sr(Rs.layout_symbol["symbol-placement"]),"symbol-spacing":new sr(Rs.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new sr(Rs.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new tr(Rs.layout_symbol["symbol-sort-key"]),"symbol-z-order":new sr(Rs.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new sr(Rs.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new sr(Rs.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new sr(Rs.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new sr(Rs.layout_symbol["icon-ignore-placement"]),"icon-optional":new sr(Rs.layout_symbol["icon-optional"]),"icon-rotation-alignment":new sr(Rs.layout_symbol["icon-rotation-alignment"]),"icon-size":new tr(Rs.layout_symbol["icon-size"]),"icon-size-scale-range":new sr(Rs.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new tr(Rs.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new tr(Rs.layout_symbol["icon-text-fit-padding"]),"icon-image":new tr(Rs.layout_symbol["icon-image"]),"icon-image-use-theme":new sr({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new tr(Rs.layout_symbol["icon-rotate"]),"icon-padding":new sr(Rs.layout_symbol["icon-padding"]),"icon-keep-upright":new sr(Rs.layout_symbol["icon-keep-upright"]),"icon-offset":new tr(Rs.layout_symbol["icon-offset"]),"icon-anchor":new tr(Rs.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new sr(Rs.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new sr(Rs.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new sr(Rs.layout_symbol["text-rotation-alignment"]),"text-field":new tr(Rs.layout_symbol["text-field"]),"text-font":new tr(Rs.layout_symbol["text-font"]),"text-size":new tr(Rs.layout_symbol["text-size"]),"text-size-scale-range":new sr(Rs.layout_symbol["text-size-scale-range"]),"text-max-width":new tr(Rs.layout_symbol["text-max-width"]),"text-line-height":new tr(Rs.layout_symbol["text-line-height"]),"text-letter-spacing":new tr(Rs.layout_symbol["text-letter-spacing"]),"text-justify":new tr(Rs.layout_symbol["text-justify"]),"text-radial-offset":new tr(Rs.layout_symbol["text-radial-offset"]),"text-variable-anchor":new sr(Rs.layout_symbol["text-variable-anchor"]),"text-anchor":new tr(Rs.layout_symbol["text-anchor"]),"text-max-angle":new sr(Rs.layout_symbol["text-max-angle"]),"text-writing-mode":new sr(Rs.layout_symbol["text-writing-mode"]),"text-rotate":new tr(Rs.layout_symbol["text-rotate"]),"text-padding":new sr(Rs.layout_symbol["text-padding"]),"text-keep-upright":new sr(Rs.layout_symbol["text-keep-upright"]),"text-transform":new tr(Rs.layout_symbol["text-transform"]),"text-offset":new tr(Rs.layout_symbol["text-offset"]),"text-allow-overlap":new sr(Rs.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new sr(Rs.layout_symbol["text-ignore-placement"]),"text-optional":new sr(Rs.layout_symbol["text-optional"]),visibility:new sr(Rs.layout_symbol.visibility)})),paint:rJe||(rJe=new pc({"icon-opacity":new tr(Rs.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new tr(Rs.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new tr(Rs.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new tr(Rs.paint_symbol["text-emissive-strength"]),"icon-color":new tr(Rs.paint_symbol["icon-color"]),"icon-halo-color":new tr(Rs.paint_symbol["icon-halo-color"]),"icon-halo-width":new tr(Rs.paint_symbol["icon-halo-width"]),"icon-halo-blur":new tr(Rs.paint_symbol["icon-halo-blur"]),"icon-translate":new sr(Rs.paint_symbol["icon-translate"]),"icon-translate-anchor":new sr(Rs.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new sr(Rs.paint_symbol["icon-image-cross-fade"]),"text-opacity":new tr(Rs.paint_symbol["text-opacity"]),"text-occlusion-opacity":new tr(Rs.paint_symbol["text-occlusion-opacity"]),"text-color":new tr(Rs.paint_symbol["text-color"],{runtimeType:Rl,getOverride:N=>N.textColor,hasOverride:N=>!!N.textColor}),"text-halo-color":new tr(Rs.paint_symbol["text-halo-color"]),"text-halo-width":new tr(Rs.paint_symbol["text-halo-width"]),"text-halo-blur":new tr(Rs.paint_symbol["text-halo-blur"]),"text-translate":new sr(Rs.paint_symbol["text-translate"]),"text-translate-anchor":new sr(Rs.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new sr(Rs.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new sr(Rs.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new sr(Rs.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new sr(Rs.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new tr(Rs.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"})}))},t6e);class jte extends bl{constructor(f,_,S,E){super(f,s6e(),_,S,E,f.layout?f.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=g([]),this.hasOcclusionOpacityProperties=f.paint!==void 0&&("icon-occlusion-opacity"in f.paint||"text-occlusion-opacity"in f.paint)}_handleSpecialPaintPropertyUpdate(f){f!=="icon-occlusion-opacity"&&f!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(f,_){super.recalculate(f,_),this.appearances&&this.appearances.forEach(E=>{E.recalculate(f,_,this.iconImageUseTheme)}),this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));const S=this.layout.get("text-writing-mode");if(S){const E=[];for(const D of S)E.indexOf(D)<0&&E.push(D);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(f,_,S,E){return this._saturation===f&&this._contrast===_&&this._brightnessMin===S&&this._brightnessMax===E||(this._colorAdjustmentMatrix=function(D,z,H,Y){D=So(D),z=Va(z);const te=x(),he=D/3,ge=1-2*he,ve=[ge,he,he,0,he,ge,he,0,he,he,ge,0,0,0,0,1],Te=.5-.5*z,Ie=Y-H;return v(te,[Ie,0,0,0,0,Ie,0,0,0,0,Ie,0,H,H,H,1],[z,0,0,0,0,z,0,0,0,0,z,0,Te,Te,Te,1]),v(te,te,ve),te}(f,_,S,E),this._saturation=f,this._contrast=_,this._brightnessMin=S,this._brightnessMax=E),this._colorAdjustmentMatrix}getValueAndResolveTokens(f,_,S,E){const D=this.layout.get(f).evaluate(_,{},S,E),z=this._unevaluatedLayout._values[f];return z.isDataDriven()||km(z.value)||!D?D:sJe(_.properties,D)}getAppearanceValueAndResolveTokens(f,_,S,E,D){const z=f.getLayoutProperty(_);if(!z)return;const H=z.evaluate(S,{},E,D),Y=f.getUnevaluatedLayoutProperties()._values[_];return Y.isDataDriven()||km(Y.value)||!H||typeof H!="string"?H:sJe(S.properties,H)}createBucket(f){return new f2(f)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const f of s6e().paint.overridableProperties){if(!jte.hasPaintOverride(this.layout,f))continue;const _=this.paint.get(f),S=new aJe(_),E=new Pu(S,_.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let D=null;D=_.value.kind==="constant"||_.value.kind==="source"?new Xu("source",E):new Bl("composite",E,_.value.zoomStops,_.value.interpolationType),this.paint._values[f]=new c2(_.property,D,_.parameters)}}_handleOverridablePaintPropertyUpdate(f,_,S){return!(!this.layout||_.isDataDriven()||S.isDataDriven())&&jte.hasPaintOverride(this.layout,f)}static hasPaintOverride(f,_){const S=f.get("text-field"),E=s6e().paint.properties[_];let D=!1;const z=H=>{for(const Y of H)if(E.overrides&&E.overrides.hasOverride(Y))return void(D=!0)};if(S.value.kind==="constant"&&S.value.value instanceof ad)z(S.value.value.sections);else if(S.value.kind==="source"){const H=te=>{D||(te instanceof Ir&&yl(te.value)===wg?z(te.value.sections):te instanceof id?z(te.sections):te.eachChild(H))},Y=S.value;Y._styleExpression&&H(Y._styleExpression.expression)}return D}getProgramIds(){return["symbol"]}getDefaultProgramParams(f,_,S){return{config:new He(this,{zoom:_,lut:S}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let iJe,oJe,lJe,cJe;var Nte=Fn([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function kte(N,f,_,S,E,D,z,H){const Y=[N,f,1,_,S,1,E,D,1],te=[z,H,1],he=m([],Y),[ge,ve,Te]=_e(te,te,he);return p(Y,Y,[ge,0,0,0,ve,0,0,0,Te])}function dJe(N,f,_,S,E,D,z,H){const Y=function(te,he,ge,ve,Te,Ie,Ve,et){const at=kte(0,0,1,0,1,1,0,1),ft=kte(te,he,ge,ve,Te,Ie,Ve,et);return p(ft,ft,m([],at))}(N,f,_,S,E,D,z,H);return[Y[2]/Y[8]/nr,Y[5]/Y[8]/nr]}function Ste(N){return[N[0],Math.min(Math.max(N[1],-85.051129),jn)]}class uJe extends Xh{constructor(f,_,S,E){super(),this.id=f,this.dispatcher=S,this.coordinates=_.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.onNorthPole=!1,this.onSouthPole=!1,this.setEventedParent(E),this.options=_,this._dirty=!1}load(f,_){if(this._loaded=_||!1,this.fire(new Tc("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return f&&(this.coordinates=f),this._loaded=!0,void this._finishLoading();this._imageRequest=wm(this.map._requestManager.transformRequest(this.url,g0.Image),(S,E)=>{this._imageRequest=null,this._loaded=!0,S?this.fire(new ip(S)):E&&(this.image=E,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,f&&(this.coordinates=f),this._finishLoading())})}loaded(){return this._loaded}updateImage(f){return f.url?(this._imageRequest&&f.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=f.url,this.load(f.coordinates,this._loaded),this):this}setTexture(f){if(!(f.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new EV(this.map.painter.context,f.handle),this.width=f.dimensions[0],this.height=f.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Tc("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(f){this.map=f,this.load()}onRemove(f){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof EV||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(f){if(this.coordinates=f,this._boundsArray=void 0,this._unsupportedCoords=!1,!f.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let _=f[0][1],S=f[0][1];for(const D of f)D[1]>S&&(S=D[1]),D[1]<_&&(_=D[1]);const E=(S+_)/2;if(E>jn?this.onNorthPole=!0:E<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const D=f.map(ta.fromLngLat);this.tileID=function(z){let H=1/0,Y=1/0,te=-1/0,he=-1/0;for(const Ve of z)H=Math.min(H,Ve.x),Y=Math.min(Y,Ve.y),te=Math.max(te,Ve.x),he=Math.max(he,Ve.y);const ge=Math.max(te-H,he-Y),ve=Math.max(0,Math.floor(-Math.log2(ge))),Te=Math.pow(2,ve);let Ie=Math.floor((H+te)/2*Te);return Ie>1&&(Ie-=1),new K6(ve,Ie,Math.floor((Y+he)/2*Te))}(D),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Tc("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof EV||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(f){for(const et in this.tiles){const at=this.tiles[et];at.state!=="loaded"&&(at.state="loaded",at.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const _=tM(new K6(0,0,0),this.map.transform.projection),S=[_.projection.project(this.coordinates[0][0],this.coordinates[0][1]),_.projection.project(this.coordinates[1][0],this.coordinates[1][1]),_.projection.project(this.coordinates[2][0],this.coordinates[2][1]),_.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(et){const at=et[1].x-et[0].x,ft=et[1].y-et[0].y,ut=et[2].x-et[1].x,Nt=et[2].y-et[1].y,Mt=et[3].x-et[2].x,It=et[3].y-et[2].y,xs=et[0].x-et[3].x,es=et[0].y-et[3].y,ps=at*Nt-ut*ft,cs=ut*It-Mt*Nt,ds=Mt*es-xs*It,mn=xs*ft-at*es;return ps>0&&cs>0&&ds>0&&mn>0||ps<0&&cs<0&&ds<0&&mn<0}(S))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const E=tM(this.tileID,this.map.transform.projection),[D,z,H,Y]=this.coordinates.map(et=>{const at=E.projection.project(et[0],et[1]);return ZQe(E,at)._round()});this.perspectiveTransform=dJe(D.x,D.y,z.x,z.y,H.x,H.y,Y.x,Y.y);const te=this._boundsArray=new Xi;te.emplaceBack(D.x,D.y,0,0),te.emplaceBack(z.x,z.y,nr,0),te.emplaceBack(Y.x,Y.y,0,nr),te.emplaceBack(H.x,H.y,nr,nr),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=f.createVertexBuffer(te,Nte.members),this.boundsSegments=Gl.simpleSegment(0,0,4,2);const he=[],ge=function(et){return[Ste(et[0]),Ste(et[1]),Ste(et[2]),Ste(et[3])]}(this.coordinates),[ve,Te,Ie,Ve]=function(et){let at=et[0][0],ft=at,ut=et[0][1],Nt=ut;for(let Mt=1;Mtft&&(ft=et[Mt][0]),et[Mt][1]Nt&&(Nt=et[Mt][1]);return[at,ut,ft-at,Nt-ut]}(ge);{const et=new Xi,[at,ft,ut,Nt]=function(Sn){let Gn=Sn[0].x,dn=Gn,An=Sn[0].y,Pn=An;for(let Wn=1;Wndn&&(dn=Sn[Wn].x),Sn[Wn].yPn&&(Pn=Sn[Wn].y);return[Gn,An,dn-Gn,Pn-An]}(S),Mt=Sn=>[(Sn.x-at)/ut,(Sn.y-ft)/Nt],[It,xs,es,ps]=S.map(Mt),cs=function(Sn,Gn,dn,An,Pn,Wn,ir,Ur){const wr=kte(0,0,1,0,1,1,0,1);return p(wr,wr,m([],kte(Sn,Gn,dn,An,Pn,Wn,ir,Ur)))}(It[0],It[1],xs[0],xs[1],es[0],es[1],ps[0],ps[1]);this.elevatedGlobePerspectiveTransform=dJe(It[0],It[1],xs[0],xs[1],es[0],es[1],ps[0],ps[1]);const ds=(Sn,Gn)=>{he.push(Sn.lng);const dn=Math.round((Sn.lng-ve)/Ie*nr),An=Math.round((Sn.lat-Te)/Ve*nr),Pn=Mt(Gn),Wn=_e([],[Pn[0],Pn[1],1],cs),ir=Math.round(Wn[0]/Wn[2]*nr),Ur=Math.round(Wn[1]/Wn[2]*nr);et.emplaceBack(dn,An,ir,Ur)},mn=S[3].x-S[0].x,xn=S[3].y-S[0].y,kn=S[2].x-S[1].x,En=S[2].y-S[1].y;for(let Sn=0;Sn<65;Sn++){const Gn=Sn/64,dn=[S[0].x+Gn*mn,S[0].y+Gn*xn],An=[S[1].x+Gn*kn,S[1].y+Gn*En],Pn=An[0]-dn[0],Wn=An[1]-dn[1];for(let ir=0;ir<65;ir++){const Ur=ir/64,wr={x:dn[0]+Pn*Ur,y:dn[1]+Wn*Ur};ds(_.projection.unproject(wr.x,wr.y),wr)}}this.elevatedGlobeVertexBuffer=f.createVertexBuffer(et,Nte.members)}{this.maxLongitudeTriangleSize=0;let et=[],at=new eu;const ft=(ut,Nt,Mt)=>{at.emplaceBack(ut,Nt,Mt);const It=he[ut],xs=he[Nt],es=he[Mt],ps=Math.min(Math.min(It,xs),es),cs=Math.max(Math.max(It,xs),es)-ps;cs>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=cs),et.push(ps+cs/2)};for(let ut=0;ut<64;ut++)for(let Nt=0;Nt<64;Nt++){const Mt=65*ut+Nt,It=Mt+1,xs=Mt+65,es=xs+1;ft(Mt,xs,It),ft(It,xs,es)}[et,at]=function(ut,Nt){const Mt=Array.from({length:ut.length},(es,ps)=>ps);Mt.sort((es,ps)=>ut[es]-ut[ps]);const It=[],xs=new eu;for(let es=0;es{z.segments.push({vertexOffset:0,primitiveOffset:ge,vertexLength:_.segments[0].vertexLength,primitiveLength:ve,sortKey:void 0,vaos:{}})},Y=.51*this.maxLongitudeTriangleSize;if(Math.abs(S[0]-E)<=Y){const ge=fo(S,0,S.length,E+Y);return ge===S.length||H(ge,ao(S,ge+1,S.length,E+360-Y)-ge),z}E0}}let mJe,pJe,fJe,xJe,gJe,yJe,vJe;class bJe extends bl{constructor(f,_,S,E){super(f,{layout:mJe||(mJe=new pc({visibility:new sr(Rs["layout_raster-particle"].visibility)})),paint:pJe||(pJe=new pc({"raster-particle-array-band":new sr(Rs["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new sr(Rs["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new E0(Rs["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new sr(Rs["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new sr(Rs["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new sr(Rs["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new sr(Rs["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new sr(Rs["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"})}))},_,S,E),this._updateColorRamp(),this.lastInvalidatedAt=Wc.now()}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null),this.tileFramebuffer&&(this.tileFramebuffer.destroy(),this.tileFramebuffer=null),this.particleFramebuffer&&(this.particleFramebuffer.destroy(),this.particleFramebuffer=null)}onRemove(f){this.colorRampTexture&&this.colorRampTexture.destroy(),this.tileFramebuffer&&this.tileFramebuffer.destroy(),this.particleFramebuffer&&this.particleFramebuffer.destroy()}hasColorMap(){return!!this._transitionablePaint._values["raster-particle-color"].value.value}getProgramIds(){return["rasterParticle"]}hasOffscreenPass(){return this.visibility!=="none"}isDraped(f){return!1}_handleSpecialPaintPropertyUpdate(f){f!=="raster-particle-color"&&f!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),f==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const f=this._transitionablePaint._values["raster-particle-color"].value.expression,_=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=fV({expression:f,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:_}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=Wc.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class YGt extends bl{constructor(f,_){super(f,{},_,null),this.implementation=f,f.slot&&(this.slot=f.slot)}is3D(f){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(f){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(f){this.implementation.onAdd&&this.implementation.onAdd(f,f.painter.context.gl)}onRemove(f){this.implementation.onRemove&&this.implementation.onRemove(f,f.painter.context.gl)}}function r6e(N,f,_){const S=[0,0,1],E=pt([]);return Gt(E,E,_?-pr(N)+Math.PI:pr(N)),zt(E,E,-pr(f)),Oe(S,S,E),Le(S,S)}class Cte{constructor(f,_,S,E){this.message=(f?`${f}: `:"")+S,E&&(this.identifier=E),_!=null&&_.__line__&&(this.line=_.__line__)}}function a6e(N,f){const _=N.indexOf("://")===-1;try{return new URL(N,_&&f?"http://example.com":void 0),!0}catch{return!1}}class _Je{constructor(f,_){this.feature=f,this.instancedDataOffset=_,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class wJe{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new iV,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(f){const _=16*f,S=this.instancedDataArray.float32;let E=Math.floor(S[_+2]);const D=1.05*(S[_+2]-E);return E/=100,[S[_]%1*1.05,S[_+1]%1*1.05,D,E]}tileCoordinatesForInstance(f){const _=16*f,S=this.instancedDataArray.float32;let E=S[_+0];return E=E>nr?E-nr:E,new Xs(Math.trunc(E),Math.trunc(S[_+1]))}translationForInstance(f){const _=16*f,S=this.instancedDataArray.float32;return[S[_+4],S[_+5],S[_+6]]}rotationScaleForInstance(f){const _=16*f,S=this.instancedDataArray.float32;return[S[_+7],S[_+8],S[_+9],S[_+10],S[_+11],S[_+12],S[_+13],S[_+14],S[_+15]]}transformForInstance(f){const _=16*f,S=this.instancedDataArray.float32;return[S[_+7],S[_+8],S[_+9],S[_+4],S[_+10],S[_+11],S[_+12],S[_+5],S[_+13],S[_+14],S[_+15],S[_+6],0,0,0,1]}}class i6e{constructor(f){this.zoom=f.zoom,this.canonical=f.canonical,this.overscaledZ=this.canonical.z+Math.log2(f.overscaling),this.layers=f.layers,this.layerIds=this.layers.map(_=>_.fqid),this.projection=f.projection,this.index=f.index,this.worldview=f.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.hasPattern=!1,this.instancesPerModel={},this.validForExaggeration=0,this.maxVerticalOffset=0,this.maxScale=0,this.maxHeight=0,this.lookupDim=this.zoom>this.canonical.z+1?0:this.zoom>this.canonical.z?256:this.zoom>15?75:100,this.instanceCount=0,this.terrainElevationMin=0,this.terrainElevationMax=0,this.validForDEMTile={id:null,timestamp:0},this.modelUris=[],this.modelsRequested=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.styleDefinedModelURLs=f.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(f,_){}updateAppearances(f,_,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,_,S,E){this.tileToMeter=zn(S);const D=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const z=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?_.elevationFeatures:void 0;for(const{feature:H,id:Y,index:te,sourceLayerIndex:he}of f){const ge=Y??(H.properties&&H.properties.hasOwnProperty("id")?H.properties.id:void 0),ve=Ri(H,D);if(!this.layers[0]._featureFilter.filter(new bi(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),ve,S))continue;const Te={id:ge,sourceLayerIndex:he,index:te,geometry:D?ve.geometry:Ea(H,S,E),properties:H.properties,type:H.type,patterns:{}},Ie=this.addFeature(Te,Te.geometry,ve,z,S);Ie&&_.featureIndex.insert(H,Te.geometry,te,he,this.index,this.instancesPerModel[Ie].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const f=this.layers[0].modelManager,_=this.layers[0].scope;let S=0;for(const E of this.modelUris){const D=f.getModel(E,_);if(!D)continue;const z=this.instancesPerModel[E];if(z){const H=.5*xe(D.aabb.max,D.aabb.min)*z.maxScale+z.maxXYTranslationDistance,Y=Math.min(nr,Math.max(H/this.tileToMeter,256));S=Math.max(Y,S)}}return S}update(f,_,S,E){for(const D in this.instancesPerModel){const z=this.instancesPerModel[D];for(const H in f)z.idToFeaturesIndex.hasOwnProperty(H)&&(this.evaluate(z.features[z.idToFeaturesIndex[H]],f[H],z,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let f=!1;for(const _ in this.instancesPerModel){const S=this.instancesPerModel[_];for(const E of S.features){const D=this.layers[0],z=E.feature,H=this.canonical,Y=D.paint.get("model-rotation").evaluate(z,{},H),te=D.paint.get("model-scale").evaluate(z,{},H),he=D.paint.get("model-translation").evaluate(z,{},H);Xe(E.rotation,Y)&&Xe(E.scale,te)&&Xe(E.translation,he)||(this.evaluate(E,E.featureStates,S,!0),f=!0)}}return f}updateReplacement(f,_,S,E){if(_.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=_.updateTime;const D=_.getReplacementRegionsForTile(f.toUnwrapped(),!0);if(Gee(this.activeReplacements,D))return!1;this.activeReplacements=D;let z=!1;for(const H in this.instancesPerModel){const Y=this.instancesPerModel[H],te=Y.instancedDataArray;for(const he of Y.features){const ge=he.instancedDataOffset,ve=he.instancedDataCount;for(let Te=0;Tenr;Ve=et?Ve-nr:Ve;const at=Math.floor(Ve),ft=Math.floor(te.float32[Ie+1]);let ut=!1;for(const Nt of this.activeReplacements)if(!nXe(Nt,S,Wee.Model,E)&&!(Nt.min.x>at||at>Nt.max.x||Nt.min.y>ft||ft>Nt.max.y)&&(ut=lXe(oXe(at,ft,f.canonical,Nt.footprintTileId.canonical),Nt.footprint),ut))break;te.float32[Ie]=ut?Ve+nr:Ve,z=z||ut!==et}}}return z}isEmpty(){for(const f in this.instancesPerModel)if(this.instancesPerModel[f].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(f){if(!this.uploaded)for(const _ in this.instancesPerModel){const S=this.instancesPerModel[_];S.instancedDataArray.length<0||S.instancedDataArray.length===0||(S.instancedDataBuffer?S.instancedDataBuffer.updateData(S.instancedDataArray):S.instancedDataBuffer=f.createVertexBuffer(S.instancedDataArray,pHt.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(f){for(const S in this.instancesPerModel){const E=this.instancesPerModel[S];E.instancedDataArray.length!==0&&E.instancedDataBuffer&&E.instancedDataBuffer.destroy()}const _=this.layers[0].modelManager;if(f&&_&&this.modelUris&&this.modelsRequested)for(const S of this.modelUris)_.removeModel(S,"",!0)}addFeature(f,_,S,E,D){const z=this.layers[0],H=z.layout.get("model-id"),Y=z.layout.get("model-allow-density-reduction"),te=H.evaluate(S,{},this.canonical);if(!te)return Mr(`modelId is not evaluated for layer ${z.id} and it is not going to get rendered.`),te;(a6e(te,!1)||this.styleDefinedModelURLs[te]!==void 0)&&(this.modelUris.includes(te)||this.modelUris.push(te)),this.instancesPerModel[te]||(this.instancesPerModel[te]=new wJe);const he=this.instancesPerModel[te],ge=he.instancedDataArray,ve=new _Je(S,ge.length);let Te;E&&(Te=tc.getElevationFeature(f,E));for(const Ie of _)for(const Ve of Ie){if(Ve.x<0||Ve.x>=nr||Ve.y<0||Ve.y>=nr)continue;if(this.lookupDim!==0&&Y){const at=(this.lookupDim-1)/nr,ft=this.lookupDim*(Ve.y*at|0)+Ve.x*at|0;if(this.lookup){if(this.lookup[ft]!==0)continue;this.lookup[ft]=1}}this.instanceCount++;const et=ge.length;if(ge.resize(et+1),E){he.instancesRoadElevation||(he.instancesRoadElevation=[]);const at=Te?Te.pointElevation(new Xs(Ve.x,Ve.y)):0;he.instancesRoadElevation.push(at)}he.instancesEvaluatedElevation.push(0),ge.float32[16*et]=Ve.x,ge.float32[16*et+1]=Ve.y}return ve.instancedDataCount=he.instancedDataArray.length-ve.instancedDataOffset,ve.instancedDataCount>0&&(f.id&&(he.idToFeaturesIndex[f.id]=he.features.length),he.features.push(ve),this.evaluate(ve,{},he,!1)),te}getModelUris(){return this.modelUris}evaluate(f,_,S,E){const D=this.layers[0],z=f.feature,H=this.canonical,Y=f.rotation=D.paint.get("model-rotation").evaluate(z,_,H),te=f.scale=D.paint.get("model-scale").evaluate(z,_,H),he=f.translation=D.paint.get("model-translation").evaluate(z,_,H),ge=Object.assign({},D.paint.get("model-color").evaluate(z,_,H));ge.a=D.paint.get("model-color-mix-intensity").evaluate(z,_,H);const ve=[];this.maxVerticalOffset0?Math.sqrt(Te):0;S.maxScale=Math.max(Math.max(S.maxScale,te[0]),Math.max(te[1],te[2])),S.maxXYTranslationDistance=Math.max(S.maxXYTranslationDistance,Ie),this.maxScale=Math.max(Math.max(this.maxScale,te[0]),Math.max(te[1],te[2])),GXe(ve,Y,te);const Ve=Math.round(100*ge.a)+ge.b/1.05;for(let et=0;et10?this.tileToMeter:zn(H,Mt)),ut[ft+4]=he[0],ut[ft+5]=he[1],ut[ft+6]=he[2]+(S.instancesRoadElevation?S.instancesRoadElevation[at]:0)+Nt,ut[ft+7]=ve[0],ut[ft+8]=ve[1],ut[ft+9]=ve[2],ut[ft+10]=ve[4],ut[ft+11]=ve[5],ut[ft+12]=ve[6],ut[ft+13]=ve[8],ut[ft+14]=ve[9],ut[ft+15]=ve[10],S.instancesEvaluatedElevation[at]=he[2]}}}gr(i6e,"ModelBucket",{omit:["layers"]}),gr(wJe,"PerModelAttributes"),gr(_Je,"ModelFeature");class gF{constructor(f,_,S){this._demTile=f,this._dem=this._demTile.dem,this._scale=_,this._offset=S}static create(f,_,S){const E=S||f.findDEMTileFor(_);if(!E||!E.dem)return;const D=E.dem,z=E.tileID,H=1<<_.canonical.z-z.canonical.z;return new gF(E,D.dim/nr/H,[(_.canonical.x/H-z.canonical.x)*D.dim,(_.canonical.y/H-z.canonical.y)*D.dim])}tileCoordToPixel(f,_){const S=_*this._scale+this._offset[1];return new Xs(Math.floor(f*this._scale+this._offset[0]),Math.floor(S))}getElevationAt(f,_,S,E){const D=f*this._scale+this._offset[0],z=_*this._scale+this._offset[1],H=Math.floor(D),Y=Math.floor(z),te=this._dem;return E=!!E,S?xr(xr(te.get(H,Y,E),te.get(H,Y+1,E),z-Y),xr(te.get(H+1,Y,E),te.get(H+1,Y+1,E),z-Y),D-H):te.get(H,Y,E)}getElevationAtPixel(f,_,S){return this._dem.get(f,_,!!S)}getMeterToDEM(f){return(1<te.fqid),this.stateDependentLayerIds=this.layers.filter(te=>te.isStateDependent()).map(te=>te.id),this.modelTraits|=cF.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,E&&(this.modelTraits|=cF.HasMapboxMeshFeatures),D&&(this.modelTraits|=cF.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=z,this.worldview=Y,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const te of _)this.nodesInfo.push(new SJe(te)),NJe(te,H.featureIndexArray.length,H.grid),H.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,H.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(f,_){for(const S of this.getNodesInfo()){const E=S.node;E.footprint&&_.push({footprint:E.footprint,id:f})}}updateAppearances(f,_,S,E){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(f){const _=Object.keys(f).length!==0;if(_&&!this.stateDependentLayers.length)return;const S=_?this.stateDependentLayers:this.layers;if(!Ba(f,this.states))for(const E of S)this.evaluate(E,f);this.states=structuredClone(f)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(f){if(!this.needsUpload)return;const _=this.getNodesInfo();for(const S of _){const E=S.node;this.uploaded?this.updatePbrBuffer(E):NEe(E,f,!0)}for(const S of _)ite(S.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(f){let _=!1;if(!f.meshes)return _;for(const S of f.meshes)S.pbrBuffer&&(S.pbrBuffer.updateData(S.featureArray),_=!0);return _}needsReEvaluation(f,_,S){const E=f.transform.projectionOptions,D=f.style.getBrightness(),z=this.brightness!==D;if(!this.uploaded||this.dirty||E.name!==this.projection.name||GV(S.paint.get("model-color").value,z)||GV(S.paint.get("model-color-mix-intensity").value,z)||GV(S.paint.get("model-roughness").value,z)||GV(S.paint.get("model-emissive-strength").value,z)||GV(S.paint.get("model-height-based-emissive-strength-multiplier").value,z)){this.projection=E,this.brightness=D;const H=this.getNodesInfo();for(const Y of H)Y.state=null;return!0}return!1}evaluateTransform(f,_){if(f.transform.zoom===this.zoom)return;this.zoom=f.transform.zoom;const S=this.getNodesInfo(),E=this.id.canonical;for(const D of S){const z=D.feature;D.evaluatedTranslation=_.paint.get("model-translation").evaluate(z,{},E),D.evaluatedScale=_.paint.get("model-scale").evaluate(z,{},E)}}evaluate(f,_){const S=this.getNodesInfo();for(const E of S){if(!E.node.meshes)continue;const D=E.feature,z=_&&_[D.id];if(Ba(z,E.state))continue;E.state=structuredClone(z);const H=E.node.meshes&&E.node.meshes[0].featureData,Y=E.evaluatedColor[2],te=E.evaluatedRMEA[2],he=this.id.canonical;if(E.hasTranslucentParts=!1,H){for(let ge=0;ge=It)continue;const Gn=o6e[Sn],dn=Math.abs(Gn);dn>ds&&(cs=Gn,ds=dn,mn=En,xn=kn)}if(ds>.1){const kn=1-(It+.5*Math.abs(mn*xn))/Ie;let En=_._dem.get(es,xs)+cs*kn;const Sn=_._dem.get(es+mn,xs+xn),Gn=_._dem.get(es-mn,xs-xn,!0);(En-Sn)*(En-Gn)>0&&(En=(Sn+Gn)/2),o6e[ps]=_._dem.set(es,xs,En),sM[ps]=It}}}}}H&&(_._demTile.needsDEMTextureUpload=!0,_._dem._timestamp=Wc.now())}setFilter(f){this.filter=f?uC(f):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(f=>this.filter.filter(new bi(this.id.overscaledZ,{worldview:this.worldview}),f.feature,this.id.canonical)):this.nodesInfo}destroy(){const f=this.getNodesInfo();for(const _ of f)ite(_.node),kEe(_.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(f,_){if(_.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=_.updateTime;const S=_.getReplacementRegionsForTile(f.toUnwrapped());for(const E of this.getNodesInfo()){const D=E.node.footprint;E.hiddenByReplacement=!!D&&!S.find(z=>z.footprint===D)}}getHeightAtTileCoord(f,_){const S=[],E=[0,0,0],D=g([]);for(const z of this.getNodesInfo()){const H=z.node.meshes[0],Y=H.transformedAabb;if(fY.max[0]||_>Y.max[1])continue;if(z.node.hidden===!0)return{height:1/0,maxHeight:z.feature.properties.height,hidden:!1,verticalScale:z.evaluatedScale[2]};b(D,z.node.globalMatrix),E[0]=f,E[1]=_,Ge(E,E,D);const te=(E[0]-H.aabb.min[0])/(H.aabb.max[0]-H.aabb.min[0])*X6|0,he=Math.min(63,(E[1]-H.aabb.min[1])/(H.aabb.max[1]-H.aabb.min[1])*X6|0)*X6+Math.min(63,te),ge=H.heightmap[he];if(!(ge<0&&z.node.footprint))return z.hiddenByReplacement?void 0:{height:ge,maxHeight:z.feature.properties.height,hidden:!1,verticalScale:z.evaluatedScale[2]};if(z.node.footprint.grid.query(new Xs(f,_),new Xs(f,_),S),S.length>0)return{height:void 0,maxHeight:z.feature.properties.height,hidden:z.hiddenByReplacement,verticalScale:z.evaluatedScale[2]}}}}function GV(N,f){return N instanceof Xu&&!N.isLightConstant&&f}function ZGt(N,f,_,S,E,D,z,H){let Y=(61440&f|(61440&f)>>4)>>8,te=(3840&f|(3840&f)>>4)>>4,he=240&f|(240&f)>>4;_[3]>0&&(Y=xr(Y,255*_[0],_[3]),te=xr(te,255*_[1],_[3]),he=xr(he,255*_[2],_[3]));const ge=Y<<8|te,ve=he<<8|Math.floor(255*S[3]),Te=function(It){const xs=it(It,0,2);return Math.min(Math.round(.5*xs*255),255)}(S[2])<<8|15*S[0]<<4|15*S[1],Ie=it(E[0],0,1),Ve=it(E[1],0,1),et=it(E[2],0,1),at=it(E[3],0,1);let ft,ut,Nt,Mt;if(Ie!==Ve&&z!==D&&Ve!==Ie){const It=z-D;ut=1/(It*(Ve-Ie)),Nt=-(D+It*Ie)/(It*(Ve-Ie));const xs=it(E[4],-1,1);Mt=Math.pow(10,xs),ft=255*et<<8|255*at}else ft=65535,ut=0,Nt=1,Mt=1;if(N.emplaceBack(ge,ve,Te,ft,ut,Nt,Mt),H){const It=H.length;H.clear();for(let xs=0;xs>16&65535,he=D?Y>>16&65535:65535&Y,ge=(15&he)<8?15&he:0,ve=N.evaluatedRMEA[ge],Te=N.evaluatedColor[ge],Ie=N.emissionHeightBasedParams[ge];let Ve;if(H&&ge===2&&S.lights&&(Ve=new XO,Ve.resize(10*S.lights.length)),ZGt(z.featureArray,te,Te,ve,Ie,z.aabb.min[2],z.aabb.max[2],Ve),Ve&&H){H=!1;const et=S.meshes[S.lightMeshIndex];et.featureArray=Ve,et.featureArray._trim()}}z.featureArray._trim(),E++}}gr(Ate,"Tiled3dModelBucket",{omit:["layers"]}),gr(SJe,"Tiled3dModelFeature");const QGt=["id","tile","layer","source","sourceLayer","state"];class nM{constructor(f,_,S,E,D){this.type="Feature",this._vectorTileFeature=f,this._z=_,this._x=S,this._y=E,this.properties=f?f.properties:{},this.id=D}clone(){const f=new nM(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(f.state=Object.assign({},this.state)),this.layer&&(f.layer=Object.assign({},this.layer)),this.source&&(f.source=this.source),this.sourceLayer&&(f.sourceLayer=this.sourceLayer),f}get geometry(){return this._geometry===void 0&&this._vectorTileFeature&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._x,this._y,this._z).geometry),this._geometry}set geometry(f){this._geometry=f}toJSON(){const f={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const _ of QGt)this[_]!==void 0&&(f[_]=this[_]);return f}}class rM extends Xh{constructor(f,_,S,E){super(),this.id=f,this.type="model",this.models=[],this._options=_,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(f,_){return UXe(this.map._requestManager.transformRequest(f,g0.Model).url,_)}async loadModel(f,_,S){try{const E=await this.loadGLTFFromURI(_.uri,S);if(S.aborted)return;const D=this._modelsInfo.get(f);if(!D)return;const z=CEe(E),H=D.modelSpec,Y=new WXe(f,H.uri,H.position,H.orientation,z);rM.applyModelSpecification(Y,H),Y.computeBoundsAndApplyParent(),this.models.push(Y),D.model=Y}catch(E){if(E instanceof Error&&E.name==="AbortError")return;const D=E instanceof Error?E.message:"Unknown error";this.fire(new ip(new Error(`Could not load model ${f} from ${_.uri}: ${D}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const f=this._abortController.signal,_=[];for(const S in this._options.models){const E=this._options.models[S],D=this._modelsInfo.get(S);if(D&&D.model){D.modelSpec=E;const z=D.model;z.position=E.position!=null?new Cs(E.position[0],E.position[1]):new Cs(0,0),z.orientation=E.orientation!=null?E.orientation:[0,0,0],rM.applyModelSpecification(z,E),z.computeBoundsAndApplyParent(),this.models.push(z)}else D?D.modelSpec=E:(this._modelsInfo.set(S,{modelSpec:E,model:null}),_.push(this.loadModel(S,E,f)))}_.length!==0?(await Promise.allSettled(_),f.aborted||this.fire(new Tc("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Tc("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(f,_){_.nodeOverrides&&rM.convertNodeOverrides(f,_.nodeOverrides),_.materialOverrides&&rM.convertMaterialOverrides(f,_.materialOverrides),_.nodeOverrideNames&&(f.nodeOverrideNames=[..._.nodeOverrideNames]),_.materialOverrideNames&&(f.materialOverrideNames=[..._.materialOverrideNames]),_.featureProperties&&(f.featureProperties=_.featureProperties)}static convertNodeOverrides(f,_){if(Array.isArray(_)&&_.every(S=>typeof S=="string")){f.nodeOverrideNames=[];for(const S of _)f.nodeOverrideNames.push(S)}else Object.entries(_).forEach(([S,E])=>{const D={orientation:[0,0,0]};if(E.hasOwnProperty("orientation")){const z=E.orientation;z&&(D.orientation=z)}f.nodeOverrides.set(S,D)})}static convertMaterialOverrides(f,_){if(Array.isArray(_)&&_.every(S=>typeof S=="string")){f.materialOverrideNames=[];for(const S of _)f.materialOverrideNames.push(S)}else Object.entries(_).forEach(([S,E])=>{const D={color:new us(1,1,1),colorMix:0,emissionStrength:0,opacity:1},z=E["model-color"];z!==void 0&&(D.color.r=z[0],D.color.g=z[1],D.color.b=z[2]);const H=E["model-color-mix-intensity"];H!==void 0&&(D.colorMix=H);const Y=E["model-emissive-strength"];Y!==void 0&&(D.emissionStrength=Y);const te=E["model-opacity"];te!==void 0&&(D.opacity=te),f.materialOverrides.set(S,D)})}onAdd(f){this.map=f,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const f of this._modelsInfo.values())if(f.model==null)return!1;return!0}getModels(){return this.models}loadTile(f,_){}serialize(){return this._options}setProperty(f,_){return!1}reload(){this.cancelModelRequests();const f=Ct(this.id,this.scope);this.map.style.clearSource(f),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(f){this.cancelModelRequests()}setModels(f){this.models=[];const _=new Map;for(const S in f){const E=f[S],D=this._modelsInfo.get(S);D&&D.modelSpec.uri===E.uri&&_.set(S,D)}if(this._modelsInfo.size!==_.size){this.cancelModelRequests();for(const[S,E]of _)E.model||_.delete(S)}this._modelsInfo=_,this._options.models=f,this.load()}}function l6e(N,f,_,S){const E=1<Y>=Mt.vertexArrayOffset&&YNt.polygon).flat());const et=Te?H:null,[at,ft]=CXe(D,S,ge,he,te,z,et,ve,Ie,D.center.lat,N.tileID.canonical),ut=N.queryGeometry;return SXe(at,ft,ut.isPointQuery()?ut.screenBounds:ut.screenGeometry)}},building:class extends bl{constructor(N,f,_,S){super(N,{layout:eQe||(eQe=new pc({visibility:new sr(Rs.layout_building.visibility),"building-facade":new tr(Rs.layout_building["building-facade"]),"building-facade-floors":new tr(Rs.layout_building["building-facade-floors"]),"building-facade-unit-width":new tr(Rs.layout_building["building-facade-unit-width"]),"building-facade-window":new tr(Rs.layout_building["building-facade-window"]),"building-roof-shape":new tr(Rs.layout_building["building-roof-shape"]),"building-height":new tr(Rs.layout_building["building-height"]),"building-base":new tr(Rs.layout_building["building-base"]),"building-flood-light-wall-radius":new tr(Rs.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new tr(Rs.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new tr(Rs.layout_building["building-flip-roof-orientation"])})),paint:tQe||(tQe=new pc({"building-opacity":new sr(Rs.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new sr(Rs.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new sr(Rs.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new sr(Rs.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new sr(Rs.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new sr(Rs.paint_building["building-vertical-scale"]),"building-cast-shadows":new sr(Rs.paint_building["building-cast-shadows"]),"building-color":new tr(Rs.paint_building["building-color"]),"building-emissive-strength":new tr(Rs.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new sr(Rs.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new sr(Rs.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new sr(Rs.paint_building["building-front-cutoff"]),"building-flood-light-color":new sr(Rs.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new sr(Rs.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new sr(Rs.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new tr({type:"string",default:"default","property-type":"data-driven"})}))},f,_,S),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(N){return new JXe(N)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(N){return!0}queryRadius(N){return 0}queryIntersectsFeature(N,f,_,S,E,D,z,H,Y,te){let he=this.layout.get("building-height").evaluate(f,_);const ge=this.layout.get("building-base").evaluate(f,_),ve=N.tile.getBucket(this).getFootprint(f);if(ve){if(ve.hiddenFlags!==0)return!1;he=ve.height}const[Te,Ie]=CXe(D,S,ge,he,new Xs(0,0),z,null,[0,0],1,D.center.lat,N.tileID.canonical),Ve=N.queryGeometry;return SXe(Te,Ie,Ve.isPointQuery()?Ve.screenBounds:Ve.screenGeometry)}},line:class extends bl{constructor(N,f,_,S){const E=uQe();super(N,E,f,_,S),E.layout&&(this.layout=new Tm(E.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(N){if(N==="line-gradient"){const f=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=f._styleExpression&&f._styleExpression.expression instanceof yw,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(N,f){super.recalculate(N,f),this.paint._values["line-floorwidth"]=(()=>{if(LV)return LV;const _=uQe();return LV=new GHt(_.paint.properties["line-width"].specification),LV.useIntegerZoom=!0,LV})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,N)}createBucket(N){return new lte(N)}getProgramIds(){const N=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&N.push("lineBlendComposite"),N}getDefaultProgramParams(N,f,_){if(N==="lineBlendComposite")return{};const S=cQe(this);return{config:new He(this,{zoom:f,lut:_}),defines:S,overrideFog:!1}}queryRadius(N){const f=N,_=hQe(gC("line-width",this,f),gC("line-gap-width",this,f)),S=gC("line-offset",this,f);return _/2+Math.abs(S)+Lee(this.paint.get("line-translate"))}queryIntersectsFeature(N,f,_,S,E,D){if(N.queryGeometry.isAboveHorizon)return!1;const z=dZe(N.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),D.angle,N.pixelToTileUnitsFactor),H=N.pixelToTileUnitsFactor/2*hQe(this.paint.get("line-width").evaluate(f,_),this.paint.get("line-gap-width").evaluate(f,_)),Y=this.paint.get("line-offset").evaluate(f,_);return Y&&(S=function(te,he){const ge=[],ve=new Xs(0,0);for(let Te=0;Te=3){for(let Ie=0;Ie{this._triggered=!1,this._callback()})}trigger(){this._triggered||(this._triggered=!0,this._channel?this._channel.port1.postMessage(!0):setTimeout(()=>{this._triggered=!1,this._callback()},0))}remove(){this._channel=void 0,this._callback=()=>{}}}class CJe{constructor(f){this._stringToNumber={},this._numberToString=[];for(let _=0;_=0&&ve[3]>=0&&te.insert(Y,ve[0],ve[1],ve[2],ve[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new Vo(new cte(this.rawTileData)).layers,this.sourceLayerCoder=new CJe(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const f in this.vtLayers)this.vtFeatures[f]=[]}return this.vtLayers}query(f,_){const{tilespaceGeometry:S,transform:E,tileTransform:D,pixelPosMatrix:z,availableImages:H,worldview:Y}=_;this.loadVTLayers(),this.serializedLayersCache.clear();const te=_.queryRadius?_.queryRadius:0,he=S.bufferedTilespaceBounds,ge=this.grid.query(he.min.x,he.min.y,he.max.x,he.max.y,(Ve,et,at,ft)=>lk(S.bufferedTilespaceGeometry,Ve-te,et-te,at+te,ft+te));ge.sort(sWt);let ve=null;E.elevation&&ge.length>0&&(ve=gF.create(E.elevation,this.tileID));const Te={};let Ie;for(let Ve=0;Ve(ft||(ft=Ea(ut,this.tileID.canonical,D)),Nt.queryIntersectsFeature(S,ut,Mt,ft,this.z,E,z,ve,It,_.scope)))}return Te}loadMatchingFeature(f,_,S,E,D,z){const{featureIndex:H,bucketIndex:Y,sourceLayerIndex:te,layoutVertexArrayOffset:he}=_,ge=this.bucketLayerIDs[Y],ve=S.layers,Te=Object.keys(ve);if(Te.length&&!Jr(Te,ge))return;const Ie=S.sourceCache,Ve=this.sourceLayerCoder.decode(te),et=this.vtLayers[Ve].feature(H),at=this.getId(et,Ve);for(let ft=0;ft`${H.key}: ${H.message}`).join(", ");return void Mr(`Failed to create expression for promoteId: ${z}`)}this.promoteIdExpression=D.value}S=this.promoteIdExpression.evaluate({zoom:0},f)}else S=f.properties[E];typeof S=="boolean"&&(S=Number(S))}return S}}function TJe(N,f,_,S,E){return Tn(N,(D,z)=>{const H=f instanceof Tm?f.get(z):null;return H&&H.evaluate?H.evaluate(_,S,void 0,E):H})}function sWt(N,f){return f-N}function EJe(N,f){const _={};if(!f)return _;for(const S of N){const E=S.layerIds.map(D=>f.getLayer(D)).filter(Boolean);if(E.length!==0){S.layers=E,S.stateDependentLayerIds&&(S.stateDependentLayers=S.stateDependentLayerIds.map(D=>E.filter(z=>z.id===D)[0]));for(const D of E)_[D.fqid]=S}}return _}gr(AJe,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const Mw=32,fk=33,NC=new Uint16Array(8184);for(let N=0;N<2046;N++){let f=N+2,_=0,S=0,E=0,D=0,z=0,H=0;for(1&f?E=D=z=Mw:_=S=H=Mw;(f>>=1)>1;){const te=_+E>>1,he=S+D>>1;1&f?(E=_,D=S,_=z,S=H):(_=E,S=D,E=z,D=H),z=te,H=he}const Y=4*N;NC[Y+0]=_,NC[Y+1]=S,NC[Y+2]=E,NC[Y+3]=D}const xk=new Uint16Array(2178),kC=new Uint8Array(1089),Tte=new Uint16Array(1089);function MJe(N){return N===0?-.03125:N===32?.03125:0}const LJe={Other:0,Symbol:1,FillExtrusion:2},PJe={type:2,extent:nr,loadGeometry:()=>[[new Xs(0,0),new Xs(8193,0),new Xs(8193,8193),new Xs(0,8193),new Xs(0,0)]]};class nWt{constructor(){this.tasks={},this.taskQueue=[],Zs(["process"],this),this.invoker=new tWt(this.process),this.nextId=0}add(f,_){const S=this.nextId++,E=function({type:D,renderSourceType:z,zoom:H}){H=H||0;const Y=z===LJe.Symbol;return D==="message"?0:D!=="maybePrepare"||Y?D!=="parseTile"||Y?D==="parseTile"&&Y?300-H:D==="maybePrepare"&&Y?400-H:500:200-H:100-H}(_);if(E===0){try{f()}finally{}return null}return this.tasks[S]={fn:f,metadata:_,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 f=this.pick();if(f===null)return;const _=this.tasks[f];if(delete this.tasks[f],this.taskQueue.length&&this.invoker.trigger(),!_)return;_.fn()}finally{}}pick(){let f=null,_=1/0;for(let E=0;E>16&255)/255,(N>>8&255)/255,(255&N)/255,1)}function fWt(N,f,_){N===1?(f.rgb_color=Lte(_.readVarint()),f.paint="rgb_color"):N===2?(f.linear_gradient_idx=_.readVarint(),f.paint="linear_gradient_idx"):N===3?(f.radial_gradient_idx=_.readVarint(),f.paint="radial_gradient_idx"):N===5?_.readPackedFloat(f.dasharray):N===6?f.dashoffset=_.readFloat():N===7?f.miterlimit=_.readFloat():N===8?f.opacity=_.readVarint():N===9?f.width=_.readFloat():N===10?f.linecap=_.readVarint():N===11&&(f.linejoin=_.readVarint())}function xWt(N,f,_){N===1?f.transform=Mte(_,_.readVarint()+_.pos):N===2?f.spread_method=_.readVarint():N===3?f.stops.push(DJe(_,_.readVarint()+_.pos)):N===4?f.x1=_.readFloat():N===5?f.y1=_.readFloat():N===6?f.x2=_.readFloat():N===7&&(f.y2=_.readFloat())}function DJe(N,f){return N.readFields(gWt,{offset:0,opacity:255,rgb_color:c6e},f)}function gWt(N,f,_){N===1?f.offset=_.readFloat():N===2?f.opacity=_.readVarint():N===3&&(f.rgb_color=Lte(_.readVarint()))}function yWt(N,f,_){N===1?f.transform=Mte(_,_.readVarint()+_.pos):N===2?f.spread_method=_.readVarint():N===3?f.stops.push(DJe(_,_.readVarint()+_.pos)):N===4?f.cx=_.readFloat():N===5?f.cy=_.readFloat():N===6?f.r=_.readFloat():N===7?f.fx=_.readFloat():N===8?f.fy=_.readFloat():N===9&&(f.fr=_.readFloat())}function vWt(N,f,_){N===1?f.transform=Mte(_,_.readVarint()+_.pos):N===2?f.clip_path_idx=_.readVarint():N===3&&f.children.push(Ete(_,_.readVarint()+_.pos))}function bWt(N,f,_){N===1?f.left=f.top=_.readFloat():N===2?f.width=f.height=_.readFloat():N===3?f.top=_.readFloat():N===4?f.height=_.readFloat():N===5?f.mask_type=_.readVarint():N===6?f.mask_idx=_.readVarint():N===7&&f.children.push(Ete(_,_.readVarint()+_.pos))}class _Wt{static calculate(f={},_=[]){const S=new Map,E=new Map;if(Object.keys(f).length===0)return S;_.forEach(D=>{E.set(D.name,D.rgb_color||new us(0,0,0))});for(const[D,z]of Object.entries(f))E.has(D)?S.set(E.get(D).toString(),z):console.warn(`Ignoring unknown image variable "${D}"`);return S}}function yF(N,f=255,_){const S=f/255,E=N.toString(),D=_.has(E)?_.get(E).clone():N.clone();return D.a*=S,D.toString()}function WV(N,f){if(!qd()){const _=document.createElement("canvas");return _.width=N,_.height=f,_}return new OffscreenCanvas(N,f)}let d6e,KV=null;function u6e(N,f,_,S,E){for(const D of S.children)OJe(N,f,_,D,E)}function OJe(N,f,_,S,E){S.group?(N.save(),function(D,z,H,Y,te){const he=Y.mask_idx!=null?H.masks[Y.mask_idx]:null,ge=Y.clip_path_idx!=null?H.clip_paths[Y.clip_path_idx]:null;if(Y.transform&&(z=vF(Y.transform).preMultiplySelf(z)),!function(Ie,Ve,et){return Ie.opacity!==255||Ve||et}(Y,ge!=null,he!=null))return void u6e(D,z,H,Y,te);const ve=WV(D.canvas.width,D.canvas.height),Te=ve.getContext("2d");u6e(Te,z,H,Y,te),ge&&VJe(Te,z,H,ge),he&&HJe(Te,z,H,he,te),D.globalAlpha=Y.opacity/255,D.drawImage(ve,0,0)}(N,f,_,S.group,E),N.restore()):S.path&&(N.save(),function(D,z,H,Y,te){D.setTransform(z),Y.paint_order===1?(FJe(D,H,Y,te),BJe(D,H,Y,te)):(BJe(D,H,Y,te),FJe(D,H,Y,te))}(N,f,_,S.path,E),N.restore())}function FJe(N,f,_,S){const E=_.fill;if(!E)return;const D=E.opacity/255;switch(N.save(),N.beginPath(),GJe(_,N),E.paint){case"rgb_color":N.fillStyle=yF(E.rgb_color,E.opacity,S);break;case"linear_gradient_idx":{const z=f.linear_gradients[E.linear_gradient_idx];z.transform&&N.setTransform(vF(z.transform).preMultiplySelf(N.getTransform())),N.fillStyle=$Je(N,z,D,S);break}case"radial_gradient_idx":{const z=f.radial_gradients[E.radial_gradient_idx];z.transform&&N.setTransform(vF(z.transform).preMultiplySelf(N.getTransform())),N.fillStyle=UJe(N,z,D,S)}}N.fill(zJe(_)),N.restore()}function zJe(N){return N.rule===1?"nonzero":N.rule===2?"evenodd":void 0}function BJe(N,f,_,S){const E=_.stroke;if(!E)return;const D=WJe(_);N.lineWidth=E.width,N.miterLimit=E.miterlimit,N.setLineDash(E.dasharray),N.lineDashOffset=E.dashoffset;const z=E.opacity/255;switch(E.paint){case"rgb_color":N.strokeStyle=yF(E.rgb_color,E.opacity,S);break;case"linear_gradient_idx":N.strokeStyle=$Je(N,f.linear_gradients[E.linear_gradient_idx],z,S,!0);break;case"radial_gradient_idx":N.strokeStyle=UJe(N,f.radial_gradients[E.radial_gradient_idx],z,S,!0)}switch(E.linejoin){case 2:case 1:N.lineJoin="miter";break;case 3:N.lineJoin="round";break;case 4:N.lineJoin="bevel"}switch(E.linecap){case 1:N.lineCap="butt";break;case 2:N.lineCap="round";break;case 3:N.lineCap="square"}N.stroke(D)}function $Je(N,f,_,S,E=!1){if(f.stops.length===1){const ve=f.stops[0];return yF(ve.rgb_color,ve.opacity*_,S)}const{x1:D,y1:z,x2:H,y2:Y}=f;let te=new DOMPoint(D,z),he=new DOMPoint(H,Y);if(E){const ve=vF(f.transform);te=ve.transformPoint(te),he=ve.transformPoint(he)}const ge=N.createLinearGradient(te.x,te.y,he.x,he.y);for(const ve of f.stops)ge.addColorStop(ve.offset,yF(ve.rgb_color,ve.opacity*_,S));return ge}function UJe(N,f,_,S,E=!1){if(f.stops.length===1){const at=f.stops[0];return yF(at.rgb_color,at.opacity*_,S)}const D=vF(f.transform),{fx:z,fy:H,fr:Y,cx:te,cy:he,r:ge}=f;let ve=new DOMPoint(z,H),Te=new DOMPoint(te,he),Ie=Y,Ve=ge;if(E){ve=D.transformPoint(ve),Te=D.transformPoint(Te);const at=(D.a+D.d)/2;Ie=Y*at,Ve=f.r*at}const et=N.createRadialGradient(ve.x,ve.y,Ie,Te.x,Te.y,Ve);for(const at of f.stops)et.addColorStop(at.offset,yF(at.rgb_color,at.opacity*_,S));return et}function qJe(N,f,_,S){const E=S.transform?vF(S.transform).preMultiplySelf(f):f,D=WV(N.canvas.width,N.canvas.height),z=D.getContext("2d");for(const Y of S.children)if(Y.group)qJe(z,E,_,Y.group);else if(Y.path){const te=Y.path,he=new Path2D;he.addPath(WJe(te),E),z.fill(he,zJe(te))}const H=S.clip_path_idx!=null?_.clip_paths[S.clip_path_idx]:null;H&&VJe(z,E,_,H),N.globalCompositeOperation="source-over",N.drawImage(D,0,0)}function VJe(N,f,_,S){const E=WV(N.canvas.width,N.canvas.height);qJe(E.getContext("2d"),f,_,S),N.globalCompositeOperation="destination-in",N.drawImage(E,0,0)}function HJe(N,f,_,S,E){if(S.children.length===0)return;const D=S.mask_idx!=null?_.masks[S.mask_idx]:null;D&&HJe(N,f,_,D,E);const z=N.canvas.width,H=N.canvas.height,Y=WV(z,H),te=Y.getContext("2d"),he=S.width,ge=S.height,ve=S.left,Te=S.top,Ie=new Path2D,Ve=new Path2D;Ve.rect(ve,Te,he,ge),Ie.addPath(Ve,f),te.clip(Ie);for(const ft of S.children)OJe(te,f,_,ft,E);const et=te.getImageData(0,0,z,H),at=et.data;if(S.mask_type===1)for(let ft=0;ftf[z])return null}else{const H=1/S[z];let Y=(N[z]-_[z])*H,te=(f[z]-_[z])*H;if(Y>te){const he=Y;Y=te,te=he}if(Y>E&&(E=Y),teD)return null}return E}function ZJe(N,f,_,S,E,D,z,H,Y,te,he){const ge=S-N,ve=E-f,Te=D-_,Ie=z-N,Ve=H-f,et=Y-_,at=he[1]*et-he[2]*Ve,ft=he[2]*Ie-he[0]*et,ut=he[0]*Ve-he[1]*Ie,Nt=ge*at+ve*ft+Te*ut;if(Math.abs(Nt)<1e-15)return null;const Mt=1/Nt,It=te[0]-N,xs=te[1]-f,es=te[2]-_,ps=(It*at+xs*ft+es*ut)*Mt;if(ps<0||ps>1)return null;const cs=xs*Te-es*ve,ds=es*ge-It*Te,mn=It*ve-xs*ge,xn=(he[0]*cs+he[1]*ds+he[2]*mn)*Mt;return xn<0||ps+xn>1?null:(Ie*cs+Ve*ds+et*mn)*Mt}function XJe(N,f,_){return(N-f)/(_-f)}function QJe(N,f,_,S,E,D,z,H,Y){const te=1<<_,he=D-S,ge=z-E,ve=(N+1)/te*he+S,Te=(f+0)/te*ge+E,Ie=(f+1)/te*ge+E;H[0]=(N+0)/te*he+S,H[1]=Te,Y[0]=ve,Y[1]=Ie}class JJe{constructor(f){if(this.maximums=[],this.minimums=[],this.leaves=[],this.childOffsets=[],this.nodeCount=0,this.dem=f,this._siblingOffset=[[0,0],[1,0],[0,1],[1,1]],!this.dem)return;const _=function(D){const z=Math.ceil(Math.log2(D.dim/8)),H=[];let Y=Math.ceil(Math.pow(2,z));const te=1/Y,he=(Te,Ie,Ve,et,at)=>{const ft=et?1:0,ut=(Te+1)*Ve-ft,Nt=Ie*Ve,Mt=(Ie+1)*Ve-ft;at[0]=Te*Ve,at[1]=Nt,at[2]=ut,at[3]=Mt};let ge=new KJe(Y);const ve=[];for(let Te=0;Te=1;Y/=2){const Te=H[H.length-1];ge=new KJe(Y);for(let Ie=0;Ie0;){const{idx:Ie,t:Ve,nodex:et,nodey:at,depth:ft}=Te.pop();if(this.leaves[Ie]){QJe(et,at,ft,f,_,S,E,ge,ve);const Nt=1<=Sn[2])return Ve}continue}let ut=0;for(let Nt=0;Nt=te[he[es]]&&(he.splice(es,0,Nt),xs=!0);xs||(he[ut]=Nt),ut++}}for(let Nt=0;Nt=this.dim+1||_<-1||_>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(_+1)*this.stride+(f+1)}static pack(f,_){const S=[0,0,0,0],E=Ite.getUnpackVector(_);let D=Math.floor((f+E[3])/E[2]);return S[2]=D%256,D=Math.floor(D/256),S[1]=D%256,D=Math.floor(D/256),S[0]=D,S}getPixels(){return new RZe({width:this.stride,height:this.stride},this.pixels)}backfillBorder(f,_,S){if(this.dim!==f.dim)throw new Error("dem dimension mismatch");let E=_*this.dim,D=_*this.dim+this.dim,z=S*this.dim,H=S*this.dim+this.dim;switch(_){case-1:E=D-1;break;case 1:D=E+1}switch(S){case-1:z=H-1;break;case 1:H=z+1}const Y=-_*this.dim,te=-S*this.dim;for(let he=z;he=1;S--){const E=S===1?1:0,D=S===2?1:0;for(let z=0;z>>1^-(1&N[f]);return N}function RWt(N,f){switch(f){case"uint32":return N;case"uint16":for(let _=0;_>4|(61440&S)>>8|(240&E)<<4|61440&E,N[_+1]=15&S|(3840&S)>>4|(15&E)<<8|(3840&E)<<4}return N;case"uint8":for(let _=0;_>6|(192&E)>>4|(192&D)>>2|192&z,N[_+1]=(48&S)>>4|(48&E)>>2|48&D|(48&z)<<2,N[_+2]=(12&S)>>2|12&E|(12&D)<<2|(12&z)<<4,N[_+3]=3&S|(3&E)<<2|(3&D)<<4|(3&z)<<6}return N;default:throw new Error(`Invalid pixel format, "${f}"`)}}gr(Ite,"DEMData"),gr(JJe,"DemMinMaxQuadTree",{omit:["dem"]});var Qb=Uint8Array,YV=Uint16Array,DWt=Int32Array,tet=new Qb([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]),set=new Qb([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]),OWt=new Qb([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),net=function(N,f){for(var _=new YV(31),S=0;S<31;++S)_[S]=f+=1<>1|(21845&sm)<<1;iet[sm]=((65280&(bF=(61680&(bF=(52428&bF)>>2|(13107&bF)<<2))>>4|(3855&bF)<<4))>>8|(255&bF)<<8)>>1}var ZV=function(N,f,_){for(var S=N.length,E=0,D=new YV(f);E>Y]=te;return z},XV=new Qb(288);for(sm=0;sm<144;++sm)XV[sm]=8;for(sm=144;sm<256;++sm)XV[sm]=9;for(sm=256;sm<280;++sm)XV[sm]=7;for(sm=280;sm<288;++sm)XV[sm]=8;var oet=new Qb(32);for(sm=0;sm<32;++sm)oet[sm]=5;var BWt=ZV(XV,9),$Wt=ZV(oet,5),m6e=function(N){for(var f=N[0],_=1;_f&&(f=N[_]);return f},x2=function(N,f,_){var S=f/8|0;return(N[S]|N[S+1]<<8)>>(7&f)&_},p6e=function(N,f){var _=f/8|0;return(N[_]|N[_+1]<<8|N[_+2]<<16)>>(7&f)},UWt=function(N){return(N+7)/8|0},qWt=["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"],g2=function(N,f,_){var S=new Error(f||qWt[N]);if(S.code=N,Error.captureStackTrace&&Error.captureStackTrace(S,g2),!_)throw S;return S},VWt=new Qb(0),HWt=typeof TextDecoder<"u"&&new TextDecoder;try{HWt.decode(VWt,{stream:!0})}catch{}const GWt={gzip_data:"gzip"};class Lw extends Error{constructor(f){super(f),this.name="MRTError"}}const WWt={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},cet={uint32:1,uint16:2,uint8:4},KWt={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let f6e;class Rte{constructor(f=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=f}getLayer(f){const _=this.layers[f];if(!_)throw new Lw(`Layer '${f}' not found`);return _}getHeaderLength(f){const _=new Uint8Array(f),S=new DataView(f);if(_[0]!==13)throw new Lw("File is not a valid MRT.");return S.getUint32(1,!0)}parseHeader(f){const _=new Uint8Array(f),S=this.getHeaderLength(f);if(_.length= ${S} but got buffer of length ${_.length}`);const E=new f6e(_.subarray(0,S)).readFields(kWt,{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 Lw(`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 D of E.layers)this.layers[D.name]=new det(D,{cacheSize:this._cacheSize});return this}createDecodingTask(f){const _=[],S=this.getLayer(f.layerName);for(let E of f.blockIndices){const D=S.dataIndex[E],z=D.firstByte-f.firstByte,H=D.lastByte-f.firstByte;if(S._blocksInProgress.has(E))continue;const Y={layerName:S.name,firstByte:z,lastByte:H,pixelFormat:S.pixelFormat,blockIndex:E,blockShape:[D.bands.length].concat(S.bandShape),buffer:S.buffer,codec:D.codec.codec,filters:D.filters.map(te=>te.filter)};S._blocksInProgress.add(E),_.push(Y)}return new uet(_,()=>{_.forEach(E=>S._blocksInProgress.delete(E.blockIndex))},(E,D)=>{if(_.forEach(z=>S._blocksInProgress.delete(z.blockIndex)),E)throw E;D.forEach(z=>{this.getLayer(z.layerName).processDecodedData(z)})})}}class det{constructor({version:f,name:_,units:S,tileSize:E,pixelFormat:D,buffer:z,dataIndex:H},Y){if(this.version=f,this.version!==1)throw new Lw(`Cannot parse raster layer encoded with MRT version ${f}`);this.name=_,this.units=S,this.tileSize=E,this.buffer=z,this.pixelFormat=WWt[D],this.dataIndex=H,this.bandShape=[E+2*z,E+2*z,cet[this.pixelFormat]],this._decodedBlocks=new Pte(Y?Y.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return cet[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:f})=>f).flat()}processDecodedData(f){const _=f.blockIndex.toString();this._decodedBlocks.get(_)||this._decodedBlocks.put(_,f.data)}getBlockForBand(f){let _=0;switch(typeof f){case"string":for(const[S,E]of this.dataIndex.entries()){for(const[D,z]of E.bands.entries())if(z===f)return{bandIndex:_+D,blockIndex:S,blockBandIndex:D};_+=E.bands.length}break;case"number":for(const[S,E]of this.dataIndex.entries()){if(f>=_&&f<_+E.bands.length)return{bandIndex:f,blockIndex:S,blockBandIndex:f-_};_+=E.bands.length}break;default:throw new Lw(`Invalid band \`${JSON.stringify(f)}\`. Expected string or integer.`)}return{blockIndex:-1,blockBandIndex:-1}}getDataRange(f){let _=1/0,S=-1/0;const E=[],D=new Set;for(const z of f){const{blockIndex:H}=this.getBlockForBand(z);if(H<0)throw new Lw(`Invalid band: ${JSON.stringify(z)}`);const Y=this.dataIndex[H];E.includes(H)||E.push(H),D.add(H),_=Math.min(_,Y.firstByte),S=Math.max(S,Y.lastByte)}if(D.size>this.cacheSize)throw new Lw(`Number of blocks to decode (${D.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:_,lastByte:S,blockIndices:E}}hasBand(f){const{blockIndex:_}=this.getBlockForBand(f);return _>=0}hasDataForBand(f){const{blockIndex:_}=this.getBlockForBand(f);return _>=0&&!!this._decodedBlocks.get(_.toString())}getBandView(f){const{blockIndex:_,blockBandIndex:S}=this.getBlockForBand(f);if(_<0)throw new Lw(`Band not found: ${JSON.stringify(f)}`);const E=this._decodedBlocks.get(_.toString());if(!E)throw new Lw(`Data for band ${JSON.stringify(f)} of layer "${this.name}" not decoded.`);const D=this.dataIndex[_],z=this.bandShape.reduce((te,he)=>te*he,1),H=S*z,Y=E.subarray(H,H+z);return{data:Y,bytes:new Uint8Array(Y.buffer).subarray(Y.byteOffset,Y.byteOffset+Y.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:D.offset,scale:D.scale}}}Rte.setPbf=function(N){f6e=N};class uet{constructor(f,_,S){this.tasks=f,this._onCancel=_,this._onComplete=S,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(f,_){this._finalized||(this._onComplete(f,_),this._finalized=!0)}}Rte.performDecoding=function(N,f){const _=new Uint8Array(N);return Promise.all(f.tasks.map(S=>{const{layerName:E,firstByte:D,lastByte:z,pixelFormat:H,blockShape:Y,blockIndex:te,filters:he,codec:ge}=S,ve=_.subarray(D,z+1),Te=new Uint32Array(Y[0]*Y[1]*Y[2]);let Ie;if(ge!=="gzip_data")throw new Lw(`Unhandled codec: ${ge}`);return Ie=function(Ve,et){if(!globalThis.DecompressionStream&&et==="gzip_data")return Promise.resolve((Mt=function(es){es[0]==31&&es[1]==139&&es[2]==8||g2(6,"invalid gzip data");var ps=es[3],cs=10;4&ps&&(cs+=2+(es[10]|es[11]<<8));for(var ds=(ps>>3&1)+(ps>>4&1);ds>0;ds-=!es[cs++]);return cs+(2&ps)}(at=Ve),Mt+8>at.length&&g2(6,"invalid gzip data"),function(es,ps,cs,ds){var mn=es.length;if(!mn||ps.f&&!ps.l)return cs||new Qb(0);var xn=!cs,kn=xn||ps.i!=2,En=ps.i;xn&&(cs=new Qb(3*mn));var Sn=function(Pd){var Ux=cs.length;if(Pd>Ux){var gp=new Qb(Math.max(2*Ux,Pd));gp.set(cs),cs=gp}},Gn=ps.f||0,dn=ps.p||0,An=ps.b||0,Pn=ps.l,Wn=ps.d,ir=ps.m,Ur=ps.n,wr=8*mn;do{if(!Pn){Gn=x2(es,dn,1);var vr=x2(es,dn+1,3);if(dn+=3,!vr){var or=es[(tl=UWt(dn)+4)-4]|es[tl-3]<<8,Or=tl+or;if(Or>mn){En&&g2(0);break}kn&&Sn(An+or),cs.set(es.subarray(tl,Or),An),ps.b=An+=or,ps.p=dn=8*Or,ps.f=Gn;continue}if(vr==1)Pn=BWt,Wn=$Wt,ir=9,Ur=5;else if(vr==2){var sa=x2(es,dn,31)+257,Ta=x2(es,dn+10,15)+4,ya=sa+x2(es,dn+5,31)+1;dn+=14;for(var xi=new Qb(ya),jo=new Qb(19),gi=0;gi>4)<16)xi[gi++]=tl;else{var Yl=0,bd=0;for(tl==16?(bd=3+x2(es,dn,3),dn+=2,Yl=xi[gi-1]):tl==17?(bd=3+x2(es,dn,7),dn+=3):tl==18&&(bd=11+x2(es,dn,127),dn+=7);bd--;)xi[gi++]=Yl}}var Lm=xi.subarray(0,sa),_d=xi.subarray(sa);ir=m6e(Lm),Ur=m6e(_d),Pn=ZV(Lm,ir),Wn=ZV(_d,Ur)}else g2(1);if(dn>wr){En&&g2(0);break}}kn&&Sn(An+131072);for(var tu=(1<>4;if((dn+=15&Yl)>wr){En&&g2(0);break}if(Yl||g2(2),zf<256)cs[An++]=zf;else{if(zf==256){su=dn,Pn=null;break}var Pm=zf-254;zf>264&&(Pm=x2(es,dn,(1<<(wu=tet[gi=zf-257]))-1)+aet[gi],dn+=wu);var Ui=Wn[p6e(es,dn)&Qu],Mg=Ui>>4;if(Ui||g2(3),dn+=15&Ui,_d=zWt[Mg],Mg>3){var wu=set[Mg];_d+=p6e(es,dn)&(1<wr){En&&g2(0);break}kn&&Sn(An+131072);var xp=An+Pm;if(An<_d){var Lg=0-_d,Bf=Math.min(_d,xp);for(Lg+An<0&&g2(3);AnPd.length)&&(gp=Pd.length),new Qb(Pd.subarray(0,gp))}(cs,0,An):cs.subarray(0,An)}(at.subarray(Mt,-8),{i:2},new Qb(((ut=at)[(Nt=ut.length)-4]|ut[Nt-3]<<8|ut[Nt-2]<<16|ut[Nt-1]<<24)>>>0),ft)));var at,ft,ut,Nt,Mt;const It=GWt[et];if(!It)throw new Error(`Unhandled codec: ${et}`);const xs=new globalThis.DecompressionStream(It);return new Response(new Blob([Ve]).stream().pipeThrough(xs)).arrayBuffer().then(es=>new Uint8Array(es))}(ve,ge).then(Ve=>(function(et,at){et.readFields(MWt,at)}(new f6e(Ve),Te),new KWt[H](Te.buffer))),Ie.then(Ve=>{for(let et=he.length-1;et>=0;et--)switch(he[et]){case"delta_filter":PWt(Ve,Y);break;case"zigzag_filter":IWt(Ve);break;case"bitshuffle_filter":RWt(Ve,H);break;default:throw new Lw(`Unhandled filter "${he[et]}"`)}return{layerName:E,blockIndex:te,data:Ve}}).catch(Ve=>{throw Ve})}))},gr(uet,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),gr(Rte,"MapboxRasterTile"),gr(det,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const het=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class x6e{static from(f){if(!(f instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[_,S]=new Uint8Array(f,0,2);if(_!==219)throw new Error("Data does not appear to be in a KDBush format.");const E=S>>4;if(E!==1)throw new Error(`Got v${E} data when expected v1.`);const D=het[15&S];if(!D)throw new Error("Unrecognized array type.");const[z]=new Uint16Array(f,2,1),[H]=new Uint32Array(f,4,1);return new x6e(H,z,D,f)}constructor(f,_=64,S=Float64Array,E){if(isNaN(f)||f<0)throw new Error(`Unpexpected numItems value: ${f}.`);this.numItems=+f,this.nodeSize=Math.min(Math.max(+_,2),65535),this.ArrayType=S,this.IndexArrayType=f<65536?Uint16Array:Uint32Array;const D=het.indexOf(this.ArrayType),z=2*f*this.ArrayType.BYTES_PER_ELEMENT,H=f*this.IndexArrayType.BYTES_PER_ELEMENT,Y=(8-H%8)%8;if(D<0)throw new Error(`Unexpected typed array class: ${S}.`);E&&E instanceof ArrayBuffer?(this.data=E,this.ids=new this.IndexArrayType(this.data,8,f),this.coords=new this.ArrayType(this.data,8+H+Y,2*f),this._pos=2*f,this._finished=!0):(this.data=new ArrayBuffer(8+z+H+Y),this.ids=new this.IndexArrayType(this.data,8,f),this.coords=new this.ArrayType(this.data,8+H+Y,2*f),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+D]),new Uint16Array(this.data,2,1)[0]=_,new Uint32Array(this.data,4,1)[0]=f)}add(f,_){const S=this._pos>>1;return this.ids[S]=S,this.coords[this._pos++]=f,this.coords[this._pos++]=_,S}finish(){const f=this._pos>>1;if(f!==this.numItems)throw new Error(`Added ${f} items when expected ${this.numItems}.`);return g6e(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(f,_,S,E){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:D,coords:z,nodeSize:H}=this,Y=[0,D.length-1,0],te=[];for(;Y.length;){const he=Y.pop()||0,ge=Y.pop()||0,ve=Y.pop()||0;if(ge-ve<=H){for(let et=ve;et<=ge;et++){const at=z[2*et],ft=z[2*et+1];at>=f&&at<=S&&ft>=_&&ft<=E&&te.push(D[et])}continue}const Te=ve+ge>>1,Ie=z[2*Te],Ve=z[2*Te+1];Ie>=f&&Ie<=S&&Ve>=_&&Ve<=E&&te.push(D[Te]),(he===0?f<=Ie:_<=Ve)&&(Y.push(ve),Y.push(Te-1),Y.push(1-he)),(he===0?S>=Ie:E>=Ve)&&(Y.push(Te+1),Y.push(ge),Y.push(1-he))}return te}within(f,_,S){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:E,coords:D,nodeSize:z}=this,H=[0,E.length-1,0],Y=[],te=S*S;for(;H.length;){const he=H.pop()||0,ge=H.pop()||0,ve=H.pop()||0;if(ge-ve<=z){for(let et=ve;et<=ge;et++)pet(D[2*et],D[2*et+1],f,_)<=te&&Y.push(E[et]);continue}const Te=ve+ge>>1,Ie=D[2*Te],Ve=D[2*Te+1];pet(Ie,Ve,f,_)<=te&&Y.push(E[Te]),(he===0?f-S<=Ie:_-S<=Ve)&&(H.push(ve),H.push(Te-1),H.push(1-he)),(he===0?f+S>=Ie:_+S>=Ve)&&(H.push(Te+1),H.push(ge),H.push(1-he))}return Y}}function g6e(N,f,_,S,E,D){if(E-S<=_)return;const z=S+E>>1;met(N,f,z,S,E,D),g6e(N,f,_,S,z-1,1-D),g6e(N,f,_,z+1,E,1-D)}function met(N,f,_,S,E,D){for(;E>S;){if(E-S>600){const te=E-S+1,he=_-S+1,ge=Math.log(te),ve=.5*Math.exp(2*ge/3),Te=.5*Math.sqrt(ge*ve*(te-ve)/te)*(he-te/2<0?-1:1);met(N,f,_,Math.max(S,Math.floor(_-he*ve/te+Te)),Math.min(E,Math.floor(_+(te-he)*ve/te+Te)),D)}const z=f[2*_+D];let H=S,Y=E;for(QV(N,f,S,_),f[2*E+D]>z&&QV(N,f,S,E);Hz;)Y--}f[2*S+D]===z?QV(N,f,S,Y):(Y++,QV(N,f,Y,E)),Y<=_&&(S=Y+1),_<=Y&&(E=Y-1)}}function QV(N,f,_,S){y6e(N,_,S),y6e(f,2*_,2*S),y6e(f,2*_+1,2*S+1)}function y6e(N,f,_){const S=N[f];N[f]=N[_],N[_]=S}function pet(N,f,_,S){const E=N-_,D=f-S;return E*E+D*D}o.$=Rf,o.A=class{constructor(N,f,_){this.target=N,this.parent=f,this.mapId=_,this.callbacks={},this.cancelCallbacks={},Zs(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new nWt}send(N,f,_,S,E=!1,D){const z=Math.round(1e18*Math.random()).toString(36).substring(0,10);_&&(_.metadata=D,this.callbacks[z]=_);const H=new Set;return this.target.postMessage({id:z,type:N,hasCallback:!!_,targetMapId:S,mustQueue:E,sourceMapId:this.mapId,data:Ec(f,H)},H),{cancel:()=>{_&&delete this.callbacks[z],this.target.postMessage({id:z,type:"",targetMapId:S,sourceMapId:this.mapId})}}}receive(N){const f=N.data;if(!f)return;const _=f.id;if(_&&(!f.targetMapId||this.mapId===f.targetMapId))if(f.type===""){const S=this.cancelCallbacks[_];delete this.cancelCallbacks[_],S&&S.cancel()}else if(f.mustQueue||aa(self)){const S=this.callbacks[_],E=this.scheduler.add(()=>this.processTask(_,f),S&&S.metadata||{type:"message"});E&&(this.cancelCallbacks[_]=E)}else this.processTask(_,f)}processTask(N,f){if(delete this.cancelCallbacks[N],f.type===""){const _=this.callbacks[N];delete this.callbacks[N],_&&(f.error?_(ec(f.error)):_(null,ec(f.data)))}else{const _=new Set,S=f.hasCallback?(D,z)=>{this.target.postMessage({id:N,type:"",sourceMapId:this.mapId,error:D?Ec(D):null,data:Ec(z,_)},_)}:()=>{},E=ec(f.data);if(this.parent[f.type])this.parent[f.type](f.sourceMapId,E,S);else if(this.parent.getWorkerSource){const D=f.type.split("."),{source:z,scope:H}=E;this.parent.getWorkerSource(f.sourceMapId,{type:D[0],source:z,scope:H,uid:0})[D[1]](E,S)}else S(new Error(`Could not find function ${f.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=ip,o.C=Tc,o.D=gd,o.E=Xh,o.F=Ct,o.G=2,o.H=RV,o.I=Zt,o.J=MQe,o.K=Ng,o.L=MS,o.M=Ox,o.N=b0,o.O=vd,o.P=Xs,o.Q=qo,o.R=g0,o.S=Th,o.T=pk,o.U=km,o.V=Cte,o.W=ik,o.X=Fc,o.Y=Iu,o.Z=Xd,o._=A1,o.a=function(N){return Gr.API_CDN_URL_REGEX.test(N)},o.a$=cte,o.a0=Kc,o.a1=Pf,o.a2=ox,o.a3=is,o.a4=LS,o.a5=class extends Cte{},o.a6=Qd,o.a7=yd,o.a8=Rs,o.a9=function(N){const f=N.value;return f?ox(f)?a6e(f,!0)?[]:[new Cte(N.key,f,`invalid url "${f}"`)]:[new Cte(N.key,f,`string expected, "${Ox(f)}" found`)]:[]},o.aA=aQe,o.aB=function(N){let f=1/0,_=1/0,S=-1/0,E=-1/0;for(const D of N)f=Math.min(f,D.x),_=Math.min(_,D.y),S=Math.max(S,D.x),E=Math.max(E,D.y);return{min:new Xs(f,_),max:new Xs(S,E)}},o.aC=it,o.aD=v,o.aE=dt,o.aF=$t,o.aG=L0,o.aH=Ln,o.aI=Br,o.aJ=function(N,f){const _={};for(let S=0;S=0?f.slice(_+1):""}catch{return""}},o.aN=class{constructor(N){this.entries={},this.scheduler=N}request(N,f,_,S){const E=this.entries[N]=this.entries[N]||{callbacks:[]};if(E.result){const[D,z]=E.result;return this.scheduler?this.scheduler.add(()=>{S(D,z)},f):S(D,z),()=>{}}return E.callbacks.push(S),E.cancel||(E.cancel=_((D,z)=>{E.result=[D,z];for(const H of E.callbacks)this.scheduler?this.scheduler.add(()=>{H(D,z)},f):H(D,z);setTimeout(()=>delete this.entries[N],3e3)})),()=>{E.result||(E.callbacks=E.callbacks.filter(D=>D!==S),E.callbacks.length||(E.cancel(),delete this.entries[N]))}}},o.aO=function(N,f,_){const S=JSON.stringify(N.request);return N.data&&(this.deduped.entries[S]={result:[null,N.data]}),this.deduped.request(S,{type:"parseTile",renderSourceType:N.renderSourceType,zoom:N.tileZoom},E=>{const D=gy(N.request,(z,H,Y)=>{z?sp(z)?E(null,null):E(z):H&&E(null,{rawData:H,vectorTile:_?void 0:new Vo(new cte(H)),responseHeaders:new Map(Y.entries())})});return()=>{D.cancel(),E(null,null)}},f)},o.aP=function(N){return N?{cacheControl:N.get("cache-control"),expires:N.get("expires")}:{cacheControl:void 0,expires:void 0}},o.aQ=function(N){go++,go>Ef&&(N.getActor().send("enforceCacheSizeLimit",xy),go=0)},o.aR=Eg,o.aS=hJe,o.aT=bJe,o.aU=Cs,o.aV=uJe,o.aW=function(N,f){const _=document.createElement("video");_.muted=!0,_.onloadstart=function(){f(null,_)};for(let S=0;S{}}},o.aX=EV,o.aY=rM,o.aZ=Zs,o.a_=Rte,o.aa=lC,o.ab=pc,o.ac=sr,o.ad=class{constructor(N){this.specification=N}possiblyEvaluate(N,f){return Zn(N.expression.evaluate(f))}interpolate(N,f,_){return{x:xr(N.x,f.x,_),y:xr(N.y,f.y,_),z:xr(N.z,f.z,_),azimuthal:xr(N.azimuthal,f.azimuthal,_),polar:xr(N.polar,f.polar,_)}}},o.ae=bi,o.af=Bl,o.ag=ta,o.ah=Ge,o.ai=K,o.aj=gt,o.ak=Tm,o.al=zS,o.am=xr,o.an=nr,o.ao=Ha,o.ap=pr,o.aq=us,o.ar=class{constructor(N){this.specification=N}possiblyEvaluate(N,f){return function([_,S]){const E=Zn([1,_,S]);return{x:E.x,y:E.y,z:E.z}}(N.expression.evaluate(f))}interpolate(N,f,_){return{x:xr(N.x,f.x,_),y:xr(N.y,f.y,_),z:xr(N.z,f.z,_)}}},o.as=function(N,f,_=0,S=!0){const E=new Xs(_,_),D=N.sub(E),z=f.add(E),H=[D,new Xs(z.x,D.y),z,new Xs(D.x,z.y)];return S&&H.push(D.clone()),H},o.at=function(N,f){const _=[];for(let S=0;Sthis.buckets[ge].layers.some(ve=>z.has(ve.fqid))),Y=Object.keys(this.buckets).some(ge=>this.buckets[ge].layers.some(ve=>ve.hasTransition&&ve.hasTransition())),te=this._firstPrepareComplete&&D!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(f));const he=this._lastUpdatedBrightness!==S;this._lastAvailableImagesCount=D,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||S||this._hasAppearances||H||Y||te)&&(!(this._hasAppearances||H||Y||te)&&this._lastUpdatedBrightness&&S&&Math.abs(this._lastUpdatedBrightness-S)<.001||(this.updateBuckets(f,he,void 0,te||H||Y,z,E),this._lastUpdatedBrightness=S))}evaluateQueryRenderedFeaturePadding(){let N=0;for(const f in this.buckets){const _=this.buckets[f];_.evaluateQueryRenderedFeaturePadding&&(N=Math.max(N,_.evaluateQueryRenderedFeaturePadding()))}return N}queryRenderedFeatures(N,f,_,S,E,D,z){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const H=this.evaluateQueryRenderedFeaturePadding(),Y=function(te,he){const ge=L([],[.5*te.width,.5*-te.height,1]);return k(ge,ge,[1,-1,0]),v(ge,ge,te.calculateProjMatrix(he.toUnwrapped())),Float32Array.from(ge)}(E,this.tileID);return this.latestFeatureIndex.query(N,{tilespaceGeometry:f,pixelPosMatrix:Y,transform:S,availableImages:_,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:H,scope:z})}querySourceFeatures(N,f){const _=this.latestFeatureIndex;if(!_||!_.rawTileData)return;const S=_.loadVTLayers(),E=f?f.sourceLayer:"",D=S._geojsonTileLayer||S[E];if(!D)return;const z=uC(f&&f.filter),{z:H,x:Y,y:te}=this.tileID.canonical,he={z:H,x:Y,y:te};for(let ge=0;ge_)S=!1;else if(f)if(this.expirationTime_.appearances&&_.appearances.length>0))return!0;return!1}updateBuckets(N,f,_,S,E,D){if(!this.latestFeatureIndex||!N.style)return;const z=D||N.style.listImages(),H=N.style.getBrightness(),Y=E||new Set;for(const te in this.buckets){if(!N.style.hasLayer(te))continue;const he=this.buckets[te],ge=he.layers[0],ve=ge.sourceLayer||"_geojsonTileLayer",Te=N.style.getLayerSourceCache(ge),Ie=he.layers.some(Mt=>Y.has(Mt.fqid)),Ve=(S||Ie)&&he instanceof f2?N.style.getOwnLayer(te):void 0;let et=_&&_[ve]||{};Te&&!_&&(et=Te._state.getState(ve,void 0));const at=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},ft=Object.keys(et).length>0&&!f;he.hasAppearances=he.layers.some(Mt=>Mt.appearances&&Mt.appearances.length>0);const ut=ft?he.stateDependentLayers:he.layers;if(ft&&he.stateDependentLayers.length!==0||f||Ie||S){const Mt=this.latestFeatureIndex.loadVTLayers()[ve];if(he.update(et,Mt,z,at,ut,f,H,this.tileID.canonical),(S||Ie)&&!f&&he instanceof f2&&Ve&&Ve.type==="symbol"){const It=he;It.text&&It.text.uboBinder&&It.text.uboBinder.updateDynamicExpressions(Ve,Mt,this.tileID.canonical,z,et,H),It.icon&&It.icon.uboBinder&&It.icon.uboBinder.updateDynamicExpressions(Ve,Mt,this.tileID.canonical,z,et,H)}if(he instanceof f2){const It=he,xs=N.context;It.text&&It.text.uboBinder&&It.text.uboBinder.upload(xs),It.icon&&It.icon.uboBinder&&It.icon.uboBinder.upload(xs)}}if(ft&&he.stateDependentLayers.length!==0||f||he.hasAppearances){const Mt={zoom:N.transform.zoom,pitch:N.transform.pitch,brightness:N.style.getBrightness()||0,worldview:N.worldview},It=he.updateAppearances(this.tileID.canonical,et,z,Mt,N.imageManager,ft&&he.stateDependentLayers.length!==0);if(It&&It.hasUboChanges){const xs=N.context;he instanceof f2&&he.text&&he.text.uboBinder&&he.text.uboBinder.upload(xs),he instanceof f2&&he.icon&&he.icon.uboBinder&&he.icon.uboBinder.upload(xs)}}(he instanceof lte||he instanceof qee)&&N._terrain&&N._terrain.enabled&&Te&&he.uploadPending()&&N._terrain._clearRenderCacheForTile(Te.id,this.tileID);const Nt=N&&N.style&&N.style.getOwnLayer(te);Nt&&(this.queryPadding=Math.max(this.queryPadding,Nt.queryRadius(he)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Ve--){const et=4*Ve,at=NC[et+0],ft=NC[et+1],ut=NC[et+2],Nt=NC[et+3],Mt=at+ut>>1,It=ft+Nt>>1,xs=Mt+It-ft,es=It+at-Mt,ps=ft*fk+at,cs=Nt*fk+ut,ds=It*fk+Mt,mn=Math.hypot((xk[2*ps+0]+xk[2*cs+0])/2-xk[2*ds+0],(xk[2*ps+1]+xk[2*cs+1])/2-xk[2*ds+1])>=16;kC[ds]=kC[ds]||(mn?1:0),Ve<1022&&(kC[ds]=kC[ds]||kC[(ft+es>>1)*fk+(at+xs>>1)]||kC[(Nt+es>>1)*fk+(ut+xs>>1)])}const he=new Xi,ge=new eu;let ve=0;function Te(Ve,et){const at=et*fk+Ve;return Tte[at]===0&&(he.emplaceBack(xk[2*at+0],xk[2*at+1],Ve*nr/Mw,et*nr/Mw),Tte[at]=++ve),Tte[at]-1}function Ie(Ve,et,at,ft,ut,Nt){const Mt=Ve+at>>1,It=et+ft>>1;if(Math.abs(Ve-ut)+Math.abs(et-Nt)>1&&kC[It*fk+Mt])Ie(ut,Nt,Ve,et,Mt,It),Ie(at,ft,ut,Nt,Mt,It);else{const xs=Te(Ve,et),es=Te(at,ft),ps=Te(ut,Nt);ge.emplaceBack(xs,es,ps)}}return Ie(0,0,Mw,Mw,Mw,0),Ie(Mw,Mw,0,0,0,Mw),{vertices:he,indices:ge}}(this.tileID.canonical,f);S=D.vertices,E=D.indices}else{S=new Xi,E=new eu;for(const{x:z,y:H}of _)S.emplaceBack(z,H,0,0);const D=rF(S.int16.subarray(0,4*S.length),void 0,4);for(let z=0;z0&&(z=b(new Float64Array(16),f.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(N,S,f,E,z,D),this._makeGlobeTileDebugTextBuffer(N,S,f,E,z,D)}_globePoint(N,f,_,S,E,D,z){let H=mV(N,f,_);if(D){const Y=1<<_.z,te=Ln(S.center.lng),he=$n(S.center.lat),ge=(_.x+.5)/Y-te;let ve=0;ge>.5?ve=-1:ge<-.5&&(ve=1);let Te=(N/nr+_.x)/Y+ve,Ie=(f/nr+_.y)/Y;Te=(Te-te)*S._pixelsPerMercatorPixel+te,Ie=(Ie-he)*S._pixelsPerMercatorPixel+he;const Ve=[Te*S.worldSize,Ie*S.worldSize,0];Ge(Ve,Ve,D),H=FS(H,Ve,z)}return Ge(H,H,E)}_makeGlobeTileDebugBorderBuffer(N,f,_,S,E,D){const z=new Pi,H=new RS,Y=new Uo,te=(ge,ve,Te,Ie,Ve)=>{const et=(Te-ge)/(Ve-1),at=(Ie-ve)/(Ve-1),ft=z.length;for(let ut=0;utte*ge+ve;for(let ge=0;ge1)return!1;const _=f.getSource().maxzoom,S=1<<_,E=Math.floor(N.x),D=Math.floor((N.x-E)*S),z=Math.floor(N.y*S),H=this.findDEMTileFor(new Eg(_,E,_,D,z));return!(!H||!H.dem)}getAtPointOrZero(N,f=0){return this.getAtPoint(N,f)||0}getAtPoint(N,f,_=!0){if(this.isUsingMockSource())return null;f==null&&(f=null);const S=this._source();if(!S||N.y<0||N.y>1)return f;const E=S.getSource().maxzoom,D=1<{const H=this.getAtTileOffset(N,E,D,z),Y=S.upVector(N.canonical,E.x,E.y);return we(Y,Y,H*S.upVectorScale(N.canonical,f,_).metersToTile),Y}}getForTilePoints(N,f,_,S){if(this.isUsingMockSource())return!1;const E=gF.create(this,N,S);return!!E&&(f.forEach(D=>{D[2]=this.exaggeration()*E.getElevationAt(D[0],D[1],_)}),!0)}getMinMaxForTile(N){if(this.isUsingMockSource())return null;const f=this.findDEMTileFor(N);if(!f||!f.dem)return null;const _=f.dem.tree,S=f.tileID,E=1<0&&(S+=(N[E]-0)*(N[E]-0)),f[E]<0&&(S+=(0-f[E])*(0-f[E]));return S},o.cL=function(N){return N*N*N*N*N},o.cM=an,o.cN=45,o.cO=tF,o.cP=function(N,f,_){const S=Math.sqrt(N*N+f*f+_*_),E=S>0?Math.acos(_/S)*mr:0;let D=N!==0||f!==0?Math.atan2(-f,-N)*mr+90:0;return D<0&&(D+=360),[S,D,E]},o.cQ=ee,o.cR=Zn,o.cS=zn,o.cT=le,o.cU=al,o.cV=ue,o.cW=function(N){return[Math.pow(N[0],1/2.2),Math.pow(N[1],1/2.2),Math.pow(N[2],1/2.2)]},o.cX=UXe,o.cY=CEe,o.cZ=WXe,o.c_=a6e,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=nF,o.cl=Ny,o.cm=VXe,o.cn=K6,o.co=vZe,o.cp=function(N,f,_,S,E,D,z,H,Y){if(Y.name==="globe")return vZe(N,f,new K6(_,S,E),!1);const te=tM({z:_,x:S,y:E},Y);return new al([(D+te.x/te.scale)*f,f*(te.y/te.scale),z],[(D+te.x2/te.scale)*f,f*(te.y2/te.scale),H])},o.cq=function(N,f,_){return N[0]=Math.min(f[0],_[0]),N[1]=Math.min(f[1],_[1]),N[2]=Math.min(f[2],_[2]),N[3]=Math.min(f[3],_[3]),N},o.cr=function(N,f,_){return N[0]=Math.max(f[0],_[0]),N[1]=Math.max(f[1],_[1]),N[2]=Math.max(f[2],_[2]),N[3]=Math.max(f[3],_[3]),N},o.cs=function(N){const f=Math.round((N+45+360)%360/90)%4;return Jn[f]},o.ct=jn,o.cu=nt,o.cv=6,o.cw=function(N){const f=g(new Float64Array(16));v(f,N.pixelMatrix,N.globeMatrix);const _=[0,Jt,0],S=[0,ws,0];return Ge(_,_,f),Ge(S,S,f),[_[0]>0&&_[0]<=N.width&&_[1]>0&&_[1]<=N.height&&!KTe(N,new Cs(N.center.lat,90)),S[0]>0&&S[0]<=N.width&&S[1]>0&&S[1]<=N.height&&!KTe(N,new Cs(N.center.lat,-90))]},o.cx=function(N,f){const{scale:_}=N.tileTransform,S=_*nr/(N.tileSize*Math.pow(2,f.zoom-N.tileID.overscaledZ+N.tileID.canonical.z));return function(E,D,z){var H=D[1],Y=D[2],te=D[3],he=z[0],ge=z[1];return E[0]=D[0]*he,E[1]=H*he,E[2]=Y*ge,E[3]=te*ge,E}(new Float32Array(4),f.inverseAdjustmentMatrix,[S,S])},o.cy=ste,o.cz=q,o.d=function(N){return Gr.API_TILEJSON_REGEX.test(N)},o.d$=nVt,o.d0=Md,o.d1=class{static calculate(N,f,_){const S=new Set,E=new Map,D=new Set,z=new Set;for(const Y of Object.values(N))for(const[te,he]of Object.entries(Y.floors)){D.add(te),he.isDefault&&z.add(te),he.conflicts&&E.set(te,he.conflicts);const ge=te===f,ve=he.connections&&f&&he.connections.has(f);(ge||ve)&&S.add(te)}const H=Y=>{const te=E.get(Y)||new Set;for(const he of S)if((E.get(he)||new Set).has(Y)||te.has(he))return!0;return!1};if(_)for(const Y of _)D.has(Y)&&(H(Y)||S.add(Y));for(const Y of z)S.has(Y)||H(Y)||S.add(Y);return S}},o.d2=mte,o.d3=GEe,o.d4=ki,o.d5=function(){return{API_URL:Gr.API_URL,DRACO_URL:Gr.DRACO_URL,MESHOPT_URL:Gr.MESHOPT_URL,MESHOPT_SIMD_URL:Gr.MESHOPT_SIMD_URL,BUILDING_GEN_URL:Gr.BUILDING_GEN_URL}},o.d6=tk,o.d7=zb,o.d8=rd,o.d9=_r,o.dA=Iee,o.dB=Pi,o.dC=eu,o.dD=function(N,f){return[Math.pow(N[0],2.2)*f,Math.pow(N[1],2.2)*f,Math.pow(N[2],2.2)*f]},o.dE=h,o.dF=function(N,f){var _=Math.sin(f),S=Math.cos(f);return N[0]=S,N[1]=_,N[2]=0,N[3]=-_,N[4]=S,N[5]=0,N[6]=0,N[7]=0,N[8]=1,N},o.dG=_e,o.dH=_Ze,o.dI=Va,o.dJ=So,o.dK=n6e,o.dL=function(N,f){const _=[0,0,0];return Ge(_,_,pV(uk(f.canonical))),Ge(_,_,N),_},o.dM=N=>({u_matrix:new w(N),u_texsize:new F1(N),u_pixels_to_tile_units:new V(N),u_device_pixel_ratio:new Eh(N),u_width_scale:new Eh(N),u_floor_width_scale:new Eh(N),u_image:new G6(N),u_units_to_pixels:new F1(N),u_tile_units_to_pixels:new Eh(N),u_alpha_discard_threshold:new Eh(N),u_trim_offset:new F1(N),u_trim_fade_range:new F1(N),u_trim_gradient_mix_range:new F1(N),u_trim_color:new tF(N),u_zbias_factor:new Eh(N),u_tile_to_meter:new Eh(N),u_ground_shadow_factor:new W6(N),u_pattern_transition:new Eh(N)}),o.dN=N=>({u_matrix:new w(N),u_pixels_to_tile_units:new V(N),u_device_pixel_ratio:new Eh(N),u_width_scale:new Eh(N),u_floor_width_scale:new Eh(N),u_units_to_pixels:new F1(N),u_dash_image:new G6(N),u_gradient_image:new G6(N),u_image_height:new Eh(N),u_texsize:new F1(N),u_tile_units_to_pixels:new Eh(N),u_alpha_discard_threshold:new Eh(N),u_trim_offset:new F1(N),u_trim_fade_range:new F1(N),u_trim_gradient_mix_range:new F1(N),u_trim_color:new tF(N),u_zbias_factor:new Eh(N),u_tile_to_meter:new Eh(N),u_ground_shadow_factor:new W6(N)}),o.dO=N=>({u_camera_to_center_distance:new Eh(N),u_extrude_scale:new V(N),u_device_pixel_ratio:new Eh(N),u_matrix:new w(N),u_inv_rot_matrix:new w(N),u_merc_center:new F1(N),u_tile_id:new W6(N),u_zoom_transition:new Eh(N),u_up_dir:new W6(N),u_emissive_strength:new Eh(N)}),o.dP=tV,o.dQ=sGt,o.dR=class{constructor(N,f,_,S){this.context=N,this.format=S,this.size=_,this.texture=N.gl.createTexture();const[E,D,z]=this.size,{gl:H}=N;H.bindTexture(H.TEXTURE_3D,this.texture),N.pixelStoreUnpackFlipY.set(!1),N.pixelStoreUnpack.set(1),N.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in f&&f.data&&H.texImage3D(H.TEXTURE_3D,0,this.format,E,D,z,0,bEe(this.format),_Ee(this.format),f.data)}bind(N,f){const{context:_}=this,{gl:S}=_;S.bindTexture(S.TEXTURE_3D,this.texture),N!==this.minFilter&&(S.texParameteri(S.TEXTURE_3D,S.TEXTURE_MAG_FILTER,N),S.texParameteri(S.TEXTURE_3D,S.TEXTURE_MIN_FILTER,N),this.minFilter=N),f!==this.wrapS&&(S.texParameteri(S.TEXTURE_3D,S.TEXTURE_WRAP_S,f),S.texParameteri(S.TEXTURE_3D,S.TEXTURE_WRAP_T,f),this.wrapS=f)}destroy(){const{gl:N}=this.context;N.deleteTexture(this.texture),this.texture=null}},o.dS=kZe,o.dT=(N,f,_,S,E,D)=>{const z=N.transform,H=z.projection.name==="globe";let Y;if(D.paint.get("circle-pitch-alignment")==="map")if(H){const he=_Ze(z.zoom,f.canonical)*z._pixelsPerMercatorPixel;Y=Float32Array.from([he,0,0,he])}else Y=z.calculatePixelsToTileUnitsMatrix(_);else Y=new Float32Array([z.pixelsToGLUnits[0],0,0,z.pixelsToGLUnits[1]]);const te={u_camera_to_center_distance:N.transform.getCameraToCenterDistance(z.projection),u_matrix:N.translatePosMatrix(f.projMatrix,_,D.paint.get("circle-translate"),D.paint.get("circle-translate-anchor")),u_device_pixel_ratio:Wc.devicePixelRatio,u_extrude_scale:Y,u_inv_rot_matrix:cVt,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:D.paint.get("circle-emissive-strength")};if(H){te.u_inv_rot_matrix=S,te.u_merc_center=E,te.u_tile_id=[f.canonical.x,f.canonical.y,1<{const he=N.transform,ge=he.pitch<15?iQe(.07,.7,it((14-he.zoom)/5,0,1)):.07,ve=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:lQe(N,f,_,S),u_texsize:f.imageAtlasTexture?f.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:he.calculatePixelsToTileUnitsMatrix(f),u_device_pixel_ratio:E,u_width_scale:D,u_floor_width_scale:z,u_image:0,u_tile_units_to_pixels:oQe(f,he),u_units_to_pixels:[1/he.pixelsToGLUnits[0],1/he.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:H,u_trim_fade_range:_.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:_.paint.get("line-trim-color").toPremultipliedRenderColor(ve?null:_.lut).toArray01(),u_zbias_factor:ge,u_tile_to_meter:zn(f.tileID.canonical,0),u_ground_shadow_factor:Y,u_pattern_transition:te}},o.dX=(N,f,_,S,E,D,z,H,Y,te)=>{const he=N.transform,ge=he.calculatePixelsToTileUnitsMatrix(f),ve=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Te=he.pitch<15?iQe(.07,.7,it((14-he.zoom)/5,0,1)):.07;return{u_matrix:lQe(N,f,_,S),u_pixels_to_tile_units:ge,u_device_pixel_ratio:D,u_width_scale:z,u_floor_width_scale:H,u_units_to_pixels:[1/he.pixelsToGLUnits[0],1/he.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:E,u_texsize:dQe(_)&&f.lineAtlasTexture?f.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:oQe(f,N.transform),u_alpha_discard_threshold:0,u_trim_offset:Y,u_trim_fade_range:_.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:_.paint.get("line-trim-color").toPremultipliedRenderColor(ve?null:_.lut).toArray01(),u_zbias_factor:Te,u_tile_to_meter:zn(f.tileID.canonical,0),u_ground_shadow_factor:te}},o.dY=js,o.dZ=fV,o.d_=fn,o.da=function(N){const f=N.indexOf(lt);return f>=0?N.slice(0,f):N},o.db=function(N){return N.indexOf(lt)>=0},o.dc=function(N){const f=N.lastIndexOf(lt);return f>=0?N.slice(f+1):""},o.dd=function(N){const f=[],_=N.id;return _===void 0&&f.push({message:`layers.${_}: missing required property "id"`}),N.render===void 0&&f.push({message:`layers.${_}: missing required method "render"`}),N.renderingMode&&N.renderingMode!=="2d"&&N.renderingMode!=="3d"&&f.push({message:`layers.${_}: property "renderingMode" must be either "2d" or "3d"`}),f},o.de=function(N,f,_,S){return N.type==="custom"?new YGt(N,f):new eWt[N.type](N,f,_,S)},o.df=vn,o.dg=uC,o.dh=Ps,o.di=class extends nM{constructor(N,f){super(N._vectorTileFeature,N._z,N._x,N._y,N.id),N.state&&(this.state=Object.assign({},N.state)),this.target=f.target,this.namespace=f.namespace,f.properties&&(this.properties=f.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=N.source,this.sourceLayer=N.sourceLayer,this.layer=N.layer)}toJSON(){const N=super.toJSON();return N.target=this.target,N.namespace=this.namespace,N}},o.dj=sk,o.dk=function(N){return N({pluginStatus:Ed,pluginURL:tf}),sk.on("pluginStateChange",N),N},o.dl=qTe,o.dm=class extends O1{constructor(N){super(N),this.current=A}set(N,f,_){if(this.fetchUniformLocation(N,f)){for(let S=0;S<9;S++)if(_[S]!==this.current[S]){this.current=_,this.gl.uniformMatrix3fv(this.location,!1,_);break}}}},o.dn=ea,o.dp=function(N,f,_){const S=zS(_.zoom),E=N.style.map._antialias,D=N.terrain&&N.terrain.exaggeration()>0;return S===0&&!E&&!D},o.dq=function(N){const f=N.pixelsPerMeter,_=f/Ys(1,N.center.lat),S=g(new Float64Array(16));return k(S,S,[N.point.x,N.point.y,0]),C(S,S,[_,_,f]),Float32Array.from(S)},o.dr=Ree,o.ds=function(N){const f=80.051129;N=it(N,-80.051129,f)/f*90;const _=Math.pow(Math.abs(Math.sin(pr(N))),3);return Math.round(_*(ks.length-1))},o.dt=function(N,f,_,S){const E=f.getNorth(),D=f.getSouth(),z=f.getWest(),H=f.getEast(),Y=1<0){const Ie=180/S;p(Te,Te,[Ie/te+1,0,0,0,Ie/he+1,0,-.5*Ie/ge,.5*Ie/ve,1])}return Te[2]=Y,Te[5]=N.x,Te[8]=N.y,Te},o.du=pV,o.dv=uk,o.dw=function(N,f,_){const S=g(new Float64Array(16)),E=(f/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(N,f=!1){const _=aXe(new Xs(0,0),new Xs(nr,nr),N),S=[];if(f&&!cEe(_,this._globalClipBounds))return S;for(const E of this._activeRegions){if(E.hiddenByOverlap||!cEe(_,E))continue;const D=HVt(E.min,E.max,N);S.push({min:D.min,max:D.max,sourceId:this._sourceIds[E.priority],footprint:E.footprint,footprintTileId:E.tileId,order:E.order,clipMask:E.clipMask,clipScope:E.clipScope})}return S}setSources(N){this._setSources(N.map(f=>({getSourceId:()=>f.cache.id,getFootprints:()=>{const _=[];for(const S of f.cache.getVisibleCoordinates()){const E=f.cache.getTile(S).buckets[f.layer];E&&E.updateFootprints(S.toUnwrapped(),_)}return _},getOrder:()=>f.order,getClipMask:()=>f.clipMask,getClipScope:()=>f.clipScope})))}_addSource(N){const f=N.getFootprints();if(f.length===0)return;const _=N.getOrder(),S=N.getClipMask(),E=N.getClipScope();for(const D of f){if(!D.footprint)continue;const z=aXe(D.footprint.min,D.footprint.max,D.id);this._activeRegions.push({min:z.min,max:z.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:D.id,footprint:D.footprint,order:_,clipMask:S,clipScope:E})}this._sourceIds.push(N.getSourceId())}_computeReplacement(){this._activeRegions.sort((f,_)=>f.priority-_.priority||Hee(f.min,_.min)||Hee(f.max,_.max)||f.order-_.order||f.clipMask-_.clipMask||function(S,E){const D=(z,H)=>z+H;return S.length-E.length||S.reduce(D,"").localeCompare(E.reduce(D,""))}(f.clipScope,_.clipScope));let N=this._activeRegions.length!==this._prevRegions.length;if(!N){let f=0;for(;!N&&f!==this._activeRegions.length;){const _=this._activeRegions[f],S=this._prevRegions[f];N=_.priority!==S.priority||!rXe(_,S)||_.order!==S.order||_.clipMask!==S.clipMask||!Ba(_.clipScope,S.clipScope),this._activeRegions[f].hiddenByOverlap=S.hiddenByOverlap,++f}}if(N){++this._updateTime;for(const _ of this._activeRegions)_.order!==jV&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,_.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,_.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,_.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,_.max.y));const f=_=>{const S=this._activeRegions;if(_>=S.length)return _;const E=S[_].priority;for(;_1){let _=0,S=f(_);for(;_!==S;){let E=_;const D=_;for(;E!==S;){const z=this._activeRegions[E];z.hiddenByOverlap=!1;for(let H=0;H=0;f--)this._addSource(N[f]);this._computeReplacement()}},o.eH=Xi,o.eI=Nte,o.eJ=RS,o.eK=jV,o.eL=class{constructor(N){this._createGrid(N),this._createPoles(N)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const N of this._poleSegments)N.destroy();for(const N of this._gridSegments)N.withSkirts.destroy(),N.withoutSkirts.destroy()}_fillGridMeshWithLods(N,f){const _=new Pi,S=new eu,E=[],D=N+1+2,z=f[0]+1,H=f[0]+1+(1+f.length),Y=(te,he,ge)=>{let ve=te===D-1?te-2:te===0?te:te-1;return ve+=ge?24575:0,[ve,he]};for(let te=0;te>>=0,N=Math.imul(2747636419^N,2654435769)>>>0,N=Math.imul(N^N>>>16,2654435769)>>>0,(N=Math.imul(N^N>>>16,2654435769)>>>0)/4294967296},o.ec=gZe,o.ed=GTe,o.ee=R1,o.ef=M,o.eg=function(N,f){return N[0]=f[0],N[1]=f[1],N[2]=f[2],N[3]=f[4],N[4]=f[5],N[5]=f[6],N[6]=f[8],N[7]=f[9],N[8]=f[10],N},o.eh=PS,o.ei=$6,o.ej=function(N,f,_,S,E){return it((N-f)/(_-f)*(E-S)+S,S,E)},o.ek=Gt,o.el=function(N,f){var _=f[0],S=f[1],E=f[2],D=f[3],z=f[4],H=f[5],Y=f[6],te=f[7],he=f[8],ge=he*z-H*te,ve=-he*D+H*Y,Te=te*D-z*Y,Ie=_*ge+S*ve+E*Te;return Ie?(N[0]=ge*(Ie=1/Ie),N[1]=(-he*S+E*te)*Ie,N[2]=(H*S-E*z)*Ie,N[3]=ve*Ie,N[4]=(he*_-E*Y)*Ie,N[5]=(-H*_+E*D)*Ie,N[6]=Te*Ie,N[7]=(-te*_+S*Y)*Ie,N[8]=(z*_-S*D)*Ie,N):null},o.em=ca,o.en=2,o.eo=Ee,o.ep=Dt,o.eq=O,o.er=function(N,f){var _=new d(3);O(_,f);var S=1/_[0],E=1/_[1],D=1/_[2],z=f[0]*S,H=f[1]*E,Y=f[2]*D,te=f[4]*S,he=f[5]*E,ge=f[6]*D,ve=f[8]*S,Te=f[9]*E,Ie=f[10]*D,Ve=z+he+Ie,et=0;return Ve>0?(et=2*Math.sqrt(Ve+1),N[3]=.25*et,N[0]=(ge-Te)/et,N[1]=(ve-Y)/et,N[2]=(H-te)/et):z>he&&z>Ie?(et=2*Math.sqrt(1+z-he-Ie),N[3]=(ge-Te)/et,N[0]=.25*et,N[1]=(H+te)/et,N[2]=(ve+Y)/et):he>Ie?(et=2*Math.sqrt(1+he-z-Ie),N[3]=(ve-Y)/et,N[0]=(H+te)/et,N[1]=.25*et,N[2]=(ge+Te)/et):(et=2*Math.sqrt(1+Ie-z-he),N[3]=(H-te)/et,N[0]=(ve+Y)/et,N[1]=(ge+Te)/et,N[2]=.25*et),N},o.es=function(N,f){var _=2*Math.acos(f[3]),S=Math.sin(_/2);return S>c?(N[0]=f[0]/S,N[1]=f[1]/S,N[2]=f[2]/S):(N[0]=1,N[1]=0,N[2]=0),_},o.et=l6e,o.eu=ate,o.ev=rte,o.ew=[1,1,1],o.ex=gF,o.ey=function(N,f,_,S){var E=f[0],D=f[1],z=f[2],H=f[3];return N[0]=E+S*(_[0]-E),N[1]=D+S*(_[1]-D),N[2]=z+S*(_[2]-z),N[3]=H+S*(_[3]-H),N},o.ez=cF,o.f=Wo,o.f0=jZe,o.f1=function(N){const f=[0,0,0],_=g(new Float64Array(16));return v(_,N.pixelMatrix,N.globeMatrix),Ge(f,f,_),new Xs(f[0],f[1])},o.f2=T0,o.f3=function(N,f,_=!1){if(Ed===Ru.deferred||Ed===Ru.loading||Ed===Ru.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");tf=Wc.resolveURL(N),Ed=Ru.deferred,tm=f,l2(),_||nk()},o.f4=xo,o.f5=qa,o.f6=Qn,o.f7=function(N){const f=Px();if(!f)return;const _=f.delete(Jm);N&&_.then(()=>N()).catch(N)},o.f8=gr,o.f9=yC,o.fA=ri,o.fB=function(N){let f=0;if(new Uint32Array(N,0,1)[0]!==OXe){const _=new Uint32Array(N,0,7),[,,S,E,D,z]=_;f=_.byteLength+E+D+z+D,(S!==N.byteLength||f>=N.byteLength)&&Mr("Invalid b3dm header information.")}return $Xe(N,f)},o.fC=function(N,f){const _=CEe(N);for(const S of _){for(const E of S.meshes)wHt(E);S.lights&&(S.lightMeshIndex=S.meshes.length,S.meshes.push(jHt(S.lights,f)))}return _},o.fD=Ate,o.fE=aa,o.fF=$x,o.fG=Ru,o.fH=function(N){Do(),pu!=null&&pu.then(f=>{f.keys().then(_=>{for(let S=0;S<_.length-N;S++)f.delete(_[S]).catch(E=>Mr(E.message))}).catch(_=>Mr(_.message))}).catch(f=>Mr(f.message))},o.fa=2,o.fb=kg,o.fc=tM,o.fd=oV,o.fe=CJe,o.ff=AJe,o.fg=sQe,o.fh=Ai,o.fi="hd_road_elevation",o.fj=tc,o.fk=Tn,o.fl=qee,o.fm=BS,o.fn=VEe,o.fo=1,o.fp=f2,o.fq=function(N,f,_,S,E,D,z,H=1,Y,te,he,ge){N.createArrays(),N.tilePixelRatio=nr/(512*N.overscaling),N.compareText={},N.iconsNeedLinear=!1;const ve=N.layers[0].layout,Te=N.layers[0]._unevaluatedLayout._values,Ie={};Ie.scaleFactor=H,Ie.textSizeScaleRange=ve.get("text-size-scale-range"),Ie.iconSizeScaleRange=ve.get("icon-size-scale-range");const[Ve,et]=Ie.textSizeScaleRange,[at,ft]=Ie.iconSizeScaleRange;Ie.textScaleFactor=it(Ie.scaleFactor,Ve,et),Ie.iconScaleFactor=it(Ie.scaleFactor,at,ft);const ut=Te["text-size"],Nt=Te["icon-size"];if(N.textSizeData.kind==="composite"){const{minZoom:cs,maxZoom:ds}=N.textSizeData;Ie.compositeTextSizes=[ut.possiblyEvaluate(new bi(cs,{worldview:he}),D),ut.possiblyEvaluate(new bi(ds,{worldview:he}),D)]}if(N.iconSizeData.kind==="composite"){const{minZoom:cs,maxZoom:ds}=N.iconSizeData;Ie.compositeIconSizes=[Nt.possiblyEvaluate(new bi(cs,{worldview:he}),D,ge),Nt.possiblyEvaluate(new bi(ds,{worldview:he}),D,ge)]}Ie.layoutTextSize=ut.possiblyEvaluate(new bi(z+1,{worldview:he}),D),Ie.layoutIconSize=Nt.possiblyEvaluate(new bi(z+1,{worldview:he}),D,ge),Ie.textMaxSize=ut.possiblyEvaluate(new bi(18,{worldview:he}),D);const Mt=ve.get("symbol-placement"),It=ve.get("text-rotation-alignment")==="map"&&Mt!=="point",xs=ve.get("text-size");let es=!1;const ps=[];for(const cs of N.features){const ds=ve.get("text-font").evaluate(cs,{},D).join(","),mn=xs.evaluate(cs,{},D)*Ie.textScaleFactor,xn=Ie.layoutTextSize.evaluate(cs,{},D)*Ie.textScaleFactor,kn=Ie.layoutIconSize.evaluate(cs,{},D,ge)*Ie.iconScaleFactor,En={horizontal:{},vertical:void 0},Sn=cs.text;let Gn,dn=[0,0];if(Sn){const Di=Sn.toString(),Ld=ve.get("text-letter-spacing").evaluate(cs,{},D)*Mm,tl=ve.get("text-line-height").evaluate(cs,{},D)*Mm,Oo=CS(Di)?Ld:0,Yl=ve.get("text-anchor").evaluate(cs,{},D),bd=ve.get("text-variable-anchor");if(!bd){const su=ve.get("text-radial-offset").evaluate(cs,{},D);if(su)dn=$Qe(Yl,[su*Mm,KEe]);else{const zf=ve.get("text-offset").evaluate(cs,{},D);dn=[zf[0]*Mm,zf[1]*Mm]}}let Lm=It?"center":ve.get("text-justify").evaluate(cs,{},D);const _d=Mt==="point",tu=_d?ve.get("text-max-width").evaluate(cs,{},D)*Mm:1/0,Qu=su=>{N.allowVerticalPlacement&&ef(Di)&&(En.vertical=OEe(Sn,f,_,E,ds,tu,tl,Yl,su,Oo,dn,Sv.vertical,!0,xn,mn,Y,Ie.textScaleFactor))};if(!It&&bd){const su=Lm==="auto"?bd.map(Pm=>YEe(Pm)):[Lm];let zf=!1;for(let Pm=0;Pm=0||!ef(Di)){const su=OEe(Sn,f,_,E,ds,tu,tl,Yl,Lm,Oo,dn,Sv.horizontal,!1,xn,mn,Y,Ie.textScaleFactor);su&&(En.horizontal[Lm]=su)}Qu(_d?"left":Lm)}}let An,Pn,Wn,ir,Ur,wr,vr=!1;const or=ve.get("icon-text-fit").evaluate(cs,{},D);if(cs.icon&&cs.icon.hasPrimary()){const Di=FV(cs.icon,N.iconSizeData,Te["icon-size"],D,N.zoom,cs,Y,Ie.iconScaleFactor,he,ge);An=Di.iconPrimary,Wn=Di.iconSecondary;const Ld=An.toString();if(Pn=S.get(Ld),Pn&&(Ur=ve.get("icon-offset").evaluate(cs,{},D),wr=ve.get("icon-anchor").evaluate(cs,{},D),Gn=ute(E.get(Ld),Wn?E.get(Wn.toString()):void 0,Ur,wr),vr=Pn.sdf,N.sdfIcons===void 0?N.sdfIcons=Pn.sdf:N.sdfIcons!==Pn.sdf&&Mr("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(Pn.pixelRatio!==N.pixelRatio||ve.get("icon-rotate").constantOr(1)!==0)&&(N.iconsNeedLinear=!0)),Wn){const tl=Wn.toString();ir=S.get(tl)}}es=es||!(!cs.icon||!cs.icon.hasSecondary());const Or=yte(En.horizontal)||En.vertical;N.iconsInText||(N.iconsInText=!!Or&&Or.iconsInText);const sa=xn*Ie.textScaleFactor/Mm,{defaultShapedIcon:Ta,verticallyShapedIcon:ya}=PGt(N,Gn,ve,cs,D,En,sa,Ur,or);or!=="none"&&Gn&&(jQe(Gn)||NQe(Gn))&&(gte(0,Pn,An,Gn,Ta,or,te,S,E),gte(0,ir,Wn,Gn,Ta,or,te,S,E),ya&&(gte(0,Pn,An,Gn,ya,or,te,S,E),gte(0,ir,Wn,Gn,ya,or,te,S,E))),Gn=Ta;const{iconBBox:xi,iconVerticalBBox:jo,textBBox:gi,textVerticalBBox:Ao}=AGt(N,Gn,ya,ve,cs,D,kn,Ur,Ie,E,wr,En,xn,dn,ge);ps.push({feature:cs,shapedTextOrientations:En,shapedText:Or,shapedIcon:Gn,iconPrimary:An,iconSecondary:Wn,iconOffset:Ur,iconAnchor:wr,verticallyShapedIcon:ya,layoutTextSize:xn,layoutIconSize:kn,textOffset:dn,isSDFIcon:vr,iconTextFit:or,iconCollisionBounds:xi,iconVerticalCollisionBounds:jo,textCollisionBounds:gi,textVerticalCollisionBounds:Ao})}return{featureData:ps,sizes:Ie,hasAnySecondaryIcon:es,textAlongLine:It,symbolPlacement:Mt}},o.fr=HEe,o.fs=qEe,o.ft=PQe,o.fu=IQe,o.fv=function(N,f,_,S,E,D,z,H,Y,te){N.iconAtlasPositions=te.iconPositions;const{featureData:he,hasAnySecondaryIcon:ge,sizes:ve,textAlongLine:Te,symbolPlacement:Ie}=f;for(const Ve of he){const{shapedIcon:et,verticallyShapedIcon:at,feature:ft,shapedTextOrientations:ut,shapedText:Nt,layoutTextSize:Mt,textOffset:It,isSDFIcon:xs,iconPrimary:es,iconSecondary:ps,iconTextFit:cs,iconOffset:ds,iconCollisionBounds:mn,iconVerticalCollisionBounds:xn,textCollisionBounds:kn}=Ve;HQe(et,te.iconPositions,es,ps),HQe(at,te.iconPositions,es,ps),LGt(ut,te.iconPositions),MGt(es,ps,te.iconPositions),(Nt||et)&&IGt(N,ft,ut,et,at,Y,ve,Mt,0,It,xs,S,E,z,H,ge,cs,ds,Te,Ie,mn,xn,kn)}_&&N.generateCollisionDebugBuffers(D,N.collisionBoxArray,ve.textScaleFactor)},o.fw=lte,o.fx=Vo,o.fy=function(N){return N<=1?1:Math.pow(2,Math.floor(Math.log2(N)))},o.fz=Ite,o.g=Gr,o.h=function(N,f){return np(Object.assign(N,{method:"GET"}),f)},o.i=function(N){return Gr.API_STYLE_REGEX.test(N)&&!Co(N)},o.j=function(N){return btoa(encodeURIComponent(N).replace(/%([0-9A-F]{2})/g,(f,_)=>String.fromCharCode(+("0x"+_))))},o.k=ep,o.l=function(N){return decodeURIComponent(atob(N).split("").map(f=>"%"+("00"+f.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(N,f){return np(Object.assign(N,{type:"json"}),f)},o.n=wm,o.o=Wc,o.p=function(N,f){return np(Object.assign(N,{method:"POST"}),f)},o.q=hx,o.r=Ms,o.s=function(N){try{const f=self[N];return f.setItem("_mapbox_test_",1),f.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=Ht,o.u=function(){return function N(f){return f?(f^Math.random()*(16>>f/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,N)}()},o.v=function(N){return!!N&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(N)},o.w=Mr,o.x=class{constructor(N){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(N&&N.maxTextureMemoryMB?N.maxTextureMemoryMB:256)*1024,this.finalizationRegistry=new FinalizationRegistry(f=>{this.cache.delete(f),this.clearExpiredTextures()})}calculateTextureMemory(N){return N.image?Math.ceil(N.image.width*N.image.height*4*(N.patternPositions.size>0?1.33:1)):0}evictTexture(N){const f=this.textures.get(N);if(f){const _=this.calculateTextureMemory(N);f.destroy(),this.textures.delete(N),this.textureAccessTimes.delete(N),this.textureMemoryUsed-=_}}evictTexturesIfNeeded(N){for(;this.textureMemoryUsed+N>this.maxTextureMemory&&this.textures.size>0;){let f=null,_=1/0;for(const[S]of this.textures.entries()){const E=this.textureAccessTimes.get(S)||0;E<_&&(_=E,f=S)}if(!f)break;this.evictTexture(f)}}findCachedAtlas(N){const f=this.cache.get(N.hash);if(f){const _=f.deref();if(_&&_.contentDescriptor&&this.isMipmapCompatible(N,_.contentDescriptor))return _}for(const[,_]of this.cache.entries()){const S=_.deref();if(S&&S.contentDescriptor){const E=N.subsetOf(S.contentDescriptor),D=this.isMipmapCompatible(N,S.contentDescriptor);if(E&&D)return S}}}getTextureForAtlas(N,f,_){this.textureAccessTimes.set(N,performance.now());let S=this.textures.get(N);if(S)return S;if(N.image){const E=this.calculateTextureMemory(N);return this.evictTexturesIfNeeded(E),S=new pk(f,N.image,_,{useMipmap:!!N.patternPositions.size}),this.textures.set(N,S),this.textureMemoryUsed+=E,S}return null}clearExpiredTextures(){for(const[N]of this.textures.entries())if(!this.isAtlasCached(N)){const f=this.textures.get(N);if(f){const _=this.calculateTextureMemory(N);f.destroy(),this.textureMemoryUsed-=_}this.textures.delete(N),this.textureAccessTimes.delete(N)}}isAtlasCached(N){if(!N.contentDescriptor)return!1;const f=this.cache.get(N.contentDescriptor.hash);return!!f&&f.deref()===N}getOrCache(N){if(!("image"in N)){const E=this.cache.get(N.sourceAtlasHash);if(E){const D=E.deref();if(D)return D}return Mr("ImageAtlasReference points to GC'd atlas - atlas may have been evicted"),null}if(!N.contentDescriptor)return N;const f=N.contentDescriptor,_=f.hash,S=this.cache.get(_);if(S){const E=S.deref();if(E&&E.contentDescriptor&&this.isMipmapCompatible(f,E.contentDescriptor))return E}return this.cache.set(_,new WeakRef(N)),this.finalizationRegistry.register(N,_,N),N}isMipmapCompatible(N,f){return!N.requiresMipMaps||f.requiresMipMaps}destroyTextures(){for(const N of this.textures.values())N&&N.destroy();this.textures.clear(),this.textureAccessTimes.clear(),this.textureMemoryUsed=0}clear(){for(const N of this.textures.values())N&&N.destroy();this.cache.clear(),this.textures.clear(),this.textureAccessTimes.clear(),this.textureMemoryUsed=0}},o.y=qd,o.z=h6e}),i(["require","./shared"],function(o,c){function d(_s){const We=_s?_s.url.toString():void 0;return We?performance.getEntriesByName(We):[]}function u(_s){if(typeof _s=="number"||typeof _s=="boolean"||typeof _s=="string"||_s==null)return JSON.stringify(_s);if(Array.isArray(_s)){let it="[";for(const gt of _s)it+=`${u(gt)},`;return`${it}]`}let We="{";for(const it of Object.keys(_s).sort())We+=`${it}:${u(_s[it])},`;return`${We}}`}function h(_s){let We="";for(const it of c.b5)We+=`/${u(_s[it])}`;return We}function m(_s,We){return function it(gt){return typeof gt=="string"&>===We||(Array.isArray(gt)?gt.some(it):!(!gt||typeof gt!="object")&&Object.values(gt).some(it))}(_s)}class p{constructor(We){this.keyCache=Object.create(null),this._layers=Object.create(null),this._layerConfigs=Object.create(null),We&&this.replace(We)}replace(We,it){this._layerConfigs=Object.create(null),this._layers=Object.create(null),this.update(We,[],it)}update(We,it,gt){this._options=gt;for(const Ht of We)this._layerConfigs[Ht.id]=Ht,(this._layers[Ht.id]=c.de(Ht,this.scope,null,this._options)).compileFilter(gt),this.keyCache[Ht.id]&&delete this.keyCache[Ht.id];for(const Ht of it)delete this.keyCache[Ht],delete this._layerConfigs[Ht],delete this._layers[Ht];this.familiesBySource=Object.create(null);const St=function(Ht,ts){const Ms=Object.create(null);for(let Zs=0;Zsthis._layers[_r.id]),Ms=ts[0];if(Ms.visibility==="none")continue;const js=Ms.source||"";let Zs=this.familiesBySource[js];Zs||(Zs=this.familiesBySource[js]=Object.create(null));const Tn=Ms.sourceLayer||"_geojsonTileLayer";let vn=Zs[Tn];vn||(vn=Zs[Tn]=[]),vn.push(ts)}}}const x=1*c.fa;class y{constructor(We){const it={},gt=[];for(const Ms in We){const js=We[Ms],Zs=it[Ms]={};for(const Tn in js.glyphs){const vn=js.glyphs[+Tn];if(!vn||vn.bitmap.width===0||vn.bitmap.height===0)continue;const _r=vn.metrics.localGlyph?x:1,Jr={x:0,y:0,w:vn.bitmap.width+2*_r,h:vn.bitmap.height+2*_r};gt.push(Jr),Zs[Tn]=Jr}}const{w:St,h:Ht}=c.J(gt),ts=new c.f9({width:St||1,height:Ht||1});for(const Ms in We){const js=We[Ms];for(const Zs in js.glyphs){const Tn=js.glyphs[+Zs];if(!Tn||Tn.bitmap.width===0||Tn.bitmap.height===0)continue;const vn=it[Ms][Zs],_r=Tn.metrics.localGlyph?x:1;c.f9.copy(Tn.bitmap,ts,{x:0,y:0},{x:vn.x+_r,y:vn.y+_r},Tn.bitmap)}}this.image=ts,this.positions=it}}function g(_s,We,it){_s[We]?it&&(_s[We].center=it):_s[We]={floorIds:new Set,center:it||[0,0],floors:{}}}function b(_s,We,it,gt){for(const St of We)g(_s,St),_s[St].floors[it]=gt,_s[St].floorIds.add(it)}function v(_s){return{id:_s.properties.id.toString(),center:[_s.properties.center_lon||0,_s.properties.center_lat||0]}}function k(_s,We){const it=_s.properties.id.toString(),gt=!!_s.properties.is_default&&_s.properties.is_default,St=_s.properties.connected_floor_ids?new Set(_s.properties.connected_floor_ids.toString().split(";")):new Set,Ht=_s.properties.conflicted_floor_ids?new Set(_s.properties.conflicted_floor_ids.toString().split(";")):new Set,ts=_s.properties.structure_ids?new Set(_s.properties.structure_ids.toString().split(";")):new Set,Ms=_s.properties.name.toString(),js=_s.properties.z_index,Zs=function(Tn,vn){const _r=Tn.loadGeometry();if(!_r||_r.length===0)return;const Jr=_r.map(ha=>ha.map(Mr=>c.fb(Mr,vn,Tn.extent)));return Jr.length===0?void 0:{type:"Polygon",coordinates:[Jr[0]]}}(_s,We);return{id:it,isDefault:gt,connections:St,conflicts:Ht,buildings:ts,name:Ms,zIndex:js,geometry:Zs}}function C(_s,We){return We.every(it=>_s.properties&&_s.properties[it]!=null)}function T(_s){return C(_s,["type","id","name"])&&_s.properties.type==="structure"}function M(_s){return C(_s,["type","id","name","z_index"])&&_s.properties.type==="floor"}c.f8(y,"GlyphAtlas");class P{constructor(We){this.tileID=new c.aR(We.tileID.overscaledZ,We.tileID.wrap,We.tileID.canonical.z,We.tileID.canonical.x,We.tileID.canonical.y),this.tileZoom=We.tileZoom,this.uid=We.uid,this.zoom=We.zoom,this.lut=We.lut,this.canonical=We.tileID.canonical,this.pixelRatio=We.pixelRatio,this.tileSize=We.tileSize,this.source=We.source,this.scope=We.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=We.showCollisionBoxes,this.collectResourceTiming=!!We.request&&We.request.collectResourceTiming,this.promoteId=We.promoteId,this.renderSourceType=We.renderSourceType,this.tileTransform=c.fc(We.tileID.canonical,We.projection),this.projection=We.projection,this.worldview=We.worldview,this.localizableLayerIds=We.localizableLayerIds,this.brightness=We.brightness,this.extraShadowCaster=!!We.extraShadowCaster,this.tessellationStep=We.tessellationStep,this.scaleFactor=We.scaleFactor,this.worldview=We.worldview,this.indoor=We.indoor}parse(We,it,gt,St,Ht,ts){this.status="parsing",this.data=We,this.collisionBoxArray=new c.fd;const Ms=new c.fe(Object.keys(We.layers).sort()),js=new c.ff(this.tileID,this.promoteId);js.bucketLayerIDs=[];const Zs={},Tn=new c.fg(256,256),vn={featureIndex:js,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:Tn,availableImages:gt,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(vn.activeFloors=function(Mr,Xr,Qt,Zn){const aa=Xr.indoorState.activeFloorsVisible;if(!Xr.sourceLayers)return aa?Xr.indoorState.activeFloors:void 0;const zr=function(ur,ao){if(!ur)return c.w("No source layers defined in indoor specification"),ao;if(ur.size===0)return ao;const fo=ur.difference(ao);for(const Va of fo)c.w(`Missing source layer required in indoor specification: ${Va}`);return ao.intersection(ao)}(Xr.sourceLayers,new Set(Object.keys(Mr.layers))),Na=Xr.indoorState,oa=function(ur,ao,fo,Va,So){const $a={};for(const Gr of ao){const Qn=ur.layers[Gr];if(Qn)for(let qa=0;qa=Va.maxzoom||Va.visibility==="none")continue;L(fo,this.zoom,vn.brightness,gt,this.worldview,vn.activeFloors);const So=Zs[Va.id]=Va.createBucket({index:js.bucketLayerIDs.length,layers:fo,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Na,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:St,worldview:this.worldview,localizable:ur,availableImages:gt,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});js.bucketLayerIDs.push(fo.map(Gr=>c.F(Gr.id,Gr.scope)));let $a=So.prepare?So.prepare():null;$a!=null?($a=$a.then(()=>So.populate(oa,vn,this.tileID.canonical,this.tileTransform)),_r.push($a)):So.populate(oa,vn,this.tileID.canonical,this.tileTransform)}}const ha=()=>{Tn.trim();const Mr=!(!vn.elevationFeatures||!vn.elevationFeatures.some(Va=>Va.heightRange.min<0));let Xr,Qt,Zn,aa,zr,Na,oa;const ur={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},ao=()=>{if(Xr)return this.status="done",ts(Xr);if(this.extraShadowCaster)this.status="done",ts(null,{buckets:Object.values(Zs).filter(Va=>!Va.isEmpty()),featureIndex:js,collisionBoxArray:null,hasTunnelGeometry:Mr,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:vn.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(Qt&&Zn&&aa&&oa){const So=new y(Qt),$a=new Map;for(const[qa,xo]of Zn.entries()){const{imagePosition:Wo}=c.fn(qa,xo,c.fo);$a.set(qa,Wo)}const Gr={};for(const qa in Zs){const xo=Zs[qa];xo instanceof c.fp&&(L(xo.layers,this.zoom,vn.brightness,gt,this.worldview,vn.activeFloors),Gr[qa]=c.fq(xo,Qt,So.positions,Zn,$a,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,zr,this.worldview,gt))}const Qn={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Ht,Zn,zr,()=>{Qn.iconsPending=!1,fo(Gr,So,Qn,void 0,oa)}),this.rasterizeIfNeeded(Ht,aa,Na,()=>{Qn.patternsPending=!1,fo(Gr,So,Qn,void 0,oa)})}},fo=(Va,So,$a,Gr,Qn)=>{if($a.iconsPending||$a.patternsPending)return;const qa=Zn.size>0||aa.size>0,xo=Object.keys(Va).length>0;if(!qa&&!xo)return this.status="done",void ts(null,{buckets:Object.values(Zs).filter(Co=>!Co.isEmpty()),featureIndex:js,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Mr,glyphAtlasImage:So.image,lineAtlas:Tn,imageAtlas:null,brightness:vn.brightness});const Wo=(Co,Ko)=>{for(const Ud in Zs){const Mu=Zs[Ud];if(Ud in Va)c.fv(Mu,Va[Ud],this.showCollisionBoxes,gt,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,Zn,Ko);else if(Mu.hasPattern&&(Mu instanceof c.fw||Mu instanceof c.fl||Mu instanceof c.e0)){L(Mu.layers,this.zoom,vn.brightness,gt,this.worldview,vn.activeFloors);const Qm=Object.fromEntries(Ko.patternPositions);Mu.addFeatures(vn,this.tileID.canonical,Qm,gt,this.tileTransform,this.brightness)}}this.status="done",ts(null,{buckets:Object.values(Zs).filter(Ud=>!Ud.isEmpty()),featureIndex:js,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Mr,glyphAtlasImage:So.image,lineAtlas:Tn,imageAtlas:Co,brightness:vn.brightness})};if(qa){const Co=new Map,Ko=c.fr(Zn,Co),Ud=c.fr(aa,Co),Mu=new c.fs(Ko,Ud,Qn,this.lut,Co);Ht.send("checkAtlasCache",{descriptor:Mu,scope:this.scope},(Qm,Gc)=>{let lh,qd;if(Qm&&c.w(`[Worker] Error checking atlas cache: ${Qm.message}`),Gc)lh=new c.ft(Gc.sourceHash),qd=Gc;else{const Wc=new c.fu(Zn,aa,this.lut,Qn);lh=Wc,qd=Wc}Wo(lh,qd)})}else Wo(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Va=c.fk(vn.glyphDependencies,Gr=>Object.keys(Gr).map(Number));Object.keys(Va).length?Ht.send("getGlyphs",{uid:this.uid,stacks:Va},(Gr,Qn)=>{Xr||(Xr=Gr,Qt=Qn,ao())},void 0,!1,ur):Qt={},oa=new Map;const So=Array.from(vn.iconDependencies.keys()).map(Gr=>c.I.parse(Gr));So.length?Ht.send("getImages",{images:So,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(Gr,Qn)=>{if(!Xr){Xr=Gr,Zn=new Map,zr=this.updateImageMapAndGetImageTaskQueue(Zn,Qn.images,vn.iconDependencies);for(const[qa,xo]of Qn.versions.entries())oa.set(qa,xo);ao()}},void 0,!1,ur):(Zn=new Map,zr=new Map);const $a=Array.from(vn.patternDependencies.keys()).map(Gr=>c.I.parse(Gr));$a.length?Ht.send("getImages",{images:$a,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(Gr,Qn)=>{if(!Xr){Xr=Gr,aa=new Map,Na=this.updateImageMapAndGetImageTaskQueue(aa,Qn.images,vn.patternDependencies);for(const[qa,xo]of Qn.versions.entries())oa.set(qa,xo);ao()}},void 0,!1,ur):(aa=new Map,Na=new Map)}if(vn.elevationFeatures&&vn.elevationFeatures.length>0){const Va=[];for(const $a of Object.values(Zs))if($a instanceof c.fl){const Gr=$a.getUnevaluatedPortalGraph();Gr&&Va.push(Gr)}const So=c.fm.evaluate(Va);for(const $a of Object.values(Zs))if($a instanceof c.fl){const Gr=We.layers[Ms.decode($a.sourceLayerIndex)];$a.setEvaluatedPortalGraph(So,Gr,this.tileID.canonical,vn.availableImages,vn.brightness)}}ao()};_r.length>0?Promise.allSettled(_r).then(ha).catch(ts):ha()}updateParameters(We){this.scaleFactor=We.scaleFactor,this.showCollisionBoxes=We.showCollisionBoxes,this.projection=We.projection,this.brightness=We.brightness,this.tileTransform=c.fc(We.tileID.canonical,We.projection),this.extraShadowCaster=We.extraShadowCaster,this.lut=We.lut,this.worldview=We.worldview,this.indoor=We.indoor}rasterizeIfNeeded(We,it,gt,St){Array.from(it.values()).some(Ht=>Ht.usvg)?this.rasterize(We,it,gt,St):St()}updateImageMapAndGetImageTaskQueue(We,it,gt){const St=new Map;for(const Ht of it.keys()){const ts=gt.get(Ht)||[];for(const Ms of ts){const js=Ms.toString(),Zs=it.get(Ms.id.toString());Zs.usvg?St.has(js)||(St.set(js,Ms),We.set(js,Object.assign({},Zs))):We.set(js,Zs)}}return St}rasterize(We,it,gt,St){this.rasterizeTask=We.send("rasterizeImages",{scope:this.scope,tasks:gt},(Ht,ts)=>{if(!Ht)for(const[Ms,js]of ts.entries()){const Zs=Object.assign(it.get(Ms),{data:js});it.set(Ms,Zs)}St()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function L(_s,We,it,gt,St,Ht){const ts=new c.ae(We,{brightness:it,worldview:St,activeFloors:Ht});for(const Ms of _s)Ms.recalculate(ts,gt)}class I extends c.E{constructor({actor:We,layerIndex:it,availableImages:gt,availableModels:St,isSpriteLoaded:Ht,tileProvider:ts,brightness:Ms,maxUniformBufferBindings:js,maxUniformBlockSizeDwords:Zs,disableSymbolUBO:Tn}){super(),this.actor=We,this.layerIndex=it,this.availableImages=gt,this.availableModels=St,this.loadVectorData=c.aO,this.tileProvider=ts,this.loading={},this.loaded={},this.deduped=new c.aN(We.scheduler),this.isSpriteLoaded=Ht,this.scheduler=We.scheduler,this.brightness=Ms,this.maxUniformBufferBindings=js,this.maxUniformBlockSizeDwords=Zs,this.disableSymbolUBO=Tn}loadTileData(We,it){if(!this.tileProvider)return this.loadVectorData(We,it);const gt=new AbortController,{z:St,x:Ht,y:ts}=We.tileID.canonical;return this.tileProvider.loadTile({z:St,x:Ht,y:ts},{request:We.request,signal:gt.signal}).then(Ms=>{if(gt.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 js=new Map;Ms.expires&&js.set("expires",Ms.expires),Ms.cacheControl&&js.set("cache-control",Ms.cacheControl),it(null,{rawData:Ms.data,responseHeaders:js})}).catch(Ms=>{gt.signal.aborted||it(Ms instanceof Error?Ms:new Error(String(Ms)))}),()=>gt.abort()}loadTile(We,it){const gt=We.uid,St=We&&We.request,Ht=St&&St.collectResourceTiming,ts=this.loading[gt]=new P(We);ts.maxUniformBufferBindings=this.maxUniformBufferBindings,ts.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,ts.disableSymbolUBO=this.disableSymbolUBO,ts.abort=this.loadTileData(We,(Ms,js)=>{const Zs=!this.loading[gt];if(delete this.loading[gt],ts.cancelRasterize(),Zs||Ms||!js)return ts.status="done",Zs||(this.loaded[gt]=ts),it(Ms);const Tn=js.rawData,vn={},_r=c.aP(js.responseHeaders);_r&&_r.expires&&(vn.expires=_r.expires),_r&&_r.cacheControl&&(vn.cacheControl=_r.cacheControl),ts.vectorTile=js.vectorTile||new c.fx(new c.a$(Tn));const Jr=()=>{ts.parse(ts.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(ha,Mr)=>{if(ha||!Mr)return it(ha);const Xr={};if(Ht){const Qt=d(St);Qt.length>0&&(Xr.resourceTiming=JSON.parse(JSON.stringify(Qt)))}it(null,Object.assign({rawTileData:Tn.slice(0),responseHeaders:js.responseHeaders},Mr,vn,Xr))})};this.isSpriteLoaded?Jr():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(Jr,{type:"parseTile",renderSourceType:We.renderSourceType,zoom:We.tileZoom}):Jr()}),this.loaded=this.loaded||{},this.loaded[gt]=ts})}reloadTile(We,it){const gt=this.loaded,St=We.uid;if(gt&>[St]){const Ht=gt[St];Ht.updateParameters(We);const ts=(Ms,js)=>{const Zs=Ht.reloadCallback;Zs&&(delete Ht.reloadCallback,Ht.parse(Ht.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Zs)),it(Ms,js)};Ht.status==="parsing"?Ht.reloadCallback=ts:Ht.status==="done"&&(Ht.vectorTile?Ht.parse(Ht.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,ts):ts())}else it(null,void 0)}abortTile(We,it){const gt=We.uid,St=this.loading[gt];St&&(St.abort&&St.abort(),delete this.loading[gt]),it()}removeTile(We,it){const gt=this.loaded,St=We.uid;gt&>[St]&&delete gt[St],it()}}class O{constructor(We){this.loading={}}loadTile(We,it){const gt=We.uid,{cancel:St}=c.b1(We.request,(Ht,ts,Ms)=>{const js=!this.loading[gt];if(delete this.loading[gt],js||Ht||!ts)return it(Ht);this.decodeTile(gt,ts,We.encoding).then(Zs=>{const{expires:Tn,cacheControl:vn}=c.aP(Ms);it(null,Object.assign(Zs,{expires:Tn,cacheControl:vn}))}).catch(Zs=>it(Zs))});this.loading[gt]={cancel:St}}async decodeTile(We,it,gt){const St=await createImageBitmap(new Blob([new Uint8Array(it)],{type:"image/png"})),Ht=1-(St.width-c.fy(St.width))/2,ts=Ht<1,Ms=this.getImageData(St,Ht);return St.close(),{dem:new c.fz(We,Ms,gt,ts),borderReady:ts}}reloadTile(We,it){it(null,null)}abortTile(We,it){const gt=We.uid,St=this.loading[gt];St&&(St.cancel(),delete this.loading[gt]),it()}removeTile(We,it){it()}getImageData(We,it){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(We.width,We.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=We.width,this.offscreenCanvas.height=We.height,this.offscreenCanvasContext.drawImage(We,0,0,We.width,We.height);const gt=this.offscreenCanvasContext.getImageData(-it,-it,We.width+2*it,We.height+2*it);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),gt}}c.a_.setPbf(c.a$);class ${constructor(We){this._mrt=new c.a_(We.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=We.uid,this.tileID=We.tileID,this.source=We.source}parse(We,it){const gt=this._mrt;this.status="parsing",this._entireBuffer=We;try{gt.parseHeader(We),this._isHeaderLoaded=!0;const St=[];for(const Ht in gt.layers){const ts=gt.getLayer(Ht),Ms=ts.getDataRange(ts.getBandList()),js=gt.createDecodingTask(Ms),Zs=We.slice(Ms.firstByte,Ms.lastByte+1),Tn=c.a_.performDecoding(Zs,js).then(vn=>js.complete(null,vn)).catch(vn=>js.complete(vn,null));St.push(Tn)}Promise.allSettled(St).then(()=>it(null,gt)).catch(Ht=>it(Ht))}catch(St){it(St)}}}class q{constructor({actor:We}){this.actor=We,this.loading={},this.loaded={}}loadTile(We,it){const gt=We.uid,St=We.request,Ht=this.loading[gt]=new $(We),{cancel:ts}=c.b1(St,(Ms,js,Zs)=>{const Tn=!this.loading[gt];if(delete this.loading[gt],Tn||Ms||!js)return Ht.status="done",Tn||(this.loaded[gt]=Ht),it(Ms);Ht.parse(js,(vn,_r)=>{if(vn||!_r)return it(vn);it(null,_r,Zs)}),this.loaded[gt]=Ht});Ht.abort=ts}reloadTile(We,it){it(null,void 0)}abortTile(We,it){const gt=We.uid,St=this.loading[gt];St&&(St.abort&&St.abort(),delete this.loading[gt]),it()}removeTile(We,it){const gt=We.uid;this.loaded[gt]&&delete this.loaded[gt],it()}decodeRasterArray(We,it){c.a_.performDecoding(We.buffer,We.task).then(gt=>it(null,gt)).catch(gt=>it(gt))}}const W=c.fA.prototype.toGeoJSON;class G{constructor(We){this._feature=We,this.extent=c.an,this.type=We.type,this.properties=We.tags,"id"in We&&!isNaN(We.id)&&(this.id=parseInt(We.id,10))}loadGeometry(){if(this._feature.type===1){const We=[];for(const it of this._feature.geometry)We.push([new c.P(it[0],it[1])]);return We}{const We=[];for(const it of this._feature.geometry){const gt=[];for(const St of it)gt.push(new c.P(St[0],St[1]));We.push(gt)}return We}}toGeoJSON(We,it,gt){return W.call(this,We,it,gt)}}class K{constructor(We,it){this.name=We,this.extent=c.an,this.length=it.length,this._jsonFeatures=it}feature(We){return new G(this._jsonFeatures[We])}}class ee{constructor(We){this.layers={},this.extent=c.an;for(const it of Object.keys(We))this.layers[it]=new K(it,We[it])}}const J=64/4096;class le{constructor(){this.features=new Map}clear(){this.features.clear()}load(We=[],it){for(const gt of We){const St=gt.id;if(St==null)continue;let Ht=this.features.get(St);Ht&&this.updateCache(Ht,it),gt.geometry?(Ht=oe(gt),this.updateCache(Ht,it),this.features.set(St,Ht)):this.features.delete(St),this.updateCache(Ht,it)}}updateCache(We,it){for(const{canonical:gt,uid:St}of Object.values(it)){const{z:Ht,x:ts,y:Ms}=gt;ue(We,Math.pow(2,Ht),ts,Ms)&&delete it[St]}}getTile(We,it,gt){const St=Math.pow(2,We),Ht=[];for(const ts of this.features.values())ue(ts,St,it,gt)&&Ht.push(je(ts,St,it,gt));return{features:Ht}}getFeatures(){return[...this.features.values()]}}function ue({minX:_s,minY:We,maxX:it,maxY:gt},St,Ht,ts){return _s<(Ht+1+J)/St&&We<(ts+1+J)/St&&it>(Ht-J)/St&>>(ts-J)/St}function oe(_s){const{id:We,geometry:it,properties:gt}=_s;if(!it)return;if(it.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:St,coordinates:Ht}=it,ts={id:We,type:1,geometry:[],tags:gt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},Ms=ts.geometry;if(St==="Point")ie(Ht,Ms,ts);else if(St==="MultiPoint")for(const js of Ht)ie(js,Ms,ts);else if(St==="LineString")ts.type=2,de(Ht,Ms,ts);else if(St==="MultiLineString")ts.type=2,we(Ht,Ms,ts);else if(St==="Polygon")ts.type=3,we(Ht,Ms,ts,!0);else{if(St!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");ts.type=3;for(const js of Ht)we(js,Ms,ts,!0)}return ts}function ie([_s,We],it,gt){const St=c.aH(_s);let Ht=c.aL(We);Ht=Ht<0?0:Ht>1?1:Ht,it.push(St,Ht),gt.minX=Math.min(gt.minX,St),gt.minY=Math.min(gt.minY,Ht),gt.maxX=Math.max(gt.maxX,St),gt.maxY=Math.max(gt.maxY,Ht)}function de(_s,We,it,gt=!1,St=!1){const Ht=[];for(const ts of _s)ie(ts,Ht,it);We.push(Ht),gt&&function(ts,Ms){let js=0;for(let Zs=0,Tn=ts.length,vn=Tn-2;Zs0===Ms)for(let Zs=0,Tn=ts.length;Zs=ts&&vn>=ts||(Zs>=ts?(Tn+=Math.round(ha*((ts-Zs)/Jr)),Zs=ts):vn>=ts&&(_r=Tn+Math.round(ha*((ts-Zs)/Jr)),vn=ts),Tn>=ts&&_r>=ts||(Tn>=ts?(Zs+=Math.round(Jr*((ts-Tn)/ha)),Tn=ts):_r>=ts&&(vn=Zs+Math.round(Jr*((ts-Tn)/ha)),_r=ts),Ms&&Zs===Ms[Ms.length-1][0]&&Tn===Ms[Ms.length-1][1]||(Ms=[[Zs,Tn]],St.push(Ms)),Ms.push([vn,_r])))))}}function fe(_s,We,it,gt,St){const Ht=(it-J)/We,ts=(gt-J)/We,Ms=(it+1+J)/We,js=(gt+1+J)/We;function Zs(_r,Jr){let ha=0;return _rMs&&(ha|=2),Jrjs&&(ha|=8),ha}let Tn=[];for(let _r=1;_r<=8;_r*=2){let Jr=_s[_s.length-2],ha=_s[_s.length-1],Mr=!(Zs(Jr,ha)&_r);for(let Xr=0;Xr<_s.length;Xr+=2){const Qt=_s[Xr],Zn=_s[Xr+1],aa=!(Zs(Qt,Zn)&_r);aa!==Mr&&(8&_r?Tn.push(Jr+(Qt-Jr)*(js-ha)/(Zn-ha),js):4&_r?Tn.push(Jr+(Qt-Jr)*(ts-ha)/(Zn-ha),ts):2&_r?Tn.push(Ms,ha+(Zn-ha)*(Ms-Jr)/(Qt-Jr)):1&_r&&Tn.push(Ht,ha+(Zn-ha)*(Ht-Jr)/(Qt-Jr))),aa&&Tn.push(Qt,Zn),Jr=Qt,ha=Zn,Mr=aa}if(!(_s=Tn).length||_r===8)break;Tn=[]}const vn=[];for(let _r=0;_r>31}function Ne(_s,We){const{geometry:it,type:gt}=_s;let St=0,Ht=0;if(gt===1){We.writeVarint(De(1,it.length));for(const ts of it){const Ms=ts[0]-St,js=ts[1]-Ht;We.writeVarint(Be(Ms)),We.writeVarint(Be(js)),St+=Ms,Ht+=js}}else for(const ts of it){if(ts.length===0)continue;We.writeVarint(De(1,1));const Ms=ts.length-(gt===3?1:0);for(let js=0;js_s},Oe=Math.fround||(Ae=new Float32Array(1),_s=>(Ae[0]=+_s,Ae[0]));var Ae;class Xe{constructor(We){this.options=Object.assign(Object.create(_e),We),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(We){const{log:it,minZoom:gt,maxZoom:St}=this.options;it&&console.time("total time");const Ht=`prepare ${We.length} points`;it&&console.time(Ht),this.points=We;const ts=[];for(let js=0;js=gt;js--){const Zs=+Date.now();Ms=this.trees[js]=this._createTree(this._cluster(Ms,js)),it&&console.log("z%d: %d clusters in %dms",js,Ms.numItems,+Date.now()-Zs)}return it&&console.timeEnd("total time"),this}getClusters(We,it){let gt=((We[0]+180)%360+360)%360-180;const St=Math.max(-90,Math.min(90,We[1]));let Ht=We[2]===180?180:((We[2]+180)%360+360)%360-180;const ts=Math.max(-90,Math.min(90,We[3]));if(We[2]-We[0]>=360)gt=-180,Ht=180;else if(gt>Ht){const vn=this.getClusters([gt,St,180,ts],it),_r=this.getClusters([-180,St,Ht,ts],it);return vn.concat(_r)}const Ms=this.trees[this._limitZoom(it)],js=Ms.range(Qe(gt),Ye(ts),Qe(Ht),Ye(St)),Zs=Ms.data,Tn=[];for(const vn of js){const _r=this.stride*vn;Tn.push(Zs[_r+5]>1?Ue(Zs,_r,this.clusterProps):this.points[Zs[_r+3]])}return Tn}getChildren(We){const it=this._getOriginId(We),gt=this._getOriginZoom(We),St="No cluster with the specified id.",Ht=this.trees[gt];if(!Ht)throw new Error(St);const ts=Ht.data;if(it*this.stride>=ts.length)throw new Error(St);const Ms=this.options.radius/(this.options.extent*Math.pow(2,gt-1)),js=Ht.within(ts[it*this.stride],ts[it*this.stride+1],Ms),Zs=[];for(const Tn of js){const vn=Tn*this.stride;ts[vn+4]===We&&Zs.push(ts[vn+5]>1?Ue(ts,vn,this.clusterProps):this.points[ts[vn+3]])}if(Zs.length===0)throw new Error(St);return Zs}getLeaves(We,it,gt){const St=[];return this._appendLeaves(St,We,it=it||10,gt=gt||0,0),St}getTile(We,it,gt){const St=this.trees[this._limitZoom(We)],Ht=Math.pow(2,We),{extent:ts,radius:Ms}=this.options,js=Ms/ts,Zs=(gt-js)/Ht,Tn=(gt+1+js)/Ht,vn={features:[]};return this._addTileFeatures(St.range((it-js)/Ht,Zs,(it+1+js)/Ht,Tn),St.data,it,gt,Ht,vn),it===0&&this._addTileFeatures(St.range(1-js/Ht,Zs,1,Tn),St.data,Ht,gt,Ht,vn),it===Ht-1&&this._addTileFeatures(St.range(0,Zs,js/Ht,Tn),St.data,-1,gt,Ht,vn),vn.features.length?vn:null}getClusterExpansionZoom(We){let it=this._getOriginZoom(We)-1;for(;it<=this.options.maxZoom;){const gt=this.getChildren(We);if(it++,gt.length!==1)break;We=gt[0].properties.cluster_id}return it}_appendLeaves(We,it,gt,St,Ht){const ts=this.getChildren(it);for(const Ms of ts){const js=Ms.properties;if(js&&js.cluster?Ht+js.point_count<=St?Ht+=js.point_count:Ht=this._appendLeaves(We,js.cluster_id,gt,St,Ht):Ht1;let Tn,vn,_r;if(Zs)Tn=Ze(it,js,this.clusterProps),vn=it[js],_r=it[js+1];else{const Mr=this.points[it[js+3]];Tn=Mr.properties;const[Xr,Qt]=Mr.geometry.coordinates;vn=Qe(Xr),_r=Ye(Qt)}const Jr={type:1,geometry:[[Math.round(this.options.extent*(vn*Ht-gt)),Math.round(this.options.extent*(_r*Ht-St))]],tags:Tn};let ha;ha=Zs||this.options.generateId?it[js+3]:this.points[it[js+3]].id,ha!==void 0&&(Jr.id=ha),ts.features.push(Jr)}}_limitZoom(We){return Math.max(this.options.minZoom,Math.min(Math.floor(+We),this.options.maxZoom+1))}_cluster(We,it){const{radius:gt,extent:St,reduce:Ht,minPoints:ts}=this.options,Ms=gt/(St*Math.pow(2,it)),js=We.data,Zs=[],Tn=this.stride;for(let vn=0;vnit&&(Xr+=js[Zn+5])}if(Xr>Mr&&Xr>=ts){let Qt,Zn=_r*Mr,aa=Jr*Mr,zr=-1;const Na=(vn/Tn<<5)+(it+1)+this.points.length;for(const oa of ha){const ur=oa*Tn;if(js[ur+2]<=it)continue;js[ur+2]=it;const ao=js[ur+5];Zn+=js[ur]*ao,aa+=js[ur+1]*ao,js[ur+4]=Na,Ht&&(Qt||(Qt=this._map(js,vn,!0),zr=this.clusterProps.length,this.clusterProps.push(Qt)),Ht(Qt,this._map(js,ur)))}js[vn+4]=Na,Zs.push(Zn/Xr,aa/Xr,1/0,Na,-1,Xr),Ht&&Zs.push(zr)}else{for(let Qt=0;Qt1)for(const Qt of ha){const Zn=Qt*Tn;if(!(js[Zn+2]<=it)){js[Zn+2]=it;for(let aa=0;aa>5}_getOriginZoom(We){return(We-this.points.length)%32}_map(We,it,gt){if(We[it+5]>1){const ts=this.clusterProps[We[it+6]];return gt?Object.assign({},ts):ts}const St=this.points[We[it+3]].properties,Ht=this.options.map(St);return gt&&Ht===St?Object.assign({},Ht):Ht}}function Ue(_s,We,it){return{type:"Feature",id:_s[We+3],properties:Ze(_s,We,it),geometry:{type:"Point",coordinates:[(gt=_s[We],360*(gt-.5)),nt(_s[We+1])]}};var gt}function Ze(_s,We,it){const gt=_s[We+5],St=gt>=1e4?`${Math.round(gt/1e3)}k`:gt>=1e3?Math.round(gt/100)/10+"k":gt,Ht=_s[We+6],ts=Ht===-1?{}:Object.assign({},it[Ht]);return Object.assign(ts,{cluster:!0,cluster_id:_s[We+3],point_count:gt,point_count_abbreviated:St})}function Qe(_s){return _s/360+.5}function Ye(_s){const We=Math.sin(_s*Math.PI/180),it=.5-.25*Math.log((1+We)/(1-We))/Math.PI;return it<0?0:it>1?1:it}function nt(_s){const We=(180-360*_s)*Math.PI/180;return 360*Math.atan(Math.exp(We))/Math.PI-90}function rt(_s,We,it,gt){let St=gt;const Ht=We+(it-We>>1);let ts,Ms=it-We;const js=_s[We],Zs=_s[We+1],Tn=_s[it],vn=_s[it+1];for(let _r=We+3;_rSt)ts=_r,St=Jr;else if(Jr===St){const ha=Math.abs(_r-Ht);hagt&&(ts-We>3&&rt(_s,We,ts,gt),_s[ts+2]=St,it-ts>3&&rt(_s,ts,it,gt))}function Fe(_s,We,it,gt,St,Ht){let ts=St-it,Ms=Ht-gt;if(ts!==0||Ms!==0){const js=((_s-it)*ts+(We-gt)*Ms)/(ts*ts+Ms*Ms);js>1?(it=St,gt=Ht):js>0&&(it+=ts*js,gt+=Ms*js)}return ts=_s-it,Ms=We-gt,ts*ts+Ms*Ms}function dt(_s,We,it,gt){const St={id:_s??null,type:We,geometry:it,tags:gt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(We==="Point"||We==="MultiPoint"||We==="LineString")Dt(St,it);else if(We==="Polygon")Dt(St,it[0]);else if(We==="MultiLineString")for(const Ht of it)Dt(St,Ht);else if(We==="MultiPolygon")for(const Ht of it)Dt(St,Ht[0]);return St}function Dt(_s,We){for(let it=0;it0&&(ts+=gt?(St*Tn-Zs*Ht)/2:Math.sqrt(Math.pow(Zs-St,2)+Math.pow(Tn-Ht,2))),St=Zs,Ht=Tn}const Ms=We.length-3;We[2]=1,rt(We,0,Ms,it),We[Ms+2]=1,We.size=Math.abs(ts),We.start=0,We.end=We.size}function qs(_s,We,it,gt){for(let St=0;St<_s.length;St++){const Ht=[];Gt(_s[St],Ht,it,gt),We.push(Ht)}}function As(_s){return _s/360+.5}function Bt(_s){const We=Math.sin(_s*Math.PI/180),it=.5-.25*Math.log((1+We)/(1-We))/Math.PI;return it<0?0:it>1?1:it}function At(_s,We,it,gt,St,Ht,ts,Ms){if(gt/=We,Ht>=(it/=We)&&ts=gt)return null;const js=[];for(const Zs of _s){const Tn=Zs.geometry;let vn=Zs.type;const _r=St===0?Zs.minX:Zs.minY,Jr=St===0?Zs.maxX:Zs.maxY;if(_r>=it&&Jr=gt)continue;let ha=[];if(vn==="Point"||vn==="MultiPoint")Is(Tn,ha,it,gt,St);else if(vn==="LineString")jt(Tn,ha,it,gt,St,!1,Ms.lineMetrics);else if(vn==="MultiLineString")cn(Tn,ha,it,gt,St,!1);else if(vn==="Polygon")cn(Tn,ha,it,gt,St,!0);else if(vn==="MultiPolygon")for(const Mr of Tn){const Xr=[];cn(Mr,Xr,it,gt,St,!0),Xr.length&&ha.push(Xr)}if(ha.length){if(Ms.lineMetrics&&vn==="LineString"){for(const Mr of ha)js.push(dt(Zs.id,vn,Mr,Zs.tags));continue}vn!=="LineString"&&vn!=="MultiLineString"||(ha.length===1?(vn="LineString",ha=ha[0]):vn="MultiLineString"),vn!=="Point"&&vn!=="MultiPoint"||(vn=ha.length===3?"Point":"MultiPoint"),js.push(dt(Zs.id,vn,ha,Zs.tags))}}return js.length?js:null}function Is(_s,We,it,gt,St){for(let Ht=0;Ht<_s.length;Ht+=3){const ts=_s[Ht+St];ts>=it&&ts<=gt&&qt(We,_s[Ht],_s[Ht+1],_s[Ht+2])}}function jt(_s,We,it,gt,St,Ht,ts){let Ms=Qs(_s);const js=St===0?Gs:Ls;let Zs,Tn,vn=_s.start;for(let Xr=0;Xr<_s.length-3;Xr+=3){const Qt=_s[Xr],Zn=_s[Xr+1],aa=_s[Xr+2],zr=_s[Xr+3],Na=_s[Xr+4],oa=St===0?Qt:Zn,ur=St===0?zr:Na;let ao=!1;ts&&(Zs=Math.sqrt(Math.pow(Qt-zr,2)+Math.pow(Zn-Na,2))),oait&&(Tn=js(Ms,Qt,Zn,zr,Na,it),ts&&(Ms.start=vn+Zs*Tn)):oa>gt?ur=it&&(Tn=js(Ms,Qt,Zn,zr,Na,it),ao=!0),ur>gt&&oa<=gt&&(Tn=js(Ms,Qt,Zn,zr,Na,gt),ao=!0),!Ht&&ao&&(ts&&(Ms.end=vn+Zs*Tn),We.push(Ms),Ms=Qs(_s)),ts&&(vn+=Zs)}let _r=_s.length-3;const Jr=_s[_r],ha=_s[_r+1],Mr=St===0?Jr:ha;Mr>=it&&Mr<=gt&&qt(Ms,Jr,ha,_s[_r+2]),_r=Ms.length-3,Ht&&_r>=3&&(Ms[_r]!==Ms[0]||Ms[_r+1]!==Ms[1])&&qt(Ms,Ms[0],Ms[1],Ms[2]),Ms.length&&We.push(Ms)}function Qs(_s){const We=[];return We.size=_s.size,We.start=_s.start,We.end=_s.end,We}function cn(_s,We,it,gt,St,Ht){for(const ts of _s)jt(ts,We,it,gt,St,Ht,!1)}function qt(_s,We,it,gt){_s.push(We,it,gt)}function Gs(_s,We,it,gt,St,Ht){const ts=(Ht-We)/(gt-We);return qt(_s,Ht,it+(St-it)*ts,1),ts}function Ls(_s,We,it,gt,St,Ht){const ts=(Ht-it)/(St-it);return qt(_s,We+(gt-We)*ts,Ht,1),ts}function sn(_s,We){const it=[];for(let gt=0;gt<_s.length;gt++){const St=_s[gt],Ht=St.type;let ts;if(Ht==="Point"||Ht==="MultiPoint"||Ht==="LineString")ts=Hs(St.geometry,We);else if(Ht==="MultiLineString"||Ht==="Polygon"){ts=[];for(const Ms of St.geometry)ts.push(Hs(Ms,We))}else if(Ht==="MultiPolygon"){ts=[];for(const Ms of St.geometry){const js=[];for(const Zs of Ms)js.push(Hs(Zs,We));ts.push(js)}}it.push(dt(St.id,Ht,ts,St.tags))}return it}function Hs(_s,We){const it=[];it.size=_s.size,_s.start!==void 0&&(it.start=_s.start,it.end=_s.end);for(let gt=0;gt<_s.length;gt+=3)it.push(_s[gt]+We,_s[gt+1],_s[gt+2]);return it}function nn(_s,We){if(_s.transformed)return _s;const it=1<<_s.z,gt=_s.x,St=_s.y;for(const Ht of _s.features){const ts=Ht.geometry,Ms=Ht.type;if(Ht.geometry=[],Ms===1)for(let js=0;js0&&We.size<(St?ts:gt))return void(it.numPoints+=We.length/3);const Ms=[];for(let js=0;jsts)&&(it.numSimplified++,Ms.push(We[js],We[js+1])),it.numPoints++;St&&function(js,Zs){let Tn=0;for(let vn=0,_r=js.length,Jr=_r-2;vn<_r;Jr=vn,vn+=2)Tn+=(js[vn]-js[Jr])*(js[vn+1]+js[Jr+1]);if(Tn>0===Zs)for(let vn=0,_r=js.length;vn<_r/2;vn+=2){const Jr=js[vn],ha=js[vn+1];js[vn]=js[_r-2-vn],js[vn+1]=js[_r-1-vn],js[_r-2-vn]=Jr,js[_r-1-vn]=ha}}(Ms,Ht),_s.push(Ms)}const Kr={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,promoteId:null,generateId:!1,debug:0};class jr{constructor(We,it){const gt=(it=this.options=function(Ht,ts){for(const Ms in ts)Ht[Ms]=ts[Ms];return Ht}(Object.create(Kr),it)).debug;if(gt&&console.time("preprocess data"),it.maxZoom<0||it.maxZoom>24)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 St=function(Ht,ts){const Ms=[];if(Ht.type==="FeatureCollection")for(let js=0;js1&&console.time("creation"),Jr=this.tiles[_r]=_n(We,it,gt,St,Zs),this.tileCoords.push({z:it,x:gt,y:St}),Tn)){Tn>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",it,gt,St,Jr.numFeatures,Jr.numPoints,Jr.numSimplified),console.timeEnd("creation"));const ao=`z${it}`;this.stats[ao]=(this.stats[ao]||0)+1,this.total++}if(Jr.source=We,Ht==null){if(it===Zs.indexMaxZoom||Jr.numPoints<=Zs.indexMaxPoints)continue}else{if(it===Zs.maxZoom||it===Ht)continue;if(Ht!=null){const ao=Ht-it;if(gt!==ts>>ao||St!==Ms>>ao)continue}}if(Jr.source=null,We.length===0)continue;Tn>1&&console.time("clipping");const ha=.5*Zs.buffer/Zs.extent,Mr=.5-ha,Xr=.5+ha,Qt=1+ha;let Zn=null,aa=null,zr=null,Na=null,oa=At(We,vn,gt-ha,gt+Xr,0,Jr.minX,Jr.maxX,Zs),ur=At(We,vn,gt+Mr,gt+Qt,0,Jr.minX,Jr.maxX,Zs);We=null,oa&&(Zn=At(oa,vn,St-ha,St+Xr,1,Jr.minY,Jr.maxY,Zs),aa=At(oa,vn,St+Mr,St+Qt,1,Jr.minY,Jr.maxY,Zs),oa=null),ur&&(zr=At(ur,vn,St-ha,St+Xr,1,Jr.minY,Jr.maxY,Zs),Na=At(ur,vn,St+Mr,St+Qt,1,Jr.minY,Jr.maxY,Zs),ur=null),Tn>1&&console.timeEnd("clipping"),js.push(Zn||[],it+1,2*gt,2*St),js.push(aa||[],it+1,2*gt,2*St+1),js.push(zr||[],it+1,2*gt+1,2*St),js.push(Na||[],it+1,2*gt+1,2*St+1)}}getTile(We,it,gt){We=+We,it=+it,gt=+gt;const St=this.options,{extent:Ht,debug:ts}=St;if(We<0||We>24)return null;const Ms=1<1&&console.log("drilling down to z%d-%d-%d",We,it,gt);let Zs,Tn=We,vn=it,_r=gt;for(;!Zs&&Tn>0;)Tn--,vn>>=1,_r>>=1,Zs=this.tiles[Xs(Tn,vn,_r)];return Zs&&Zs.source?(ts>1&&(console.log("found parent tile z%d-%d-%d",Tn,vn,_r),console.time("drilling down")),this.splitTile(Zs.source,Tn,vn,_r,We,it,gt),ts>1&&console.timeEnd("drilling down"),this.tiles[js]?nn(this.tiles[js],Ht):null):null}}function Xs(_s,We,it){return 32*((1<<_s)*it+We)+_s}function Ba(_s,We){const it=_s.tileID.canonical;if(!this._geoJSONIndex)return void We(null,null);const gt=this._geoJSONIndex.getTile(it.z,it.x,it.y);if(!gt)return void We(null,null);const St=Zs=>Zs.tags&&"3d_elevation_id"in Zs.tags&&"source"in Zs.tags&&Zs.tags.source==="elevation",Ht=gt.features.filter(Zs=>St(Zs));let ts={_geojsonTileLayer:gt.features};Ht.length>0&&(ts={_geojsonTileLayer:gt.features.filter(Zs=>!St(Zs)),hd_road_elevation:Ht});const Ms=new ee(ts),js=function(Zs){const Tn=new c.a$;for(const vn of Object.keys(Zs))Tn.writeMessage(3,Se,{name:vn,features:Zs[vn]});return Tn.finish()}(ts).buffer;We(null,{vectorTile:Ms,rawData:js})}class Hr extends I{constructor(We){super(We),this.loadVectorData=Ba,this._dynamicIndex=new le}loadData(We,it){const gt=We&&We.request,St=gt&>.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(We,(Ht,ts)=>{if(Ht||!ts)return it(Ht);if(typeof ts!="object")return it(new Error(`Input data given to '${We.source}' is not a valid GeoJSON object.`));{try{if(We.filter){const js=c.X(We.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(js.result==="error")throw new Error(js.value.map(Zs=>`${Zs.key}: ${Zs.message}`).join(", "));ts.features=ts.features.filter(Zs=>js.value.evaluate({zoom:0},Zs))}We.dynamic?(ts.type==="Feature"&&(ts={type:"FeatureCollection",features:[ts]}),We.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(ts.features,this.loaded),We.cluster&&(ts.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=We.cluster?new Xe(function({superclusterOptions:js,clusterProperties:Zs}){if(!Zs||!js)return js;const Tn={},vn={},_r={accumulated:null,zoom:0},Jr={properties:null},ha=Object.keys(Zs);for(const Mr of ha){const[Xr,Qt]=Zs[Mr],Zn=c.X(Qt),aa=c.X(typeof Xr=="string"?[Xr,["accumulated"],["get",Mr]]:Xr);Tn[Mr]=Zn.value,vn[Mr]=aa.value}return js.map=Mr=>{Jr.properties=Mr;const Xr={};for(const Qt of ha)Xr[Qt]=Tn[Qt].evaluate(_r,Jr);return Xr},js.reduce=(Mr,Xr)=>{Jr.properties=Xr;for(const Qt of ha)_r.accumulated=Mr[Qt],Mr[Qt]=vn[Qt].evaluate(_r,Jr)},js}(We)).load(ts.features):We.dynamic?this._dynamicIndex:function(js,Zs){return new jr(js,Zs)}(ts,We.geojsonVtOptions)}catch(js){return it(js)}const Ms={};if(St){const js=d(gt);js&&(Ms.resourceTiming={},Ms.resourceTiming[We.source]=JSON.parse(JSON.stringify(js)))}it(null,Ms)}})}reloadTile(We,it){const gt=this.loaded;return gt&>[We.uid]?We.partial?it(null,void 0):super.reloadTile(We,it):this.loadTile(We,it)}loadGeoJSON(We,it){if(We.request)c.m(We.request,it);else{if(typeof We.data!="string")return it(new Error(`Input data given to '${We.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return it(null,JSON.parse(We.data))}catch{return it(new Error(`Input data given to '${We.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(We,it){try{it(null,this._geoJSONIndex.getClusterExpansionZoom(We.clusterId))}catch(gt){it(gt)}}getClusterChildren(We,it){try{it(null,this._geoJSONIndex.getChildren(We.clusterId))}catch(gt){it(gt)}}getClusterLeaves(We,it){try{it(null,this._geoJSONIndex.getLeaves(We.clusterId,We.limit,We.offset))}catch(gt){it(gt)}}}class mr{constructor(We,it,gt){this.tileID=new c.aR(We.tileID.overscaledZ,We.tileID.wrap,We.tileID.canonical.z,We.tileID.canonical.x,We.tileID.canonical.y),this.tileZoom=We.tileZoom,this.uid=We.uid,this.zoom=We.zoom,this.canonical=We.tileID.canonical,this.pixelRatio=We.pixelRatio,this.tileSize=We.tileSize,this.source=We.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=We.projection,this.brightness=it,this.worldview=gt}parse(We,it,gt,St){this.status="parsing";const Ht=new c.aR(gt.tileID.overscaledZ,gt.tileID.wrap,gt.tileID.canonical.z,gt.tileID.canonical.x,gt.tileID.canonical.y),ts=[],Ms=it.familiesBySource[gt.source],js=new c.ff(Ht,gt.promoteId);js.bucketLayerIDs=[],js.is3DTile=!0,c.fB(We).then(Zs=>{const Tn=Zs.json.extensionsUsed&&Zs.json.extensionsUsed.includes("MAPBOX_mesh_features")||Zs.json.asset.extras&&Zs.json.asset.extras.MAPBOX_mesh_features,vn=Zs.json.extensionsUsed&&Zs.json.extensionsUsed.includes("EXT_meshopt_compression"),_r=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const Jr in Ms)for(const ha of Ms[Jr]){const Mr=ha[0];js.bucketLayerIDs.push(ha.map(Zn=>c.F(Zn.id,Zn.scope))),Mr.recalculate(_r,[]);const Xr=c.fC(Zs,1/c.cS(gt.tileID.canonical)),Qt=new c.fD(ha,Xr,Ht,Tn,vn,this.brightness,js,this.worldview);Tn||(Qt.needsUpload=!0),ts.push(Qt),Qt.evaluate(Mr)}this.status="done",St(null,{buckets:ts,featureIndex:js,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(Zs=>St(new Error(Zs.message)))}}class pr{constructor({actor:We,layerIndex:it,availableImages:gt,availableModels:St,brightness:Ht,worldview:ts}){this.actor=We,this.layerIndex=it,this.availableImages=gt,this.availableModels=St,this.brightness=Ht,this.loading={},this.loaded={},this.worldview=ts}loadTile(We,it){const gt=We.uid,St=this.loading[gt]=new mr(We,this.brightness,this.worldview);c.b1(We.request,(Ht,ts)=>{const Ms=!this.loading[gt];return delete this.loading[gt],Ms||Ht?(St.status="done",Ms||(this.loaded[gt]=St),it(Ht)):ts&&ts.byteLength!==0?void St.parse(ts,this.layerIndex,We,(js,Zs)=>{St.status="done",this.loaded=this.loaded||{},this.loaded[gt]=St,js||!Zs?it(js):it(null,Zs)}):(St.status="done",this.loaded[gt]=St,it())})}reloadTile(We,it){const gt=this.loaded,St=We.uid;if(gt&>[St]){const Ht=gt[St];Ht.projection=We.projection,Ht.brightness=We.brightness;const ts=(Ms,js)=>{Ht.reloadCallback&&(delete Ht.reloadCallback,this.loadTile(We,it)),it(Ms,js)};Ht.status==="parsing"?Ht.reloadCallback=ts:Ht.status==="done"&&this.loadTile(We,it)}}abortTile(We,it){const gt=We.uid;this.loading[gt]&&delete this.loading[gt],it()}removeTile(We,it){const gt=this.loaded,St=We.uid;gt&>[St]&&delete gt[St],it()}}const rn=new Map,Jn=new Map;class ea{constructor(We){this.self=We,this.actor=new c.A(We,this),this.layerIndexes={},this.availableImages={},this.availableModels={},this.isSpriteLoaded={},this.imageRasterizer=new c.z,this.rtlPluginParsingListeners=[],this.projections={},this.defaultProjection=c.c0({name:"mercator"}),this.workerSourceTypes={vector:I,geojson:Hr,"raster-dem":O,"raster-array":q,"batched-model":pr},this.workerSources={},this.self.registerWorkerSource=(it,gt)=>{if(this.workerSourceTypes[it])throw new Error(`Worker source with name "${it}" already registered.`);this.workerSourceTypes[it]=gt},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 gt of this.rtlPluginParsingListeners)gt(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(We,it,gt){delete this.layerIndexes[We],delete this.availableImages[We],delete this.availableModels[We],delete this.workerSources[We],gt()}checkIfReady(We,it,gt){gt()}setReferrer(We,it){this.referrer=it}spriteLoaded(We,it){this.isSpriteLoaded[We]||(this.isSpriteLoaded[We]={});const{scope:gt,isLoaded:St}=it;if(this.isSpriteLoaded[We][gt]=St,this.workerSources[We]&&this.workerSources[We][gt])for(const Ht in this.workerSources[We][gt]){const ts=this.workerSources[We][gt][Ht];for(const Ms in ts){const js=ts[Ms];js instanceof I&&(js.isSpriteLoaded=St,js.fire(new c.C("isSpriteLoaded")))}}}setImages(We,it,gt){this.availableImages[We]||(this.availableImages[We]={});const{scope:St,images:Ht}=it;if(this.availableImages[We][St]=Ht,this.workerSources[We]&&this.workerSources[We][St]){for(const ts in this.workerSources[We][St]){const Ms=this.workerSources[We][St][ts];for(const js in Ms)Ms[js].availableImages=Ht}gt()}else gt()}setModels(We,{scope:it,models:gt},St){if(this.availableModels[We]||(this.availableModels[We]={}),this.availableModels[We][it]=gt,this.workerSources[We]&&this.workerSources[We][it]){for(const Ht in this.workerSources[We][it]){const ts=this.workerSources[We][it][Ht];for(const Ms in ts)ts[Ms].availableModels=gt}St()}else St()}setProjection(We,it){this.projections[We]=c.c0(it)}setBrightness(We,it,gt){this.brightness=it,gt()}setContextParams(We,it,gt){this.maxUniformBufferBindings=it.maxBindingPoints,this.maxUniformBlockSizeDwords=it.maxUniformBlockSizeDwords,this.disableSymbolUBO=it.disableSymbolUBO,gt()}setWorldview(We,it,gt){this.worldview=it,gt()}setLayers(We,it,gt){this.getLayerIndex(We,it.scope).replace(it.layers,it.options),gt()}updateLayers(We,it,gt){this.getLayerIndex(We,it.scope).update(it.layers,it.removedIds,it.options),gt()}loadTile(We,it,gt){it.projection=this.projections[We]||this.defaultProjection,this.getWorkerSource(We,it).loadTile(it,gt)}decodeRasterArray(We,it,gt){this.getWorkerSource(We,it).decodeRasterArray(it,gt)}reloadTile(We,it,gt){it.projection=this.projections[We]||this.defaultProjection,this.getWorkerSource(We,it).reloadTile(it,gt)}abortTile(We,it,gt){this.getWorkerSource(We,it).abortTile(it,gt)}removeTile(We,it,gt){this.getWorkerSource(We,it).removeTile(it,gt)}removeSource(We,it,gt){if(!(this.workerSources[We]&&this.workerSources[We][it.scope]&&this.workerSources[We][it.scope][it.type]&&this.workerSources[We][it.scope][it.type][it.source]))return;const St=this.workerSources[We][it.scope][it.type][it.source];delete this.workerSources[We][it.scope][it.type][it.source],St.removeSource!==void 0?St.removeSource(it,gt):gt()}loadTileProvider(We,it,gt){(async function(St,Ht){const ts=Jn.get(St);if(ts)return ts;const Ms=rn.get(St);if(Ms!==void 0)return Ms;const js=import(Ht).then(Zs=>{const Tn=Zs.default;if(typeof Tn!="function")throw new Error(`TileProvider "${St}" module must default-export a class`);if(typeof Tn.prototype.loadTile!="function")throw new Error(`TileProvider "${St}" class must have a loadTile method`);return Jn.set(St,Tn),Tn}).finally(()=>{rn.delete(St)});return rn.set(St,js),js})(it.name,it.url).then(St=>{const Ht=new St(it.options);return this.getWorkerSource(We,{type:it.type,source:it.source,scope:it.scope},Ht),Ht.load&&it.request?Ht.load({request:it.request}):null}).then(St=>gt(null,St)).catch(St=>gt(St instanceof Error?St:new Error(typeof St=="string"?St:"Unknown error")))}loadWorkerSource(We,it,gt){try{this.self.importScripts(it.url),gt()}catch(St){gt(St)}}syncRTLPluginState(We,it,gt){if(c.fF.isParsed())gt(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(gt);else try{c.fF.setState(it);const St=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||St==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(St),c.fF.isParsed()?gt(null,!0):this.rtlPluginParsingListeners.push(gt))}catch(St){gt(St)}}setConfig(We,it){Object.assign(c.g,it)}getAvailableImages(We,it){this.availableImages[We]||(this.availableImages[We]={});let gt=this.availableImages[We][it];return gt||(gt=[]),gt}getAvailableModels(We,it){this.availableModels[We]||(this.availableModels[We]={});let gt=this.availableModels[We][it];return gt||(gt={}),gt}getLayerIndex(We,it){this.layerIndexes[We]||(this.layerIndexes[We]={});let gt=this.layerIndexes[We][it];return gt||(gt=this.layerIndexes[We][it]=new p,gt.scope=it),gt}getWorkerSource(We,it,gt){const{type:St,source:Ht,scope:ts}=it,Ms=this.workerSources;if(Ms[We]||(Ms[We]={}),Ms[We][ts]||(Ms[We][ts]={}),Ms[We][ts][St]||(Ms[We][ts][St]={}),this.isSpriteLoaded[We]||(this.isSpriteLoaded[We]={}),!Ms[We][ts][St][Ht]){const js={send:(Tn,vn,_r,Jr,ha,Mr)=>this.actor.send(Tn,vn,_r,We,ha,Mr),scheduler:this.actor.scheduler},Zs=this.workerSourceTypes[St];if(!Zs)throw new Error(`Unknown worker source type "${St}".`);Ms[We][ts][St][Ht]=new Zs({actor:js,layerIndex:this.getLayerIndex(We,ts),availableImages:this.getAvailableImages(We,ts),availableModels:this.getAvailableModels(We,ts),isSpriteLoaded:this.isSpriteLoaded[We][ts],tileProvider:gt,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return Ms[We][ts][St][Ht]}rasterizeImagesWorker(We,it,gt){const St=new Map;for(const[Ht,{image:ts,imageVariant:Ms}]of it.tasks.entries()){const js=this.imageRasterizer.rasterize(Ms,ts,it.scope,We);St.set(Ht,js)}gt(void 0,St)}removeRasterizedImages(We,it,gt){this.imageRasterizer.removeImagesFromCacheByIds(it.imageIds,it.scope,We),gt()}enforceCacheSizeLimit(We,it){c.fH(it)}getWorkerPerformanceMetrics(We,it,gt){gt(void 0,void 0)}}return c.fE(self)&&(self.worker=new ea(self)),ea}),i(["./shared"],function(o){var c="3.22.0";const d={create:"create",load:"load",fullLoad:"fullLoad"},u={mark(R){performance.mark(R)},measure(R,w,A){performance.measure(R,w,A)}};function h(R){const w=R.name.split("?")[0];return o.a(w)&&w.includes("mapbox-gl.js")?"javascript":o.a(w)&&w.includes("mapbox-gl.css")?"css":o.b(w)?"fontRange":o.c(w)?"sprite":o.i(w)?"style":o.d(w)?"tilejson":"other"}var m,p={},x=function(){if(m)return p;function R(F){return!w(F)}function w(F){return typeof window>"u"||typeof document>"u"?"not a browser":function(){if(!("Worker"in window&&"Blob"in window&&"URL"in window))return!1;var Z,X,ae=new Blob([""],{type:"text/javascript"}),pe=URL.createObjectURL(ae);try{X=new Worker(pe),Z=!0}catch{Z=!1}return X&&X.terminate(),URL.revokeObjectURL(pe),Z}()?function(){var Z=document.createElement("canvas");Z.width=Z.height=1;var X=Z.getContext("2d");if(!X)return!1;var ae=X.getImageData(0,0,1,1);return ae&&ae.width===Z.width}()?(A[V=F&&F.failIfMajorPerformanceCaveat]===void 0&&(A[V]=function(Z){var X,ae=function(pe){var ke=document.createElement("canvas"),Me=Object.create(R.webGLContextAttributes);return Me.failIfMajorPerformanceCaveat=pe,ke.getContext("webgl2",Me)}(Z);if(!ae)return!1;try{X=ae.createShader(ae.VERTEX_SHADER)}catch{return!1}return!(!X||ae.isContextLost())&&(ae.shaderSource(X,"void main() {}"),ae.compileShader(X),ae.getShaderParameter(X,ae.COMPILE_STATUS)===!0)}(V)),A[V]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var V}m=1,p.supported=R,p.notSupportedReason=w;var A={};return R.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},p}();function y(R,w,A){const F=document.createElement(R);return w!=null&&(F.className=w),A&&A.appendChild(F),F}function g(R,w,A){const F=document.createElementNS("http://www.w3.org/2000/svg",R);for(const V of Object.keys(w))F.setAttributeNS(null,V,String(w[V]));return A&&A.appendChild(F),F}const b=typeof document<"u"?document.documentElement&&document.documentElement.style:null,v=b&&b.userSelect!==void 0?"userSelect":"WebkitUserSelect";let k;function C(){b&&v&&(k=b[v],b[v]="none")}function T(){b&&v&&(b[v]=k)}function M(R){R.preventDefault(),R.stopPropagation(),window.removeEventListener("click",M,!0)}function P(){window.addEventListener("click",M,!0),window.setTimeout(()=>{window.removeEventListener("click",M,!0)},0)}function L(R,w){const A=R.getBoundingClientRect();return $(R,A,w)}function I(R,w){const A=R.getBoundingClientRect(),F=[];for(let V=0;Vthis._skuTokenExpiresAt}transformRequest(w,A){return this._transformRequestFn&&this._transformRequestFn(w,A)||{url:w}}normalizeStyleURL(w,A){if(!o.e(w))return w;const F=ee(w);return F.params.push(`sdk=js-${c}`),F.path=`/styles/v1${F.path}`,this._makeAPIURL(F,this._customAccessToken||A)}normalizeGlyphsURL(w,A){if(!o.e(w))return w;const F=ee(w);return F.path=`/fonts/v1${F.path}`,this._makeAPIURL(F,this._customAccessToken||A)}normalizeModelURL(w,A){if(!o.e(w))return w;const F=ee(w);return F.path=`/models/v1${F.path}`,this._makeAPIURL(F,this._customAccessToken||A)}normalizeSourceURL(w,A,F,V){if(!o.e(w))return w;const Z=ee(w);return Z.path=`/v4/${Z.authority}.json`,Z.params.push("secure"),F&&Z.params.push(`language=${F}`),V&&Z.params.push(`worldview=${V}`),this._makeAPIURL(Z,this._customAccessToken||A)}normalizeIconsetURL(w,A){const F=ee(w);return o.e(w)?(F.path=`/styles/v1${F.path}/iconset.pbf`,this._makeAPIURL(F,this._customAccessToken||A)):J(F)}normalizeSpriteURL(w,A,F,V){const Z=ee(w);return o.e(w)?(Z.path=`/styles/v1${Z.path}/sprite${A}${F}`,this._makeAPIURL(Z,this._customAccessToken||V)):(Z.path+=`${A}${F}`,J(Z))}normalizeTileURL(w,A,F){if(this._isSkuTokenExpired()&&this._createSkuToken(),w&&!o.e(w))return w;const V=ee(w);V.path=V.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${A||F&&V.authority!=="raster"&&F===512?"@2x":""}${o.k.supported?".webp":"$1"}`),V.authority==="raster"?V.path=`/${o.g.RASTER_URL_PREFIX}${V.path}`:V.authority==="rasterarrays"?V.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${V.path}`:V.authority==="3dtiles"?V.path=`/${o.g.TILES3D_URL_PREFIX}${V.path}`:(V.path=V.path.replace(/^.+\/v4\//,"/"),V.path=`/${o.g.TILE_URL_VERSION}${V.path}`);const Z=this._customAccessToken||function(X){for(const ae of X){const pe=ae.match(/^access_token=(.*)$/);if(pe)return pe[1]}return null}(V.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&Z&&this._skuToken&&V.params.push(`sku=${this._skuToken}`),this._makeAPIURL(V,Z)}canonicalizeTileURL(w,A){const F=ee(w);if(!F.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!F.path.match(/\.[\w]+$/))return w;let V="mapbox://";F.path.match(/^\/raster\/v1\//)?V+=`raster/${F.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:F.path.match(/^\/rasterarrays\/v1\//)?V+=`rasterarrays/${F.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:V+=`tiles/${F.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let Z=F.params;return A&&(Z=Z.filter(X=>!X.match(/^access_token=/))),Z.length&&(V+=`?${Z.join("&")}`),V}canonicalizeTileset(w,A){const F=!!A&&o.e(A),V=[];for(const Z of w.tiles||[])o.f(Z)?V.push(this.canonicalizeTileURL(Z,F)):V.push(Z);return V}_makeAPIURL(w,A){const F="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",V=ee(o.g.API_URL);if(w.protocol=V.protocol,w.authority=V.authority,w.protocol==="http"){const Z=w.params.indexOf("secure");Z>=0&&w.params.splice(Z,1)}if(V.path!=="/"&&(w.path=`${V.path}${w.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return J(w);if(A=A||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!A)throw new Error(`An API access token is required to use Mapbox GL. ${F}`);if(A[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${F}`)}return w.params=w.params.filter(Z=>Z.indexOf("access_token")===-1),w.params.push(`access_token=${A||""}`),J(w)}}const K=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function ee(R){const w=R.match(K);if(!w)throw new Error("Unable to parse URL object");return{protocol:w[1],authority:w[2],path:w[3]||"/",params:w[4]?w[4].split("&"):[]}}function J(R){const w=R.params.length?`?${R.params.join("&")}`:"";return`${R.protocol}://${R.authority}${R.path}${w}`}const le="mapbox.eventData";function ue(R){if(!R)return null;const w=R.split(".");if(!w||w.length!==3)return null;try{return JSON.parse(o.l(w[1]))}catch{return null}}function oe(R){return!(!o.g.EVENTS_URL||!R&&!o.g.ACCESS_TOKEN)}class ie{constructor(w){this.type=w,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(w){const A=ue(o.g.ACCESS_TOKEN);let F="";return F=A&&A.u?o.j(A.u):o.g.ACCESS_TOKEN||"",w?`${le}.${w}:${F}`:`${le}:${F}`}fetchEventData(){const w=o.s("localStorage"),A=this.getStorageKey(),F=this.getStorageKey("uuid"),V=this.getStorageKey("uuidTimestamp");if(w)try{const Z=localStorage.getItem(A);Z&&(this.eventData=JSON.parse(Z));const X=localStorage.getItem(F);X&&(this.anonId=X);const ae=localStorage.getItem(V);ae&&(this.anonIdTimestamp=Number(ae));const pe=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(A,JSON.stringify(this.eventData)),X&&localStorage.setItem(V,X.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(w){}postEvent(w,A,F,V){if(!o.g.EVENTS_URL)return;const Z=ee(o.g.EVENTS_URL);Z.params.push(`access_token=${V||o.g.ACCESS_TOKEN||""}`);const X={event:this.type,created:new Date(w).toISOString()},ae=A?Object.assign(X,A):X,pe={url:J(Z),headers:{"Content-Type":"text/plain"},body:JSON.stringify([ae])};this.pendingRequest=o.p(pe,ke=>{this.pendingRequest=null,F(ke),this.saveEventData(),this.processRequests(V)})}queueRequest(w,A){this.queue.push(w),this.processRequests(A)}}class de extends ie{constructor(w){super("metrics"),w&&(this.data=w)}postMetricsEvent(w){if(!oe(w))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const A=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:A},w)}processRequests(w){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:A,payload:F}=this.queue.shift();this.postEvent(A,F,()=>{},w)}}const we=new class extends ie{constructor(R){super("appUserTurnstile"),this._customAccessToken=R}postTurnstileEvent(R,w){oe(w)&&Array.isArray(R)&&R.some(A=>o.e(A)||o.f(A))&&this.queueRequest(Date.now(),w)}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const w=ue(o.g.ACCESS_TOKEN),A=w?w.u:o.g.ACCESS_TOKEN;let F=A!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),F=!0);const V=this.queue.shift();if(this.eventData.lastSuccess){const Z=new Date(this.eventData.lastSuccess),X=new Date(V),ae=(V-this.eventData.lastSuccess)/864e5;F=F||ae>=1||ae<-1||Z.getDate()!==X.getDate()}else F=!0;F?this.postEvent(V,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:q,"enabled.telemetry":!1,userId:this.anonId},Z=>{Z||(this.eventData.lastSuccess=V,this.eventData.tokenU=A)},R):this.processRequests()}},je=we.postTurnstileEvent.bind(we),xe=new class extends ie{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(R,w,A,F){this.skuToken=w,this.errorCb=F,o.g.EVENTS_URL&&(A||o.g.ACCESS_TOKEN?this.queueRequest({id:R,timestamp:Date.now()},A):this.errorCb(new Error(W)))}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{id:w,timestamp:A}=this.queue.shift();w&&this.success[w]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(A,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:q,skuToken:this.skuToken,userId:this.anonId},F=>{F?this.errorCb(F):w&&(this.success[w]=!0)},R))}remove(){this.errorCb=null}},fe=xe.postMapLoadEvent.bind(xe),Se=new class extends ie{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(R){let w=this.mapInstanceIdMap.get(R);return w||(w=o.u(),this.mapInstanceIdMap.set(R,w)),w}getEventId(R){const w=this.eventIdPerMapInstanceMap.get(R)||0;return this.eventIdPerMapInstanceMap.set(R,w+1),w}postStyleLoadEvent(R,w){const{map:A,style:F,importedStyles:V}=w;if(!oe(R))return;const Z=this.getMapInstanceId(A),X={mapInstanceId:Z,eventId:this.getEventId(Z),style:F};V.length&&(X.importedStyles=V),this.queueRequest({timestamp:Date.now(),payload:X},R)}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:w,payload:A}=this.queue.shift();this.postEvent(w,A,()=>{},R)}},Ee=Se.postStyleLoadEvent.bind(Se),Le=new de({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),De=Le.postMetricsEvent.bind(Le),Be=new de({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),Ne=Be.postMetricsEvent.bind(Be),Ge=new class extends ie{constructor(){super("gljs.performance")}postPerformanceEvent(R,w){oe(R)&&this.queueRequest({timestamp:Date.now(),performanceData:w},R)}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:w,performanceData:A}=this.queue.shift(),F=function(V){const Z=performance.getEntriesByType("resource"),X=performance.getEntriesByType("mark"),ae=function(tt){const ct={};if(tt){for(const ot in tt)if(ot!=="other")for(const wt of tt[ot]){const _t=`${ot}ResolveRangeMin`,Rt=`${ot}ResolveRangeMax`,$t=`${ot}RequestCount`,kt=`${ot}RequestCachedCount`;ct[_t]=Math.min(ct[_t]||1/0,wt.startTime),ct[Rt]=Math.max(ct[Rt]||-1/0,wt.responseEnd);const ks=Jt=>{ct[Jt]===void 0&&(ct[Jt]=0),++ct[Jt]};wt.transferSize!==void 0&&wt.transferSize===0&&ks(kt),ks($t)}}return ct}(function(tt,ct){const ot={};if(tt)for(const wt of tt){const _t=ct(wt);ot[_t]===void 0&&(ot[_t]=[]),ot[_t].push(wt)}return ot}(Z,h)),pe=window.devicePixelRatio,ke=navigator.connection||navigator.mozConnection||navigator.webkitConnection,Me=ke?ke.effectiveType:void 0,Ke={counters:[],metadata:[],attributes:[]},He=(tt,ct,ot)=>{ot!=null&&tt.push({name:ct,value:ot.toString()})};for(const tt in ae)He(Ke.counters,tt,ae[tt]);if(V.interactionRange[0]!==1/0&&V.interactionRange[1]!==-1/0&&(He(Ke.counters,"interactionRangeMin",V.interactionRange[0]),He(Ke.counters,"interactionRangeMax",V.interactionRange[1])),X)for(const tt of Object.values(d)){const ct=X.find(ot=>ot.name===tt);ct&&He(Ke.counters,tt,ct.startTime)}return He(Ke.counters,"visibilityHidden",V.visibilityHidden),He(Ke.attributes,"style",function(tt){if(tt)for(const ct of tt){const ot=ct.name.split("?")[0];if(o.i(ot)){const wt=ot.split("/").slice(-2);if(wt.length===2)return`mapbox://styles/${wt[0]}/${wt[1]}`}}}(Z)),He(Ke.attributes,"terrainEnabled",V.terrainEnabled?"true":"false"),He(Ke.attributes,"fogEnabled",V.fogEnabled?"true":"false"),He(Ke.attributes,"projection",V.projection),He(Ke.attributes,"zoom",V.zoom),He(Ke.metadata,"devicePixelRatio",pe),He(Ke.metadata,"connectionEffectiveType",Me),He(Ke.metadata,"navigatorUserAgent",navigator.userAgent),He(Ke.metadata,"screenWidth",window.screen.width),He(Ke.metadata,"screenHeight",window.screen.height),He(Ke.metadata,"windowWidth",window.innerWidth),He(Ke.metadata,"windowHeight",window.innerHeight),He(Ke.metadata,"mapWidth",V.width/pe),He(Ke.metadata,"mapHeight",V.height/pe),He(Ke.metadata,"webglRenderer",V.renderer),He(Ke.metadata,"webglVendor",V.vendor),He(Ke.metadata,"sdkVersion",c),He(Ke.metadata,"sdkIdentifier","mapbox-gl-js"),Ke}(A);for(const V of F.metadata);for(const V of F.counters);for(const V of F.attributes);this.postEvent(w,F,()=>{},R)}},_e=Ge.postPerformanceEvent.bind(Ge),Oe=new class extends ie{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(R,w,A,F){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const V=ee(o.g.API_URL+o.g.SESSION_PATH);V.params.push(`sku=${w||""}`),V.params.push(`access_token=${F||o.g.ACCESS_TOKEN||""}`);const Z={url:J(V),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(Z,X=>{this.pendingRequest=null,A(X),this.saveEventData(),this.processRequests(F)})}getSessionAPI(R,w,A,F){this.skuToken=w,this.errorCb=F,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(A||o.g.ACCESS_TOKEN?this.queueRequest({id:R,timestamp:Date.now()},A):this.errorCb(new Error(W)))}processRequests(R){if(this.pendingRequest||this.queue.length===0)return;const{id:w,timestamp:A}=this.queue.shift();w&&this.success[w]||this.getSession(A,this.skuToken,F=>{F?this.errorCb(F):w&&(this.success[w]=!0)},R)}remove(){this.errorCb=null}},Ae=Oe.getSessionAPI.bind(Oe),Xe=new Set;function Ue(R,w){w?Xe.add(R):Xe.delete(R)}class Ze{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,A){this._updatedSourceCaches[w]=A,this.setDirty()}discardSourceCacheUpdate(w){delete this._updatedSourceCaches[w]}updateLayer(w){const A=w.scope;this._updatedLayers[A]=this._updatedLayers[A]||new Set,this._updatedLayers[A].add(w.id),this.setDirty()}removeLayer(w){const A=w.scope;this._removedLayers[A]=this._removedLayers[A]||{},this._updatedLayers[A]=this._updatedLayers[A]||new Set,this._removedLayers[A][w.id]=w,this._updatedLayers[A].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 A in this._updatedLayers)w[A]=w[A]||{},w[A].updatedIds=Array.from(this._updatedLayers[A].values());for(const A in this._removedLayers)w[A]=w[A]||{},w[A].removedIds=Object.keys(this._removedLayers[A]);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,A){this._updatedImages[A]=this._updatedImages[A]||new Set,this._updatedImages[A].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 Qe(R){const{userImage:w}=R;return!!(w&&w.render&&w.render())&&(R.data.replace(new Uint8Array(w.data.buffer)),!0)}const Ye={workerUrl:"",workerClass:null,workerParams:void 0};function nt(R){return Ye.workerClass!=null?new Ye.workerClass:new self.Worker(Ye.workerUrl,Object.assign({name:R},Ye.workerParams))}const rt="mapboxgl_preloaded_worker_pool";class Fe{constructor(w){this.active={},this.name=w}acquire(w,A=Fe.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{A.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[rt]}numActive(){return Object.keys(this.active).length}}Fe.workerCount=2;class dt{constructor(w,A,F="Worker",V=Fe.workerCount){this.workerPool=w,this.actors=[],this.currentActor=0,this.id=o.r();const Z=this.workerPool.acquire(this.id,V);for(let X=0;X{this.ready=!0})}broadcast(w,A,F){o.t(this.actors,(V,Z)=>{V.send(w,A,Z)},F=F||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(w=>{w.remove()}),this.actors=[],this.workerPool.release(this.id)}}let Dt,pt;function zt(){return Dt||(Dt=new Fe),Dt}dt.Actor=o.A;class Gt 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 dt((pt||(pt=new Fe("ImageRasterizer")),pt),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 A=this.atlasTexture.get(w);A&&(A.destroy(),this.atlasTexture.delete(w))}addImageProvider(w,A){this.imageProviders.has(A)||this.imageProviders.set(A,new Map),this.imageProviders.get(A).set(w.id,w)}removeImageProvider(w,A){this.imageProviders.has(A)&&this.imageProviders.get(A).delete(w)}getPendingImageProviders(){const w=[];for(const A of this.imageProviders.values())for(const F of A.values())F.hasPendingRequests()&&w.push(F);return w}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new o.z),this._imageRasterizer}isLoaded(){for(const w of this.loaded.keys())if(!this.loaded.get(w))return!1;return!0}setLoaded(w,A){if(this.loaded.get(A)!==w&&(this.loaded.set(A,w),w)){for(const{ids:F,callback:V}of this.requestors)this._notify(F,A,V);this.requestors=[]}}hasImage(w,A){return!!this.getImage(w,A)}getImage(w,A){return this.images.get(A).get(w.toString())}addImage(w,A,F){if(this._validate(w,F)){this.images.get(A).set(w.toString(),F);const V=this.imageVersions.get(A),Z=V.get(w.toString())||0;V.set(w.toString(),Z+1)}}_validate(w,A){let F=!0;return this._validateStretch(A.stretchX,A.data&&A.data.width)||(this.fire(new o.B(new Error(`Image "${w.name}" has invalid "stretchX" value`))),F=!1),this._validateStretch(A.stretchY,A.data&&A.data.height)||(this.fire(new o.B(new Error(`Image "${w.name}" has invalid "stretchY" value`))),F=!1),this._validateContent(A.content,A)||(this.fire(new o.B(new Error(`Image "${w.name}" has invalid "content" value`))),F=!1),F}_validateStretch(w,A){if(!w)return!0;let F=0;for(const V of w){if(V[0]o.I.from(A))}getImageVersions(w){const A=this.imageVersions.get(w);if(A)return A}getImages(w,A,F){const V=[],Z=[],X=this.imageProviders.get(A);for(const Me of w){if(!Me.iconsetId){V.push(Me);continue}const Ke=X.get(Me.iconsetId);Ke&&(this.getImage(Me,A)?Z.push(Me):Ke.addPendingRequest(Me))}if(V.length===0)return void this._notify(Z,A,F);let ae=!0;const pe=!!this.loaded.get(A),ke=this.images.get(A);if(!pe)for(const Me of V)ke.has(Me.toString())||(ae=!1);pe||ae?this._notify(V,A,F):this.requestors.push({ids:V,scope:A,callback:F})}rasterizeImages(w,A){const F=new Map,{tasks:V,scope:Z}=w;for(const[X,ae]of V.entries()){const pe=this.getImage(ae.id,Z);pe&&F.set(X,{image:pe,imageVariant:ae})}this._rasterizeImages(Z,F,A)}_rasterizeImages(w,A,F){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:A,scope:w},F);else{const V=new Map;for(const[Z,{image:X,imageVariant:ae}]of A.entries())V.set(Z,this.imageRasterizer.rasterize(ae,X,w,0));F(void 0,V)}}getUpdatedImages(w){return this.updatedImages.get(w)||new Set}_notify(w,A,F){const V=this.images.get(A),Z=new Map;for(const X of w){if(!V.get(X.toString())){if(X.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:X.name}))}const ae=V.get(X.toString());if(!ae){o.w(`Image "${X.name}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);continue}const pe={data:ae.usvg?null:ae.data.clone(),pixelRatio:ae.pixelRatio,sdf:ae.sdf,usvg:ae.usvg,stretchX:ae.stretchX,stretchY:ae.stretchY,content:ae.content,hasRenderCallback:!!(ae.userImage&&ae.userImage.render)};ae.usvg&&Object.assign(pe,{width:ae.icon.usvg_tree.width,height:ae.icon.usvg_tree.height}),Z.set(o.I.toString(X),pe)}F(null,{images:Z,versions:this.getImageVersions(A)})}getPixelSize(w){const{width:A,height:F}=this.atlasImage.get(w);return{width:A,height:F}}getPattern(w,A,F){const V=w.toString(),Z=this.patterns.get(A),X=Z.get(V),ae=this.getImage(w,A);if(!ae)return null;if(X){if(X.position.version===ae.version)return X.position;X.position.version=ae.version}else{if(ae.usvg&&!ae.data){const pe=this.getPatternInFlightId(V,A);if(this.patternsInFlight.has(pe))return null;this.patternsInFlight.add(pe);const ke=new o.D(w).scaleSelf(o.o.devicePixelRatio),Me=new Map([[ke.toString(),{image:ae,imageVariant:ke}]]);return this._rasterizeImages(A,Me,(Ke,He)=>this.storePatternImage(ke,A,ae,F,He)),null}this.storePattern(w,A,ae)}return this._updatePatternAtlas(A,F),Z.get(V).position}getPatternInFlightId(w,A){return o.F(w,A)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(w,A,F,V,Z){const X=w.toString(),ae=Z?Z.get(X):void 0;ae&&(F.data=ae,this.storePattern(w.id,A,F),this._updatePatternAtlas(A,V),this.patternsInFlight.delete(this.getPatternInFlightId(w.id.toString(),A)))}storePattern(w,A,F){const V={w:F.data.width+2*o.G,h:F.data.height+2*o.G,x:0,y:0},Z=new o.H(V,F,o.G);this.patterns.get(A).set(w.toString(),{bin:V,position:Z})}destroyAtlasTextures(){for(const w of this.atlasTexture.values())w&&w.destroy();this.atlasTexture.clear()}bind(w,A){const F=w.gl;let V=this.atlasTexture.get(A);V?this.dirty&&(V.update(this.atlasImage.get(A)),this.dirty=!1):(V=new o.T(w,this.atlasImage.get(A),F.RGBA8),this.atlasTexture.set(A,V)),V.bind(F.LINEAR,F.CLAMP_TO_EDGE)}_updatePatternAtlas(w,A){const F=this.patterns.get(w),V=Array.from(F.values()).map(({bin:ke})=>ke),{w:Z,h:X}=o.J(V),ae=this.atlasImage.get(w);ae.resize({width:Z||1,height:X||1});const pe=this.images.get(w);for(const[ke,{bin:Me,position:Ke}]of F.entries()){let He=Ke.padding;const tt=Me.x+He,ct=Me.y+He,ot=pe.get(ke).data,wt=ot.width,_t=ot.height;He=He>1?He-1:He,o.q.copy(ot,ae,{x:0,y:0},{x:tt,y:ct},{width:wt,height:_t},A),o.q.copy(ot,ae,{x:0,y:_t-He},{x:tt,y:ct-He},{width:wt,height:He},A),o.q.copy(ot,ae,{x:0,y:0},{x:tt,y:ct+_t},{width:wt,height:He},A),o.q.copy(ot,ae,{x:wt-He,y:0},{x:tt-He,y:ct},{width:He,height:_t},A),o.q.copy(ot,ae,{x:0,y:0},{x:tt+wt,y:ct},{width:He,height:_t},A),o.q.copy(ot,ae,{x:wt-He,y:_t-He},{x:tt-He,y:ct-He},{width:He,height:He},A),o.q.copy(ot,ae,{x:0,y:_t-He},{x:tt+wt,y:ct-He},{width:He,height:He},A),o.q.copy(ot,ae,{x:0,y:0},{x:tt+wt,y:ct+_t},{width:He,height:He},A),o.q.copy(ot,ae,{x:wt-He,y:0},{x:tt-He,y:ct+_t},{width:He,height:He},A)}this.dirty=!0}beginFrame(){for(const w of this.images.keys())this.callbackDispatchedThisFrame.set(w,new Set)}dispatchRenderCallbacks(w,A){const F=this.images.get(A);for(const V of w){if(this.callbackDispatchedThisFrame.get(A).has(V.toString()))continue;this.callbackDispatchedThisFrame.get(A).add(V.toString());const Z=F.get(V.toString());Qe(Z)&&this.updateImage(V,A,Z)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function qs(R){const w=R.value,A=R.valueSpec,F=R.style,V=R.styleSpec,Z=R.key,X=R.arrayElementValidator||Hr;if(!Array.isArray(w))return[new o.V(Z,w,`array expected, ${o.M(w)} found`)];if(A.length&&w.length!==A.length)return[new o.V(Z,w,`array length ${A.length} expected, length ${w.length} found`)];if(A["min-length"]&&w.lengthV)return[new o.V(w,A,`${A} is greater than the maximum value ${V}`)]}return[]}function Bt(R){const w=R.key,A=R.value;if(!o.K(A))return[new o.V(w,A,`object expected, ${o.M(A)} found`)];const F=R.valueSpec,V=o.L(A.type);let Z,X,ae,pe={};const ke=V!=="categorical"&&A.property===void 0,Me=!ke,Ke=function(ot){const wt=ot.stops;return Array.isArray(wt)&&Array.isArray(wt[0])&&o.K(wt[0][0])}(A),He=mr({key:R.key,value:R.value,valueSpec:R.styleSpec.function,style:R.style,styleSpec:R.styleSpec,objectElementValidators:{stops:function(ot){if(V==="identity")return[new o.V(ot.key,ot.value,'identity function may not have a "stops" property')];let wt=[];const _t=ot.value;return wt=wt.concat(qs({key:ot.key,value:_t,valueSpec:ot.valueSpec,style:ot.style,styleSpec:ot.styleSpec,arrayElementValidator:tt})),Array.isArray(_t)&&_t.length===0&&wt.push(new o.V(ot.key,_t,"array must have at least one stop")),wt},default:function(ot){return Hr({key:ot.key,value:ot.value,valueSpec:F,style:ot.style,styleSpec:ot.styleSpec})}}});return V==="identity"&&ke&&He.push(new o.V(R.key,R.value,'missing required property "property"')),V==="identity"||A.stops||He.push(new o.V(R.key,R.value,'missing required property "stops"')),V==="exponential"&&F.expression&&!o.O(F)&&He.push(new o.V(R.key,R.value,"exponential functions not supported")),R.styleSpec.$version>=8&&(Me&&!o.Q(F)?He.push(new o.V(R.key,R.value,"property functions not supported")):ke&&!o.S(F)&&He.push(new o.V(R.key,R.value,"zoom functions not supported"))),V!=="categorical"&&!Ke||A.property!==void 0||He.push(new o.V(R.key,R.value,'"property" property is required')),He;function tt(ot){let wt=[];const _t=ot.value,Rt=ot.key;if(!Array.isArray(_t))return[new o.V(Rt,_t,`array expected, ${o.M(_t)} found`)];if(_t.length!==2)return[new o.V(Rt,_t,`array length 2 expected, length ${_t.length} found`)];if(Ke){if(!o.K(_t[0]))return[new o.V(Rt,_t,`object expected, ${o.M(_t[0])} found`)];const $t=_t[0];if($t.zoom===void 0)return[new o.V(Rt,_t,"object stop key must have zoom")];if($t.value===void 0)return[new o.V(Rt,_t,"object stop key must have value")];const kt=o.L($t.zoom);if(typeof kt!="number")return[new o.V(Rt,$t.zoom,"stop zoom values must be numbers")];if(ae&&ae>kt)return[new o.V(Rt,$t.zoom,"stop zoom values must appear in ascending order")];kt!==ae&&(ae=kt,X=void 0,pe={}),wt=wt.concat(mr({key:`${Rt}[0]`,value:_t[0],valueSpec:{zoom:{}},style:ot.style,styleSpec:ot.styleSpec,objectElementValidators:{zoom:As,value:ct}}))}else wt=wt.concat(ct({key:`${Rt}[0]`,value:_t[0],style:ot.style,styleSpec:ot.styleSpec},_t));return o.U(o.W(_t[1]))?wt.concat([new o.V(`${Rt}[1]`,_t[1],"expressions are not allowed in function stops.")]):wt.concat(Hr({key:`${Rt}[1]`,value:_t[1],valueSpec:F,style:ot.style,styleSpec:ot.styleSpec}))}function ct(ot,wt){const _t=o.M(ot.value),Rt=o.L(ot.value),$t=ot.value!==null?ot.value:wt;if(Z){if(_t!==Z)return[new o.V(ot.key,$t,`${_t} stop domain type must match previous stop domain type ${Z}`)]}else Z=_t;if(_t!=="number"&&_t!=="string"&&_t!=="boolean"&&typeof Rt!="number"&&typeof Rt!="string"&&typeof Rt!="boolean")return[new o.V(ot.key,$t,"stop domain value must be a number, string, or boolean")];if(_t!=="number"&&V!=="categorical"){let kt=`number expected, ${_t} found`;return o.Q(F)&&V===void 0&&(kt+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V(ot.key,$t,kt)]}return V!=="categorical"||_t!=="number"||typeof Rt=="number"&&isFinite(Rt)&&Math.floor(Rt)===Rt?V!=="categorical"&&_t==="number"&&typeof Rt=="number"&&typeof X=="number"&&X!==void 0&&Rtnew o.V(`${R.key}${F.key}`,R.value,F.message));const A=w.value.expression||w.value._styleExpression.expression;if(R.expressionContext==="property"&&R.propertyKey==="text-font"&&!A.outputDefined())return[new o.V(R.key,R.value,`Invalid data expression for "${R.propertyKey}". Output values must be contained as literals within the expression.`)];if(R.expressionContext==="property"&&R.propertyType==="layout"&&!o.$(A))return[new o.V(R.key,R.value,'"feature-state" data expressions are not supported with layout properties.')];if(R.expressionContext==="filter")return Is(A,R);if(R.expressionContext==="appearance")return jt(A,R);if(R.expressionContext&&R.expressionContext.indexOf("cluster")===0){if(!o.Z(A,["zoom","feature-state"]))return[new o.V(R.key,R.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(R.expressionContext==="cluster-initial"&&!o._(A))return[new o.V(R.key,R.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Is(R,w){const A=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(w.valueSpec&&w.valueSpec.expression)for(const V of w.valueSpec.expression.parameters)A.delete(V);if(A.size===0)return[];const F=[];return R instanceof o.a0&&A.has(R.name)?[new o.V(w.key,w.value,`["${R.name}"] expression is not supported in a filter for a ${w.object.type} layer with id: ${w.object.id}`)]:(R.eachChild(V=>{F.push(...Is(V,w))}),F)}function jt(R,w){const A=new Set;if(w.valueSpec&&w.valueSpec.expression)for(const V of w.valueSpec.expression.parameters)A.add(V);if(A.size===0)return[];const F=[];return R instanceof o.a0&&!A.has(R.name)?[new o.V(w.key,w.value,`["${R.name}"] is not an allowed parameter`)]:(R.eachChild(V=>{F.push(...jt(V,w))}),F)}function Qs(R){const w=R.key,A=R.value,F=R.valueSpec,V=[];return Array.isArray(F.values)?F.values.indexOf(o.L(A))===-1&&V.push(new o.V(w,A,`expected one of [${F.values.join(", ")}], ${JSON.stringify(A)} found`)):Object.keys(F.values).indexOf(o.L(A))===-1&&V.push(new o.V(w,A,`expected one of [${Object.keys(F.values).join(", ")}], ${JSON.stringify(A)} found`)),V}function cn(R){return o.a4(o.W(R.value))?At(Object.assign({},R,{expressionContext:"filter",valueSpec:R.styleSpec[`filter_${R.layerType||"fill"}`]})):qt(R)}function qt(R){const w=R.value,A=R.key;if(!Array.isArray(w))return[new o.V(A,w,`array expected, ${o.M(w)} found`)];if(w.length<1)return[new o.V(A,w,"filter array must have at least 1 element")];const F=R.styleSpec;let V=Qs({key:`${A}[0]`,value:w[0],valueSpec:F.filter_operator});const Z=()=>{w.length>=2&&(o.a2(w[1])||V.push(new o.V(`${A}[1]`,w[1],`string expected, ${o.M(w[1])} found`)));for(let X=2;X":case">=":w.length>=2&&o.L(w[1])==="$type"&&V.push(new o.V(A,w,`"$type" cannot be use with operator "${w[0]}"`)),w.length!==3&&V.push(new o.V(A,w,`filter array for operator "${w[0]}" must have 3 elements`)),Z();break;case"==":case"!=":w.length!==3&&V.push(new o.V(A,w,`filter array for operator "${w[0]}" must have 3 elements`)),Z();break;case"in":case"!in":Z();break;case"any":case"all":case"none":for(let X=1;X{ke in A&&w.push(new o.V(F,A[ke],`"${ke}" is prohibited for ref layers`))}),V.layers.forEach(ke=>{o.L(ke.id)===ae&&(pe=ke)}),pe?pe.ref?w.push(new o.V(F,A.ref,"ref cannot reference another ref layer")):X=o.L(pe.type):typeof ae=="string"&&w.push(new o.V(F,A.ref,`ref layer "${ae}" not found`))}else if(X!=="background"&&X!=="sky"&&X!=="slot")if(A.source)if(o.a2(A.source)){const pe=V.sources&&V.sources[A.source],ke=pe&&o.L(pe.type);pe?ke==="vector"&&X==="raster"?w.push(new o.V(F,A.source,`layer "${A.id}" requires a raster source`)):ke==="raster"&&X!=="raster"?w.push(new o.V(F,A.source,`layer "${A.id}" requires a vector source`)):ke!=="vector"||A["source-layer"]?ke==="raster-dem"&&X!=="hillshade"?w.push(new o.V(F,A.source,"raster-dem source can only be used with layer type 'hillshade'.")):ke!=="raster-array"||["raster","raster-particle"].includes(X)?X==="line"&&A.paint&&(A.paint["line-gradient"]||A.paint["line-trim-offset"])&&ke==="geojson"&&!pe.lineMetrics?w.push(new o.V(F,A,`layer "${A.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):X==="raster-particle"&&ke!=="raster-array"&&w.push(new o.V(F,A.source,`layer "${A.id}" requires a 'raster-array' source.`)):w.push(new o.V(F,A.source,"raster-array source can only be used with layer type 'raster'.")):w.push(new o.V(F,A,`layer "${A.id}" must specify a "source-layer"`)):w.push(new o.V(F,A.source,`source "${A.source}" not found`))}else w.push(new o.V(`${F}.source`,A.source,'"source" must be a string'));else w.push(new o.V(F,A,'missing required property "source"'));return w=w.concat(mr({key:F,value:A,valueSpec:Z.layer,style:R.style,styleSpec:R.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Hr({key:`${F}.type`,value:A.type,valueSpec:Z.layer.type,style:R.style,styleSpec:R.styleSpec,object:A,objectKey:"type"}),filter:pe=>cn(Object.assign({layerType:X},pe)),layout:pe=>mr({layer:A,key:pe.key,value:pe.value,valueSpec:{},style:pe.style,styleSpec:pe.styleSpec,objectElementValidators:{"*":ke=>sn(Object.assign({layerType:X},ke))}}),paint:pe=>mr({layer:A,key:pe.key,value:pe.value,valueSpec:{},style:pe.style,styleSpec:pe.styleSpec,objectElementValidators:{"*":ke=>Ls(Object.assign({layerType:X,layer:A},ke))}}),appearances(pe){const ke=qs({key:pe.key,value:pe.value,valueSpec:pe.valueSpec,style:pe.style,styleSpec:pe.styleSpec,arrayElementValidator:He=>function(tt){const{key:ct,layer:ot,layerType:wt}=tt,_t=o.L(tt.value),Rt=o.L(_t.name),$t=o.L(_t.condition),kt=mr({key:ct,value:_t,valueSpec:tt.styleSpec.appearance,style:tt.style,styleSpec:tt.styleSpec,objectElementValidators:{condition:ks=>function(Jt){const ws=[];return ws.push(...At({key:Jt.key,value:Jt.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),ws}(Object.assign({layer:ot,layerType:wt},ks)),properties:ks=>function(Jt){const ws=[],{styleSpec:Vt,layer:Xt,layerType:ms}=Jt,Us=Vt[`paint_${ms}`],Cs=Vt[`layout_${ms}`],pn=Jt.object[Jt.objectKey];for(const an in pn){const Ln=an in Us?"paint":an in Cs?"layout":void 0;if(!Ln){ws.push(new o.V(Jt.key,an,`unknown property "${an}" for layer type "${ms}"`));continue}const $n=Object.assign({},Jt,{key:`${Jt.key}.${an}`,object:pn,objectKey:an,layer:Xt,layerType:ms,value:pn[an],valueSpec:Ln==="paint"?Us[an]:Cs[an]});ws.push(...Gs($n,Ln))}return ws}(Object.assign({layer:ot,layerType:wt},ks))}});return Rt!=="hidden"&&$t===void 0&&kt.push(new o.V(tt.key,"name",'Appearance with name different than "hidden" must have a condition')),kt}(Object.assign({layerType:X,layer:A},He))}),Me=Array.isArray(pe.value)?pe.value:[],Ke=new Set;return Me.forEach((He,tt)=>{const ct=o.L(He.name);if(ct)if(Ke.has(ct)){const ot=o.L(A.id);ke.push(new o.V(pe.key,ct,`Duplicated appearance name "${ct}" for layer "${ot}"`))}else Ke.add(ct)}),ke}}})),w}function nn({key:R,value:w}){return o.a2(w)?[]:[new o.V(R,w,`string expected, ${o.M(w)} found`)]}const tn={promoteId:function R({key:w,value:A}){if(o.a2(A))return nn({key:w,value:A});if(Array.isArray(A)){const V=[],Z=o.W(A),X=o.X(Z);return X.result==="error"?(X.value.forEach(ae=>{V.push(new o.V(`${w}${ae.key}`,null,`${ae.message}`))}),V):(o.Z(X.value.expression,["zoom","heatmap-density","line-progress","raster-value","sky-radial-progress","accumulated","is-supported-script","pitch","distance-from-center","measure-light","raster-particle-speed"])||V.push(new o.V(`${w}`,null,"promoteId expression should be only feature dependent")),V)}if(!o.K(A))return[new o.V(w,A,`string, expression or object expected, "${o.M(A)}" found`)];const F=[];for(const V in A)F.push(...R({key:`${w}.${V}`,value:A[V]}));return F}};function _n(R){const w=R.value,A=R.key,F=R.styleSpec,V=R.style;if(!o.K(w))return[new o.V(A,w,`object expected, ${o.M(w)} found`)];if(!("type"in w))return[new o.V(A,w,'"type" is required')];const Z=o.L(w.type);let X=[];switch(["vector","raster","raster-dem","raster-array"].includes(Z)&&("url"in w||"tiles"in w||X.push(new o.a5(A,w,'Either "url" or "tiles" is required.'))),Z){case"vector":case"raster":case"raster-dem":case"raster-array":return X=X.concat(mr({key:A,value:w,valueSpec:F[`source_${Z.replace("-","_")}`],style:R.style,styleSpec:F,objectElementValidators:tn})),X;case"geojson":if(X=mr({key:A,value:w,valueSpec:F.source_geojson,style:V,styleSpec:F,objectElementValidators:tn}),"cluster"in w&&"clusterProperties"in w){if(!o.K(w.clusterProperties))return[new o.V(`${A}.clusterProperties`,w,`object expected, ${o.M(w)} found`)];for(const ae in w.clusterProperties){const pe=w.clusterProperties[ae];if(!Array.isArray(pe))return[new o.V(`${A}.clusterProperties.${ae}`,pe,"array expected")];const[ke,Me]=pe,Ke=typeof ke=="string"?[ke,["accumulated"],["get",ae]]:ke;X.push(...At({key:`${A}.${ae}.map`,value:Me,expressionContext:"cluster-map"})),X.push(...At({key:`${A}.${ae}.reduce`,value:Ke,expressionContext:"cluster-reduce"}))}}return X;case"video":return mr({key:A,value:w,valueSpec:F.source_video,style:V,styleSpec:F});case"image":return mr({key:A,value:w,valueSpec:F.source_image,style:V,styleSpec:F});case"canvas":return[new o.V(A,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return Qs({key:`${A}.type`,value:w.type,valueSpec:{values:Cn(F)}})}}function Cn(R){return R.source.reduce((w,A)=>{const F=R[A];return F.type.type==="enum"&&(w=w.concat(Object.keys(F.type.values||{}))),w},[])}function Un(R){const w=R.value,A=R.styleSpec,F=A.light,V=R.style;if(w===void 0)return[];if(!o.K(w))return[new o.V("light",w,`object expected, ${o.M(w)} found`)];let Z=[];for(const X in w){const ae=X.match(/^(.*)-transition$/),pe=X.match(/^(.*)-use-theme$/);Z=Z.concat(pe&&F[pe[1]]?Hr({key:X,value:w[X],valueSpec:{type:"string"},style:V,styleSpec:A}):ae&&F[ae[1]]&&F[ae[1]].transition?Hr({key:X,value:w[X],valueSpec:A.transition,style:V,styleSpec:A}):F[X]?Hr({key:X,value:w[X],valueSpec:F[X],style:V,styleSpec:A}):[new o.V(X,w[X],`unknown property "${X}"`)])}return Z}function Kr(R){const w=R.value;if(!w)return[];const A=R.key;if(!o.K(w))return[new o.V(A,w,`object expected, ${o.M(w)} found`)];let F=[];const V=R.styleSpec,Z=V["light-3d"],X=R.style,ae=R.style.lights;for(const Me of["type","id"])if(!(Me in w))return F=F.concat([new o.V(A,w,`missing property "${Me}"`)]),F;if(!o.a2(w.type))return F=F.concat([new o.V(`${A}.type`,w.type,"string expected")]),F;if(ae)for(let Me=0;Me[],array:qs,boolean:function(R){const w=R.value,A=R.key;return o.a1(w)?[]:[new o.V(A,w,`boolean expected, ${o.M(w)} found`)]},number:As,color:function({key:R,value:w}){return o.a2(w)?o.a3.parseCSSColor(w)===null?[new o.V(R,w,`color expected, "${w}" found`)]:[]:[new o.V(R,w,`color expected, ${o.M(w)} found`)]},enum:Qs,filter:cn,function:Bt,layer:Hs,object:mr,source:_n,model:o.a9,light:Un,"light-3d":Kr,terrain:jr,fog:Xs,string:nn,formatted:function(R){return nn(R).length===0?[]:At(R)},resolvedImage:function(R){return nn(R).length===0?[]:At(R)},projection:function(R){const w=R.value,A=R.styleSpec,F=A.projection,V=R.style;if(o.K(w)){let Z=[];for(const X in w)Z=Z.concat(Hr({key:X,value:w[X],valueSpec:F[X],style:V,styleSpec:A}));return Z}return o.a2(w)?[]:[new o.V("projection",w,`object or string expected, ${o.M(w)} found`)]},import:function(R){const w=R.key,{value:A,styleSpec:F}=R;if(!o.K(A))return[new o.V(w,A,"import must be an object")];const{data:V,...Z}=A;Object.defineProperty(Z,"__line__",{value:A.__line__,enumerable:!1});let X=mr(Object.assign({},R,{value:Z,valueSpec:F.import}));return o.L(Z.id)===""&&X.push(new o.V(`${R.key}.id`,Z,"import id can't be an empty string")),V&&(X=X.concat(rn(V,F,{key:`${R.key}.data`}))),X},iconset:function(R){const w=R.value,A=R.key,F=R.styleSpec,V=R.style;if(!o.K(w))return[new o.V(A,w,"object expected")];if(!w.type)return[new o.V(A,w,'"type" is required')];const Z=o.L(w.type);let X=[];if(X=X.concat(mr({key:A,value:w,valueSpec:F[`iconset_${Z}`],style:V,styleSpec:F})),function(ae,pe){return!(ae!=="source"||!pe.source)}(Z,w)){const ae=V.sources&&V.sources[w.source],pe=ae&&o.L(ae.type);ae?pe!=="raster-array"&&X.push(new o.V(A,w.source,`iconset cannot be used with a source of type ${String(pe)}, it only be used with a "raster-array" source type`)):X.push(new o.V(A,w.source,`source "${w.source}" not found`))}return X}};function Hr(R,w=!1){const A=R.value,F=R.valueSpec,V=R.styleSpec;if(F.expression){if(o.a6(o.L(A)))return Bt(R);if(o.U(o.W(A)))return At(R)}if(F.type&&Ba[F.type]){const Z=Ba[F.type](R);return w===!0&&Z.length>0&&Array.isArray(R.value)?At(R):Z}return mr(Object.assign({},R,{valueSpec:F.type?V[F.type]:F}))}function mr(R){const w=R.key,A=R.value,F=R.valueSpec||{},V=R.objectElementValidators||{},Z=R.style,X=R.styleSpec;if(!o.K(A))return[new o.V(w,A,`object expected, ${o.M(A)} found`)];let ae=[];for(const pe in A){const ke=pe.split(".")[0];let Me;V[ke]?Me=V[ke]:F[ke]?Me=Hr:V["*"]?Me=V["*"]:F["*"]&&(Me=Hr),Me?ae=ae.concat(Me({key:(w&&`${w}.`)+pe,value:A[pe],valueSpec:F[ke]||F["*"],style:Z,styleSpec:X,object:A,objectKey:pe},A)):ae.push(new o.a5(w,A[pe],`unknown property "${pe}"`))}for(const pe in F){if(V[pe])continue;const ke=F[pe];ke.required&&ke.default===void 0&&A[pe]===void 0&&ae.push(new o.V(w,A,`missing required property "${pe}"`))}return ae}function pr({key:R,value:w}){const A=nn({key:R,value:w});if(A.length)return A;const F=w;return F.indexOf("{fontstack}")===-1&&A.push(new o.V(R,w,'"glyphs" url must include a "{fontstack}" token')),F.indexOf("{range}")===-1&&A.push(new o.V(R,w,'"glyphs" url must include a "{range}" token')),A}function rn(R,w=o.a8,A={}){return mr({key:A.key||"",value:R,valueSpec:Object.assign(w.$root,{"*":{type:"*"}}),styleSpec:w,style:R,objectElementValidators:{glyphs:pr}})}function Jn(R,w=o.a8){return vn(rn(R,w))}const ea=R=>vn(_n(R)),_s=R=>vn(Un(R)),We=R=>vn(Kr(R)),it=R=>vn(jr(R)),gt=R=>vn(Xs(R)),St=R=>vn(function(w){const A=w.value,F=w.style,V=w.styleSpec,Z=V.snow;if(A===void 0)return[];if(!o.K(A))return[new o.V("snow",A,`object expected, ${o.M(A)} found`)];let X=[];for(const ae in A){const pe=ae.match(/^(.*)-transition$/);X=X.concat(pe&&Z[pe[1]]&&Z[pe[1]].transition?Hr({key:ae,value:A[ae],valueSpec:V.transition,style:F,styleSpec:V}):Z[ae]?Hr({key:ae,value:A[ae],valueSpec:Z[ae],style:F,styleSpec:V}):[new o.a5(ae,A[ae],`unknown property "${ae}"`)])}return X}(R)),Ht=R=>vn(function(w){const A=w.value,F=w.style,V=w.styleSpec,Z=V.rain;if(A===void 0)return[];if(!o.K(A))return[new o.V("rain",A,`object expected, ${o.M(A)} found`)];let X=[];for(const ae in A){const pe=ae.match(/^(.*)-transition$/);X=X.concat(pe&&Z[pe[1]]&&Z[pe[1]].transition?Hr({key:ae,value:A[ae],valueSpec:V.transition,style:F,styleSpec:V}):Z[ae]?Hr({key:ae,value:A[ae],valueSpec:Z[ae],style:F,styleSpec:V}):[new o.a5(ae,A[ae],`unknown property "${ae}"`)])}return X}(R)),ts=R=>vn(Hs(R)),Ms=R=>vn(cn(R)),js=R=>vn(Ls(R)),Zs=R=>vn(sn(R)),Tn=R=>vn(o.a9(R));function vn(R){return R.slice().sort((w,A)=>w.line&&A.line?w.line-A.line:0)}function _r(R,w){let A=!1;if(w&&w.length)for(const F of w)F instanceof o.a5?o.w(F.message):(R.fire(new o.B(new Error(F.message))),A=!0);return A}const Jr=o.a8.light;let ha;class Mr extends o.E{constructor(w,A="flat"){super(),this._transitionable=new o.aa(ha||(ha=new o.ab({anchor:new o.ac(Jr.anchor),position:new o.ad(Jr.position),color:new o.ac(Jr.color),intensity:new o.ac(Jr.intensity)}))),this.setLight(w,A),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(w,A,F={}){this._validate(_s,w,F)||(this._transitionable.setTransitionOrValue(w),this.id=A)}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,A,F){return(!F||F.validate!==!1)&&_r(this,w.call(Jn,Object.assign({value:A,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const Xr=o.a8.terrain;let Qt=class extends o.E{constructor(R,w,A,F,V){super(),this.scope=A,this._transitionable=new o.aa(new o.ab({source:new o.ac(Xr.source),exaggeration:new o.ac(Xr.exaggeration)}),A,F),this._transitionable.setTransitionOrValue(R,F),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=w,this.worldview=V}get(){return this._transitionable.serialize()}set(R,w){this._transitionable.setTransitionOrValue(R,w)}updateTransitions(R){this._transitioning=this._transitionable.transitioned(R,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(R){this.properties=this._transitioning.possiblyEvaluate(R)}getExaggeration(R){return this._transitioning.possiblyEvaluate(new o.ae(R,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const R=this._transitionable._values.exaggeration;if(!R)return null;const w=R.value.expression;if(!w)return null;let A=-1,F=-1,V=1;for(const Z of w.zoomStops)V=w.evaluate(new o.ae(Z,{worldview:this.worldview})),V>.01?(A=Z,F=-1):F=Z;return V<.01&&A>0&&F>A?[A,F]:null}isZoomDependent(){const R=this._transitionable._values.exaggeration;return R!=null&&R.value!=null&&R.value.expression!=null&&R.value.expression instanceof o.af}};const Zn=.05;function aa(R,w,A,F){const V=o.aj(45,65,A),[Z,X]=zr(R,F);let ae=1-Math.min(1,Math.exp((w-Z)/(X-Z)*-6));return ae*=ae*ae,ae=Math.min(1,1.00747*ae),ae*V*R.alpha}function zr(R,w){const A=.5/Math.tan(.5*w);return[R.range[0]+A,R.range[1]+A]}function Na(R,w,A,F,V){const Z=o.ah([],[w,A,F],V.mercatorFogMatrix);return aa(R,o.ai(Z),V.pitch,V._fov)}function oa(R,w,A,F,V,Z,X){const ae=[[A,F,0],[V,F,0],[V,Z,0],[A,Z,0]];let pe=Number.MAX_VALUE,ke=-Number.MAX_VALUE;for(const Me of ae){const Ke=o.ah([],Me,w),He=o.ai(Ke);pe=Math.min(pe,He),ke=Math.max(ke,He)}return[aa(R,pe,X.pitch,X._fov),aa(R,ke,X.pitch,X._fov)]}const ur=o.a8.fog;class ao extends o.E{constructor(w,A,F,V){super();const Z=new o.ab({range:new o.ac(ur.range),color:new o.ac(ur.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(ur["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(ur["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(ur["horizon-blend"]),"star-intensity":new o.ac(ur["star-intensity"]),"vertical-range":new o.ac(ur["vertical-range"])});this._transitionable=new o.aa(Z,F,new Map(V)),this.set(w,V),this._transitioning=this._transitionable.untransitioned(),this._transform=A,this.properties=new o.ak(Z),this.scope=F}get state(){const w=this._transform,A=w.projection.name==="globe",F=o.al(w.zoom),V=this.properties.get("range"),Z=[.5,3];return{range:A?[o.am(Z[0],V[0],F),o.am(Z[1],V[1],F)]:V,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(w,A,F={}){if(this._validate(gt,w,F))return;const V=Object.assign({},w);for(const Z of Object.keys(ur))V[Z]===void 0&&(V[Z]=ur[Z].default);this._options=V,this._transitionable.setTransitionOrValue(this._options,A)}getOpacity(w){if(!this._transform.projection.supportsFog)return 0;const A=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.aj(45,65,w))*A.a}getOpacityAtLatLng(w,A){return this._transform.projection.supportsFog?function(F,V,Z){const X=o.ag.fromLngLat(V),ae=Z.elevation?Z.elevation.getAtPointOrZero(X):0;return Na(F,X.x,X.y,ae,Z)}(this.state,w,A):0}getOpacityForTile(w){if(!this._transform.projection.supportsFog)return[1,1];const A=this._transform.calculateFogTileMatrix(w.toUnwrapped());return oa(this.state,A,0,0,o.an,o.an,this._transform)}getOpacityForBounds(w,A,F,V,Z){return this._transform.projection.supportsFog?oa(this.state,w,A,F,V,Z,this._transform):[1,1]}getFovAdjustedRange(w){return this._transform.projection.supportsFog?zr(this.state,w):[0,1]}isVisibleOnFrustum(w){if(!this._transform.projection.supportsFog)return!1;const A=[4,5,6,7];for(const F of A){const V=w.points[F];let Z;if(V[2]>=0)Z=V;else{const X=w.points[F-4];Z=o.ao(X,V,X[2]/(X[2]-V[2]))}if(Na(this.state,Z[0],Z[1],0,this._transform)>=Zn)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,A,F){return(!F||F.validate!==!1)&&_r(this,w.call(Jn,Object.assign({value:A,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let fo,Va,So,$a=class extends o.E{constructor(R,w,A,F){super();const V=fo||(fo=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(V,A,new Map(F)),this.set(R,F),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(V),this.scope=A}get state(){const R=this.properties.get("opacity"),w=this.properties.get("color"),A=this.properties.get("direction"),F=o.ap(A[0]),V=-Math.max(o.ap(A[1]),.01),Z=[Math.cos(F)*Math.cos(V),Math.sin(F)*Math.cos(V),Math.sin(V)],X=this.properties.get("vignette"),ae=this.properties.get("vignette-color");return ae.a=X,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(w.r,w.g,w.b,w.a*R),direction:Z,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:ae}}get(){return this._transitionable.serialize()}set(R,w,A={}){if(this._validate(St,R,A))return;const F=Object.assign({},R),V=o.a8.snow;for(const Z of Object.keys(V))F[Z]===void 0&&(F[Z]=V[Z].default);this._options=F,this._transitionable.setTransitionOrValue(this._options,w)}updateConfig(R){this._transitionable.setTransitionOrValue(this._options,new Map(R))}updateTransitions(R){this._transitioning=this._transitionable.transitioned(R,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(R){this.properties=this._transitioning.possiblyEvaluate(R)}_validate(R,w,A){return(!A||A.validate!==!1)&&_r(this,R.call(Jn,Object.assign({value:w,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},Gr=class extends o.E{constructor(R,w,A,F){super();const V=Va||(Va=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(V,A,new Map(F)),this.set(R,F),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(V),this.scope=A}get state(){const R=this.properties.get("opacity"),w=this.properties.get("color"),A=this.properties.get("direction"),F=o.ap(A[0]),V=-Math.max(o.ap(A[1]),.01),Z=[Math.cos(F)*Math.cos(V),Math.sin(F)*Math.cos(V),Math.sin(V)],X=this.properties.get("vignette-color");return X.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(w.r,w.g,w.b,w.a*R),direction:Z,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:X}}get(){return this._transitionable.serialize()}set(R,w,A={}){if(this._validate(Ht,R,A))return;const F=Object.assign({},R),V=o.a8.rain;for(const Z of Object.keys(V))F[Z]===void 0&&(F[Z]=V[Z].default);this._options=F,this._transitionable.setTransitionOrValue(this._options,w)}updateConfig(R){this._transitionable.setTransitionOrValue(this._options,new Map(R))}updateTransitions(R){this._transitioning=this._transitionable.transitioned(R,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(R){this.properties=this._transitioning.possiblyEvaluate(R)}_validate(R,w,A){return(!A||A.validate!==!1)&&_r(this,R.call(Jn,Object.assign({value:w,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class Qn extends o.E{constructor(w,A,F,V){super(),this.scope=F,this._options=w,this.properties=new o.ak(A),this._transitionable=new o.aa(A,F,new Map(V)),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,A){this._options=w,this._transitionable.setTransitionOrValue(w.properties,A)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const qa=()=>So||(So=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 xo;const Wo=()=>xo||(xo=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 Co{constructor(w,A,F){this.screenBounds=w,this.cameraPoint=F.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=A,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,F)}static createFromScreenPoints(w,A){let F,V;if(w instanceof o.P||typeof w[0]=="number"){const Z=o.P.convert(w);F=[Z],V=A.isPointAboveHorizon(Z)}else{const Z=o.P.convert(w[0]),X=o.P.convert(w[1]),ae=Z.add(X)._div(2);F=[Z,X],V=o.as(Z,X).every(pe=>A.isPointAboveHorizon(pe))&&A.isPointAboveHorizon(ae)}return new Co(F,V,A)}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 A=this.screenBounds[0],F=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],V=o.as(A,F,0,!1);return this.cameraPoint.y>F.y&&(this.cameraPoint.x>A.x&&this.cameraPoint.x=F.x?V[2]=this.cameraPoint:this.cameraPoint.x<=A.x&&(V[3]=this.cameraPoint)),o.at(V,w)}bufferedCameraGeometryGlobe(w){const A=this.screenBounds[0],F=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],V=o.as(A,F,w),Z=this.cameraPoint.clone(),X=+(Z.x>A.x)+ +(Z.x>F.x);switch(3*(+(Z.y>A.y)+ +(Z.y>F.y))+X){case 0:V[0]=Z,V[4]=Z.clone();break;case 1:V.splice(1,0,Z);break;case 2:V[1]=Z;break;case 3:V.splice(4,0,Z);break;case 5:V.splice(2,0,Z);break;case 6:V[3]=Z;break;case 7:V.splice(3,0,Z);break;case 8:V[2]=Z}return V}containsTile(w,A,F,V=0){const Z=Math.max(w.queryPadding,w.evaluateQueryRenderedFeaturePadding())/A._pixelsPerMercatorPixel+1,X=F?this._bufferedCameraMercator(Z,A):this._bufferedScreenMercator(Z,A);let ae=w.tileID.wrap+(X.unwrapped?V:0);const pe=X.polygon.map(wt=>o.au(w.tileTransform,wt,ae));if(!o.av(pe,0,0,o.an,o.an))return;ae=w.tileID.wrap+(this.screenGeometryMercator.unwrapped?V:0);const ke=this.screenGeometryMercator.polygon.map(wt=>o.aw(w.tileTransform,wt,ae)),Me=ke.map(wt=>new o.P(wt[0],wt[1])),Ke=A.getFreeCameraOptions().position||new o.ag(0,0,0),He=o.aw(w.tileTransform,Ke,ae),tt=ke.map(wt=>{const _t=o.ax(wt,wt,He);return o.ay(_t,_t),new o.az(He,_t)}),ct=o.aA(w,1,A.zoom)*A._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Me,tilespaceRays:tt,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,A){const F=Mu(w);if(this._screenRaycastCache[F])return this._screenRaycastCache[F];{let V;return V=A.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(w),A):{polygon:this.bufferedScreenGeometry(w).map(Z=>A.pointCoordinate3D(Z)),unwrapped:!0},this._screenRaycastCache[F]=V,V}}_bufferedCameraMercator(w,A){const F=Mu(w);if(this._cameraRaycastCache[F])return this._cameraRaycastCache[F];{let V;return V=A.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(w),A):{polygon:this.bufferedCameraGeometry(w).map(Z=>A.pointCoordinate3D(Z)),unwrapped:!0},this._cameraRaycastCache[F]=V,V}}_projectAndResample(w,A){const F=function(Z,X){const ae=o.aD([],X.pixelMatrix,X.globeMatrix),pe=[0,-o.aF,0,1],ke=[0,o.aF,0,1],Me=[0,0,0,1];o.aE(pe,pe,ae),o.aE(ke,ke,ae),o.aE(Me,Me,ae);const Ke=new o.P(pe[0]/pe[3],pe[1]/pe[3]),He=new o.P(ke[0]/ke[3],ke[1]/ke[3]),tt=o.aG(Z,Ke)&&pe[3]1?Ko(Z.slice(0,wt),X):[],$t=wtnew o.P(Ud(ws.x),ws.y)),$t=$t.map(ws=>new o.P(Ud(ws.x),ws.y));const kt=[...Rt];kt.length===0&&kt.push($t[$t.length-1]);const ks=o.am(kt[kt.length-1].y,($t.length===0?Rt[0]:$t[0]).y,_t);let Jt;return Jt=tt?[new o.P(0,ks),new o.P(0,0),new o.P(1,0),new o.P(1,ks)]:[new o.P(1,ks),new o.P(1,1),new o.P(0,1),new o.P(0,ks)],kt.push(...Jt),$t.length===0?kt.push(Rt[0]):kt.push(...$t),{polygon:kt.map(ws=>new o.ag(ws.x,ws.y)),unwrapped:!1}}(w,A);if(F)return F;const V=function(Z,X){let ae=!1,pe=-1/0,ke=0;for(let Ke=0;Kepe&&(pe=Z[Ke].x,ke=Ke);for(let Ke=0;Ke.5&&(tt.x{Ke.x-=1}),{polygon:Z,unwrapped:ae}}(Ko(w,A).map(Z=>new o.P(Ud(Z.x),Z.y)),A);return{polygon:V.polygon.map(Z=>new o.ag(Z.x,Z.y)),unwrapped:V.unwrapped}}}function Ko(R,w){return o.aI(R,A=>{const F=w.pointCoordinate3D(A);A.x=F.x,A.y=F.y},1/256)}function Ud(R){return R<0?1+R%1:R%1}function Mu(R){return 100*R|0}function Qm(R,w,A){try{w=function(V){if(!V.variants)return V;if(!Array.isArray(V.variants))throw new Error("variants must be an array");for(const Z of V.variants){if(Z==null||typeof Z!="object"||Z.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(Z.capabilities))throw new Error("capabilities must be an array");if(Z.capabilities.length===1&&Z.capabilities[0]==="meshopt")return Object.assign(V,Z)}return V}(w)}catch(V){return new Error("Failed to process TileJSON variants",{cause:V})}const F=o.aJ(Object.assign({},w,R),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return R.url&&w.tiles&&R.tiles&&(F.tiles=w.tiles),F.tiles=A.canonicalizeTileset(F,R.url),F}function Gc(R,w,A,F,V){const Z=function(ae,pe){if(ae)return V(ae);if(pe){R.url&&pe.tiles&&R.tiles&&delete R.tiles;const ke=Qm(R,pe,w);if(ke instanceof Error)return V(ke);V(null,ke)}},X=function(ae,pe,ke){if(!ae)return null;if(!pe&&!ke)return ae;ke=ke||ae.worldview_default;const Me=Object.values(ae.language||{});if(Me.length===0)return null;const Ke=Object.values(ae.worldview||{});if(Ke.length===0)return null;const He=Me.every(ct=>ct===pe),tt=Ke.every(ct=>ct===ke);return He&&tt?ae:pe in(ae.language_options||{})||ke in(ae.worldview_options||{})?null:ae.language_options&&ae.worldview_options?ae:null}(R.data,A,F);return X?o.o.frame(()=>Z(null,X)):R.url?o.m(w.transformRequest(w.normalizeSourceURL(R.url,null,A,F),o.R.Source),Z):o.o.frame(()=>{const{data:ae,...pe}=R;Z(null,pe)})}function lh(R,w){const A=Math.pow(2,w.z),F=Math.floor(o.aH(R.getWest())*A),V=Math.floor(o.aL(R.getNorth())*A),Z=Math.ceil(o.aH(R.getEast())*A),X=Math.ceil(o.aL(R.getSouth())*A);return w.x>=F&&w.x=V&&w.ythis.maxzoom||w.z{this._tileJSONRequest=null,this._loaded=!0,X?(A&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${A}`),F&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${F}`),this.fire(new o.B(X))):ae&&(this._setTileJSON(ae),je(ae.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),w&&w(X)};this.provider=this._options.provider;const Z=function(X){if("provider"in X&&!X.provider)return null;let ae=X.provider;if(!ae&&"url"in X&&X.url&&(ae=o.aM(X.url)),!ae)return null;const pe=o.g.TILE_PROVIDER_URLS[ae];if(!pe)return null;let ke;try{ke=new URL(pe,o.g.API_URL).href}catch{return o.w(`TileProvider "${ae}" has an invalid URL: "${pe}"`),null}return{name:ae,url:ke}}(this._options);if(this.provider&&!Z)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(w&&w());this._tileJSONRequest=Z?this._loadWithProvider(Z,V):Gc(this._options,this.map._requestManager,A,F,V)}_loadWithProvider(w,A){this.provider=w.name;const F=new AbortController,V=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,Z=V?Object.assign({},this._options,{url:V.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:w.name,url:w.url,source:this.id,scope:this.scope,type:this.type,options:Z,request:V},(X,ae)=>{if(F.signal.aborted)return;if(X)return void A(X);const pe=ae?ae.find(ke=>ke!=null):null;if(pe){const ke=Qm(this._options,pe,this.map._requestManager);ke instanceof Error?A(ke):A(null,ke)}else A(null,{tiles:this._options.tiles})}),{cancel:()=>{F.abort()}}}_setTileJSON(w){if(Object.assign(this,w),this.hasWorldviews=!!w.worldview_options,w.worldview_default&&(this.worldviewDefault=w.worldview_default),w.vector_layers){this.vectorLayers=w.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const A of w.vector_layers)this.vectorLayerIds.push(A.id),w.worldview&&w.worldview[A.source]&&this.localizableLayerIds.add(A.id)}this.tileBounds=qd.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,A){const F=w.tileID.canonical.url(this.tiles,this.scheme),V=this.map._requestManager.normalizeTileURL(F),Z=this.map._requestManager.transformRequest(V,o.R.Tile),X=this.map.style?this.map.style.getLut(this.scope):null,ae=X?{image:X.image.clone()}:null,pe={request:Z,data:void 0,uid:w.uid,tileID:w.tileID,tileZoom:w.tileZoom,zoom:w.tileID.overscaledZ,maxZoom:this.maxzoom,lut:ae,tileSize:this.tileSize*w.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,renderSourceType:w.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:w.isExtraShadowCaster,tessellationStep:this.map._tessellationStep,scaleFactor:this.map.getScaleFactor(),worldview:this.map.getWorldview()||this.worldviewDefault,indoor:this.map.getIndoorTileOptions(this.id,this.scope)};if(this.hasWorldviews&&o.e(F)&&(pe.localizableLayerIds=this.localizableLayerIds),pe.request.collectResourceTiming=this._collectResourceTiming,w.actor&&w.state!=="expired")w.state==="loading"?w.reloadCallback=A:w.request=w.actor.send("reloadTile",pe,ke.bind(this));else if(w.actor=this._tileWorkers[V]=this._tileWorkers[V]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)w.request=w.actor.send("loadTile",pe,ke.bind(this),void 0,!0);else{const Me=o.aO.call({deduped:this._deduped},pe,(Ke,He)=>{if(Ke||!He)ke.call(this,Ke);else{const tt=o.aP(He.responseHeaders);pe.data={rawData:He.rawData.slice(0),expires:tt.expires,cacheControl:tt.cacheControl},w.actor&&w.actor.send("loadTile",pe,ke.bind(this),void 0,!0)}},!0);w.request={cancel:Me}}function ke(Me,Ke){return delete w.request,w.aborted?A(null):Me?A(Me):(Ke&&Ke.resourceTiming&&(w.resourceTiming=Ke.resourceTiming),this.map._refreshExpiredTiles&&Ke&&w.setExpiryData(Ke),w.loadVectorData(Ke,this.map.painter),o.aQ(this.dispatcher),A(null,Ke),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,A){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 Kh extends o.E{constructor(w,A,F,V){super(),this.id=w,this.dispatcher=F,this.setEventedParent(V),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"},A),Object.assign(this,o.aJ(A,["url","scheme","tileSize"]))}load(w){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const A=this.map.getWorldview();this._tileJSONRequest=Gc(this._options,this.map._requestManager,null,A,(F,V)=>{this._tileJSONRequest=null,this._loaded=!0,F?this.fire(new o.B(F)):V&&(Object.assign(this,V),V.raster_layers&&(this.rasterLayers=V.raster_layers,this.rasterLayerIds=this.rasterLayers.map(Z=>Z.id)),this.tileBounds=qd.fromTileJSON(V),je(V.tiles),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),w&&w(F)})}loaded(){return this._loaded}onAdd(w){this.map=w,this.load()}reload(){this.cancelTileJSONRequest();const w=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(w))}setTiles(w){return this._options.tiles=w,this.reload(),this}setUrl(w){return this.url=w,this._options.url=w,this.reload(),this}onRemove(w){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(w){return!this.tileBounds||this.tileBounds.contains(w.canonical)}loadTile(w,A){const F=o.o.devicePixelRatio>=2,V=this.map._requestManager.normalizeTileURL(w.tileID.canonical.url(this.tiles,this.scheme),F,this.tileSize);w.request=o.n(this.map._requestManager.transformRequest(V,o.R.Tile),(Z,X,ae)=>{if(delete w.request,w.aborted)return w.state="unloaded",A(null);if(Z)return w.state="errored",A(Z);if(!X)return A(null);const pe=o.aP(ae);this.map._refreshExpiredTiles&&w.setExpiryData(pe),w.setTexture(X,this.map.painter),w.state="loaded",o.aQ(this.dispatcher),A(null)})}abortTile(w,A){w.request&&(w.request.cancel(),delete w.request),A&&A()}unloadTile(w,A){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(),A&&A()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function zb([R,w],A,F,{scaled:V=!0}={}){const{tileSize:Z,buffer:X}=F,{x:ae,y:pe,z:ke}=A;if(!isFinite(ae)||!isFinite(pe)||!isFinite(ke))throw new Error("Invalid MRT header");const Me=2**ke,Ke=Me*o.aH(R),He=Me*o.aL(w);return function([tt,ct],ot,{scaled:wt=!0}={}){if(!ot)throw new Error("bandView is undefined");const{data:_t,tileSize:Rt,buffer:$t,offset:kt,scale:ks,dimension:Jt}=ot;if(tt<-$t||tt>Rt+$t||ct<-$t||ct>Rt+$t)throw new Error(`Point (${tt}, ${ct}) out of bounds for tileSize=${Rt}, buffer=${$t}`);const ws=(ct+$t)*(Rt+2*$t)+(tt+$t);if(new Uint32Array(_t.buffer)[ws]===4294967295)return null;let Vt=[];Vt=wt?[]:new ot.data.constructor(Jt);for(let Xt=0;Xt{if(delete w.request,w.aborted)return w.state="unloaded",A(null);if(ae)return ae.name==="AbortError"?void 0:(w.state="errored",A(ae));if(this.map._refreshExpiredTiles&&pe){const Me=o.aP(ke);w.setExpiryData(Me)}if(this.partial&&w.state!=="expired")w.state="empty";else if(!this.partial){if(!pe)return A(null);w.state="loaded",w._isHeaderLoaded=!0,w._mrt=pe}A(null)};w.request=this.partial?w.fetchHeader(void 0,X.bind(this)):w.actor.send("loadTile",Z,X.bind(this),void 0,!0)}abortTile(w){w.request&&(w.request.cancel(),delete w.request),w.actor&&w.actor.send("abortTile",{uid:w.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(w,A){const F=w.texturePerLayer;if(w.flushAllQueues(),F.size){w.destroy(!1);for(const V of F.values())this.map.painter.saveTileTexture(V)}else w.destroy()}prepareTile(w,A,F,V){w._isHeaderLoaded&&(w.state!=="empty"&&(w.state="reloading"),w.fetchBandForRender(A,F,V,(Z,X)=>{Z?(w.state="errored",this.fire(new o.B(Z))):X&&(w._isHeaderLoaded=!0,w.setTexturePerLayer(F,X,this.map.painter),w.state="loaded"),this.triggerRepaint(w)}))}getInitialBand(w){if(!this.rasterLayers)return 0;const A=this.rasterLayers.find(({id:Z})=>Z===w),F=A&&A.fields,V=F&&F.bands&&F.bands;return V?V[0]:0}getTextureDescriptor(w,A,F){if(!w)return;const V=A.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!V)return;let Z=null;A instanceof o.aS?Z=A.paint.get("raster-array-band"):A instanceof o.aT&&(Z=A.paint.get("raster-particle-array-band"));const X=Z||this.getInitialBand(V);if(X==null)return;if(!w.textureDescriptorPerLayer.get(A.id))return void this.prepareTile(w,V,A.id,X);if(w.updateNeeded(A.id,X)&&!F)return;const ae=w.textureDescriptorPerLayer.get(A.id);return Object.assign({},ae,{texture:w.texturePerLayer.get(A.id)})}getImages(w,A){const F=new Map;for(const V of w)for(const Z of A){const[X,ae]=Z.split("/"),pe=V.getLayer(X);if(!pe||!pe.hasBand(ae)||!pe.hasDataForBand(ae))continue;const{bytes:ke,tileSize:Me,buffer:Ke}=pe.getBandView(ae),He=Me+2*Ke,tt={data:new o.q({width:He,height:He},ke),pixelRatio:2,sdf:!1,usvg:!1,version:0};F.set(Z,tt)}return F}queryRasterArrayValueByBandId(w,A,F){const V=A._mrt;return new Promise(Z=>{const X={},ae=new Set;for(const[pe,ke]of Object.entries(V.layers)){if(F.layerName&&pe!==F.layerName)continue;const Me={};X[pe]=Me;for(const{bands:Ke}of ke.dataIndex)for(const He of Ke)F.bands&&!F.bands.includes(He)||(ae.add(o.F(pe,He)),A.fetchBand(pe,null,He,tt=>{o.o.frame(()=>{Me[He]=tt?null:zb([w.lng,w.lat],V,ke.getBandView(He)),ae.delete(o.F(pe,He)),ae.size===0&&Z(X)})},!1))}ae.size===0&&Z(X)})}_loadTileForQuery(w,A){if(this._loadTileLoaded[w.uid])return void A(null,w._mrt);if(this._loadTilePending[w.uid])return void this._loadTilePending[w.uid].push(A);this._loadTilePending[w.uid]=[A];const F=this.map._requestManager.normalizeTileURL(w.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),V=this.map._requestManager.transformRequest(F,o.R.Tile);w.actor.send("loadTile",{request:V,uid:w.uid,tileID:w.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(Z,X,ae)=>{if(Z)return this._loadTilePending[w.uid].forEach(pe=>pe(Z,null)),void delete this._loadTilePending[w.uid];if(!X)return this._loadTilePending[w.uid].forEach(pe=>pe(null,null)),void delete this._loadTilePending[w.uid];if(this.map._refreshExpiredTiles&&X){const pe=o.aP(ae);w.setExpiryData(pe)}w._mrt=X,w._isHeaderLoaded=!0,w.state="loaded",this._loadTilePending[w.uid].forEach(pe=>pe(null,X)),this._loadTileLoaded[w.uid]=!0,delete this._loadTilePending[w.uid]},void 0,!0)}queryRasterArrayValueByAllBands(w,A,F){return new Promise((V,Z)=>{this._loadTileForQuery(A,(X,ae)=>{X?Z(X):V(ae?this.queryRasterArrayValueByBandId(w,A,F):null)})})}queryRasterArrayValue(w,A){const F=o.aU.convert(w),V=this.findLoadedParent(F);return V&&V._mrt?A.bands||!this.partial?this.queryRasterArrayValueByBandId(F,V,A):this.queryRasterArrayValueByAllBands(F,V,A):Promise.resolve(null)}findLoadedParent(w){const A=o.ag.fromLngLat(w,this.map.transform.tileSize),F=this.maxzoom+1,V=1<0&&(ae[new o.aR(R.overscaledZ,V,w.z,F,w.y-1).key]={backfilled:!1},ae[new o.aR(R.overscaledZ,R.wrap,w.z,w.x,w.y-1).key]={backfilled:!1},ae[new o.aR(R.overscaledZ,X,w.z,Z,w.y-1).key]={backfilled:!1}),w.y+1{if(this._loaded=!0,this._pendingLoad=null,F)this.fire(new o.B(F));else{const Z={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&V&&V.resourceTiming&&V.resourceTiming[this.id]&&(Z.resourceTiming=V.resourceTiming[this.id]),R&&(this._partialReload=!0),this.fire(new o.C("data",Z)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(R),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const R=o.F(this.id,this.scope);this.map.style.clearSource(R),this._updateWorkerData()}loadTile(R,w){const A=R.actor?"reloadTile":"loadTile";R.actor=this.actor;const F=this.map.style?this.map.style.getLut(this.scope):null,V=F?{image:F.image.clone()}:null,Z=this._partialReload,X={type:this.type,uid:R.uid,tileID:R.tileID,tileZoom:R.tileZoom,zoom:R.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:V,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:R.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:Z,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};R.request=this.actor.send(A,X,(ae,pe)=>Z&&!pe?(R.state="loaded",w(null)):(delete R.request,R.destroy(!1),R.aborted?w(null):ae?w(ae):(R.loadVectorData(pe,this.map.painter,A==="reloadTile"),w(null))),void 0,A==="loadTile")}abortTile(R){R.request&&(R.request.cancel(),delete R.request),R.aborted=!0}unloadTile(R,w){this.actor.send("removeTile",{uid:R.uid,type:this.type,source:this.id,scope:this.scope}),R.destroy()}onRemove(R){this._pendingLoad&&this._pendingLoad.cancel()}serialize(){return Object.assign({},this._options,{type:this.type,data:this._data})}hasTransition(){return!1}},video:class extends o.aV{constructor(R,w,A,F){super(R,w,A,F),this.roundZoom=!0,this.type="video",this.options=w}load(){this._loaded=!1;const R=this.options;this.urls=[];for(const w of R.urls)this.urls.push(this.map._requestManager.transformRequest(w,o.R.Source).url);o.aW(this.urls,(w,A)=>{this._loaded=!0,w?this.fire(new o.B(w)):A&&(this.video=A,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading())})}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(R){if(this.video){const w=this.video.seekable;Rw.end(0)?this.fire(new o.B(new o.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${w.start(0)} and ${w.end(0)}-second mark.`))):this.video.currentTime=R}}getVideo(){return this.video}onAdd(R){this.map||(this.map=R,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)))}prepare(){if(Object.keys(this.tiles).length===0||this.video.readyState<2)return;const R=this.map.painter.context,w=R.gl;this.texture?this.video.paused||(this.texture.bind(w.LINEAR,w.CLAMP_TO_EDGE),w.texSubImage2D(w.TEXTURE_2D,0,0,0,w.RGBA,w.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(R,this.video,w.RGBA8),this.texture.bind(w.LINEAR,w.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(R)}serialize(){return{type:"video",urls:this.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:o.aV,model:o.aY,"batched-model":class extends o.E{constructor(R,w,A,F){super(),this.type="batched-model",this.id=R,this.tileSize=512,this._options=w,this.tiles=this._options.tiles,this.maxzoom=w.maxzoom||19,this.minzoom=w.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=A,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(F)}onAdd(R){this.map=R,this.load()}reload(){this.cancelTileJSONRequest();const R=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(R))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(R){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const w=Array.isArray(this.map._language)?this.map._language.join():this.map._language,A=this.map.getWorldview();this._tileJSONRequest=Gc(this._options,this.map._requestManager,w,A,(F,V)=>{this._tileJSONRequest=null,this._loaded=!0,F?(w&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${w}`),A&&A.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${A}`),this.fire(new o.B(F))):V&&(Object.assign(this,V),V.bounds&&(this.tileBounds=new qd(V.bounds,this.minzoom,this.maxzoom)),je(V.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),R&&R(F)})}hasTransition(){return!1}hasTile(R){return!this.tileBounds||this.tileBounds.contains(R.canonical)}loaded(){return this._loaded}loadTile(R,w){const A=this.map._requestManager.normalizeTileURL(R.tileID.canonical.url(this.tiles,this.scheme)),F={request:this.map._requestManager.transformRequest(A,o.R.Tile),data:void 0,uid:R.uid,tileID:R.tileID,tileZoom:R.tileZoom,zoom:R.tileID.overscaledZ,tileSize:this.tileSize*R.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:R.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:o.o.devicePixelRatio,promoteId:this.promoteId};if(R.actor&&R.state!=="expired")if(R.state==="loading")R.reloadCallback=w;else{if(R.buckets){const Z=Object.values(R.buckets);for(const X of Z)X.dirty=!0;return void(R.state="loaded")}R.request=R.actor.send("reloadTile",F,V.bind(this))}else R.actor=this.dispatcher.getActor(),R.request=R.actor.send("loadTile",F,V.bind(this),void 0,!0);function V(Z,X){return R.aborted?w(null):Z&&Z.status!==404?w(Z):(this.map._refreshExpiredTiles&&X&&R.setExpiryData(X),R.loadModelData(X,this.map.painter),R.state="loaded",void w(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(R,w,A,F){super(R,w,A,F),w.coordinates?Array.isArray(w.coordinates)&&w.coordinates.length===4&&!w.coordinates.some(V=>!Array.isArray(V)||V.length!==2||V.some(Z=>typeof Z!="number"))||this.fire(new o.B(new o.V(`sources.${R}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.B(new o.V(`sources.${R}`,null,'missing required property "coordinates"'))),w.animate&&typeof w.animate!="boolean"&&this.fire(new o.B(new o.V(`sources.${R}`,null,'optional "animate" property must be a boolean value'))),w.canvas?typeof w.canvas=="string"||w.canvas instanceof HTMLCanvasElement||this.fire(new o.B(new o.V(`sources.${R}`,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new o.B(new o.V(`sources.${R}`,null,'missing required property "canvas"'))),this.options=w,this.animate=w.animate===void 0||w.animate}load(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof HTMLCanvasElement?this.options.canvas:document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new o.B(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint()},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1)},this._finishLoading())}getCanvas(){return this.canvas}onAdd(R){this.map=R,this.load(),this.canvas&&this.animate&&this.play()}onRemove(R){this.pause()}prepare(){let R=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,R=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,R=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const w=this.map.painter.context;this.texture?!R&&!this._playing||this.texture instanceof o.aX||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(w,this.canvas,w.gl.RGBA8,{premultiply:!0}),this._prepareData(w)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const R of[this.canvas.width,this.canvas.height])if(isNaN(R)||R<=0)return!0;return!1}},custom:class extends o.E{constructor(R,w,A,F){super(),this.id=R,this.type="custom",this._dataType="raster",this._dispatcher=A,this._implementation=w,this.setEventedParent(F),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new o.B(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new o.B(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new qd(this._implementation.bounds,this.minzoom,this.maxzoom));const V=w;V.update=this._update.bind(this),V.clearTiles=this._clearTiles.bind(this),V.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.aJ(w,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return o.aJ(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(R){this.map=R,this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(R),this.load()}onRemove(R){this._implementation.onRemove&&this._implementation.onRemove(R)}hasTile(R){if(this._implementation.hasTile){const{x:w,y:A,z:F}=R.canonical;return this._implementation.hasTile({x:w,y:A,z:F})}return!this.tileBounds||this.tileBounds.contains(R.canonical)}loadTile(R,w){const{x:A,y:F,z:V}=R.tileID.canonical,Z=new AbortController,X=Promise.resolve(this._implementation.loadTile({x:A,y:F,z:V},{signal:Z.signal})).then((function(ae){return delete R.request,R.aborted?(R.state="unloaded",w(null)):ae===void 0?(R.state="errored",w(null)):ae===null?(this.loadTileData(R,{width:this.tileSize,height:this.tileSize,data:null}),R.state="loaded",w(null)):function(pe){return pe instanceof ImageData||pe instanceof HTMLCanvasElement||pe instanceof ImageBitmap||pe instanceof HTMLImageElement}(ae)?(this.loadTileData(R,ae),R.state="loaded",void w(null)):(R.state="errored",w(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(ae=>{ae.name!=="AbortError"&&(R.state="errored",w(ae))});X.cancel=()=>Z.abort(),R.request=X}loadTileData(R,w){R.setTexture(w,this.map.painter)}unloadTile(R,w){if(R.texture&&R.texture instanceof o.T?(R.destroy(!1),R.texture&&R.texture instanceof o.T&&this.map.painter.saveTileTexture(R.texture)):R.destroy(),this._implementation.unloadTile){const{x:A,y:F,z:V}=R.tileID.canonical;this._implementation.unloadTile({x:A,y:F,z:V})}w&&w()}abortTile(R,w){R.request&&R.request.cancel&&(R.request.cancel(),delete R.request),w&&w()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(R=>({x:R.canonical.x,y:R.canonical.y,z:R.canonical.z}))}_clearTiles(){const R=o.F(this.id,this.scope);this.map.style.clearSource(R)}_update(){this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}}},Ef=function(R,w,A,F){const V=new xy[w.type](R,w,A,F);if(V.id!==R)throw new Error(`Expected Source id to be ${R} instead of ${V.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],V),V};function Mf(R,w,A=""){return`${A}:${w.id||""}:${w.layer.id}:${function(F){if("layerId"in F)return`layer:${F.layerId}`;{const{featuresetId:V,importId:Z}=F;return`featureset:${V}${Z?`:import:${Z}`:""}`}}(R.target)}`}function pu(R,w,A,F=""){if(R.uniqueFeatureID){const V=Mf(R,w,F);if(A.has(V))return!0;A.add(V)}return!1}function Px(R,w,A,F,V=!1,Z=void 0){const X=w.sourceCache.transform,ae=w.sourceCache.tilesIn(R,w.has3DLayers,V);ae.sort(ep);const pe=[];for(const ke of ae){const Me=ke.tile.queryRenderedFeatures(w,ke,A,F,X,V,Z);Object.keys(Me).length&&pe.push({wrappedTileID:ke.tile.tileID.wrapped().key,queryResults:Me})}for(const ke in w.layers){const Me=w.layers[ke];if(Me.styleLayer){const Ke=Me.styleLayer.queryRenderedFeatures(R,w.sourceCache,F);Object.keys(Ke).length&&pe.push({wrappedTileID:0,queryResults:Ke})}}return pe.length===0?{}:function(ke){const Me={},Ke={};for(const He of ke){const tt=He.queryResults,ct=He.wrappedTileID,ot=Ke[ct]=Ke[ct]||{};for(const wt in tt){const _t=tt[wt],Rt=ot[wt]=ot[wt]||{},$t=Me[wt]=Me[wt]||[];for(const kt of _t)Rt[kt.featureIndex]||(Rt[kt.featureIndex]=!0,$t.push(kt))}}return Me}(pe)}function Do(R,w,A,F,V,Z){const X={},ae=F.queryRenderedSymbols(R),pe=[];for(const ke of Object.keys(ae).map(Number))pe.push(V[ke]);pe.sort(ep);for(const ke of pe){const Me=ke.featureIndex.lookupSymbolFeatures(ae[ke.bucketInstanceId],ke.bucketIndex,ke.sourceLayerIndex,w,A,Z);for(const Ke in Me){const He=X[Ke]=X[Ke]||[],tt=Me[Ke];tt.sort((ct,ot)=>{const wt=ke.featureSortOrder;if(wt){const _t=wt.indexOf(ct.featureIndex);return wt.indexOf(ot.featureIndex)-_t}return ot.featureIndex-ct.featureIndex});for(const ct of tt)He.push(ct)}}return X}function go(R,w){const A=R.getRenderableIds().map(Z=>R.getTileByID(Z)),F=[],V={};for(let Z=0;Z{if(Z)A(Z);else try{const pe=F.getHeaderLength(X);if(pe>w)return void(this.request=this.fetchHeader(pe,A));F.parseHeader(X),this._isHeaderLoaded=!0;let ke=0;for(const Me of Object.values(F.layers))ke=Math.max(ke,Me.dataIndex[Me.dataIndex.length-1].lastByte);X.byteLength>=ke&&(this.entireBuffer=X),A(null,this.entireBuffer||X,ae)}catch(pe){A(pe)}}),this.request}fetchBandForRender(w,A,F,V){this.fetchBand(w,A,F,Z=>{if(Z)return void V(Z);this.updateTextureDescriptor(w,A,F);const X=this.textureDescriptorPerLayer.get(A);V(null,X?X.img:null)})}fetchBand(w,A,F,V,Z=!0){const X=this._mrt;if(!this._isHeaderLoaded||!X)return void V(new Error("Tile header is not ready"));const ae=this.actor;if(!ae)return void V(new Error("Can't fetch tile band without an actor"));let pe;const ke=o.F(String(F),o.F(this.tileID.key,w));let Me=this._taskQueue.get(ke);Me?Me.add(V):(Me=new Set,Me.add(V),this._taskQueue.set(ke,Me));const Ke=(ot,wt)=>{pe.complete(ot,wt),ot?V(ot):(Me.forEach(_t=>_t(null,wt)),this._taskQueue.delete(ke))},He=(ot,wt)=>{if(ot)return V(ot);const _t=ae.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:wt,task:pe},Ke,void 0,!0);if(A!==null){const Rt=this._workQueuePerLayer.get(A)||[];Rt.push(()=>{_t&&_t.cancel(),pe.cancel()}),this._workQueuePerLayer.has(A)||this._workQueuePerLayer.set(A,Rt)}};let tt;try{tt=X.getLayer(w)}catch(ot){if(this.state==="reloading")return;throw ot}if(!tt)return void V(new Error(`Unknown sourceLayer "${w}"`));if(tt.hasDataForBand(F))return Me.forEach(ot=>ot(null,null)),void this._taskQueue.delete(ke);const ct=tt.getDataRange([F]);if(pe=X.createDecodingTask(ct),!pe||pe.tasks.length)if(A!==null&&this.flushQueues(A),this.entireBuffer)He(null,this.entireBuffer.slice(ct.firstByte,ct.lastByte+1));else{const ot=Object.assign({},this.requestParams,{headers:{Range:`bytes=${ct.firstByte}-${ct.lastByte}`}}),wt=o.b1(ot,He);if(A!==null){const _t=this._fetchQueuePerLayer.get(A)||[];_t.push(()=>{wt.cancel(),pe.cancel()}),this._fetchQueuePerLayer.has(A)||this._fetchQueuePerLayer.set(A,_t)}}}updateNeeded(w,A){return(!this.textureDescriptorPerLayer.get(w)||this.textureDescriptorPerLayer.get(w).band!==A||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(w,A,F){if(!this._mrt)return;const V=this._mrt.getLayer(w);if(!V||!V.hasBand(F)||!V.hasDataForBand(F))return;const{bytes:Z,tileSize:X,buffer:ae,offset:pe,scale:ke}=V.getBandView(F),Me=X+2*ae,Ke=new o.q({width:Me,height:Me},Z),He=this.texturePerLayer.get(A);He&&He instanceof o.T&&He.update(Ke,{premultiply:!1}),this.textureDescriptorPerLayer.set(A,{layer:w,band:F,img:Ke,buffer:ae,offset:pe,tileSize:X,format:V.pixelFormat,mix:[ke,256*ke,65536*ke,16777216*ke]})}destroy(w=!1){if(super.destroy(w),delete this._mrt,!w)for(const A of this.texturePerLayer.values())A&&A instanceof o.T&&A.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 Ix{constructor(w,A){this.max=w,this.onRemove=A,this.reset()}reset(){for(const w in this.data)for(const A of this.data[w])A.timeout&&clearTimeout(A.timeout),this.onRemove(A.value);return this.data={},this.order=[],this}add(w,A,F){const V=w.wrapped().key;this.data[V]===void 0&&(this.data[V]=[]);const Z={value:A,timeout:void 0};if(F!==void 0&&(Z.timeout=setTimeout(()=>{this.remove(w,Z)},F)),this.data[V].push(Z),this.order.push(V),this.order.length>this.max){const X=this._getAndRemoveByKey(this.order[0]);X&&this.onRemove(X)}return this}has(w){return w.wrapped().key in this.data}getAndRemove(w){return this.has(w)?this._getAndRemoveByKey(w.wrapped().key):null}_getAndRemoveByKey(w){const A=this.data[w].shift();return A.timeout&&clearTimeout(A.timeout),this.data[w].length===0&&delete this.data[w],this.order.splice(this.order.indexOf(w),1),A.value}getByKey(w){const A=this.data[w];return A?A[0].value:null}get(w){return this.has(w)?this.data[w.wrapped().key][0].value:null}remove(w,A){if(!this.has(w))return this;const F=w.wrapped().key,V=A===void 0?0:this.data[F].indexOf(A),Z=this.data[F][V];return this.data[F].splice(V,1),Z.timeout&&clearTimeout(Z.timeout),this.data[F].length===0&&delete this.data[F],this.onRemove(Z.value),this.order.splice(this.order.indexOf(F),1),this}setMaxSize(w){for(this.max=w;this.order.length>this.max;){const A=this._getAndRemoveByKey(this.order[0]);A&&this.onRemove(A)}return this}filter(w){const A=[];for(const F in this.data)for(const V of this.data[F])w(V.value)||A.push(V);for(const F of A)this.remove(F.value.tileID,F)}}class Ah{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(w,A,F){const V=String(A);if(this.stateChanges[w]=this.stateChanges[w]||{},this.stateChanges[w][V]=this.stateChanges[w][V]||{},Object.assign(this.stateChanges[w][V],F),this.deletedStates[w]===null){this.deletedStates[w]={};for(const Z in this.state[w])Z!==V&&(this.deletedStates[w][Z]=null)}else if(this.deletedStates[w]&&this.deletedStates[w][V]===null){this.deletedStates[w][V]={};for(const Z in this.state[w][V])F[Z]||(this.deletedStates[w][V][Z]=null)}else for(const Z in F)this.deletedStates[w]&&this.deletedStates[w][V]&&this.deletedStates[w][V][Z]===null&&delete this.deletedStates[w][V][Z]}removeFeatureState(w,A,F){if(this.deletedStates[w]===null)return;const V=String(A);if(this.deletedStates[w]=this.deletedStates[w]||{},F&&A!==void 0)this.deletedStates[w][V]!==null&&(this.deletedStates[w][V]=this.deletedStates[w][V]||{},this.deletedStates[w][V][F]=null);else if(A!==void 0)if(this.stateChanges[w]&&this.stateChanges[w][V])for(F in this.deletedStates[w][V]={},this.stateChanges[w][V])this.deletedStates[w][V][F]=null;else this.deletedStates[w][V]=null;else this.deletedStates[w]=null}getState(w,A){const F=this.state[w]||{},V=this.stateChanges[w]||{},Z=this.deletedStates[w];if(Z===null)return{};if(A!==void 0){const ae=String(A),pe=Object.assign({},F[ae],V[ae]);if(Z){const ke=Z[A];if(ke===null)return{};for(const Me in ke)delete pe[Me]}return pe}const X=Object.assign({},F,V);if(Z)for(const ae in Z)delete X[ae];return X}initializeTileState(w,A){w.refreshFeatureState(A)}coalesceChanges(w,A){const F={};for(const V in this.stateChanges){this.state[V]=this.state[V]||{};const Z={};for(const X in this.stateChanges[V])this.state[V][X]||(this.state[V][X]={}),Object.assign(this.state[V][X],this.stateChanges[V][X]),Z[X]=this.state[V][X];F[V]=Z}for(const V in this.deletedStates){this.state[V]=this.state[V]||{};const Z={};if(this.deletedStates[V]===null)for(const X in this.state[V])Z[X]={},this.state[V][X]={};else for(const X in this.deletedStates[V]){if(this.deletedStates[V][X]===null)this.state[V][X]={};else if(this.state[V][X])for(const ae of Object.keys(this.deletedStates[V][X]))delete this.state[V][X][ae];Z[X]=this.state[V][X]}F[V]=F[V]||{},Object.assign(F[V],Z)}if(this.stateChanges={},this.deletedStates={},Object.keys(F).length!==0)for(const V in w)w[V].refreshFeatureState(A,F)}}class Vl extends o.E{constructor(w,A,F){super(),this.id=w,this._renderSourceType=F,this._maxzoomOverride=null,A.on("data",V=>{V.dataType==="source"&&V.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&V.dataType==="source"&&V.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),A.on("error",()=>{this._sourceErrored=!0}),this._source=A,this._tiles={},this._cache=new Ix(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=A.minTileCacheSize,this._maxTileCacheSize=A.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new Ah,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,A){return w.renderSourceType=this._renderSourceType,w.isExtraShadowCaster=this._shadowCasterTiles[w.tileID.key],this._source.loadTile(w,A)}_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 A in this._tiles){const F=this._tiles[A];F.upload(w,this.map?this.map.painter:void 0),F.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(w=>w.tileID).sort(tp).map(w=>w.key)}getRenderableIds(w,A){const F=[];for(const V in this._tiles)this._isIdRenderable(+V,w,A)&&F.push(this._tiles[V]);return w?F.sort((V,Z)=>{const X=V.tileID,ae=Z.tileID,pe=new o.P(X.canonical.x,X.canonical.y)._rotate(this.transform.angle),ke=new o.P(ae.canonical.x,ae.canonical.y)._rotate(this.transform.angle);return X.overscaledZ-ae.overscaledZ||ke.y-pe.y||ke.x-pe.x}).map(V=>V.tileID.key):F.map(V=>V.tileID).sort(tp).map(V=>V.key)}hasRenderableParent(w){const A=this.findLoadedParent(w,0);return!!A&&this._isIdRenderable(A.tileID.key)}_isIdRenderable(w,A,F){return this._tiles[w]&&this._tiles[w].hasData()&&!this._coveredTiles[w]&&(A||!this._tiles[w].holdingForFade())&&(F||!this._shadowCasterTiles[w])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const w in this._tiles)this._tiles[w].state!=="errored"&&this._reloadTile(+w,"reloading")}}_reloadTile(w,A){const F=this._tiles[w];F&&(F.state!=="loading"&&(F.state=A),this._loadTile(F,this._tileLoaded.bind(this,F,w,A)))}_tileLoaded(w,A,F,V,Z){if(V){if(w.state="errored",o.b2(V)){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 ae=this.map.painter.terrain;this.update(this.transform,ae.getScaledDemTileSize(),!0),ae.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B(V,{tile:w}));return}w.timeAdded=o.o.now(),F==="expired"&&(w.refreshedUponExpiration=!0),this._setTileReloadTimer(A,w),this._source.type==="raster-dem"&&w.dem&&this._backfillDEM(w),this._state.initializeTileState(w,this.map?this.map.painter:null);let X=new Map;Z&&Z.responseHeaders&&(X=Z.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:w,coord:w.tileID,sourceCacheId:this.id,responseHeaders:X}))}_hasTunnelGeometry(){for(const w in this._tiles){const A=this._tiles[w];if(A&&A.hasTunnelGeometry)return!0}return!1}_backfillDEM(w){const A=this.getRenderableIds();for(let V=0;V1||(Math.abs(X)>1&&(Math.abs(X+pe)===1?X+=pe:Math.abs(X-pe)===1&&(X-=pe)),Z.dem&&V.dem&&(V.dem.backfillBorder(Z.dem,X,ae),V.neighboringTiles&&V.neighboringTiles[ke]&&(V.neighboringTiles[ke].backfilled=!0)))}}getTile(w){return this.getTileByID(w.key)}getTileByID(w){return this._tiles[w]}_retainLoadedChildren(w,A,F,V){for(const Z in this._tiles){let X=this._tiles[Z];if(V[Z]||!X.hasData()||X.tileID.overscaledZ<=A||X.tileID.overscaledZ>F)continue;let ae=X.tileID;for(;X&&X.tileID.overscaledZ>A+1;){const ke=X.tileID.scaledTo(X.tileID.overscaledZ-1);X=this._tiles[ke.key],X&&X.hasData()&&(ae=ke)}let pe=ae;for(;pe.overscaledZ>A;)if(pe=pe.scaledTo(pe.overscaledZ-1),w[pe.key]){V[ae.key]=ae;break}}}findLoadedParent(w,A){if(w.key in this._loadedParentTiles){const F=this._loadedParentTiles[w.key];return F&&F.tileID.overscaledZ>=A?F:null}for(let F=w.overscaledZ-1;F>=A;F--){const V=w.scaledTo(F),Z=this._getLoadedTile(V);if(Z)return Z}}_getLoadedTile(w){const A=this._tiles[w.key];return A&&A.hasData()?A:this._cache.getByKey(this._source.reparseOverscaled?w.wrapped().key:w.canonical.key)}updateCacheSize(w,A){A=A||this._source.tileSize;const F=Math.ceil(w.width/A)+1,V=Math.ceil(w.height/A)+1,Z=Math.floor(F*V*5),X=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,Z):Z,ae=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,X):X;this._cache.setMaxSize(ae)}handleWrapJump(w){const A=Math.round((w-(this._prevLng===void 0?w:this._prevLng))/360);if(this._prevLng=w,A){const F={};for(const V in this._tiles){const Z=this._tiles[V];Z.tileID=Z.tileID.unwrapTo(Z.tileID.wrap+A),F[Z.tileID.key]=Z}this._tiles=F;for(const V in this._timers)clearTimeout(this._timers[V]),delete this._timers[V];for(const V in this._tiles)this._setTileReloadTimer(+V,this._tiles[V])}}update(w,A,F,V,Z){if(this.transform=w,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!F)return;this.updateCacheSize(w,A),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const X=this._source.type==="batched-model";let ae,pe=this._source.maxzoom;this._maxzoomOverride!==null&&(pe=Math.min(pe,this._maxzoomOverride));const ke=this.map&&this.map.painter?this.map.painter._terrain:null;if(ke&&ke.sourceCache===this&&ke.attenuationRange()){const tt=ke.attenuationRange()[0],ct=Math.floor(tt)-Math.log2(ke.getDemUpscale());pe>ct&&(pe=ct)}const Me=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)ae=w.getVisibleUnwrappedCoordinates(this._source.tileID).map(tt=>new o.aR(tt.canonical.z,tt.wrap,tt.canonical.z,tt.canonical.x,tt.canonical.y));else if(this.tileCoverLift!==0){const tt=w.clone();tt.tileCoverLift=this.tileCoverLift,ae=tt.coveringTiles({tileSize:A||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:pe,roundZoom:this._source.roundZoom&&!F,reparseOverscaled:Me,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:X}),this._source.minzoom<=1&&w.projection.name==="globe"&&(ae.push(new o.aR(1,0,1,0,0)),ae.push(new o.aR(1,0,1,1,0)),ae.push(new o.aR(1,0,1,0,1)),ae.push(new o.aR(1,0,1,1,1)))}else if(ae=w.coveringTiles({tileSize:A||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:pe,roundZoom:this._source.roundZoom&&!F,reparseOverscaled:Me,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:X}),this._source.hasTile){const tt=this._source.hasTile.bind(this._source);ae=ae.filter(ct=>tt(ct))}}else ae=[];if(ae.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const tt=w.coveringZoomLevel({tileSize:A||this._source.tileSize,roundZoom:this._source.roundZoom&&!F}),ct=Math.min(tt,pe);if(X){const ot=w.extendTileCover(ae,ct);for(const wt of ot)ae.push(wt)}else if(Z){const ot=this.transform.getFrustum(ct),wt=w.extendTileCoverToNearPlane(ae,ot,ct);for(const _t of wt)ae.push(_t);if(ct>=18&&this._hasTunnelGeometry()){const _t=w.extendTileCoverForTunnels(ae,ot,ct,20);for(const Rt of _t)ae.push(Rt)}}else if(this.castsShadows&&V){const ot=w.extendTileCover(ae,ct,V,16);for(const wt of ot)this._shadowCasterTiles[wt.key]=!0,ae.push(wt)}}const Ke=this._updateRetainedTiles(ae);if(this._supportsFading&&ae.length!==0){const tt={},ct={},ot=o.o.now(),wt=Object.keys(Ke);for(const Rt of wt){const $t=Ke[Rt],kt=this._tiles[Rt];if(!kt||kt.fadeEndTime!==void 0&&kt.fadeEndTime<=ot)continue;const ks=this.findLoadedParent($t,Math.max($t.overscaledZ-Vl.maxOverzooming,this._source.minzoom));ks&&(this._addTile(ks.tileID),tt[ks.tileID.key]=ks.tileID),ct[Rt]=$t}const _t=ae[ae.length-1].overscaledZ;for(const Rt in this._tiles){const $t=this._tiles[Rt];if(Ke[Rt]||!$t.hasData())continue;let kt=$t.tileID;for(;kt.overscaledZ>_t;){kt=kt.scaledTo(kt.overscaledZ-1);const ks=this._tiles[kt.key];if(ks&&ks.hasData()&&ct[kt.key]){Ke[Rt]=$t.tileID;break}}}for(const Rt in tt)Ke[Rt]||(this._coveredTiles[Rt]=!0,Ke[Rt]=tt[Rt])}for(const tt in Ke)this._tiles[tt].clearFadeHold();const He=o.b3(this._tiles,Ke);for(const tt of He){const ct=this._tiles[tt];ct.hasSymbolBuckets&&!ct.holdingForFade()?ct.setHoldDuration(this.map._fadeDuration):ct.hasSymbolBuckets&&!ct.symbolFadeFinished()||this._removeTile(+tt)}this._updateLoadedParentTileCache(),this._renderSourceType===o.b4.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const w in this._tiles)this._tiles[w].holdingForFade()&&this._removeTile(+w)}_updateRetainedTiles(w){const A={};if(w.length===0)return A;const F={},V=w.reduce((ke,Me)=>Math.min(ke,Me.overscaledZ),1/0),Z=w[0].overscaledZ,X=Math.max(Z-Vl.maxOverzooming,this._source.minzoom),ae=Math.max(Z+Vl.maxUnderzooming,this._source.minzoom),pe={};for(const ke of w){const Me=this._addTile(ke);A[ke.key]=ke,Me.hasData()||V=this._source.maxzoom){const He=ke.children(this._source.maxzoom)[0],tt=this.getTile(He);if(tt&&tt.hasData()){A[He.key]=He;continue}}else{const He=ke.children(this._source.maxzoom);if(A[He[0].key]&&A[He[1].key]&&A[He[2].key]&&A[He[3].key])continue}let Ke=Me.wasRequested();for(let He=ke.overscaledZ-1;He>=X;--He){const tt=ke.scaledTo(He);if(F[tt.key]||(F[tt.key]=!0,Me=this.getTile(tt),!Me&&Ke&&(Me=this._addTile(tt)),Me&&(A[tt.key]=tt,Ke=Me.wasRequested(),Me.hasData())))break}}return A}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const w in this._tiles){const A=[];let F,V=this._tiles[w].tileID;for(;V.overscaledZ>0;){if(V.key in this._loadedParentTiles){F=this._loadedParentTiles[V.key];break}A.push(V.key);const Z=V.scaledTo(V.overscaledZ-1);if(F=this._getLoadedTile(Z),F)break;V=Z}for(const Z of A)this._loadedParentTiles[Z]=F}}_addTile(w){let A=this._tiles[w.key];if(A)return A.isExtraShadowCaster!==!0||this._shadowCasterTiles[w.key]||this._reloadTile(w.key,"reloading"),A;A=this._cache.getAndRemove(w),A&&(this._setTileReloadTimer(w.key,A),A.tileID=w,this._state.initializeTileState(A,this.map?this.map.painter:null),this._cacheTimers[w.key]&&(clearTimeout(this._cacheTimers[w.key]),delete this._cacheTimers[w.key],this._setTileReloadTimer(w.key,A)));const F=!!A;if(!F){const V=this.map?this.map.painter:null,Z=this._source.tileSize*w.overscaleFactor();A=this._source.type==="raster-array"?new _m(w,Z,this.transform.tileZoom,V,this._isRaster):new o.b0(w,Z,this.transform.tileZoom,V,this._isRaster,this._source.worldview),this._loadTile(A,this._tileLoaded.bind(this,A,w.key,A.state))}return A.uses++,this._tiles[w.key]=A,F||this._source.fire(new o.C("dataloading",{tile:A,coord:A.tileID,dataType:"source"})),A}_setTileReloadTimer(w,A){w in this._timers&&(clearTimeout(this._timers[w]),delete this._timers[w]);const F=A.getExpiryTimeout();F&&(this._timers[w]=setTimeout(()=>{this._reloadTile(w,"expired"),delete this._timers[w]},F))}_removeTile(w){const A=this._tiles[w];A&&(A.uses--,delete this._tiles[w],this._timers[w]&&(clearTimeout(this._timers[w]),delete this._timers[w]),A.uses>0||(A.hasData()&&A.state!=="reloading"||A.state==="empty"?this._cache.add(A.tileID,A,A.getExpiryTimeout()):(A.aborted=!0,this._abortTile(A),this._unloadTile(A))))}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,A,F){const V=[],Z=this.transform;if(!Z)return V;const X=Z.projection.name==="globe",ae=o.aH(Z.center.lng);for(const pe in this._tiles){const ke=this._tiles[pe];if(F&&ke.clearQueryDebugViz(),ke.holdingForFade())continue;let Me;if(X){const Ke=ke.tileID.canonical;if(Ke.z===0){const He=[Math.abs(o.aC(ae,...Cd(Ke,-1))-ae),Math.abs(o.aC(ae,...Cd(Ke,1))-ae)];Me=[0,2*He.indexOf(Math.min(...He))-1]}else{const He=[Math.abs(o.aC(ae,...Cd(Ke,-1))-ae),Math.abs(o.aC(ae,...Cd(Ke,0))-ae),Math.abs(o.aC(ae,...Cd(Ke,1))-ae)];Me=[He.indexOf(Math.min(...He))-1]}}else Me=[0];for(const Ke of Me){const He=w.containsTile(ke,Z,A,Ke);He&&V.push(He)}}return V}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(w){return this._getRenderableCoordinates(w)}_getRenderableCoordinates(w,A){const F=this.getRenderableIds(w,A).map(Z=>this._tiles[Z].tileID),V=this.transform.projection.name==="globe";for(const Z of F)Z.projMatrix=this.transform.calculateProjMatrix(Z.toUnwrapped()),Z.expandedProjMatrix=V?this.transform.calculateProjMatrix(Z.toUnwrapped(),!1,!0):Z.projMatrix;return F}sortCoordinatesByDistance(w){const A=w.slice(),F=this.transform._camera.position,V=this.transform._camera.forward(),Z={};for(const X of A){const ae=1/(1<Z[X.key]-Z[ae.key]),A}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const w=o.o.now();for(const A in this._tiles){const F=this._tiles[A];if(F.fadeEndTime!==void 0&&F.fadeEndTime>=w)return!0}}return!1}setFeatureState(w,A,F){this._state.updateState(w=w||"_geojsonTileLayer",A,F)}removeFeatureState(w,A,F){this._state.removeFeatureState(w=w||"_geojsonTileLayer",A,F)}getFeatureState(w,A){return this._state.getState(w=w||"_geojsonTileLayer",A)}setDependencies(w,A,F){const V=this._tiles[w];V&&V.setDependencies(A,F)}reloadTilesForDependencies(w,A){for(const F in this._tiles)this._tiles[F].hasDependency(w,A)&&this._reloadTile(+F,"reloading");this._cache.filter(F=>!F.hasDependency(w,A))}_preloadTiles(w,A){if(!this._sourceLoaded){const pe=()=>{this._sourceLoaded&&(this._source.off("data",pe),this._preloadTiles(w,A))};return void this._source.on("data",pe)}const F=new Map,V=Array.isArray(w)?w:[w],Z=this.map.painter.terrain,X=this.usedForTerrain&&Z?Z.getScaledDemTileSize():this._source.tileSize;for(const pe of V){const ke=pe.coveringTiles({tileSize:X,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const Me of ke)F.set(Me.key,Me);this.usedForTerrain&&pe.updateElevation(!1)}const ae=Array.from(F.values());o.t(ae,(pe,ke)=>{const Me=new o.b0(pe,this._source.tileSize*pe.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(Me,Ke=>{this._source.type==="raster-dem"&&Me.dem&&this._backfillDEM(Me),ke(Ke,Me)})},A)}}function tp(R,w){const A=Math.abs(2*R.wrap)-+(R.wrap<0),F=Math.abs(2*w.wrap)-+(w.wrap<0);return R.overscaledZ-w.overscaledZ||F-A||w.canonical.y-R.canonical.y||w.canonical.x-R.canonical.x}function Cd(R,w){const A=1<0:F.type==="building"?V=!F.isHidden(w)&&F.paint.get("building-opacity")>0:F.type==="model"&&(V=!F.isHidden(w)&&F.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!V&&A.visible,A.visible=V}}updateZOffset(w,A){this.currentBuildingBuckets=[];for(const V of this.layers){const Z=V.layer,X=this.style.getLayerSourceCache(Z);let ae=1;Z.type==="fill-extrusion"?ae=V.visible?Z.paint.get("fill-extrusion-vertical-scale"):0:Z.type==="building"&&(ae=V.visible?Z.paint.get("building-vertical-scale"):0);let pe=X?X.getTile(A):null;if(!pe&&X)for(const ke in X._tiles){const Me=X._tiles[ke];if(A.canonical.isChildOf(Me.tileID.canonical)){pe=Me;break}}this.currentBuildingBuckets.push({bucket:pe?pe.getBucket(Z):null,tileID:pe?pe.tileID:A,verticalScale:ae})}w.hasAnyZOffset=!1;let F=!1;for(let V=0;V{F in w&&(A[F]=w[F])}),A}function sp(R){R=R.slice();const w=Object.create(null);for(const A of R)w[A.id]=A;for(let A=0;A0?(V-X)/ae:0;return this.points[Z].mult(1-pe).add(this.points[A].mult(pe))}}class Rx{constructor(w,A,F){const V=this.boxCells=[],Z=this.circleCells=[];this.xCellCount=Math.ceil(w/F),this.yCellCount=Math.ceil(A/F);for(let X=0;Xthis.width||V<0||A>this.height)return!Z&&[];const ae=[];if(w<=0&&A<=0&&this.width<=F&&this.height<=V){if(Z)return!0;for(let pe=0;pe0:ae}_queryCircle(w,A,F,V,Z){const X=w-F,ae=w+F,pe=A-F,ke=A+F;if(ae<0||X>this.width||ke<0||pe>this.height)return!V&&[];const Me=[];return this._forEachCell(X,pe,ae,ke,this._queryCellCircle,Me,{hitTest:V,circle:{x:w,y:A,radius:F},seenUids:{box:{},circle:{}}},Z),V?Me.length>0:Me}query(w,A,F,V,Z){return this._query(w,A,F,V,!1,Z)}hitTest(w,A,F,V,Z){return this._query(w,A,F,V,!0,Z)}hitTestCircle(w,A,F,V){return this._queryCircle(w,A,F,!0,V)}_queryCell(w,A,F,V,Z,X,ae,pe){const ke=ae.seenUids,Me=this.boxCells[Z];if(Me!==null){const He=this.bboxes;for(const tt of Me)if(!ke.box[tt]){ke.box[tt]=!0;const ct=4*tt;if(w<=He[ct+2]&&A<=He[ct+3]&&F>=He[ct+0]&&V>=He[ct+1]&&(!pe||pe(this.boxKeys[tt]))){if(ae.hitTest)return X.push(!0),!0;X.push({key:this.boxKeys[tt],x1:He[ct],y1:He[ct+1],x2:He[ct+2],y2:He[ct+3]})}}}const Ke=this.circleCells[Z];if(Ke!==null){const He=this.circles;for(const tt of Ke)if(!ke.circle[tt]){ke.circle[tt]=!0;const ct=3*tt;if(this._circleAndRectCollide(He[ct],He[ct+1],He[ct+2],w,A,F,V)&&(!pe||pe(this.circleKeys[tt]))){if(ae.hitTest)return X.push(!0),!0;{const ot=He[ct],wt=He[ct+1],_t=He[ct+2];X.push({key:this.circleKeys[tt],x1:ot-_t,y1:wt-_t,x2:ot+_t,y2:wt+_t})}}}}}_queryCellCircle(w,A,F,V,Z,X,ae,pe){const ke=ae.circle,Me=ae.seenUids,Ke=this.boxCells[Z];if(Ke!==null){const tt=this.bboxes;for(const ct of Ke)if(!Me.box[ct]){Me.box[ct]=!0;const ot=4*ct;if(this._circleAndRectCollide(ke.x,ke.y,ke.radius,tt[ot+0],tt[ot+1],tt[ot+2],tt[ot+3])&&(!pe||pe(this.boxKeys[ct])))return X.push(!0),!0}}const He=this.circleCells[Z];if(He!==null){const tt=this.circles;for(const ct of He)if(!Me.circle[ct]){Me.circle[ct]=!0;const ot=3*ct;if(this._circlesCollide(tt[ot],tt[ot+1],tt[ot+2],ke.x,ke.y,ke.radius)&&(!pe||pe(this.circleKeys[ct])))return X.push(!0),!0}}}_forEachCell(w,A,F,V,Z,X,ae,pe){const ke=this._convertToXCellCoord(w),Me=this._convertToYCellCoord(A),Ke=this._convertToXCellCoord(F),He=this._convertToYCellCoord(V);for(let tt=ke;tt<=Ke;tt++)for(let ct=Me;ct<=He;ct++)if(Z.call(this,w,A,F,V,this.xCellCount*ct+tt,X,ae,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,A,F,V,Z,X){const ae=V-w,pe=Z-A,ke=F+X;return ke*ke>ae*ae+pe*pe}_circleAndRectCollide(w,A,F,V,Z,X,ae){const pe=(X-V)/2,ke=Math.abs(w-(V+pe));if(ke>pe+F)return!1;const Me=(ae-Z)/2,Ke=Math.abs(A-(Z+Me));if(Ke>Me+F)return!1;if(ke<=pe||Ke<=Me)return!0;const He=ke-pe,tt=Ke-Me;return He*He+tt*tt<=F*F}}const uv=Math.tan(85*Math.PI/180);function rd(R,w,A,F,V,Z,X){const ae=o.bb();if(A)if(Z.name==="globe"){const pe=o.bc(V,w);o.aD(ae,ae,pe)}else{const pe=o.bd([],X);ae[0]=pe[0],ae[1]=pe[1],ae[4]=pe[2],ae[5]=pe[3],F||o.ba(ae,ae,V.angle)}else o.aD(ae,V.labelPlaneMatrix,R);return ae}function Tc(R,w,A,F,V,Z,X){const ae=rd(R,w,A,F,V,Z,X);return Z.name==="globe"&&A||(ae[2]=ae[6]=ae[10]=ae[14]=0),ae}function ip(R,w,A,F,V,Z,X){if(A){if(Z.name==="globe"){const ae=rd(R,w,A,F,V,Z,X);return o.b7(ae,ae),o.aD(ae,R,ae),ae}{const ae=o.b8(R),pe=o.b9([]);return pe[0]=X[0],pe[1]=X[1],pe[4]=X[2],pe[5]=X[3],o.aD(ae,ae,pe),F||o.ba(ae,ae,-V.angle),ae}}return V.glCoordMatrix}function Vd(R,w,A,F){const V=[R,w,A,1];A?o.aE(V,V,F):xr(V,V,F);const Z=V[3];return V[0]/=Z,V[1]/=Z,V[2]/=Z,V}function op(R,w){return Math.min(.5+R/w*.5,1.5)}function Xh(R,w){const A=R[0]/R[3],F=R[1]/R[3];return A>=-w[0]&&A<=w[0]&&F>=-w[1]&&F<=w[1]}function Zt(R,w,A,F,V,Z,X,ae,pe,ke,Me=1){const Ke=A.transform,He=F?R.textSizeData:R.iconSizeData,tt=o.bj(He,A.transform.zoom,Me),ct=Ke.projection.name==="globe",ot=[256/A.width*2+1,256/A.height*2+1],wt=F?R.text.dynamicLayoutVertexArray:R.icon.dynamicLayoutVertexArray;wt.clear();let _t=null;ct&&(_t=F?R.text.globeExtVertexArray:R.icon.globeExtVertexArray);const Rt=R.lineVertexArray,$t=F?R.text.placedSymbolArray:R.icon.placedSymbolArray,kt=A.transform.width/A.transform.height;let ks,Jt=!1;for(let ws=0;ws<$t.length;ws++){const Vt=$t.get(ws),{numGlyphs:Xt,writingMode:ms}=Vt;if(ms!==o.bk.vertical||Jt||ks===o.bk.horizontal||(Jt=!0),ks=ms,(Vt.hidden||ms===o.bk.vertical)&&!Jt){er(Xt,wt);continue}Jt=!1;const Us=new o.P(Vt.tileAnchorX,Vt.tileAnchorY),Cs=R.elevationType==="road",pn=!!Ke.elevation||Cs;let{x:an,y:Ln,z:$n}=Ke.projection.projectTilePoint(Us.x,Us.y,ke.canonical),Ys=null;if(pn){const Qr=Cs?R.getElevationFeatureForText(ws):null;Ys={getElevation:pe,elevation:Ke.elevation,elevationFeature:Qr};const[Ga,li,ni]=pe(Us,Ke.elevation,Qr);an+=Ga,Ln+=li,$n+=ni}const Es=[an,Ln,$n,1];if(o.aE(Es,Es,w),!Xh(Es,ot)){er(Xt,wt);continue}const hn=Es[3],fn=op(A.transform.getCameraToCenterDistance(Ke.projection),hn),jn=o.bl(He,tt,Vt),yr=X?jn/fn:jn*fn,rr=Vd(an,Ln,$n,V);if(rr[3]<=0){er(Xt,wt);continue}let ar={};const zn=o.ap(R.layers[0].layout.get("text-max-angle")),ta=Math.cos(zn),va=X?null:Ys,Br=is(Vt,yr,!1,ae,w,V,Z,R.glyphOffsetArray,Rt,wt,_t,rr,Us,ar,kt,va,Ke.projection,ke,X,ta);Jt=Br.useVertical,va&&Br.needsFlipping&&(ar={}),(Br.notEnoughRoom||Jt||Br.needsFlipping&&is(Vt,yr,!0,ae,w,V,Z,R.glyphOffsetArray,Rt,wt,_t,rr,Us,ar,kt,va,Ke.projection,ke,X,ta).notEnoughRoom)&&er(Xt,wt)}F?(R.text.dynamicLayoutVertexBuffer.updateData(wt),_t&&R.text.globeExtVertexBuffer&&R.text.globeExtVertexBuffer.updateData(_t)):(R.icon.dynamicLayoutVertexBuffer.updateData(wt),_t&&R.icon.globeExtVertexBuffer&&R.icon.globeExtVertexBuffer.updateData(_t))}function $e(R,w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt,ct,ot,wt){const{lineStartIndex:_t,glyphStartIndex:Rt,segment:$t}=ae,kt=Rt+ae.numGlyphs,ks=_t+ae.lineLength,Jt=w.getoffsetX(Rt),ws=w.getoffsetX(kt-1),Vt=Dn(R*Jt,A,F,V,Z,X,$t,_t,ks,pe,ke,Me,Ke,He,!0,tt,ct,ot,wt);if(!Vt)return null;const Xt=Dn(R*ws,A,F,V,Z,X,$t,_t,ks,pe,ke,Me,Ke,He,!0,tt,ct,ot,wt);return Xt?{first:Vt,last:Xt}:null}function yt(R,w,A,F){return R===o.bk.horizontal&&Math.abs(F)>Math.abs(A)?{useVertical:!0}:R===o.bk.vertical?F>0?{needsFlipping:!0}:null:w!==0&&function(V,Z){return V===0||Math.abs(Z/V)>uv}(A,F)?w===1?{needsFlipping:!0}:null:A<0?{needsFlipping:!0}:null}function is(R,w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt,ct,ot,wt,_t,Rt,$t){const kt=w/24,ks=R.lineOffsetX*kt,Jt=R.lineOffsetY*kt,{lineStartIndex:ws,glyphStartIndex:Vt,numGlyphs:Xt,segment:ms,writingMode:Us,flipState:Cs}=R,pn=ws+R.lineLength,an=Ln=>{if(Me){const[hn,fn,jn]=Ln.up,yr=ke.length;o.bm(Me,yr+0,hn,fn,jn),o.bm(Me,yr+1,hn,fn,jn),o.bm(Me,yr+2,hn,fn,jn),o.bm(Me,yr+3,hn,fn,jn)}const[$n,Ys,Es]=Ln.point;o.bn(ke,$n,Ys,Es,Ln.angle)};if(Xt>1){const Ln=$e(kt,ae,ks,Jt,A,Ke,He,R,pe,Z,tt,ot,!1,wt,_t,Rt,$t);if(!Ln)return{notEnoughRoom:!0};if(F&&!A){let[$n,Ys,Es]=Ln.first.point,[hn,fn,jn]=Ln.last.point;[$n,Ys]=Vd($n,Ys,Es,X),[hn,fn]=Vd(hn,fn,jn,X);const yr=yt(Us,Cs,(hn-$n)*ct,fn-Ys);if(R.flipState=yr&&yr.needsFlipping?1:2,yr)return yr}an(Ln.first);for(let $n=Vt+1;$n0?hn:en(He,Es,$n,1,V,void 0,wt,_t.canonical),jn=yt(Us,Cs,(fn[0]-$n[0])*ct,fn[1]-$n[1]);if(R.flipState=jn&&jn.needsFlipping?1:2,jn)return jn}const Ln=Dn(kt*ae.getoffsetX(Vt),ks,Jt,A,Ke,He,ms,ws,pn,pe,Z,tt,ot,!1,!1,wt,_t,Rt,$t);if(!Ln)return{notEnoughRoom:!0};an(Ln)}return{}}function us(R,w,A,F,V){const{x:Z,y:X,z:ae}=F.projectTilePoint(R.x,R.y,w);if(!V)return Vd(Z,X,ae,A);const[pe,ke,Me]=V.getElevation(R,V.elevation,V.elevationFeature);return Vd(Z+pe,X+ke,ae+Me,A)}function en(R,w,A,F,V,Z,X,ae){const pe=us(R.sub(w)._unit()._add(R),ae,V,X,Z);return o.ax(pe,A,pe),o.ay(pe,pe),o.bg(pe,A,pe,F)}function Dn(R,w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt,ct,ot,wt,_t,Rt){const $t=F?R-w:R+w;let kt=$t>0?1:-1,ks=0;F&&(kt*=-1,ks=Math.PI),kt<0&&(ks+=Math.PI);let Jt=ae+X+(kt>0?0:1)|0,ws=V,Vt=V,Xt=0,ms=0;const Us=Math.abs($t),Cs=[],pn=[];let an=Z,Ln=an,$n=o.be([]);const Ys=()=>en(Ln,an,Vt,Us-Xt+1,Me,He,ot,wt.canonical);for(;Xt+ms<=Us;){if(Jt+=kt,Jt=pe)return null;if(Vt=ws,Ln=an,Cs.push(Vt),tt&&pn.push(Ln),an=new o.P(ke.getx(Jt),ke.gety(Jt)),ws=Ke[Jt],!ws){const va=us(an,wt.canonical,Me,ot,He);ws=va[3]>0?Ke[Jt]=va:Ys()}Xt+=ms;const zn=o.ax([],ws,Vt),ta=o.bf(Vt,ws);if(A&&ta>0&&ms>0&&o.bi($n,zn)/(ms*ta)0,$t),ws=ke*Jt.perspectiveRatio,Vt=(F.x1*A+ae.x-F.padding)*ws+Jt.point.x,Xt=(F.y1*A+ae.y-F.padding)*ws+Jt.point.y,ms=(F.x2*A+ae.x+F.padding)*ws+Jt.point.x,Us=(F.y2*A+ae.y+F.padding)*ws+Jt.point.y,Cs=Jt.perspectiveRatio<=.55||Jt.occluded;return!this.isInsideGrid(Vt,Xt,ms,Us)||!pe&&this.grid.hitTest(Vt,Xt,ms,Us,Ke)||Cs?{box:[],offscreen:!1,occluded:Jt.occluded}:{box:[Vt,Xt,ms,Us],offscreen:this.isOffscreen(Vt,Xt,ms,Us),occluded:!1}}placeCollisionCircles(w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt,ct,ot,wt){const _t=[],Rt=this.transform.elevation,$t=w.getProjection(),kt=w.elevationType==="road",ks=!!Rt||kt,Jt=o.bu.getAtTileOffsetFunc(wt,this.transform.center.lat,this.transform.worldSize,$t),ws=new o.P(F.tileAnchorX,F.tileAnchorY),Vt=new o.P(F.tileAnchorX,F.tileAnchorY);let{x:Xt,y:ms,z:Us}=$t.projectTilePoint(Vt.x,Vt.y,wt.canonical),Cs=null;if(ks){const ta=kt?w.getElevationFeatureForText(V):null;Cs={getElevation:Jt,elevation:Rt,elevationFeature:ta};const[va,Br,Qr]=Jt(ws,Rt,ta);Xt+=va,ms+=Br,Us+=Qr}const pn=$t.name==="globe",an=this.projectAndGetPerspectiveRatio(pe,Xt,ms,Us,wt,pn||!!Rt||this.transform.pitch>0,$t),{perspectiveRatio:Ln}=an,$n=(He?ae/Ln:ae*Ln)/o.by,Ys=Vd(Xt,ms,Us,ke),Es=F.lineOffsetX*$n,hn=F.lineOffsetY*$n,fn=o.ap(w.layers[0].layout.get("text-max-angle")),jn=Math.cos(fn),yr=an.signedDistanceFromCamera>0?$e($n,X,Es,hn,kt&&F.flipState===1,Ys,Vt,F,Z,ke,{},ks&&!He?Cs:null,He&&ks,$t,wt,He,jn):null;let rr=!1,ar=!1,zn=!0;if(yr&&!an.occluded){const ta=.5*ct*Ln+ot,va=new o.P(-100,-100),Br=new o.P(this.screenRightBoundary,this.screenBottomBoundary),Qr=new Gp,{first:Ga,last:li}=yr,ni=Ga.path.length;let Ii=[];for(let ri=ni-1;ri>=1;ri--)Ii.push(Ga.path[ri]);for(let ri=1;ri(ks&&!pn&&(El=Jt(Xcri[3]<=0)&&(Ii=[]));let Ri=[];if(Ii.length>0){let ri=1/0,Mo=-1/0,El=1/0,Xc=-1/0;for(const Wl of Ii)ri=Math.min(ri,Wl[0]),El=Math.min(El,Wl[1]),Mo=Math.max(Mo,Wl[0]),Xc=Math.max(Xc,Wl[1]);Mo>=va.x&&ri<=Br.x&&Xc>=va.y&&El<=Br.y&&(Ri=[Ii.map(Wl=>new o.P(Wl[0],Wl[1]))],(riBr.x||ElBr.y)&&(Ri=o.bv(Ri,va.x,va.y,Br.x,Br.y)))}for(const ri of Ri){Qr.reset(ri,.25*ta);let Mo=0;Mo=Qr.length<=.5*ta?1:Math.ceil(Qr.paddedLength/Ea)+1;for(let El=0;El0?(o.aE(pe,pe,w),this.fogState&&Z&&ae.name!=="globe"&&(ke=function(He,tt,ct,ot,wt,_t){const Rt=_t.calculateFogTileMatrix(wt),$t=[tt,ct,ot];return o.ah($t,$t,Rt),aa(He,o.ai($t),_t.pitch,_t._fov)}(this.fogState,A,F,V,Z.toUnwrapped(),this.transform)>.9)):xr(pe,pe,w);const Me=pe[3];return{point:new o.P((pe[0]/Me+1)/2*this.transform.width+Ha,(-pe[1]/Me+1)/2*this.transform.height+Ha),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(ae)/Me*.5,1.5),signedDistanceFromCamera:Me,occluded:X&&pe[2]>Me||ke}}isOffscreen(w,A,F,V){return F=this.screenRightBoundary||Vthis.screenBottomBoundary}isInsideGrid(w,A,F,V){return F>=0&&w=0&&AF.collisionGroupID===A}}return this.collisionGroups[w]}}function Rl(R,w,A,F,V){const{horizontalAlign:Z,verticalAlign:X}=o.bF(R),ae=-(Z-.5)*w,pe=-(X-.5)*A,ke=o.bG(R,F);return new o.P(ae+ke[0]*V,pe+ke[1]*V)}function bc(R,w,A,F,V){const Z=new o.P(R,w);return A&&Z._rotate(F?V:-V),Z}class Gi{constructor(w,A,F,V,Z,X){this.transform=w.clone(),this.projection=w.projection.name,this.collisionIndex=new Zi(this.transform,Z),this.buildingIndex=X,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=A,this.retainedQueryData={},this.collisionGroups=new ui(F),this.collisionCircleArrays={},this.prevPlacement=V,V&&(V.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(w,A,F,V,Z=1){const X=F.getBucket(A),ae=F.latestFeatureIndex;if(!X||!ae||A.fqid!==X.layerIds[0])return;const pe=X.layers[0].layout,ke=X.layers[0].paint,Me=F.collisionBoxArray,Ke=Math.pow(2,this.transform.zoom-F.tileID.overscaledZ),He=F.tileSize/o.an,tt=F.tileID.toUnwrapped();this.transform.setProjection(X.projection);const ct=(ot=F.tileID,wt=X.getProjection(),_t=this.transform,wt.name===this.projection?_t.calculateProjMatrix(ot.toUnwrapped()):_g(_t,wt,ot));var ot,wt,_t;const Rt=pe.get("text-pitch-alignment")==="map",$t=pe.get("text-rotation-alignment")==="map";A.compileFilter(A.options);const kt=A.dynamicFilter(),ks=A.dynamicFilterNeedsFeature(),Jt=A.dynamicFilterNeedsGeometry(),ws=this.transform.calculatePixelsToTileUnitsMatrix(F),Vt=Tc(ct,F.tileID.canonical,Rt,$t,this.transform,X.getProjection(),ws);let Xt=null;const ms=X.getProjection().createInversionMatrix(this.transform,F.tileID.canonical);if(Rt){const hn=ip(ct,F.tileID.canonical,Rt,$t,this.transform,X.getProjection(),ws);Xt=o.aD([],this.transform.labelPlaneMatrix,hn)}let Us=null;kt&&F.latestFeatureIndex&&(Us={unwrappedTileID:tt,dynamicFilter:kt,dynamicFilterNeedsFeature:ks,needGeometry:Jt}),this.retainedQueryData[X.bucketInstanceId]=new ti(X.bucketInstanceId,ae,X.sourceLayerIndex,X.index,F.tileID);const[Cs,pn]=X.layers[0].layout.get("text-size-scale-range"),an=o.aC(Z,Cs,pn),[Ln,$n]=pe.get("icon-size-scale-range"),Ys=o.aC(Z,Ln,$n),Es={bucket:X,layout:pe,paint:ke,posMatrix:ct,invMatrix:ms,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:Vt,labelToScreenMatrix:Xt,clippingData:Us,scale:Ke,textPixelRatio:He,holdingForFade:F.holdingForFade(),collisionBoxArray:Me,partiallyEvaluatedTextSize:o.bj(X.textSizeData,this.transform.zoom,an),partiallyEvaluatedIconSize:o.bj(X.iconSizeData,this.transform.zoom,Ys),collisionGroup:this.collisionGroups.get(X.sourceID),latestFeatureIndex:F.latestFeatureIndex};if(V)for(const hn of X.sortKeyRanges){const{sortKey:fn,symbolInstanceStart:jn,symbolInstanceEnd:yr}=hn;w.push({sortKey:fn,symbolInstanceStart:jn,symbolInstanceEnd:yr,parameters:Es})}else w.push({symbolInstanceStart:0,symbolInstanceEnd:X.symbolInstances.length,parameters:Es})}attemptAnchorPlacement(w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt,ct,ot,wt,_t,Rt,$t,kt,ks){const{textOffset0:Jt,textOffset1:ws,crossTileID:Vt}=ot,Xt=[Jt,ws],ms=Rl(w,X,ae,Xt,pe),Us=this.collisionIndex.placeCollisionBox(_t,pe,A,F,V,Z,bc(ms.x,ms.y,ke,Me,this.transform.angle),ct,Ke,He,tt.predicate);if($t){const Cs=_t.getSymbolInstanceIconSize(ks,this.transform.zoom,ot.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(_t,Cs,$t,F,V,Z,bc(ms.x,ms.y,ke,Me,this.transform.angle),ct,Ke,He,tt.predicate).box.length===0)return}if(Us.box.length>0){let Cs;return this.prevPlacement&&this.prevPlacement.variableOffsets[Vt]&&this.prevPlacement.placements[Vt]&&this.prevPlacement.placements[Vt].text&&(Cs=this.prevPlacement.variableOffsets[Vt].anchor),this.variableOffsets[Vt]={textOffset:Xt,width:X,height:ae,anchor:w,textScale:pe,prevAnchor:Cs},this.markUsedJustification(_t,w,ot,Rt),_t.allowVerticalPlacement&&(this.markUsedOrientation(_t,Rt,ot),this.placedOrientations[Vt]=Rt),{shift:ms,placedGlyphBoxes:Us}}}placeLayerBucketPart(w,A,F,V,Z=1){const{bucket:X,layout:ae,paint:pe,posMatrix:ke,textLabelPlaneMatrix:Me,labelToScreenMatrix:Ke,clippingData:He,textPixelRatio:tt,mercatorCenter:ct,invMatrix:ot,holdingForFade:wt,collisionBoxArray:_t,partiallyEvaluatedTextSize:Rt,partiallyEvaluatedIconSize:$t,collisionGroup:kt,latestFeatureIndex:ks}=w.parameters,Jt=ae.get("text-optional"),ws=ae.get("icon-optional"),Vt=ae.get("text-allow-overlap"),Xt=ae.get("icon-allow-overlap"),ms=ae.get("text-rotation-alignment")==="map",Us=ae.get("icon-rotation-alignment")==="map",Cs=ae.get("text-pitch-alignment")==="map",pn=pe.get("symbol-z-offset"),an=ae.get("symbol-elevation-reference")==="sea",Ln=ae.get("symbol-placement"),[$n,Ys]=ae.get("text-size-scale-range"),[Es,hn]=ae.get("icon-size-scale-range"),fn=o.aC(Z,$n,Ys),jn=o.aC(Z,Es,hn),yr=ae.get("text-variable-anchor"),rr=ms&&Ln!=="point",ar=Us&&Ln!=="point",zn=yr&&X.hasTextData(),ta=X.hasIconTextFit()&&zn&&X.hasIconData();this.transform.setProjection(X.projection);const va=zn||rr,Br=ar||ta;let Qr=Vt&&(Xt||!X.hasIconData()||ws),Ga=Xt&&(Vt||!X.hasTextData()||Jt);const li=!pn.isConstant();!X.collisionArrays&&_t&&X.deserializeCollisionBoxes(_t),F&&V&&X.updateCollisionDebugBuffers(this.transform.zoom,_t,fn,jn);const ni=(Ea,Ri,ri)=>{const{crossTileID:Mo,numVerticalGlyphVertices:El}=Ea;let Xc=null;if(He&&He.dynamicFilterNeedsFeature||li){const tc=this.retainedQueryData[X.bucketInstanceId],fc=ks.loadFeature({featureIndex:Ea.featureIndex,bucketIndex:tc.bucketIndex,sourceLayerIndex:tc.sourceLayerIndex,layoutVertexArrayOffset:0}),_l=fc.properties?fc.properties.worldview:null;if(X.localizable&&X.worldview&&typeof _l=="string")if(_l==="all")fc.properties.$localized=!0;else{if(!_l.split(",").includes(X.worldview))return;fc.properties.$localized=!0,fc.properties.worldview=X.worldview}Xc=He&&He.needGeometry?o.bD(fc,!0):fc}if(He&&!(0,He.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:X.worldview},Xc,this.retainedQueryData[X.bucketInstanceId].tileID.canonical,new o.P(Ea.tileAnchorX,Ea.tileAnchorY),this.transform.calculateDistanceTileData(He.unwrappedTileID)))return this.placements[Mo]=new Dc(!1,!1,!1,!0),void A.add(Mo);const Wl=pn.evaluate(Xc,{});if((Ea.zOffset||0)+(Wl||0)>0&&this.frontCutoffStart>0){const tc=2*this.frontCutoffStart-1,fc=[Ea.tileAnchorX,Ea.tileAnchorY,0,1],_l=o.aE(o.bE(),fc,ke);if(_l[1]/_l[3]{tc.tileID=this.retainedQueryData[X.bucketInstanceId].tileID;const fc=this.transform.elevation;tc.elevation=an?Wl:Wl+o.bu.getAtTileOffset(tc.tileID,new o.P(tc.tileAnchorX,tc.tileAnchorY),fc,Mh),tc.elevation+=Ea.zOffset},Ny=ri.textBox;if(Ny){pp(Ny);const tc=_l=>{let _u=o.bk.horizontal;if(X.allowVerticalPlacement&&!_l&&this.prevPlacement){const ux=this.prevPlacement.placedOrientations[Mo];ux&&(this.placedOrientations[Mo]=ux,_u=ux,this.markUsedOrientation(X,_u,Ea))}return _u},fc=(_l,_u)=>{if(X.allowVerticalPlacement&&El>0&&ri.verticalTextBox){for(const ux of X.writingModes)if(ux===o.bk.vertical?(mi=_u(),zc=mi):mi=_l(),mi&&mi.box&&mi.box.length)break}else mi=_l()};if(yr){let _l=yr;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Mo]){const Md=this.prevPlacement.variableOffsets[Mo];_l.indexOf(Md.anchor)>0&&(_l=_l.filter(ky=>ky!==Md.anchor),_l.unshift(Md.anchor))}const _u=(Md,ky,ok)=>{const DS=X.getSymbolInstanceTextSize(Rt,Ea,this.transform.zoom,Ri),OS=(Md.x2-Md.x1)*DS+2*Md.padding,fC=(Md.y2-Md.y1)*DS+2*Md.padding,h2=Ea.hasIconTextFit&&!Xt?ky:null;h2&&pp(h2);let Ew={box:[],offscreen:!1,occluded:!1};const xC=Vt?2*_l.length:_l.length;for(let L0=0;L0=_l.length,Ea,Ri,X,ok,h2,Rt,$t);if(lk&&(Ew=lk.placedGlyphBoxes,Ew&&Ew.box&&Ew.box.length)){Vo=!0,Ho=lk.shift;break}}return Ew};fc(()=>_u(Ny,ri.iconBox,o.bk.horizontal),()=>{const Md=ri.verticalTextBox;return Md&&pp(Md),X.allowVerticalPlacement&&!(mi&&mi.box&&mi.box.length)&&El>0&&Md?_u(Md,ri.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),mi&&(Vo=mi.box,Ai=mi.offscreen,Kl=mi.occluded);const ux=tc(!(!mi||!mi.box));if(!Vo&&this.prevPlacement){const Md=this.prevPlacement.variableOffsets[Mo];Md&&(this.variableOffsets[Mo]=Md,this.markUsedJustification(X,Md.anchor,Ea,ux))}}else{const _l=(_u,ux)=>{const Md=X.getSymbolInstanceTextSize(Rt,Ea,this.transform.zoom,Ri),ky=this.collisionIndex.placeCollisionBox(X,Md,_u,ct,ot,va,new o.P(0,0),Vt,tt,ke,kt.predicate);return ky&&ky.box&&ky.box.length&&(this.markUsedOrientation(X,ux,Ea),this.placedOrientations[Mo]=ux),ky};fc(()=>_l(Ny,o.bk.horizontal),()=>{const _u=ri.verticalTextBox;return X.allowVerticalPlacement&&El>0&&_u?(pp(_u),_l(_u,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),tc(!!(mi&&mi.box&&mi.box.length))}}if(Ml=mi,Vo=Ml&&Ml.box&&Ml.box.length>0,Ai=Ml&&Ml.offscreen,Kl=Ml&&Ml.occluded,Ea.useRuntimeCollisionCircles){const tc=Ea.centerJustifiedTextSymbolIndex>=0?Ea.centerJustifiedTextSymbolIndex:Ea.verticalPlacedTextSymbolIndex,fc=X.text.placedSymbolArray.get(tc),_l=o.bl(X.textSizeData,Rt,fc),_u=ae.get("text-padding");Ou=this.collisionIndex.placeCollisionCircles(X,Vt,fc,tc,X.lineVertexArray,X.glyphOffsetArray,_l,ke,Me,Ke,F,Cs,kt.predicate,Ea.collisionCircleDiameter*_l/o.by,_u,this.retainedQueryData[X.bucketInstanceId].tileID),Vo=Vt||Ou.circles.length>0&&!Ou.collisionDetected,Ai=Ai&&Ou.offscreen,Kl=Ou.occluded}if(ri.iconFeatureIndex&&(Ff=ri.iconFeatureIndex),ri.iconBox){const tc=fc=>{pp(fc);const _l=Ea.hasIconTextFit&&Ho?bc(Ho.x,Ho.y,ms,Cs,this.transform.angle):new o.P(0,0),_u=X.getSymbolInstanceIconSize($t,this.transform.zoom,Ea.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(X,_u,fc,ct,ot,Br,_l,Xt,tt,ke,kt.predicate)};zc&&zc.box&&zc.box.length&&ri.verticalIconBox?(Ji=tc(ri.verticalIconBox),Ci=Ji.box.length>0):(Ji=tc(ri.iconBox),Ci=Ji.box.length>0),Ai=Ai&&Ji.offscreen,ld=Ji.occluded}const al=Jt||Ea.numHorizontalGlyphVertices===0&&El===0,wv=ws||Ea.numIconVertices===0;if(al||wv?wv?al||(Ci=Ci&&Vo):Vo=Ci&&Vo:Ci=Vo=Ci&&Vo,Vo&&Ml&&Ml.box&&this.collisionIndex.insertCollisionBox(Ml.box,ae.get("text-ignore-placement"),X.bucketInstanceId,zc&&zc.box&&ph?ph:$l,kt.ID),Ci&&Ji&&this.collisionIndex.insertCollisionBox(Ji.box,ae.get("icon-ignore-placement"),X.bucketInstanceId,Ff,kt.ID),Ou&&(Vo&&this.collisionIndex.insertCollisionCircles(Ou.circles,ae.get("text-ignore-placement"),X.bucketInstanceId,$l,kt.ID),F)){const tc=X.bucketInstanceId;let fc=this.collisionCircleArrays[tc];fc===void 0&&(fc=this.collisionCircleArrays[tc]=new Lr);for(let _l=0;_l=0;--Ri){const ri=Ea[Ri];ni(X.symbolInstances.get(ri),ri,X.collisionArrays[ri])}X.hasAnyZOffset&&o.w(`${X.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(X.hasAnyZOffset){const Ea=X.getSortedIndexesByZOffset();for(let Ri=0;Ri=0&&(w.text.placedSymbolArray.get(Z).crossTileID=Ke>=0&&Z!==Ke?0:ke),X>=0&&(w.text.placedSymbolArray.get(X).crossTileID=Ke>=0&&X!==Ke?0:ke),ae>=0&&(w.text.placedSymbolArray.get(ae).crossTileID=Ke>=0&&ae!==Ke?0:ke),pe>=0&&(w.text.placedSymbolArray.get(pe).crossTileID=Ke>=0&&pe!==Ke?0:ke)}markUsedOrientation(w,A,F){const V=A===o.bk.horizontal||A===o.bk.horizontalOnly?A:0,Z=A===o.bk.vertical?A:0,{leftJustifiedTextSymbolIndex:X,centerJustifiedTextSymbolIndex:ae,rightJustifiedTextSymbolIndex:pe,verticalPlacedTextSymbolIndex:ke}=F,Me=w.text.placedSymbolArray;X>=0&&(Me.get(X).placedOrientation=V),ae>=0&&(Me.get(ae).placedOrientation=V),pe>=0&&(Me.get(pe).placedOrientation=V),ke>=0&&(Me.get(ke).placedOrientation=Z)}commit(w){this.commitTime=w,this.zoomAtLastRecencyCheck=this.transform.zoom;const A=this.prevPlacement;let F=!1;this.prevZoomAdjustment=A?A.zoomAdjustment(this.transform.zoom):0;const V=A?A.symbolFadeChange(w):1,Z=A?A.opacities:{},X=A?A.variableOffsets:{},ae=A?A.placedOrientations:{};for(const pe in this.placements){const ke=this.placements[pe],Me=Z[pe];Me?(this.opacities[pe]=new rl(Me,V,ke.text,ke.icon,null,ke.clipped),F=F||ke.text!==Me.text.placed||ke.icon!==Me.icon.placed):(this.opacities[pe]=new rl(null,V,ke.text,ke.icon,ke.skipFade,ke.clipped),F=F||ke.text||ke.icon)}for(const pe in Z){const ke=Z[pe];if(!this.opacities[pe]){const Me=new rl(ke,V,!1,!1);Me.isHidden()||(this.opacities[pe]=Me,F=F||ke.text.placed||ke.icon.placed)}}for(const pe in X)this.variableOffsets[pe]||!this.opacities[pe]||this.opacities[pe].isHidden()||(this.variableOffsets[pe]=X[pe]);for(const pe in ae)this.placedOrientations[pe]||!this.opacities[pe]||this.opacities[pe].isHidden()||(this.placedOrientations[pe]=ae[pe]);F?this.lastPlacementChangeTime=w:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=A?A.lastPlacementChangeTime:w)}updateLayerOpacities(w,A,F,V){V&&(this.lastReplacementSourceUpdateTime=V.updateTime);const Z=new Set;for(const X of A){const ae=X.getBucket(w);ae&&X.latestFeatureIndex&&w.fqid===ae.layerIds[0]&&(this.updateBucketOpacities(ae,Z,X,X.collisionBoxArray,F,V,X.tileID,w.scope),ae.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(ae,X.tileID),ae.elevationType==="road"&&ae.updateRoadElevation(X.tileID.canonical),ae.updateZOffset())}}updateBucketOpacities(w,A,F,V,Z,X,ae,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 ke=w.layers[0].layout,Me=w.layers[0].paint,Ke=!!w.layers[0].dynamicFilter(),He=new rl(null,0,!1,!1,!0),tt=ke.get("text-allow-overlap"),ct=ke.get("icon-allow-overlap"),ot=ke.get("text-variable-anchor"),wt=ke.get("text-rotation-alignment")==="map",_t=ke.get("text-pitch-alignment")==="map",Rt=Me.get("symbol-z-offset"),$t=ke.get("symbol-elevation-reference")==="sea",kt=!Rt.isConstant(),ks=new rl(null,0,tt&&(ct||!w.hasIconData()||ke.get("icon-optional")),ct&&(tt||!w.hasTextData()||ke.get("text-optional")),!0);!w.collisionArrays&&V&&(w.hasIconCollisionBoxData()||w.hasTextCollisionBoxData())&&w.deserializeCollisionBoxes(V);const Jt=(Vt,Xt,ms)=>{for(let Us=0;Us0||Us>0,yr=pn>0,rr=this.placedOrientations[Cs],ar=rr===o.bk.vertical,zn=rr===o.bk.horizontal||rr===o.bk.horizontalOnly;!jn&&!yr||fn.isHidden()||ws++;let ta=!1;if((jn||yr)&&X)for(const va of w.activeReplacements){if(o.bz(va,Z,o.bA.Symbol,pe)||va.min.x>an||an>va.max.x||va.min.y>Ln||Ln>va.max.y)continue;const Br=o.bB(an,Ln,ae.canonical,va.footprintTileId.canonical);if(ta=o.bC(Br,va.footprint),ta)break}if(ta&&this.collisionIndex.markSymbolAsClipped(w.bucketInstanceId,Xt.featureIndex),jn){const va=ta?lp:Hd(fn.text);Jt(w.text,ms,ar?lp:va),Jt(w.text,Us,zn?lp:va);const Br=fn.text.isHidden(),{leftJustifiedTextSymbolIndex:Qr,centerJustifiedTextSymbolIndex:Ga,rightJustifiedTextSymbolIndex:li,verticalPlacedTextSymbolIndex:ni}=Xt,Ii=w.text.placedSymbolArray,Ea=Br||ar?1:0;Qr>=0&&(Ii.get(Qr).hidden=Ea),Ga>=0&&(Ii.get(Ga).hidden=Ea),li>=0&&(Ii.get(li).hidden=Ea),ni>=0&&(Ii.get(ni).hidden=Br||zn?1:0);const Ri=this.variableOffsets[Cs];Ri&&this.markUsedJustification(w,Ri.anchor,Xt,rr);const ri=this.placedOrientations[Cs];ri&&(this.markUsedJustification(w,"left",Xt,ri),this.markUsedOrientation(w,ri,Xt))}if(yr){const va=ta?lp:Hd(fn.icon),{placedIconSymbolIndex:Br,verticalPlacedIconSymbolIndex:Qr}=Xt,Ga=w.icon.placedSymbolArray,li=fn.icon.isHidden()?1:0;Br>=0&&(Jt(w.icon,pn,ar?lp:va),Ga.get(Br).hidden=li),Qr>=0&&(Jt(w.icon,Xt.numVerticalIconVertices,zn?lp:va),Ga.get(Qr).hidden=li)}if(w.hasIconCollisionBoxData()||w.hasTextCollisionBoxData()){const va=w.collisionArrays[Vt];if(va){let Br=new o.P(0,0),Qr=!0;if(va.textBox||va.verticalTextBox){if(ot){const li=this.variableOffsets[Cs];li?(Br=Rl(li.anchor,li.width,li.height,li.textOffset,li.textScale),wt&&Br._rotate(_t?this.transform.angle:-this.transform.angle)):Qr=!1}Ke&&(Qr=!fn.clipped),va.textBox&&Qh(w.textCollisionBox.collisionVertexArray,fn.text.placed,!Qr||ar,Es,$t,Br.x,Br.y),va.verticalTextBox&&Qh(w.textCollisionBox.collisionVertexArray,fn.text.placed,!Qr||zn,Es,$t,Br.x,Br.y)}const Ga=Qr&&!!(!zn&&va.verticalIconBox);va.iconBox&&Qh(w.iconCollisionBox.collisionVertexArray,fn.icon.placed,Ga,Es,$t,Xt.hasIconTextFit?Br.x:0,Xt.hasIconTextFit?Br.y:0),va.verticalIconBox&&Qh(w.iconCollisionBox.collisionVertexArray,fn.icon.placed,!Ga,Es,$t,Xt.hasIconTextFit?Br.x:0,Xt.hasIconTextFit?Br.y:0)}}}if(w.fullyClipped=ws===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 Vt=this.collisionCircleArrays[w.bucketInstanceId];w.placementInvProjMatrix=Vt.invProjMatrix,w.placementViewportMatrix=Vt.viewportMatrix,w.collisionCircleArray=Vt.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 Qh(R,w,A,F,V,Z,X){R.emplaceBack(w?1:0,A?1:0,Z||0,X||0,F,V?1:0),R.emplaceBack(w?1:0,A?1:0,Z||0,X||0,F,V?1:0),R.emplaceBack(w?1:0,A?1:0,Z||0,X||0,F,V?1:0),R.emplaceBack(w?1:0,A?1:0,Z||0,X||0,F,V?1:0)}const wg=Math.pow(2,25),jg=Math.pow(2,24),fu=Math.pow(2,17),Hl=Math.pow(2,16),b1=Math.pow(2,9),Dx=Math.pow(2,8),y0=Math.pow(2,1);function Hd(R){if(R.opacity===0&&!R.placed)return 0;if(R.opacity===1&&R.placed)return 4294967295;const w=R.placed?1:0,A=Math.floor(127*R.opacity);return A*wg+w*jg+A*fu+w*Hl+A*b1+w*Dx+A*y0+w}const lp=0;class v0{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,A,F,V,Z,X){const ae=this._bucketParts;for(;this._currentTileIndexpe.sortKey-ke.sortKey));this._currentPartIndex{const pe=o.o.now()-X;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&pe>2};for(;this._currentPlacementIndex>=0;){const pe=A[w[this._currentPlacementIndex]],ke=this.placement.collisionIndex.transform.zoom;if(pe.type==="symbol"&&pe.visibility!=="none"&&(!pe.minzoom||pe.minzoom<=ke)&&(!pe.maxzoom||pe.maxzoom>ke)){const Me=pe,Ke=Me.layout.get("symbol-z-elevate"),He=Me.layout.get("symbol-sort-key").constantOr(1)!==void 0,tt=Me.layout.get("symbol-z-order"),ct=tt==="viewport-y"||tt==="auto"&&!(tt!=="viewport-y"&&He),ot=Me.layout.get("text-allow-overlap")||Me.layout.get("icon-allow-overlap")||Me.layout.get("text-ignore-placement")||Me.layout.get("icon-ignore-placement"),wt=ct&&ot,_t=this._inProgressLayer=this._inProgressLayer||new v0(Me),Rt=o.F(pe.source,pe.scope);if(_t.continuePlacement(Ke||wt?V[Rt]:F[Rt],this.placement,this._showCollisionBoxes,pe,ae,Z))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(w){return this.placement.commit(w),this.placement}}const ad=512/o.an/2;class gd{constructor(w,A,F){this.tileID=w,this.bucketInstanceId=F,this.index=new o.bI(A.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const V=w.canonical.x*o.an,Z=w.canonical.y*o.an;for(let X=0;Xwt-_t);for(const wt of ot){const _t=this.crossTileIDs[wt];if(this.keys[wt]===Me&&!F.has(_t)){F.add(_t),ke.crossTileID=_t;break}}}}}class Lu{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class jm{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(w){const A=Math.round((w-this.lng)/360);if(A!==0)for(const F in this.indexes){const V=this.indexes[F],Z={};for(const X in V){const ae=V[X];ae.tileID=ae.tileID.unwrapTo(ae.tileID.wrap+A),Z[ae.tileID.key]=ae}this.indexes[F]=Z}this.lng=w}addBucket(w,A,F){if(this.indexes[w.overscaledZ]&&this.indexes[w.overscaledZ][w.key]){if(this.indexes[w.overscaledZ][w.key].bucketInstanceId===A.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(w.overscaledZ,this.indexes[w.overscaledZ][w.key])}for(let Z=0;Zw.overscaledZ)for(const ae in X){const pe=X[ae];pe.tileID.isChildOf(w)&&pe.findMatches(A.symbolInstances,w,V)}else{const ae=X[w.scaledTo(Number(Z)).key];ae&&ae.findMatches(A.symbolInstances,w,V)}}for(let Z=0;Z{A[F]=!0});for(const F in this.layerIndexes)A[F]||delete this.layerIndexes[F]}}const yl=771;class ka{constructor(w,A,F,V){this.blendFunction=w,this.blendColor=A.toNonPremultipliedRenderColor(null),this.mask=F,this.blendEquation=V}}ka.Replace=[1,0,1,0],ka.disabled=new ka(ka.Replace,o.aq.transparent,[!1,!1,!1,!1]),ka.unblended=new ka(ka.Replace,o.aq.transparent,[!0,!0,!0,!0]),ka.alphaBlended=new ka([1,yl,1,yl],o.aq.transparent,[!0,!0,!0,!0]),ka.alphaBlendedNonPremultiplied=new ka([770,yl,770,yl],o.aq.transparent,[!0,!0,!0,!0]),ka.multiply=new ka([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),ka.multiplyAccumulateAlpha=new ka([774,0,1,yl],o.aq.transparent,[!0,!0,!0,!0]),ka.additive=new ka([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class Ir{constructor(w,A,F){this.func=w,this.mask=A,this.range=F}}Ir.ReadOnly=!1,Ir.ReadWrite=!0,Ir.disabled=new Ir(519,Ir.ReadOnly,[0,1]);const Fl=7680;class Sa{constructor(w,A,F,V,Z,X){this.test=w,this.ref=A,this.mask=F,this.fail=V,this.depthFail=Z,this.pass=X}}Sa.disabled=new Sa({func:519,mask:0},0,0,Fl,Fl,Fl);const Nm=1029,id=2305;class la{constructor(w,A,F){this.enable=w,this.mode=A,this.frontFace=F}}function Ox(R,w){const A=o.bO(R,3);o.bR(R,w),o.bW(R,3,A)}function Ng(R,w){const A=o.bL([]);return o.bM(A,A,-w),o.bN(A,A,-R),A}function ox(R,w){const A=[R[0],R[1],0],F=[w[0],w[1],0];if(o.ai(A)>=1e-15){const X=o.ay([],A);o.bJ(F,X,o.bi(F,X)),w[0]=F[0],w[1]=F[1]}const V=o.bh([],w,R);if(o.bK(V)<1e-15)return null;const Z=Math.atan2(-V[1],V[0]);return Ng(Math.atan2(Math.sqrt(R[0]*R[0]+R[1]*R[1]),-R[2]),Z)}la.disabled=new la(!1,Nm,id),la.backCCW=new la(!0,Nm,id),la.backCW=new la(!0,Nm,2304),la.frontCW=new la(!0,1028,2304),la.frontCCW=new la(!0,1028,id);class b0{constructor(w,A){this.position=w,this.orientation=A}get position(){return this._position}set position(w){if(w){const A=w instanceof o.ag?w:new o.ag(w[0],w[1],w[2]);this._renderWorldCopies&&(A.x=o.bs(A.x,0,1)),this._position=A}else this._position=null}lookAtPoint(w,A,F){if(this.orientation=null,!this.position)return;const V=this.position,Z=F||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(w)):0),X=o.ag.fromLngLat(w,Z),ae=[X.x-V.x,X.y-V.y,X.z-V.z];A||(A=[0,0,1]),A[2]=Math.abs(A[2]),this.orientation=ox(ae,A)}setPitchBearing(w,A){this.orientation=Ng(o.ap(w),o.ap(-A))}}class Pf{constructor(w,A){this._transform=o.b9([]),this.orientation=A,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 A;w&&o.bW(this._transform,3,[(A=w)[0],A[1],A[2],1])}get orientation(){return this._orientation}set orientation(w){this._orientation=w||o.bL([]),w&&Ox(this._transform,this._orientation)}getPitchBearing(){const w=this.forward(),A=this.right();return{bearing:Math.atan2(-A[1],A[0]),pitch:Math.atan2(Math.sqrt(w[0]*w[0]+w[1]*w[1]),-w[2])}}setPitchBearing(w,A){this._orientation=Ng(w,A),Ox(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,A){const F=new Float64Array(16);return o.b7(F,this.getWorldToCamera(w,A)),F}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(w,A,F){const V=this.position;o.bJ(V,V,-w);const Z=new Float64Array(16);return o.bP(Z,[F,F,F]),o.bx(Z,Z,V),Z[10]*=A,Z}getWorldToCamera(w,A){const F=new Float64Array(16),V=new Float64Array(4),Z=this.position;return o.bQ(V,this._orientation),o.bJ(Z,Z,-w),o.bR(F,V),o.bx(F,F,Z),F[1]*=-1,F[5]*=-1,F[9]*=-1,F[13]*=-1,F[8]*=A,F[9]*=A,F[10]*=A,F[11]*=A,F}getCameraToClipPerspective(w,A,F,V){const Z=new Float64Array(16);return o.bS(Z,w,A,F,V),Z}getCameraToClipOrthographic(w,A,F,V,Z,X){const ae=new Float64Array(16);return o.bT(ae,w,A,F,V,Z,X),ae}getDistanceToElevation(w,A=!1){const F=w===0?0:o.bU(w,A?o.bV(this.position[1]):this.position[1]),V=this.forward();return(F-this.position[2])/V[2]}clone(){return new Pf([...this.position],[...this.orientation])}}const Oc=(R,w)=>({u_matrix:R,u_ground_shadow_factor:w});class cp{constructor(w=0,A=0,F=0,V=0){if(isNaN(w)||w<0||isNaN(A)||A<0||isNaN(F)||F<0||isNaN(V)||V<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=w,this.bottom=A,this.left=F,this.right=V}interpolate(w,A,F){return A.top!=null&&w.top!=null&&(this.top=o.am(w.top,A.top,F)),A.bottom!=null&&w.bottom!=null&&(this.bottom=o.am(w.bottom,A.bottom,F)),A.left!=null&&w.left!=null&&(this.left=o.am(w.left,A.left,F)),A.right!=null&&w.right!=null&&(this.right=o.am(w.right,A.right,F)),this}getCenter(w,A){const F=o.aC((this.left+w-this.right)/2,0,w),V=o.aC((this.top+A-this.bottom)/2,0,A);return new o.P(F,V)}equals(w){return this.top===w.top&&this.bottom===w.bottom&&this.left===w.left&&this.right===w.right}clone(){return new cp(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const ch=15;class xu{constructor(w,A,F,V,Z,X,ae){this.tileSize=512,this._renderWorldCopies=Z===void 0||Z,this._minZoom=w||0,this._maxZoom=A||22,this._minPitch=F??0,this._maxPitch=V??60,this.setProjection(X),this.setMaxBounds(ae),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 cp,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new Pf,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 xu(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&&(!A||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const F=this._elevation;A||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&F.exaggeration()&&this._centerAltitudeValidForExaggeration!==F.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*F.exaggeration(),this._centerAltitudeValidForExaggeration=F.exaggeration()):(this._centerAltitude=w||0,this._centerAltitudeValidForExaggeration=F.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const w=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(w)}sampleAverageElevation(){if(!this._elevation)return 0;const w=this._elevation,A=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],F=this.horizonLineFromTop();let V=0,Z=0;for(let X=0;X{const wt=o.ck(He,Ke,tt,ct,ot);pe.has(wt)||(Z.push(new o.aR(Ke,He,tt,ct,ot)),pe.add(wt))};for(let Ke=0;KeHe.canonical.z)continue;const tt=He.canonical,ct=He.overscaledZ,ot=He.wrap,wt=1<0,$t=tt.y+10,ks=He.wrap-(Rt?0:1),Jt=He.wrap+(_t?0:1),ws=Rt?tt.x-1:wt-1,Vt=_t?tt.x+1:0;if(X)F[0]<0?(ke(ct,Jt,tt.z,Vt,tt.y),F[1]<0&&$t&&(ke(ct,ot,tt.z,tt.x,tt.y+1),ke(ct,Jt,tt.z,Vt,tt.y+1)),F[1]>0&&kt&&(ke(ct,ot,tt.z,tt.x,tt.y-1),ke(ct,Jt,tt.z,Vt,tt.y-1))):F[0]>0?(ke(ct,ks,tt.z,ws,tt.y),F[1]<0&&$t&&(ke(ct,ot,tt.z,tt.x,tt.y+1),ke(ct,ks,tt.z,ws,tt.y+1)),F[1]>0&&kt&&(ke(ct,ot,tt.z,tt.x,tt.y-1),ke(ct,ks,tt.z,ws,tt.y-1))):F[1]<0&&$t?ke(ct,ot,tt.z,tt.x,tt.y+1):kt&&ke(ct,ot,tt.z,tt.x,tt.y-1);else{const Xt=He.visibleQuadrants;1&Xt&&(ke(ct,ks,tt.z,ws,tt.y),kt&&(ke(ct,ot,tt.z,tt.x,tt.y-1),ke(ct,ks,tt.z,ws,tt.y-1))),2&Xt&&(ke(ct,Jt,tt.z,Vt,tt.y),kt&&(ke(ct,ot,tt.z,tt.x,tt.y-1),ke(ct,Jt,tt.z,Vt,tt.y-1))),4&Xt&&(ke(ct,ks,tt.z,ws,tt.y),$t&&(ke(ct,ot,tt.z,tt.x,tt.y+1),ke(ct,ks,tt.z,ws,tt.y+1))),8&Xt&&(ke(ct,Jt,tt.z,Vt,tt.y),$t&&(ke(ct,ot,tt.z,tt.x,tt.y+1),ke(ct,Jt,tt.z,Vt,tt.y+1)))}}const Me=[];for(const Ke of Z)Z.some(He=>Ke.isChildOf(He))||Me.push(Ke);if(Z=Me.filter(Ke=>!w.some(He=>!!(Ke.overscaledZ{const _t=wt.canonical.x+.5-tt[0],Rt=wt.canonical.y+.5-tt[1];return _t*_t+Rt*Rt{const ws=o.ck($t,Rt,kt,ks,Jt);Z.has(ws)||(V.push(new o.aR(Rt,$t,kt,ks,Jt)),Z.add(ws))},ae=w.reduce((Rt,$t)=>Math.max(Rt,$t.overscaledZ),F),pe=1<{const kt=Math.floor(Rt[0]),ks=Math.floor(Rt[1]),Jt=(Rt[0]-kt)*o.an,ws=(Rt[1]-ks)*o.an,Vt=Math.floor($t[0]),Xt=Math.floor($t[1]),ms=($t[0]-Vt)*o.an,Us=($t[1]-Xt)*o.an;for(let Cs=-1;Cs<=1;Cs++){const pn=kt+Cs;if(!(pn<0||pn>=pe)){Me.x=Jt-Cs*o.an,Ke.x=ms-(pn-Vt)*o.an;for(let an=-1;an<=1;an++){const Ln=ks+an;Me.y=ws-an*o.an,Ke.y=Us-(Ln-Xt)*o.an,o.cI(Me,Ke,ke)&&X(ae,0,F,pn,Ln)}}}},tt=A.points,ct=tt[o.c9],ot=tt[o.ca],wt=this._projectToGround(ct,tt[o.cb]),_t=this._projectToGround(ot,tt[o.cc]);return He(ct,wt),He(ot,_t),V}_projectToGround(w,A){return o.cd(o.ce(),w,A,w[2]/(w[2]-A[2]))}_projectToZ(w,A,F){const V=w[2]-A[2];return Math.abs(V)<1e-6?o.cf(w):o.cd(o.ce(),w,A,(w[2]-F)/V)}extendTileCoverForTunnels(w,A,F,V){if(F<18)return[];const Z=A.points,X=Z[o.cg],ae=Z[o.ch],pe=Z[o.ci],ke=Z[o.cj];if(pe[2]>=0&&ke[2]>=0||X[2]<=0||ae[2]<=0)return[];const Me=pe[2]<0?this._projectToZ(X,pe,0):pe,Ke=ke[2]<0?this._projectToZ(ae,ke,0):ke,He=-V,tt=pe[2]3&&(ot.length=3),ot}_findExtensionTilesInQuad(w,A,F,V){const Z=[],X=new Set;for(const Vt of w)X.add(Vt.key);const ae=w.reduce((Vt,Xt)=>Math.max(Vt,Xt.overscaledZ),A),pe=1<{const ms=Vt.canonical.x+.5-Jt,Us=Vt.canonical.y+.5-ws,Cs=Xt.canonical.x+.5-Jt,pn=Xt.canonical.y+.5-ws;return ms*ms+Us*Us-(Cs*Cs+pn*pn)||Vt.canonical.x-Xt.canonical.x||Vt.canonical.y-Xt.canonical.y}),Z}coveringTiles(w){let A=this.coveringZoomLevel(w);const F=A,V=this.elevation&&this.elevation.exaggeration(),Z=V&&!w.isTerrainDEM,X=this.projection.name==="mercator";if(w.minzoom!==void 0&&Aw.maxzoom&&(A=w.maxzoom);const ae=this.locationCoordinate(this.center),pe=this.center.lat,ke=1<{const fn=new o.ag(Es.x+25e-6,Es.y,Es.z),jn=new o.ag(Es.x,Es.y+25e-6,Es.z),yr=Es.toLngLat(),rr=fn.toLngLat(),ar=jn.toLngLat(),zn=this.locationCoordinate(yr),ta=this.locationCoordinate(rr),va=this.locationCoordinate(ar),Br=Math.hypot(ta.x-zn.x,ta.y-zn.y),Qr=Math.hypot(va.x-zn.x,va.y-zn.y);return Math.sqrt(Br*Qr)*ws/25e-6},Xt=Es=>{const hn=ks,fn=Jt;return{aabb:o.cp(this,ke,0,0,0,Es,fn,hn,this.projection),zoom:0,x:0,y:0,minZ:fn,maxZ:hn,wrap:Es,fullyVisible:!1}},ms=[];let Us=[];const Cs=A,pn=w.reparseOverscaled?F:A,an=(wt-this._centerAltitude)*ot,Ln=Es=>{if(!this._elevation||!Es.tileID||!X)return;const hn=this._elevation.getMinMaxForTile(Es.tileID),fn=Es.aabb;hn?(fn.min[2]=hn.min,fn.max[2]=hn.max,fn.center[2]=(fn.min[2]+fn.max[2])/2):(Es.shouldSplit=Ys(Es),Es.shouldSplit||(fn.min[2]=fn.max[2]=fn.center[2]=this._centerAltitude))},$n=(Es,hn)=>{if(.707*hn{if(Es.zoom=.9)return!0}else if(Z&&(jn=Es.aabb.distanceZ(_t)*ot),this.projection.isReprojectedInTileSpace&&F<=5){const Qr=Math.pow(2,Es.zoom),Ga=Vt(new o.ag((Es.x+.5)/Qr,(Es.y+.5)/Qr));yr=Ga>.85?1:Ga}if(!X&&!Ke){const Qr=Math.sqrt(hn*hn+fn*fn+jn*jn);let Ga=(1<0;){const Es=ms.pop(),hn=Es.x,fn=Es.y;let jn=Es.fullyVisible;const yr=()=>this.projection.name==="globe"&&(Es.y===0||Es.y===(1<rr)continue;let ar=0;if(!jn){let Br=Rt?Es.aabb.intersectsPrecise(tt):Es.aabb.intersectsPreciseFlat(tt);if(Br===0&&yr()){const Qr=new o.cn(Es.zoom,hn,fn);Br=o.co(this,ke,Qr,!0).intersectsPrecise(tt)}if(Br===0)continue;if(w.calculateQuadrantVisibility)if(tt.containsPoint(Es.aabb.center))ar=15;else for(let Qr=0;Qr<4;Qr++)Es.aabb.quadrant(Qr).intersects(tt)!==0&&(ar|=1<>1),ta={aabb:X?Es.aabb.quadrant(rr):o.cp(this,ke,Es.zoom+1,ar,zn,Es.wrap,Es.minZ,Es.maxZ,this.projection),zoom:Es.zoom+1,x:ar,y:zn,wrap:Es.wrap,fullyVisible:jn,tileID:void 0,shouldSplit:void 0,minZ:Es.minZ,maxZ:Es.maxZ};Z&&!Ke&&(ta.tileID=new o.aR(Es.zoom+1===Cs?pn:Es.zoom+1,Es.wrap,Es.zoom+1,ar,zn),Ln(ta)),ms.push(ta)}}if(this.fogCullDistSq){const Es=this.fogCullDistSq,hn=this.horizonLineFromTop();Us=Us.filter(fn=>{const jn=[0,0,0,1],yr=[o.an,o.an,0,1],rr=this.calculateFogTileMatrix(fn.tileID.toUnwrapped());o.aE(jn,jn,rr),o.aE(yr,yr,rr);const ar=o.cq([],jn,yr),zn=o.cr([],jn,yr),ta=o.cK(ar,zn);if(ta===0)return!0;let va=!1;const Br=this._elevation;if(Br&&ta>Es&&hn!==0){const Qr=this.calculateProjMatrix(fn.tileID.toUnwrapped());let Ga;w.isTerrainDEM||(Ga=Br.getMinMaxForTile(fn.tileID)),Ga||(Ga={min:Jt,max:ks});const li=o.cs(this.rotation),ni=[li[0]*o.an,li[1]*o.an,Ga.max];o.ah(ni,ni,Qr),va=(1-ni[1])*this.height*.5Es.distanceSq-hn.distanceSq).map(Es=>Es.tileID)}resize(w,A){this.width=w,this.height=A,this.pixelsToGLUnits=[2/w,-2/A],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 A=o.aC(w.lat,-o.ct,o.ct),F=this.projection.project(w.lng,A);return new o.P(F.x*this.worldSize,F.y*this.worldSize)}unproject(w){return this.projection.unproject(w.x/this.worldSize,w.y/this.worldSize)}get point(){return this.project(this.center)}get pointMerc(){return this.point._div(this.worldSize)}get pixelsPerMeterRatio(){return this.pixelsPerMeter/o.bU(1,this.center.lat)/this.worldSize}setLocationAtPoint(w,A){let F,V;const Z=this.centerPoint;if(this.projection.name==="globe"){const ae=this.worldSize;F=(A.x-Z.x)/ae,V=(A.y-Z.y)/ae}else{const ae=this.pointCoordinate(A),pe=this.pointCoordinate(Z);F=ae.x-pe.x,V=ae.y-pe.y}const X=this.locationCoordinate(w);this.setLocation(new o.ag(X.x-F,X.y-V))}setLocation(w){this.center=this.coordinateLocation(w),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(w,A){return this.projection.locationPoint(this,w,A)}locationPoint3D(w,A){return this.projection.locationPoint(this,w,A,!0)}pointLocation(w){return this.coordinateLocation(this.pointCoordinate(w))}pointLocation3D(w,A){return this.coordinateLocation(this.pointCoordinate3D(w,A))}locationCoordinate(w,A){const F=A?o.bU(A,w.lat):void 0,V=this.projection.project(w.lng,w.lat);return new o.ag(V.x,V.y,F)}coordinateLocation(w){return this.projection.unproject(w.x,w.y)}pointRayIntersection(w,A){const F=A??this._centerAltitude,V=[w.x,w.y,0,1],Z=[w.x,w.y,1,1];o.aE(V,V,this.pixelMatrixInverse),o.aE(Z,Z,this.pixelMatrixInverse);const X=Z[3];o.cu(V,V,1/V[3]),o.cu(Z,Z,1/X);const ae=V[2],pe=Z[2];return{p0:V,p1:Z,t:ae===pe?0:(F-ae)/(pe-ae)}}screenPointToMercatorRay(w){const A=[w.x,w.y,0,1],F=[w.x,w.y,1,1];return o.aE(A,A,this.pixelMatrixInverse),o.aE(F,F,this.pixelMatrixInverse),o.cu(A,A,1/A[3]),o.cu(F,F,1/F[3]),A[2]=o.bU(A[2],this._center.lat)*this.worldSize,F[2]=o.bU(F[2],this._center.lat)*this.worldSize,o.cu(A,A,1/this.worldSize),o.cu(F,F,1/this.worldSize),new o.az([A[0],A[1],A[2]],o.ay([],o.ax([],F,A)))}rayIntersectionCoordinate(w){const{p0:A,p1:F,t:V}=w,Z=o.bU(A[2],this._center.lat),X=o.bU(F[2],this._center.lat);return new o.ag(o.am(A[0],F[0],V)/this.worldSize,o.am(A[1],F[1],V)/this.worldSize,o.am(Z,X,V))}pointCoordinate(w,A=this._centerAltitude){return this.projection.pointCoordinate(this,w.x,w.y,A)}pointCoordinate3D(w,A){if(!this.elevation)return this.pointCoordinate(w,A);let F=this.projection.pointCoordinate3D(this,w.x,w.y);if(F)return new o.ag(F[0],F[1],F[2]);let V=0,Z=this.horizonLineFromTop();if(w.y>Z)return this.pointCoordinate(w,A);const X=.02*Z,ae=w.clone();for(let pe=0;pe<10&&Z-V>X;pe++){ae.y=o.am(V,Z,.66);const ke=this.projection.pointCoordinate3D(this,ae.x,ae.y);ke?(Z=ae.y,F=ke):V=ae.y}return F?new o.ag(F[0],F[1],F[2]):this.pointCoordinate(w)}isPointAboveHorizon(w){return this.projection.isPointAboveHorizon(this,w)}isPointOnSurface(w){if(w.y<0||w.y>this.height||w.x<0||w.x>this.width)return!1;if(this.elevation||this.zoom>=o.cv)return!this.isPointAboveHorizon(w);const A=this.pointCoordinate(w);return A.y>=0&&A.y<=1}_coordinatePoint(w,A){const F=A&&this.elevation?this.elevation.getAtPointOrZero(w,this._centerAltitude):this._centerAltitude,V=[w.x*this.worldSize,w.y*this.worldSize,F+w.toAltitude(),1];return o.aE(V,V,this.pixelMatrix),V[3]>0?new o.P(V[0]/V[3],V[1]/V[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:w,left:A}=this._edgeInsets,F=this.height-this._edgeInsets.bottom,V=this.width-this._edgeInsets.right,Z=this.pointLocation3D(new o.P(A,w)),X=this.pointLocation3D(new o.P(V,w)),ae=this.pointLocation3D(new o.P(V,F)),pe=this.pointLocation3D(new o.P(A,F));let ke=Math.min(Z.lng,X.lng,ae.lng,pe.lng),Me=Math.max(Z.lng,X.lng,ae.lng,pe.lng),Ke=Math.min(Z.lat,X.lat,ae.lat,pe.lat),He=Math.max(Z.lat,X.lat,ae.lat,pe.lat);const tt=Math.pow(2,-this.zoom)/16*270,ct=this.projection.name==="globe"?1:4,ot=(wt,_t,Rt,$t,kt)=>{const ks=(wt+Rt)/2,Jt=(_t+$t)/2,ws=new o.P(ks,Jt),{lng:Vt,lat:Xt}=this.pointLocation3D(ws),ms=Math.max(0,ke-Vt,Ke-Xt,Vt-Me,Xt-He);ke=Math.min(ke,Vt),Me=Math.max(Me,Vt),Ke=Math.min(Ke,Xt),He=Math.max(He,Xt),(kttt)&&(ot(wt,_t,ks,Jt,kt+1),ot(ks,Jt,Rt,$t,kt+1))};if(ot(A,w,V,w,1),ot(V,w,V,F,1),ot(V,F,A,F,1),ot(A,F,A,w,1),this.projection.name==="globe"){const[wt,_t]=o.cw(this);wt?(He=90,Me=180,ke=-180):_t&&(Ke=-90,Me=180,ke=-180)}return new o.aK(new o.aU(ke,Ke),new o.aU(Me,He))}_getBoundsRectangular(w,A){const{top:F,left:V}=this._edgeInsets,Z=this.height-this._edgeInsets.bottom,X=this.width-this._edgeInsets.right,ae=new o.P(V,F),pe=new o.P(X,F),ke=new o.P(X,Z),Me=new o.P(V,Z);let Ke=this.pointCoordinate(ae,w),He=this.pointCoordinate(pe,w);const tt=this.pointCoordinate(ke,A),ct=this.pointCoordinate(Me,A),ot=(wt,_t)=>(_t.y-wt.y)/(_t.x-wt.x);return Ke.y>1&&He.y>=0?Ke=new o.ag((1-ct.y)/ot(ct,Ke)+ct.x,1):Ke.y<0&&He.y<=1&&(Ke=new o.ag(-ct.y/ot(ct,Ke)+ct.x,0)),He.y>1&&Ke.y>=0?He=new o.ag((1-tt.y)/ot(tt,He)+tt.x,1):He.y<0&&Ke.y<=1&&(He=new o.ag(-tt.y/ot(tt,He)+tt.x,0)),new o.aK().extend(this.coordinateLocation(Ke)).extend(this.coordinateLocation(He)).extend(this.coordinateLocation(ct)).extend(this.coordinateLocation(tt))}_getBoundsRectangularTerrain(){const w=this.elevation;if(!w.visibleDemTiles.length||w.isUsingMockSource())return this._getBoundsRectangular(0,0);const A=w.visibleDemTiles.reduce((F,V)=>{if(V.dem){const Z=V.dem.tree;F.min=Math.min(F.min,Z.minimums[0]),F.max=Math.max(F.max,Z.maximums[0])}return F},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(A.min*w.exaggeration(),A.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 A=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,F=this.height/2-A*(1-this._horizonShift);return w?Math.max(0,F):F}getMaxBounds(){return this.maxBounds}setMaxBounds(w){this.maxBounds=w,this.minLat=-o.ct,this.maxLat=o.ct,this.minLng=-180,this.maxLng=180,w&&(this.minLat=w.getSouth(),this.maxLat=w.getNorth(),this.minLng=w.getWest(),this.maxLng=w.getEast(),this.maxLngKe&&(ae=Ke-ke),Ke-Mett&&(X=tt-pe),tt-He{for(let Ys=0;Ys<16;Ys++)pn[Ys]=o.am(an[Ys],Ln[Ys],$n)})(ae,ae,pe,o.cL(this.pitch>=ch?1:this.pitch/ch))}else ae=pe;const ke=o.cz([],pe,X);let Me=o.cz([],ae,X);if(this.projection.isReprojectedInTileSpace){const Xt=this.locationCoordinate(this.center),ms=o.b9([]);o.bx(ms,ms,[Xt.x*this.worldSize,Xt.y*this.worldSize,0]),o.aD(ms,ms,o.cA(this)),o.bx(ms,ms,[-Xt.x*this.worldSize,-Xt.y*this.worldSize,0]),o.aD(Me,Me,ms),o.aD(ke,ke,ms),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],Me,[this.worldSize,this.worldSize,this.worldSize/Z,1]),this.projMatrix=Me,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),A){const Xt=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);Xt[8]=2*-w.x/this.width,Xt[9]=2*w.y/this.height,this.expandedFarZProjMatrix=o.cz([],Xt,X)}else this.expandedFarZProjMatrix=this.projMatrix;const Ke=o.b7([],ae);this.frustumCorners=o.cD.fromInvProjectionMatrix(Ke,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!A);const He=new Float32Array(16);o.b9(He),o.cC(He,He,[1,-1,1]),o.cE(He,He,this._pitch),o.ba(He,He,this.angle);const tt=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(tt);const ct=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;tt[8]=2*-w.x/this.width,tt[9]=2*(w.y+ct)/this.height,this.skyboxMatrix=o.aD(He,tt,He);const ot=this.point,wt=ot.x,_t=ot.y,Rt=this.width%2/2,$t=this.height%2/2,kt=Math.cos(this.angle),ks=Math.sin(this.angle),Jt=wt-Math.round(wt)+kt*Rt+ks*$t,ws=_t-Math.round(_t)+kt*$t+ks*Rt,Vt=new Float64Array(Me);if(o.bx(Vt,Vt,[Jt>.5?Jt-1:Jt,ws>.5?ws-1:ws,0]),this.alignedProjMatrix=Vt,Me=o.bb(),o.cC(Me,Me,[this.width/2,-this.height/2,1]),o.bx(Me,Me,[1,-1,0]),this.labelPlaneMatrix=Me,Me=o.bb(),o.cC(Me,Me,[1,-1,1]),o.bx(Me,Me,[-1,-1,0]),o.cC(Me,Me,[2/this.width,2/this.height,1]),this.glCoordMatrix=Me,this.pixelMatrix=o.aD(new Float64Array(16),this.labelPlaneMatrix,ke),this._calcFogMatrices(),this._distanceTileDataCache={},Me=o.b7(new Float64Array(16),this.pixelMatrix),!Me)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=Me,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cF(this);const Xt=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(Xt,Xt,X),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=Me;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const w=this.cameraWorldSizeForFog,A=this.cameraPixelsPerMeter,F=this._camera.position,V=1/this.height/this._pixelsPerMercatorPixel,Z=[w,w,A];o.bJ(Z,Z,V),o.bJ(F,F,-1),o.cG(F,F,Z);const X=o.bb();o.bx(X,X,F),o.cC(X,X,Z),this.mercatorFogMatrix=X,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(w,A,V)}_computeCameraPosition(w){const A=(w=w||this.pixelsPerMeter)/this.pixelsPerMeter,F=this._camera.forward(),V=this.point,Z=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*A-w/this.worldSize*this._centerAltitude;return[V.x/this.worldSize-F[0]*Z,V.y/this.worldSize-F[1]*Z,w/this.worldSize*this._centerAltitude-F[2]*Z]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(w){const A=this._maxCameraBoundsDistance()*Math.cos(this._pitch),F=this._camera.position[2],V=w[2];let Z=1;this.projection.wrap&&(this.center=this.center.wrap()),V>0&&(Z=Math.min((A-F)/V,1)),this._camera.position=o.bg([],this._camera.position,w,Z),this._updateStateFromCamera()}_updateStateFromCamera(){const w=this._camera.position,A=this._camera.forward(),{pitch:F,bearing:V}=this._camera.getPitchBearing(),Z=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,X=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),ae=Math.max((w[2]-Z)/Math.cos(F),X),pe=this._zoomFromMercatorZ(ae);o.bg(w,w,A,ae),this._pitch=o.aC(F,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs(V,-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 A=0,F=o.cv,V=0,Z=1/0;for(;F-A>1e-6&&F>A;){const X=A+.5*(F-A),ae=this.tileSize*Math.pow(2,X),pe=this.getCameraToCenterDistance(this.projection,X,ae),ke=this.scaleZoom(pe/(Math.max(0,w)*this.tileSize)),Me=Math.abs(X-ke);Meke||He.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+o.cH(this.fovAboveCenter)>88||this.anyCornerOffEdge(new o.P(0,0),new o.P(this.width,this.height))}zoomDeltaToMovement(w,A){const F=o.ai(o.ax([],this._camera.position,w)),V=this._zoomFromMercatorZ(F)+A;return F-this._mercatorZfromZoom(V)}getCameraPoint(){if(this.projection.name==="globe"){const w=function([A,F,V],Z){const X=[A,F,V,1];o.aE(X,X,Z);const ae=X[3]=Math.max(X[3],1e-6);return X[0]/=ae,X[1]/=ae,X[2]/=ae,X}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new o.P(w[0],w[1])}{const w=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new o.P(0,w))}}getCameraToCenterDistance(w,A=this.zoom,F=this.worldSize){const V=o.cy(w,A,this.width,this.height,1024),Z=w.pixelSpaceConversion(this.center.lat,F,V);let X=.5/Math.tan(.5*this._fov)*this.height*Z;return this.isOrthographic&&(X=o.am(1,X,o.cL(this.pitch>=ch?1:this.pitch/ch))),X}getWorldToCameraMatrix(){const w=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&o.aD(w,w,this.globeMatrix),w}getFrustum(w){return o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,w,this.projection.zAxisUnit==="meters")}}const Kc=(R,w)=>{if(w>0&&R.terrain&&o.w("Cutoff is currently disabled on terrain"),w<=0||R.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const A=R.transform,F=A.pitch,V=A.isLODDisabled(!1)?60:30;if(F0,uniformValues:{u_cutoff_params:[A._nearZ,A._farZ,(Me-A._nearZ)/Z,(Me-He-A._nearZ)/Z]}}},dp=2048;class hv{constructor(w,A){this.aabb=w,this.lastCascade=A}}class mv{add(w,A){const F=this.receivers[w.key];F!==void 0?(F.aabb.min[0]=Math.min(F.aabb.min[0],A.min[0]),F.aabb.min[1]=Math.min(F.aabb.min[1],A.min[1]),F.aabb.min[2]=Math.min(F.aabb.min[2],A.min[2]),F.aabb.max[0]=Math.max(F.aabb.max[0],A.max[0]),F.aabb.max[1]=Math.max(F.aabb.max[1],A.max[1]),F.aabb.max[2]=Math.max(F.aabb.max[2],A.max[2])):this.receivers[w.key]=new hv(A,null)}clear(){this.receivers={}}get(w){return this.receivers[w.key]}computeRequiredCascades(w,A,F){const V=o.cU.fromPoints(w.points);let Z=0;for(const X in this.receivers){const ae=this.receivers[X];if(!ae||!V.intersectsAabb(ae.aabb))continue;ae.aabb.min=V.closestPoint(ae.aabb.min),ae.aabb.max=V.closestPoint(ae.aabb.max);const pe=ae.aabb.getCorners();for(let ke=0;ke1||He[1]<-1||He[1]>1){Me=!1;break}}if(ae.lastCascade=ke,Z=Math.max(Z,ke),Me)break}}return Z+1}}class _c{constructor(w){this.painter=w,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new mv,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,A){const F=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!A||!A.properties)return;const V=A.properties.get("shadow-intensity"),Z=A.properties.get("shadow-draw-before-layer");if(!A.shadowsEnabled()||V<=0)return;let X=-1,ae=0;for(const _t of F.style.order){const Rt=F.style._mergedLayers[_t];Rt.hasShadowPass()&&!Rt.isHidden(w.zoom)&&(X=ae),!Z||Z!==_t&&Z!==Rt.slot||(this._drawShadowAfterLayer=ae>0?ae-1:0),ae+=1}if(this._enabled=X>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=X);const pe=F.context,ke=dp,Me=dp;if(this._cascades.length===0||dp!==this._cascades[0].texture.size[0]){this._cascades=[];for(let _t=0;_t<2;++_t){const Rt=pe.gl,$t=pe.createFramebuffer(ke,Me,0,"texture"),kt=new o.T(pe,{width:ke,height:Me,data:null},Rt.DEPTH_COMPONENT16);$t.depthAttachment.set(kt.texture),this._cascades.push({framebuffer:$t,texture:kt,matrix:[],far:0,boundingSphereRadius:0,frustum:new o.cl,scale:0})}}this.shadowDirection=_0(A);let Ke=0;if(w.elevation){const _t=w.elevation,Rt=[1e4,-1e4];_t.visibleDemTiles.filter($t=>$t.dem).forEach($t=>{const kt=$t.dem.tree;Rt[0]=Math.min(Rt[0],kt.minimums[0]),Rt[1]=Math.max(Rt[1],kt.maximums[0])}),Rt[0]!==1e4&&(Ke=(Rt[1]-Rt[0])*_t.exaggeration())}const He=1.5*w.cameraToCenterDistance,tt=3*He,ct=new Float64Array(16);for(let _t=0;_t=0)return{};const Z=function(pe,ke,Me){const Ke=Me/(1<0&&(o.cT(Z[1],Z[1],[V[0]*X,0,0]),o.cT(Z[2],Z[2],[V[0]*X,0,0])),V[1]<0?(o.cT(Z[0],Z[0],[0,V[1]*X,0]),o.cT(Z[1],Z[1],[0,V[1]*X,0])):V[1]>0&&(o.cT(Z[2],Z[2],[0,V[1]*X,0]),o.cT(Z[3],Z[3],[0,V[1]*X,0]));const ae={};return ae.vertices=Z,ae.planes=[Fx(Z[1],Z[0],Z[4]),Fx(Z[2],Z[1],Z[5]),Fx(Z[3],Z[2],Z[6]),Fx(Z[0],Z[3],Z[7])],ae}addShadowReceiver(w,A,F){this._receivers.add(w,o.cU.fromTileIdAndHeight(w,A,F))}getMaxCascadeForTile(w){const A=this._receivers.get(w);return A&&A.lastCascade?A.lastCascade:0}}function Fx(R,w,A){const F=o.ax([],A,w),V=o.ax([],R,w),Z=o.bh([],F,V),X=o.ai(Z);return X===0?[0,0,1,0]:(o.bJ(Z,Z,1/X),[Z[0],Z[1],Z[2],-o.bi(Z,w)])}function _0(R){const w=R.properties.get("direction"),A=o.cP(w.x,w.y,w.z);A[2]=o.aC(A[2],0,75);const F=o.cR([A[0],A[1],A[2]]);return o.cQ(F.x,F.y,F.z)}function dh(R,w,A){const F=w.properties.get("color-use-theme")==="none",V=w.properties.get("color"),Z=w.properties.get("intensity"),X=w.properties.get("direction"),ae=[X.x,X.y,X.z],pe=A.properties.get("color-use-theme")==="none",ke=A.properties.get("color"),Me=A.properties.get("intensity"),Ke=Math.max(o.bi([0,0,1],ae),0),He=[0,0,0];o.bJ(He,ke.toPremultipliedRenderColor(pe?null:R.getLut(w.scope)).toArray01Linear().slice(0,3),Me);const tt=[0,0,0];return o.bJ(tt,V.toPremultipliedRenderColor(F?null:R.getLut(A.scope)).toArray01Linear().slice(0,3),Ke*Z),o.cW([He[0]>0?He[0]/(He[0]+tt[0]):0,He[1]>0?He[1]/(He[1]+tt[1]):0,He[2]>0?He[2]/(He[2]+tt[2]):0])}function If(R,w,A,F,V,Z){const X=R.zoom,ae=R.scale,pe=R.worldSize,ke=1/pe,Me=R.aspect,Ke=Math.sqrt(1+Me*Me)*Math.tan(.5*R.fovX),He=Ke*Ke,tt=F-A,ct=F+A;let ot,wt;He>tt/ct?(ot=F,wt=F*Ke):(ot=.5*ct*(1+He),wt=.5*Math.sqrt(tt*tt+2*(F*F+A*A)*He+ct*ct*He*He));const _t=R.projection.pixelsPerMeter(R.center.lat,pe),Rt=R._camera.getCameraToWorldMercator(),$t=[0,0,-ot*ke];o.ah($t,$t,Rt);let kt=wt*ke;const ks=function(jn){return jn[0]/=ae,jn[1]/=ae,jn[2]=o.bU(jn[2],R._center.lat),jn},Jt=R._edgeInsets;if(!(Jt.left===0&&Jt.top===0&&Jt.right===0&&Jt.bottom===0||Jt.left===Jt.right&&Jt.top===Jt.bottom)){const jn=R._camera.getWorldToCamera(R.worldSize,R.projection.zAxisUnit==="meters"?_t:1),yr=R._camera.getCameraToClipPerspective(R._fov,R.width/R.height,A,F);yr[8]=2*-R.centerOffset.x/R.width,yr[9]=2*R.centerOffset.y/R.height;const rr=new Float64Array(16);o.cz(rr,yr,jn);const ar=new Float64Array(16);o.b7(ar,rr);const zn=o.cl.fromInvProjectionMatrix(ar,pe,X,!0);for(const ta of zn.points){const va=ks(ta);kt=Math.max(kt,o.bK(o.cV([],$t,va)))}}kt*=V/(V-1);const ws=Math.acos(w[2]),Vt=Math.atan2(-w[0],-w[1]),Xt=new Pf;Xt.position=$t,Xt.setPitchBearing(ws,Vt);const ms=Xt.getWorldToCamera(pe,_t),Us=kt*pe,Cs=Math.min(R._mercatorZfromZoom(17)*pe*-2,-2*Us),pn=Xt.getCameraToClipOrthographic(-Us,Us,-Us,Us,Cs,(Us+Z*_t)/w[2]),an=new Float64Array(16);o.aD(an,pn,ms);const Ln=o.cQ(Math.floor(1e6*$t[0])/1e6*pe,Math.floor(1e6*$t[1])/1e6*pe,0),$n=.5*V,Ys=[0,0,0];o.ah(Ys,Ln,an),o.bJ(Ys,Ys,$n);const Es=[Math.floor(Ys[0]),Math.floor(Ys[1]),Math.floor(Ys[2])],hn=[0,0,0];o.ax(hn,Ys,Es),o.bJ(hn,hn,-1/$n);const fn=new Float64Array(16);return o.b9(fn),o.bx(fn,fn,hn),o.aD(an,fn,an),[an,Us]}class _1 extends o.E{constructor(w){super(),this.requestManager=w,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(w,A){return o.cX(this.requestManager.transformRequest(A,o.R.Model).url).then(F=>{const V=o.cY(F),Z=new o.cZ(w,A,void 0,void 0,V);return Z.computeBoundsAndApplyParent(),Z}).catch(F=>{if(F&&F.status===404)return null;this.fire(new o.B(new Error(`Could not load model ${w} from ${A}: ${F.message}`)))})}load(w,A,F={forceReload:!1}){this.models[A]||(this.models[A]={});const V=Object.keys(w),Z=[],X=[];for(const ae of V){const pe=w[ae];this.hasURLBeenRequested(pe)&&!F.forceReload||(this.modelByURL[pe]={modelId:ae,scope:A},Z.push(this.loadModel(ae,pe)),X.push(ae)),this.models[A][ae]||(this.models[A][ae]={model:null,numReferences:1})}this.numModelsLoading[A]=(this.numModelsLoading[A]||0)+X.length,Promise.allSettled(Z).then(ae=>{for(let pe=0;pe{this.fire(new o.B(new Error(`Could not load models: ${ae.message}`)))})}isLoaded(){for(const w in this.numModelsLoading)if(this.numModelsLoading[w]>0)return!1;return!0}hasModel(w,A,F={exactIdMatch:!1}){return!!(F.exactIdMatch?this.getModel(w,A):this.getModelByURL(this.modelUris[A][w]))}getModel(w,A){return this.models[A]||(this.models[A]={}),this.models[A][w]?this.models[A][w].model:void 0}getModelByURL(w){if(!w)return null;const A=this.modelByURL[w];return A?this.models[A.scope][A.modelId].model:null}hasModelBeenAdded(w,A){return this.models[A]&&this.models[A][w]!==void 0}getModelURIs(w){return this.modelUris[w]||{}}addModel(w,A,F){this.models[F]||(this.models[F]={}),this.modelUris[F]||(this.modelUris[F]={});const V=this.requestManager.normalizeModelURL(A);if((this.hasModel(w,F,{exactIdMatch:!0})||this.hasModelBeenAdded(w,F))&&this.modelUris[F][w]===V)this.models[F][w].numReferences++;else if(this.hasURLBeenRequested(V)){const{scope:Z,modelId:X}=this.modelByURL[V];this.models[Z][X].numReferences++}else this.modelUris[F][w]=V,this.load({[w]:this.modelUris[F][w]},F)}addModelURLs(w,A){this.models[A]||(this.models[A]={}),this.modelUris[A]||(this.modelUris[A]={});const F=this.modelUris[A];for(const V in w)F[V]=this.requestManager.normalizeModelURL(w[V])}reloadModels(w){this.load(this.modelUris[w],w,{forceReload:!0})}addModelsFromBucket(w,A){this.models[A]||(this.models[A]={}),this.modelUris[A]||(this.modelUris[A]={});const F={};for(const V of w)this.hasModel(V,A,{exactIdMatch:!0})||this.hasURLBeenRequested(V)?this.models[A][V].numReferences++:this.modelUris[A][V]&&!this.hasURLBeenRequested(V)?F[V]=this.modelUris[A][V]:!this.hasURLBeenRequested(V)&&o.c_(V,!1)&&(this.modelUris[A][V]=this.requestManager.normalizeModelURL(V),F[V]=this.modelUris[A][V]);this.load(F,A)}hasURLBeenRequested(w){return this.modelByURL[w]!==void 0}removeModel(w,A,F=!1,V=!1){if(this.models[A]&&this.models[A][w]&&(this.models[A][w].numReferences--,this.models[A][w].numReferences===0||V)){const Z=this.modelUris[A][w];F||delete this.modelUris[A][w],delete this.modelByURL[Z];const X=this.models[A][w].model;if(!X)return;delete this.models[A][w],X.destroy()}}destroy(){for(const w of Object.keys(this.models))for(const A of Object.keys(this.models[w])){const F=this.models[w][A].model;delete this.models[w][A],F&&F.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(w){return this.models[w]||(this.models[w]={}),Object.keys(this.models[w])}upload(w,A){this.models[A]||(this.models[A]={});for(const F in this.models[A])this.models[A][F].model&&this.models[A][F].model.upload(w.context)}}const gu=o.a8.colorTheme,zl=new o.ab({data:new o.ac(gu.data)});function Yo(R){if(!R.metadata||!R.metadata.content_area)return;const w=o.o.devicePixelRatio,{left:A,top:F,width:V,height:Z}=R.metadata.content_area,X=A*w,ae=F*w;return[X,ae,X+V*w,ae+Z*w]}function $o(R){if(R)return R.map(([w,A])=>[w*o.o.devicePixelRatio,A*o.o.devicePixelRatio])}class Gd{constructor(w,A,F){this.id=w,this.scope=A,this.sourceCache=F,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(w){this.missingRequests.has(w.name)||this.pendingRequests.has(w.name)||this.pendingRequests.add(w.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const w=new Map;if(!this.sourceCache.loaded())return w;const A=this.sourceCache.getVisibleCoordinates();if(A.length===0)return w;const F=this.sourceCache.getSource();if(!(F instanceof Jm))return w;const V=A.map(X=>this.sourceCache.getTile(X)),Z=F.getImages(V,Array.from(this.pendingRequests));for(const[X,ae]of Z)w.set(o.I.from({name:X,iconsetId:this.id}),ae),this.pendingRequests.delete(X);for(const X of this.pendingRequests)this.missingRequests.add(X);return this.pendingRequests.clear(),w}}class Yc{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(w,A,F,V,Z){if(Fpe*this._hysteresisRatio&&(X=this._previousClosestBuildingId):ke&&!X&&(X=this._previousClosestBuildingId),this._previousClosestBuildingId=X,X}_calculateDistance(w,A){if(!A.center)return Number.MAX_VALUE;const F=w.lat-A.center[1],V=w.lng-A.center[0];return F*F+V*V}_isBuildingVisible(w,A,F){if(!F)return!1;for(const V of w.floorIds){const Z=w.floors[V];if(!Z.geometry)continue;const X=Z.geometry;if(X.type==="Polygon"){const ae=this._convertRingToPoints(X.coordinates[0]);if(o.bw(ae,F))return!0}else if(X.type==="MultiPolygon"){const ae=this._convertMultiPolygonToPoints(X.coordinates);if(o.d0(F,ae))return!0}}return!1}_convertRingToPoints(w){return w.map(A=>new o.P(A[0],A[1]))}_convertMultiPolygonToPoints(w){return w.map(A=>A.length===0?[]:A[0].map(F=>new o.P(F[0],F[1])))}}class zx 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 Yc,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 A=!1;for(const[F,V]of Object.entries(w.buildings))if(this._buildings[F])for(const Z of V.floorIds)this._buildings[F].floorIds.add(Z),this._buildings[F].floors[Z]?this._mergeFloors(this._buildings[F].floors[Z],V.floors[Z]):(this._buildings[F].floors[Z]=V.floors[Z],A=!0);else this._buildings[F]=V,A=!0;A&&this._recalculateActiveFloors()}getIndoorTileOptions(w,A){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(w,A),indoorState:this._indoorState}:null}getControlState(){const w=this._buildings,A=this._closestBuildingId,F=A&&w?w[A]:void 0;if(!F)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let V=null;for(const X of F.floorIds)if(this._activeFloors&&this._activeFloors.has(X)){V=X;break}const Z=Array.from(F.floorIds).map(X=>({id:X,name:F.floors[X].name,zIndex:F.floors[X].zIndex})).sort((X,ae)=>ae.zIndex-X.zIndex).filter((X,ae,pe)=>ae===0||X.zIndex!==pe[ae-1].zIndex);return{selectedFloorId:V,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:Z}}_updateUI(){this._initialLoadDone=!0;const w=this._style.map.transform,A=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,w.center,w.zoom,w.getBounds(),this._makeViewportPolygon());if(A!==this._closestBuildingId){const F=this._closestBuildingId;this._closestBuildingId=A,this._onBuildingTransition(F,A),this._updateIndoorSelector()}}_onBuildingTransition(w,A){if(!this._indoorState)return;!A&&w?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!A&&!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(A,F){if(A===F)return!0;if(!A||!F||A.size!==F.size)return!1;for(const V of A)if(!F.has(V))return!1;return!0})(w,this._activeFloors)||(this._activeFloors=w,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(w,A){A.geometry&&(w.geometry?(w.geometry.type==="Polygon"&&(w.geometry={type:"MultiPolygon",coordinates:[w.geometry.coordinates]}),A.geometry.type==="Polygon"?w.geometry.coordinates.push(A.geometry.coordinates):A.geometry.type==="MultiPolygon"&&w.geometry.coordinates.push(...A.geometry.coordinates)):w.geometry=A.geometry)}_makeViewportPolygon(){const w=this._style.map.transform,A=w.width,F=w.height;return[w.pointLocation(new o.P(0,0)),w.pointLocation(new o.P(A,0)),w.pointLocation(new o.P(A,F)),w.pointLocation(new o.P(0,F))].map(V=>new o.P(V.lng,V.lat))}}const w0=(R,w)=>_r(R,w&&w.filter(A=>A.identifier!=="source.canvas")),uh=o.aJ(ki,["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"]),$b=o.aJ(ki,["setCenter","setZoom","setBearing","setPitch"]),mw=new Set(["background","sky","slot","custom"]),Ub={version:8,layers:[],sources:{}},Bx={duration:300,delay:0};class yu extends o.E{constructor(w,A={}){if(super(),this.map=w,this.scope=A.scope||"",this.globalId=null,this.fragments=[],this.importDepth=A.importDepth||0,this.importsCache=A.importsCache||new Map,this.resolvedImports=A.resolvedImports||new Set,this.transition=Object.assign({},Bx),this._buildingIndex=new g0(this),this.crossTileSymbolIndex=new Lf,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=A.styleChanges||new Ze,this._hasDataDrivenEmissive=!1,this.indoorManager=new zx(this),this.dispatcher=A.dispatcher?A.dispatcher:new dt(zt(),this),this.map.painter&&this.map.painter.context){const V=this.map.painter.context.maxUniformBufferBindings,Z=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:V,maxUniformBlockSizeDwords:Z,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}A.imageManager?this.imageManager=A.imageManager:(this.imageManager=new Gt(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=A.glyphManager?A.glyphManager:new o.d2(w._requestManager,A.localFontFamily?o.d3.all:A.localIdeographFontFamily?o.d3.ideographs:o.d3.none,A.localFontFamily||A.localIdeographFontFamily,A.useServerFontComposition),A.modelManager?this.modelManager=A.modelManager:(this.modelManager=new _1(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=A.configOptions?A.configOptions:new Map,this._configDependentLayers=A.configDependentLayers?A.configDependentLayers:new Set,this._indoorDependentLayers=A.indoorDependentLayers?A.indoorDependentLayers:new Set,this._config=A.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:A.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=A.initialConfig,this.dispatcher.broadcast("setReferrer",o.d4()),this.dispatcher.broadcast("setConfig",o.d5());const F=this;this._rtlTextPluginCallback=yu.registerForPluginStateChange(V=>{F.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:V.pluginStatus,pluginURL:V.pluginURL},(Z,X)=>{if(o.d6(Z),X&&X.every(ae=>ae))for(const ae in F._sourceCaches){const pe=F._sourceCaches[ae],ke=pe.getSource().type;ke!=="vector"&&ke!=="geojson"||pe.reload()}})}),this.on("data",V=>{if(V.dataType!=="source"||V.sourceDataType!=="metadata")return;const Z=this.getOwnSource(V.sourceId);if(Z&&Z.vectorLayerIds)for(const X in this._layers){const ae=this._layers[X];ae.source===Z.id&&this._validateLayer(ae)}})}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 A=o.d7(w);if(!A.startsWith("http"))try{return new URL(A,location.href).toString()}catch{return A}return A}return`json://${o.d8(JSON.stringify(w))}`}_diffStyle(w,A,F){this.globalId=this._getGlobalId(w);const V=(Z,X)=>{try{X(null,this.setState(Z,F))}catch(ae){X(ae,!1)}};if(typeof w=="string"){const Z=this.map._requestManager.normalizeStyleURL(w),X=this.map._requestManager.transformRequest(Z,o.R.Style);o.m(X,(ae,pe)=>{ae?this.fire(new o.B(ae)):pe&&V(pe,A)})}else typeof w=="object"&&V(w,A)}loadURL(w,A={}){this.fire(new o.C("dataloading",{dataType:"style"}));const F=typeof A.validate=="boolean"?A.validate:!o.e(w);this.globalId=this._getGlobalId(w),w=this.map._requestManager.normalizeStyleURL(w,A.accessToken),this.resolvedImports.add(w);const V=this.importsCache.get(w);if(V)return this._load(V,F);const Z=this.map._requestManager.transformRequest(w,o.R.Style);this._request=o.m(Z,(X,ae)=>{if(this._request=null,X)this.fire(new o.B(X));else if(ae)return this.importsCache.set(w,ae),this._load(ae,F)})}loadJSON(w,A={}){this.fire(new o.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(w),this._request=o.o.frame(()=>{this._request=null,this._load(w,A.validate!==!1)})}loadEmpty(){this.fire(new o.C("dataloading",{dataType:"style"})),this._load(Ub,!1)}_loadImports(w,A,F){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const V=[];for(const Z of w){const X=this._createFragmentStyle(Z),ae=new Promise(Me=>{X.once("style.import.load",Me),X.once("error",Me)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if(V.push(ae),this.resolvedImports.has(Z.url)){X.loadEmpty();continue}const pe=Z.data||this.importsCache.get(Z.url);pe?(Z.data?(X.fire(new o.C("dataloading",{dataType:"style"})),X.globalId=X._getGlobalId(pe),queueMicrotask(()=>X._load(pe,A))):X.loadJSON(pe,{validate:A}),this._isInternalStyle(pe)&&(X.globalId=null)):Z.url?X.loadURL(Z.url,{validate:A}):X.loadEmpty();const ke={style:X,id:Z.id,config:Z.config};if(F){const Me=this.fragments.findIndex(({id:Ke})=>Ke===F);this.fragments=this.fragments.slice(0,Me).concat(ke).concat(this.fragments.slice(Me))}else this.fragments.push(ke)}return Promise.allSettled(V)}getImportGlobalIds(w=this,A=new Set){for(const F of w.fragments)F.style.globalId&&A.add(F.style.globalId),this.getImportGlobalIds(F.style,A);return[...A.values()]}_createFragmentStyle(w){const A=this.scope?o.F(w.id,this.scope):w.id;let F;const V=this._initialConfig&&this._initialConfig[A];(w.config||V)&&(F=Object.assign({},w.config,V));const Z=new yu(this.map,{scope:A,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:F,configOptions:this.options,colorThemeOverride:w["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return Z.setEventedParent(this.map,{style:Z}),Z}_reloadImports(){this.mergeAll(),this._updateMapProjection(),this.updateConfigDependencies(),this._updateLayers(this._indoorDependentLayers),this.map._triggerCameraUpdate(this.camera),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),this._shouldPrecompile=this.map._precompilePrograms&&this.isRootStyle()}_isInternalStyle(w){return this.isRootStyle()&&(w.fragment||!!w.schema&&w.fragment!==!1)}_load(w,A){if(this._isInternalStyle(w)){const Z=Object.assign({},Ub,{imports:[{id:"basemap",data:w,url:""}]},w.center?{center:w.center}:{},w.bearing?{bearing:w.bearing}:{},w.pitch?{pitch:w.pitch}:{},w.zoom?{zoom:w.zoom}:{},w.light?{light:w.light}:{});return this._importedAsBasemap=!0,void this._load(Z,A)}if(this.updateConfig(this._config,w.schema),A&&w0(this,Jn(w)))return;this._loaded=!0;for(const Z in w.sources)this.addSource(Z,w.sources[Z],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(w);const F=()=>{if(w.iconsets)for(const 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 Z=sp(this.stylesheet.layers);if(this._order=Z.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 Mr(pe.properties,pe.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Mr(this.stylesheet.light)),this._layers={};for(const pe of Z){const ke=o.de(pe,this.scope,this._styleColorTheme.lut,this.options);ke.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(ke.fqid),ke.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(ke.fqid),this._hasAppearances=this._hasAppearances||ke.getAppearances().length!==0,ke.setEventedParent(this,{layer:{id:ke.id}}),this._layers[ke.id]=ke;const Me=this.getOwnLayerSourceCache(ke),Ke=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Me&&ke.canCastShadows()&&Ke&&(Me.castsShadows=!0)}if(this.glyphManager.url){const pe=new Set;for(const ke in this._layers){const Me=this._layers[ke];if(Me.type==="symbol"&&Me.layout){const Ke=Me.layout.get("text-font");Ke&&Ke.value&&Ke.value.kind==="constant"&&pe.add(Ke.value.value.join(","))}}for(const ke of pe)this.glyphManager.prefetchRange(ke,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const X=this.stylesheet.terrain;X&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(X,1)),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.snow&&this._createSnow(this.stylesheet.snow),this.stylesheet.rain&&this._createRain(this.stylesheet.rain),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new o.C("data",{dataType:"style"}));const ae=this.isRootStyle();w.imports?this._loadImports(w.imports,A).then(()=>{this._reloadImports(),this.fire(new o.C(ae?"style.load":"style.import.load"))}).catch(pe=>{this.fire(new o.B(new Error("Failed to load imports",pe))),this.fire(new o.C(ae?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(ae?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const V=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(V){const Z=this._evaluateColorThemeData(V);this._loadColorTheme(Z).then(()=>{F()}).catch(X=>{o.w(`Couldn't load color theme from the stylesheet: ${X}`),F()})}else this._styleColorTheme.lut=null,F()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(w=>w.style.hasAppearances())}mergeAll(){let w,A,F,V,Z,X,ae,pe,ke,Me;const Ke={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(He=>{if(He.stylesheet){if(He.light!=null&&(w=He.light),He.stylesheet.lights)for(const tt of He.stylesheet.lights)tt.type==="ambient"&&He.ambientLight!=null&&(A=He.ambientLight),tt.type==="directional"&&He.directionalLight!=null&&(F=He.directionalLight);V=this._prioritizeTerrain(V,He.terrain,He.stylesheet.terrain),He.stylesheet.fog&&He.fog!=null&&(Z=He.fog),He.stylesheet.snow&&He.snow!=null&&(X=He.snow),He.stylesheet.rain&&He.rain!=null&&(ae=He.rain),He.stylesheet.camera!=null&&(Me=He.stylesheet.camera),He.stylesheet.projection!=null&&(pe=He.stylesheet.projection),He.stylesheet.transition!=null&&(ke=He.stylesheet.transition),Ke[He.scope]=He._styleColorTheme}}),this.light=w,this.ambientLight=A,this.directionalLight=F,this.fog=Z,this.snow=X,this.rain=ae,this._styleColorThemeForScope=Ke,V===null?delete this.terrain:this.terrain=V,this.camera=Me||{"camera-projection":"perspective"},this.projection=pe||{name:"mercator"},this.transition=Object.assign({},Bx,ke),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(w){const A=F=>{for(const V of F.fragments)A(V.style);w(F)};A(this)}_prioritizeTerrain(w,A,F){const V=w&&w.drapeRenderMode===0;return F===null?A&&A.drapeRenderMode===0?A:V?w:null:A!=null&&(!w||V||A&&A.drapeRenderMode===1)?A:w}mergeTerrain(){let w;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(A=>{w=this._prioritizeTerrain(w,A.terrain,A.stylesheet.terrain)}),w===null?delete this.terrain:this.terrain=w}mergeProjection(){let w;this.forEachFragmentStyle(A=>{A.stylesheet.projection!=null&&(w=A.stylesheet.projection)}),this.projection=w||{name:"mercator"}}mergeSources(){const w={},A={},F={},V={};this.forEachFragmentStyle(Z=>{for(const X in Z._sourceCaches){const ae=o.F(X,Z.scope);w[ae]=Z._sourceCaches[X]}for(const X in Z._otherSourceCaches){const ae=o.F(X,Z.scope);A[ae]=Z._otherSourceCaches[X]}for(const X in Z._symbolSourceCaches){const ae=o.F(X,Z.scope);F[ae]=Z._symbolSourceCaches[X]}for(const X in Z._fillExtrusionSourceCaches){const ae=o.F(X,Z.scope);V[ae]=Z._fillExtrusionSourceCaches[X]}}),this._mergedSourceCaches=w,this._mergedOtherSourceCaches=A,this._mergedSymbolSourceCaches=F,this._mergedFillExtrusionSourceCaches=V}mergeIndoor(){this.forEachFragmentStyle(w=>{if(w.stylesheet&&w.stylesheet.indoor)for(const A of Object.values(w.stylesheet.indoor)){const F=A,V=o.F(F.sourceId,w.scope);this._mergedIndoor[V]=new Set(F.sourceLayers||[])}})}mergeLayers(){const w={},A=[],F={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(X=>{for(const ae of X._order){const pe=X._layers[ae];if(pe.type==="slot"){const ke=o.da(ae);if(w[ke])continue;w[ke]=[]}pe.slot&&w[pe.slot]?w[pe.slot].push(pe):A.push(pe)}}),this._mergedOrder=[];let V=-1;const Z=(X=[])=>{for(const ae of X)if(ae.type==="slot"){const pe=o.da(ae.id);w[pe]&&Z(w[pe]),this._mergedSlots.push(pe)}else{const pe=o.F(ae.id,ae.scope);this._mergedOrder.push(pe),F[pe]=ae,ae.is3D(!!this.terrain)&&(this._has3DLayers=!0,V=this._mergedOrder.length-1),ae.type==="circle"&&(this._hasCircleLayers=!0),ae.type==="symbol"&&(this._hasSymbolLayers=!0),ae.type==="clip"&&(this._clipLayerPresent=!0)}};if(Z(A),this._has3DLayers){const X={};for(let ae=0;aeX[ae]-X[pe])}this._mergedLayers=F,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(w){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,w),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(w){return w.data?function(A,F,V){const Z=Object.assign({},F);for(const ae of Object.keys(gu))Z[ae]===void 0&&(Z[ae]=gu[ae].default);const X=new o.aa(zl,A,new Map(V));return X.setTransitionOrValue(Z,V),X.untransitioned().possiblyEvaluate(new o.ae(0,{worldview:void 0}))}(this.scope,w,this.options).get("data"):null}_loadColorTheme(w){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const A=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((F,V)=>{const Z="data:image/png;base64,";if(!w||w.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void F();let X=w;X.startsWith(Z)||(X=Z+X);const ae=o.I.from("mapbox-reserved-lut"),pe=new Image;pe.src=X,pe.onerror=()=>{this._styleColorTheme.lutLoading=!1,V(new Error("Failed to load image data"))},pe.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==A)return void F();this._styleColorTheme.lutLoading=!1;const{width:ke,height:Me,data:Ke}=o.o.getImageData(pe);if(Me>32)return void V(new Error("The height of the image must be less than or equal to 32 pixels."));if(ke!==Me*Me)return void V(new Error("The width of the image must be equal to the height squared."));this.getImage(ae)&&this.removeImage(ae),this.addImage(ae,{data:new o.q({width:ke,height:Me},Ke),pixelRatio:1,sdf:!1,usvg:!1,version:0});const He=this.imageManager.getImage(ae,this.scope);He?(this._styleColorTheme.lut={image:He.data,data:w},F()):V(new Error("Missing LUT image."))}})}getLut(w){const A=this._styleColorThemeForScope[w];return A?A.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(A,F,V){let Z,X,ae;const pe=o.o.devicePixelRatio>1?"@2x":"";let ke=o.m(F.transformRequest(F.normalizeSpriteURL(A,pe,".json"),o.R.SpriteJSON),(He,tt)=>{ke=null,ae||(ae=He,Z=tt,Ke())}),Me=o.n(F.transformRequest(F.normalizeSpriteURL(A,pe,".png"),o.R.SpriteImage),(He,tt)=>{Me=null,ae||(ae=He,X=tt,Ke())});function Ke(){if(ae)V(ae);else if(Z&&X){const He=o.o.getImageData(X),tt={};for(const ct in Z){const{width:ot,height:wt,x:_t,y:Rt,sdf:$t,pixelRatio:kt,stretchX:ks,stretchY:Jt,content:ws}=Z[ct],Vt=new o.q({width:ot,height:wt});o.q.copy(He,Vt,{x:_t,y:Rt},{x:0,y:0},{width:ot,height:wt},null),tt[ct]={data:Vt,pixelRatio:kt!==void 0?kt:1,sdf:$t!==void 0&&$t,stretchX:ks,stretchY:Jt,content:ws,usvg:!1,version:0}}V(null,tt)}}return{cancel(){ke&&(ke.cancel(),ke=null),Me&&(Me.cancel(),Me=null)}}}(w,this.map._requestManager,(A,F)=>{if(this._spriteRequest=null,A)this.fire(new o.B(A));else if(F){const V=new Map;for(const Z in F)V.set(o.I.from(Z),F[Z]);this.addImages(V)}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,A){if(A.type==="sprite")return void this._loadSprite(A.url);const F=this.getOwnSourceCache(A.source);if(!F)return void this.fire(new o.B(new Error(`Source "${A.source}" as specified by iconset "${w}" does not exist and cannot be used as an iconset source`)));const V=F.getSource();if(V.type!=="raster-array")return void this.fire(new o.B(new Error(`Source "${A.source}" as specified by iconset "${w}" is not a "raster-array" source and cannot be used as an iconset source`)));V.partial=!1;const Z=new Gd(w,this.scope,F);this.imageManager.addImageProvider(Z,this.scope)}removeIconset(w){this.imageManager.removeImageProvider(w,this.scope)}_loadIconset(w){if(!o.e(w)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(w);const A=this.map._spriteFormat==="auto";var F,V;this._spriteRequest=(V=(Z,X)=>{if(this._spriteRequest=null,Z)A?this._loadSprite(w):this.fire(new o.B(Z));else if(X){const ae=new Map;for(const pe in X)ae.set(o.I.from(pe),X[pe]);this.addImages(ae)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))},o.b1((F=this.map._requestManager).transformRequest(F.normalizeIconsetURL(w),o.R.Iconset),(Z,X)=>{if(Z)return void V(Z);const ae={},pe=o.c$(new o.a$(X));for(const ke of pe.icons){const Me={version:1,pixelRatio:o.o.devicePixelRatio,content:Yo(ke),stretchX:ke.metadata?$o(ke.metadata.stretch_x_areas):void 0,stretchY:ke.metadata?$o(ke.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:ke};ae[ke.name]=Me}V(null,ae)}))}_validateLayer(w){const A=this.getOwnSource(w.source);if(!A)return;const F=w.sourceLayer;F&&(A.type==="geojson"||A.vectorLayerIds&&A.vectorLayerIds.indexOf(F)===-1)&&this.fire(new o.B(new Error(`Source layer "${F}" does not exist on source "${A.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,A)=>{const F=this.fragments[A];return F&&F.style&&(w.data=F.style.serialize()),w})}_serializeSources(){const w={};for(const A in this._sourceCaches){const F=this._sourceCaches[A].getSource();w[F.id]||(w[F.id]=F.serialize())}return w}_serializeLayers(w){const A=[];for(const F of w){const V=this._layers[F];V&&V.type!=="custom"&&A.push(V.serialize())}return A}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 A=this._mergedLayers[w];if(A._transitionablePaint&&A._transitionablePaint._values){const F=A._transitionablePaint._values["line-emissive-strength"];if(F&&F.value&&F.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(w){return w?this.order:this._mergedOrder}isLayerDraped(w){return!!this.terrain&&w.isDraped(this.getLayerSourceCache(w))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(w){const A=this.getOwnLayer(w);if(A)return A;this.fire(new o.B(new Error(`The layer '${w}' does not exist in the map's style.`)))}_checkSource(w){const A=this.getOwnSource(w);if(A)return A;this.fire(new o.B(new Error(`The source '${w}' does not exist in the map's style.`)))}precompilePrograms(w,A){const F=this.map.painter;if(F)for(let V=w.minzoom||0;V<(w.maxzoom||25.5);V++){const Z=w.getProgramIds();if(Z)for(const X of Z){const ae=w.getDefaultProgramParams(X,A.zoom,this._styleColorTheme.lut);ae&&(F.style=this,this.fog&&(F._fogVisible=!0,ae.overrideFog=!0,F.getOrCreateProgram(X,ae)),F._fogVisible=!1,ae.overrideFog=!1,F.getOrCreateProgram(X,ae),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(ae.overrideRtt=!0,F.getOrCreateProgram(X,ae)))}}}update(w){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(w),this.directionalLight&&this.directionalLight.recalculate(w);const A=this.calculateLightsBrightness();w.brightness=A||0,A!==this._brightness&&(this._brightness=A,this.dispatcher.broadcast("setBrightness",A)),w.worldview!==this._worldview&&(this._worldview=w.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const F=this._changes.isDirty();let V=!1;if(this._changes.isDirty()){const pe=this._changes.getLayerUpdatesByScope();for(const ke in pe){const{updatedIds:Me,removedIds:Ke}=pe[ke];(Me||Ke)&&(this._updateWorkerLayers(ke,Me,Ke),V=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(w),this.light&&this.light.updateTransitions(w),this.ambientLight&&this.ambientLight.updateTransitions(w),this.directionalLight&&this.directionalLight.updateTransitions(w),this.fog&&this.fog.updateTransitions(w),this.snow&&this.snow.updateTransitions(w),this.rain&&this.rain.updateTransitions(w),this._changes.reset()}const Z={};for(const pe in this._mergedSourceCaches){const ke=this._mergedSourceCaches[pe];Z[pe]=ke.used,ke.used=!1,ke.tileCoverLift=0}const X={};for(const pe of this._mergedOrder){const ke=this._mergedLayers[pe];if((ke.visibility!=="none"||ke.hasTransition())&&ke.recalculate(w,this._availableImages),!ke.isHidden(w.zoom)){const Me=this.getLayerSourceCache(ke);Me&&(Me.used=!0,Me.tileCoverLift=Math.max(Me.tileCoverLift,ke.tileCoverLift()))}if(ke.type==="fill-extrusion"){const Me=o.F(ke.source,ke.scope);if(Me in this._mergedFillExtrusionSourceCaches){const Ke=ke.layout&&ke.layout.get("source-max-zoom");if(Ke!=null){const He=X[Me];X[Me]=He==null?Ke:Math.min(He,Ke)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(ke,w)}):this.precompilePrograms(ke,w))}this._shouldPrecompile&&(this._precompileDone=!0);for(const pe in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[pe].setMaxzoomOverride(X[pe]!=null?X[pe]:null);this.terrain&&V&&this.mergeLayers();const ae=this.imageManager.getPendingImageProviders();for(const pe of ae)pe.sourceCache.used=!0;for(const pe in Z){const ke=this._mergedSourceCaches[pe];Z[pe]!==ke.used&&ke.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:ke.getSource().id}))}this.light&&this.light.recalculate(w),this.terrain&&this.terrain.recalculate(w),this.fog&&this.fog.recalculate(w),this.snow&&this.snow.recalculate(w),this.rain&&this.rain.recalculate(w),this.z=w.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),F&&this.fire(new o.C("data",{dataType:"style"}))}updateImageProviders(){const w=this.imageManager.getPendingImageProviders();for(const A of w){const F=A.resolvePendingRequests(),V=this.getFragmentStyle(A.scope);V&&V.addImages(F)}}_updateTilesForChangedImages(){const w={};for(const A in this._mergedSourceCaches){const F=this._mergedSourceCaches[A].getSource().scope;w[F]=w[F]||this._changes.getUpdatedImages(F),w[F].length!==0&&this._mergedSourceCaches[A].reloadTilesForDependencies(["icons","patterns"],w[F])}for(const A in w)this._changes.resetUpdatedImages(A)}_updateWorkerLayers(w,A,F){const V=this.getFragmentStyle(w);V&&this.dispatcher.broadcast("updateLayers",{layers:A?V._serializeLayers(A):[],scope:w,removedIds:F||[],options:V.options})}setState(w,A){if(this._checkLoaded(),w0(this,Jn(w)))return!1;(w=o.d9(w)).layers=sp(w.layers);const F=function(X,ae){if(!X)return[{command:ki.setStyle,args:[ae]}];let pe=[];try{if(!o.b6(X.version,ae.version))return[{command:ki.setStyle,args:[ae]}];if(o.b6(X.center,ae.center)||pe.push({command:ki.setCenter,args:[ae.center]}),o.b6(X.zoom,ae.zoom)||pe.push({command:ki.setZoom,args:[ae.zoom]}),o.b6(X.bearing,ae.bearing)||pe.push({command:ki.setBearing,args:[ae.bearing]}),o.b6(X.pitch,ae.pitch)||pe.push({command:ki.setPitch,args:[ae.pitch]}),o.b6(X.sprite,ae.sprite)||pe.push({command:ki.setSprite,args:[ae.sprite]}),o.b6(X.glyphs,ae.glyphs)||pe.push({command:ki.setGlyphs,args:[ae.glyphs]}),o.b6(X.imports,ae.imports)||function(tt=[],ct=[],ot){ct=ct||[];const wt=(tt=tt||[]).map(wm),_t=ct.map(wm),Rt=tt.reduce(ix,{}),$t=ct.reduce(ix,{}),kt=wt.slice();let ks,Jt,ws,Vt;for(ks=0,Jt=0;ks{tt.source&&ke[tt.source]?pe.push({command:ki.removeLayer,args:[tt.id]}):Ke.push(tt)});let He=X.terrain;He&&ke[He.source]&&(pe.push({command:ki.setTerrain,args:[void 0]}),He=void 0),pe=pe.concat(Me),o.b6(He,ae.terrain)||pe.push({command:ki.setTerrain,args:[ae.terrain]}),function(tt,ct,ot){ct=ct||[];const wt=(tt=tt||[]).map(wm),_t=ct.map(wm),Rt=tt.reduce(ix,{}),$t=ct.reduce(ix,{}),kt=wt.slice(),ks=Object.create(null);let Jt,ws,Vt,Xt,ms,Us,Cs;for(Jt=0,ws=0;Jt!(X.command in $b));if(F.length===0)return!1;const V=F.filter(X=>!(X.command in uh));if(V.length>0)throw new Error(`Unimplemented: ${V.map(X=>X.command).join(", ")}.`);const Z=[];return F.forEach(X=>{Z.push(this[X.command](...X.args))}),A&&Promise.all(Z).then(A).catch(A),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[A,F]of w.entries()){if(this.getImage(A))return this.fire(new o.B(new Error(`An image with the name "${A.name}" already exists.`)));this.imageManager.addImage(A,this.scope,F),this._changes.updateImage(A,this.scope)}return this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this}addImage(w,A){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,A),this._changes.updateImage(w,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this)}updateImage(w,A,F=!1){this.imageManager.updateImage(w,this.scope,A),F&&(this._changes.updateImage(w,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})))}getImage(w){return this.imageManager.getImage(w,this.scope)}removeImage(w){return this.getImage(w)?(this.imageManager.removeImage(w,this.scope),this._changes.updateImage(w,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this):this.fire(new o.B(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(w){return this.modelManager.addModelURLs(w,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.C("data",{dataType:"style"})),this}addModel(w,A,F={}){return this._checkLoaded(),this._validate(Tn,`models.${w}`,A,null,F)||(this.modelManager.addModel(w,A,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,A,F={}){if(this._checkLoaded(),this.getOwnSource(w)!==void 0)throw new Error(`There is already a source with ID "${w}".`);if(!A.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(A).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(A.type)>=0&&this._validate(ea,`sources.${w}`,A,null,F))return;this.map&&this.map._collectResourceTiming&&(A.collectResourceTiming=!0);const V=Ef(w,A,this.dispatcher,this);V.scope=this.scope,V.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(V.id),source:V.serialize(),sourceId:V.id}));const Z=X=>{const ae=(X===o.b4.Symbol?"symbol:":X===o.b4.FillExtrusion?"fill-extrusion:":"other:")+V.id,pe=o.F(ae,this.scope),ke=this._sourceCaches[ae]=new Vl(pe,V,X);X===o.b4.Symbol?this._symbolSourceCaches[V.id]=ke:X===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[V.id]=ke:this._otherSourceCaches[V.id]=ke,ke.onAdd(this.map)};Z(o.b4.Other),A.type!=="vector"&&A.type!=="geojson"||(Z(o.b4.Symbol),A.type==="vector"&&Z(o.b4.FillExtrusion)),V.onAdd&&V.onAdd(this.map),F.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(w){this._checkLoaded();const A=this.getOwnSource(w);if(!A)throw new Error("There is no source with this ID");for(const V in this._layers)if(this._layers[V].source===w)return this.fire(new o.B(new Error(`Source "${w}" cannot be removed while layer "${V}" 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 V=Object.entries(this.stylesheet.iconsets).find(([Z,X])=>X.type==="source"&&X.source===w);if(V)return this.fire(new o.B(new Error(`Source "${w}" cannot be removed while iconset "${V[0]}" is using it.`)))}const F=this.getOwnSourceCaches(w);for(const V of F){const Z=o.da(V.id);delete this._sourceCaches[Z],this._changes.discardSourceCacheUpdate(V.id),V.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:V.getSource().id})),V.setEventedParent(null),V.clearTiles()}return delete this._otherSourceCaches[w],delete this._symbolSourceCaches[w],delete this._fillExtrusionSourceCaches[w],this.mergeSources(),A.setEventedParent(null),A.onRemove&&A.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(w,A){this._checkLoaded(),this.getOwnSource(w).setData(A),this._changes.setDirty()}getOwnSource(w){const A=this.getOwnSourceCache(w);return A&&A.getSource()}getOwnSources(){const w=[];for(const A in this._otherSourceCaches){const F=this.getOwnSourceCache(A);F&&w.push(F.getSource())}return w}areTilesLoaded(){const w=this._mergedSourceCaches;for(const A in w){const F=w[A]._tiles;for(const V in F){const Z=F[V];if(Z.state!=="loaded"&&Z.state!=="errored")return!1}}return!0}setLights(w){if(this._checkLoaded(),!w)return delete this.ambientLight,void delete this.directionalLight;const A=this._getTransitionParameters();for(const Z of w){if(this._validate(We,"lights",Z))return;switch(Z.type){case"ambient":if(this.ambientLight){const X=this.ambientLight;X.set(Z),X.updateTransitions(A)}else this.ambientLight=new Qn(Z,qa(),this.scope,this.options);break;case"directional":if(this.directionalLight){const X=this.directionalLight;X.set(Z),X.updateTransitions(A)}else this.directionalLight=new Qn(Z,Wo(),this.scope,this.options)}}const F=Object.assign(A,{worldview:this.map.getWorldview()}),V=new o.ae(this.z||0,F);this.ambientLight&&this.ambientLight.recalculate(V),this.directionalLight&&this.directionalLight.recalculate(V),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const w=this.directionalLight,A=this.ambientLight;if(!w||!A)return;const F=He=>.2126*(He[0]<=.03928?He[0]/12.92:Math.pow((He[0]+.055)/1.055,2.4))+.7152*(He[1]<=.03928?He[1]/12.92:Math.pow((He[1]+.055)/1.055,2.4))+.0722*(He[2]<=.03928?He[2]/12.92:Math.pow((He[2]+.055)/1.055,2.4)),V=w.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Z=w.properties.get("intensity"),X=w.properties.get("direction"),ae=1-o.cP(X.x,X.y,X.z)[2]/90,pe=F(V)*Z*ae,ke=A.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Me=A.properties.get("intensity"),Ke=F(ke)*Me;return Number(((pe+Ke)/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 A=o.dc(w),F=this.fragments.find(({id:Z})=>Z===A);if(!F)return;const V=o.da(w);return F.style.getFragmentStyle(V)}{const A=this.fragments.find(({id:F})=>F===w);return A?A.style:void 0}}setFeaturesetSelectors(w){if(!w)return;const A=(F,V="")=>`${F}::${V}`;this._featuresetSelectors={};for(const F in w){const V={},Z=this._featuresetSelectors[F]=[];for(const X of w[F].selectors){if(X.featureNamespace){const pe=this.getOwnLayer(X.layer);if(!pe){o.w(`Layer is undefined for selector: ${X.layer}`);continue}const ke=A(pe.source,pe.sourceLayer);if(ke in V&&V[ke]!==X.featureNamespace){o.w(`"featureNamespace ${X.featureNamespace} of featureset ${F}'s selector is not associated to the same source, skip this selector`);continue}V[ke]=X.featureNamespace}let ae;if(X.properties)for(const pe in X.properties){const ke=o.X(X.properties[pe]);ke.result==="success"&&(ae=ae||{},ae[pe]=ke.value)}Z.push({layerId:X.layer,namespace:X.featureNamespace,properties:ae,uniqueFeatureID:X._uniqueFeatureID})}}}getFeaturesetDescriptors(w){const A=this.getFragmentStyle(w);if(!A||!A.stylesheet.featuresets)return[];const F=[];for(const V in A.stylesheet.featuresets)F.push({featuresetId:V,importId:A.scope?A.scope:void 0});return F}getFeaturesetLayers(w,A){const F=this.getFragmentStyle(A),V=F.stylesheet.featuresets;if(!V||!V[w])return this.fire(new o.B(new Error(`The featureset '${w}' does not exist in the map's style and cannot be queried.`))),[];const Z=[];for(const X of V[w].selectors){const ae=F.getOwnLayer(X.layer);ae&&Z.push(ae)}return Z}getConfigProperty(w,A){const F=this.getFragmentStyle(w);if(!F)return null;const V=o.F(A,F.scope),Z=F.options.get(V),X=Z?Z.value||Z.default:null;return X?X.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(w,A){const F=o.F(w,A);return this._mergedIndoor[F]}setIndoorData(w,A){this.indoorManager.setIndoorData(A)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(w,A,F){const V=this.getFragmentStyle(w);if(!V)return;const Z=V.stylesheet.schema;if(!Z||!Z[A])return;const X=o.X(F);if(X.result!=="success")return void w0(this,X.value);const ae=X.value.expression,pe=o.F(A,V.scope),ke=V.options.get(pe);if(!ke)return;let Me;const{minValue:Ke,maxValue:He,stepValue:tt,type:ct,values:ot}=Z[A],wt=o.X(Z[A].default);wt.result==="success"&&(Me=wt.value.expression),Me?(this.options.set(pe,Object.assign({},ke,{value:ae,default:Me,minValue:Ke,maxValue:He,stepValue:tt,type:ct,values:ot})),this.updateConfigDependencies(A)):this.fire(new o.B(new Error(`No schema defined for the config option "${A}" in the "${w}" fragment.`)))}getConfig(w){const A=this.getFragmentStyle(w);if(!A)return null;const F=A.stylesheet.schema;if(!F)return null;const V={};for(const Z in F){const X=o.F(Z,A.scope),ae=A.options.get(X),pe=ae?ae.value||ae.default:null;V[Z]=pe?pe.serialize():null}return V}setConfig(w,A){const F=this.getFragmentStyle(w);F&&(F.updateConfig(A,F.stylesheet.schema),this.updateConfigDependencies())}getSchema(w){const A=this.getFragmentStyle(w);return A?A.stylesheet.schema:null}setSchema(w,A){const F=this.getFragmentStyle(w);F&&(F.stylesheet.schema=A,F.updateConfig(F._config,A),this.updateConfigDependencies())}updateConfig(w,A){if(this._config=w,w||A)if(A)for(const F in A){let V,Z;const X=o.X(A[F].default);if(X.result==="success"&&(V=X.value.expression),w&&w[F]!==void 0){const He=o.X(w[F]);He.result==="success"&&(Z=He.value.expression)}const{minValue:ae,maxValue:pe,stepValue:ke,type:Me,values:Ke}=A[F];if(V){const He=o.F(F,this.scope);this.options.set(He,{default:V,value:Z,minValue:ae,maxValue:pe,stepValue:ke,type:Me,values:Ke})}else this.fire(new o.B(new Error(`No schema defined for config option "${F}".`)))}else this.fire(new o.B(new Error("Attempting to set config for a style without schema.")))}_updateLayers(w,A=()=>!0){for(const F of w){const V=this.getLayer(F);V&&A(V)&&(V.possiblyEvaluateVisibility(),this._updateLayer(V),this._changes.setDirty())}}updateConfigDependencies(w){this._updateLayers(this._configDependentLayers,A=>!w||A.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(A=>{const F=A._styleColorTheme.colorThemeOverride?A._styleColorTheme.colorThemeOverride:A._styleColorTheme.colorTheme;if(F){const V=A._evaluateColorThemeData(F);(!A._styleColorTheme.lut&&V!==""||A._styleColorTheme.lut&&V!==A._styleColorTheme.lut.data)&&A.setColorTheme(F)}}),this._changes.setDirty()}addLayer(w,A,F={}){this._checkLoaded();const V=w.id;if(this._layers[V])return void this.fire(new o.B(new Error(`Layer with id "${V}" already exists on this map`)));let Z;if(w.type==="custom"){if(w0(this,o.dd(w)))return;Z=o.de(w,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof w.source=="object"&&(this.addSource(V,w.source),w=o.d9(w),w=Object.assign(w,{source:V})),this._validate(ts,`layers.${V}`,w,{arrayIndex:-1},F))return;Z=o.de(w,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(Z),Z.setEventedParent(this,{layer:{id:V}})}const X=o.F(Z.source,Z.scope);Z.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(X),Z.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(X);let ae=this._order.length;if(A){const Ke=this._order.indexOf(A);if(Ke===-1)return void this.fire(new o.B(new Error(`Layer with id "${A}" does not exist on this map.`)));Z.slot&&Z.slot!==this._layers[A].slot?o.w(`Layer with id "${A}" has a different slot. Layers can only be rearranged within the same slot.`):ae=Ke}this._order.splice(ae,0,V),this._handleLayerOrderChange(),this._layers[V]=Z;const pe=this.getOwnLayerSourceCache(Z),ke=!!this.directionalLight&&this.directionalLight.shadowsEnabled();pe&&Z.canCastShadows()&&ke&&(pe.castsShadows=!0);const Me=this._changes.getRemovedLayer(Z);if(Me&&Z.source&&pe&&Z.type!=="custom"){this._changes.discardLayerRemoval(Z);const Ke=o.F(Z.source,Z.scope);Me.type!==Z.type?this._changes.updateSourceCache(Ke,"clear"):(this._changes.updateSourceCache(Ke,"reload"),pe.pause())}this._updateLayer(Z),Z.onAdd&&Z.onAdd(this.map),Z.scope=this.scope,this.mergeLayers()}moveLayer(w,A){this._checkLoaded();const F=this._checkLayer(w);if(!F||w===A)return;const V=this._order.indexOf(w);this._order.splice(V,1);let Z=this._order.length;if(A){const X=this._order.indexOf(A);if(X===-1)return void this.fire(new o.B(new Error(`Layer with id "${A}" does not exist on this map.`)));F.slot&&F.slot!==this._layers[A].slot?o.w(`Layer with id "${A}" has a different slot. Layers can only be rearranged within the same slot.`):Z=X}this._order.splice(Z,0,w),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(w){this._checkLoaded();const A=this._checkLayer(w);if(!A)return;A.setEventedParent(null);const F=this._order.indexOf(w);this._order.splice(F,1),delete this._layers[w],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(A.fqid),this._indoorDependentLayers.delete(A.fqid),this._changes.removeLayer(A);const V=this.getOwnLayerSourceCache(A);if(V&&V.castsShadows){let Z=!1;for(const X in this._layers)if(this._layers[X].source===A.source&&this._layers[X].canCastShadows()){Z=!0;break}V.castsShadows=Z}A.onRemove&&A.onRemove(this.map),this.mergeLayers()}getOwnLayer(w){return this._layers[w]}hasLayer(w){return w in this._mergedLayers}hasLayerType(w){for(const A in this._layers)if(this._layers[A].type===w)return!0;return!1}setLayerZoomRange(w,A,F){this._checkLoaded();const V=this._checkLayer(w);V&&(V.minzoom===A&&V.maxzoom===F||(A!=null&&(V.minzoom=A),F!=null&&(V.maxzoom=F),this._updateLayer(V)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(w,A){this._checkLoaded();const F=this._checkLayer(w);F&&F.slot!==A&&(F.slot=A,this._updateLayer(F))}setFilter(w,A,F={}){this._checkLoaded();const V=this._checkLayer(w);if(V&&!o.b6(V.filter,A))return A==null?(V.filter=void 0,void this._updateLayer(V)):void(this._validate(Ms,`layers.${V.id}.filter`,A,{layerType:V.type},F)||(V.filter=o.d9(A),this._updateLayer(V)))}getFilter(w){const A=this._checkLayer(w);if(A)return o.d9(A.filter)}setLayoutProperty(w,A,F,V={}){this._checkLoaded();const Z=this._checkLayer(w);if(Z&&!o.b6(Z.getLayoutProperty(A),F)){if(F!=null&&(!V||V.validate!==!1)&&w0(Z,Zs.call(Jn,{key:`layers.${w}.layout.${A}`,layerType:Z.type,objectKey:A,value:F,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;Z.setLayoutProperty(A,F),Z.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Z.fqid),Z.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Z.fqid),this._updateLayer(Z)}}setLayerProperty(w,A,F,V={}){this._checkLoaded();const Z=this._checkLayer(w);Z&&(A==="appearances"?(Z.setAppearances(F),this._updateLayer(Z)):Z.isPaintProperty(A)?this.setPaintProperty(w,A,F,V):this.setLayoutProperty(w,A,F,V))}getLayoutProperty(w,A){const F=this._checkLayer(w);if(F)return F.getLayoutProperty(A)}setPaintProperty(w,A,F,V={}){this._checkLoaded();const Z=this._checkLayer(w);if(!Z||o.b6(Z.getPaintProperty(A),F)||F!=null&&(!V||V.validate!==!1)&&w0(Z,js.call(Jn,{key:`layers.${w}.paint.${A}`,layerType:Z.type,objectKey:A,value:F,styleSpec:o.a8})))return;const X=Z.setPaintProperty(A,F);Z.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(Z.fqid),Z.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(Z.fqid),X&&this._updateLayer(Z),this._changes.updatePaintProperties(Z)}getPaintProperty(w,A){const F=this._checkLayer(w);if(F)return F.getPaintProperty(A)}setFeatureState(w,A){if(this._checkLoaded(),"target"in w){if("featuresetId"in w.target){const{featuresetId:pe,importId:ke}=w.target,Me=this.getFragmentStyle(ke),Ke=Me.getFeaturesetLayers(pe);for(const{source:He,sourceLayer:tt}of Ke)Me.setFeatureState({id:w.id,source:He,sourceLayer:tt},A)}else if("layerId"in w.target){const{layerId:pe}=w.target,ke=this.getLayer(pe);this.setFeatureState({id:w.id,source:ke.source,sourceLayer:ke.sourceLayer},A)}return}const F=w.source,V=w.sourceLayer,Z=this._checkSource(F);if(!Z)return;const X=Z.type;if(X==="geojson"&&V)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(X==="vector"&&!V)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 ae=this.getOwnSourceCaches(F);for(const pe of ae)pe.setFeatureState(V,w.id,A)}removeFeatureState(w,A){if(this._checkLoaded(),"target"in w){if("featuresetId"in w.target){const{featuresetId:pe,importId:ke}=w.target,Me=this.getFragmentStyle(ke),Ke=Me.getFeaturesetLayers(pe);for(const{source:He,sourceLayer:tt}of Ke)Me.removeFeatureState({id:w.id,source:He,sourceLayer:tt},A)}else if("layerId"in w.target){const{layerId:pe}=w.target,ke=this.getLayer(pe);this.removeFeatureState({id:w.id,source:ke.source,sourceLayer:ke.sourceLayer},A)}return}const F=w.source,V=this._checkSource(F);if(!V)return;const Z=V.type,X=Z==="vector"?w.sourceLayer:void 0;if(Z==="vector"&&!X)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(A&&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 ae=this.getOwnSourceCaches(F);for(const pe of ae)pe.removeFeatureState(X,w.id,A)}getFeatureState(w){if(this._checkLoaded(),"target"in w){let Z;if("featuresetId"in w.target){const{featuresetId:X,importId:ae}=w.target,pe=this.getFragmentStyle(ae),ke=pe.getFeaturesetLayers(X);for(const{source:Me,sourceLayer:Ke}of ke){const He=pe.getFeatureState({id:w.id,source:Me,sourceLayer:Ke});if(He&&!Z)Z=He;else if(!o.b6(Z,He))return void this.fire(new o.B(new Error("The same feature id exists in multiple sources in the featureset, but their feature states are not consistent through the sources.")))}}else if("layerId"in w.target){const{layerId:X}=w.target,ae=this.getLayer(X);Z=this.getFeatureState({id:w.id,source:ae.source,sourceLayer:ae.sourceLayer})}return Z}const A=w.source,F=w.sourceLayer,V=this._checkSource(A);if(V){if(V.type!=="vector"||F)return w.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(A)[0].getFeatureState(F,w.id);this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(w){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,w),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(w){w!==this._worldview&&(this._worldview=w,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const w=this.getTerrain(),A=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:A,fog:this.stylesheet.fog,snow:this.stylesheet.snow,rain:this.stylesheet.rain,indoor:this.stylesheet.indoor,center:this.stylesheet.center,"color-theme":this.stylesheet["color-theme"],zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,projection:this.stylesheet.projection,sources:this._serializeSources(),layers:this._serializeLayers(this._order)},F=>F!==void 0)}_updateFilteredLayers(w){for(const A of Object.values(this._mergedLayers))w(A)&&this._updateLayer(A)}_updateLayer(w){this._changes.updateLayer(w);const A=this.getLayerSourceCache(w),F=o.F(w.source,w.scope),V=this._changes.getUpdatedSourceCaches();w.source&&!V[F]&&A&&A.getSource().type!=="raster"&&(this._changes.updateSourceCache(F,"reload"),A.pause()),w.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(w){const A=ae=>this._mergedLayers[ae].is3D(!!this.terrain),F=this.order,V={},Z=[];for(let ae=F.length-1;ae>=0;ae--){const pe=F[ae];if(A(pe)){V[pe]=ae;for(const ke of w){const Me=ke[pe];if(Me)for(const Ke of Me)Z.push(Ke)}}}Z.sort((ae,pe)=>pe.intersectionZ-ae.intersectionZ);const X=[];for(let ae=F.length-1;ae>=0;ae--){const pe=F[ae];if(A(pe))for(let ke=Z.length-1;ke>=0;ke--){const Me=Z[ke].feature;if(Me.layer&&V[Me.layer.id]{if(mw.has(Me.type))return;const Ke=this.getOwnLayerSourceCache(Me),He=Z[Ke.id]=Z[Ke.id]||{sourceCache:Ke,layers:{},has3DLayers:!1};Me.is3D(!!this.terrain)&&(He.has3DLayers=!0),He.layers[Me.fqid]=He.layers[Me.fqid]||{styleLayer:Me,targets:[]},He.layers[Me.fqid].targets.push({filter:V})};if(A&&A.layers){if(!Array.isArray(A.layers))return this.fire(new o.B(new Error("parameters.layers must be an Array."))),[];for(const Me of A.layers){const Ke=this._layers[Me];if(!Ke)return this.fire(new o.B(new Error(`The layer '${Me}' does not exist in the map's style and cannot be queried for features.`))),[];X(Ke)}}else for(const Me in this._layers)X(this._layers[Me]);const ae=this._queryRenderedFeatures(w,Z,F),pe=this._flattenAndSortRenderedFeatures(ae),ke=[];for(const Me of pe)o.dh(Me.layer.id)===this.scope&&ke.push(Me);return ke}queryRenderedFeatureset(w,A,F){let V;A&&!Array.isArray(A)&&A.filter&&(this._validate(Ms,"queryRenderedFeatures.filter",A.filter,null,A),V=o.dg(A.filter));const Z="mock",X=[];if(A&&A.target)X.push(Object.assign({},A,{targetId:Z,filter:V}));else{const Me=this.getFeaturesetDescriptors();for(const Ke of Me)X.push({targetId:Z,filter:V,target:Ke});for(const{style:Ke}of this.fragments){const He=Ke.getFeaturesetDescriptors();for(const tt of He)X.push({targetId:Z,filter:V,target:tt})}}const ae=this.queryRenderedTargets(w,X,F),pe=[],ke=new Set;for(const Me of ae)for(const Ke of Me.variants[Z])pu(Ke,Me,ke)||pe.push(new o.di(Me,Ke));return pe}queryRenderedTargets(w,A,F){const V={},Z=(ae,pe,ke,Me)=>{const Ke=V[pe.id]=V[pe.id]||{sourceCache:pe,layers:{},has3DLayers:!1};if(Ke.layers[ae.fqid]=Ke.layers[ae.fqid]||{styleLayer:ae,targets:[]},ae.is3D(!!this.terrain)&&(Ke.has3DLayers=!0),!Me)return ke.uniqueFeatureID=!1,void Ke.layers[ae.fqid].targets.push(ke);Ke.layers[ae.fqid].targets.push(Object.assign({},ke,{namespace:Me.namespace,properties:Me.properties,uniqueFeatureID:Me.uniqueFeatureID}))};for(const ae of A)if("featuresetId"in ae.target){const{featuresetId:pe,importId:ke}=ae.target,Me=this.getFragmentStyle(ke);if(!Me||!Me._featuresetSelectors)continue;const Ke=Me._featuresetSelectors[pe];if(!Ke){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 He of Ke){const tt=Me.getOwnLayer(He.layerId);tt&&!mw.has(tt.type)&&Z(tt,Me.getOwnLayerSourceCache(tt),ae,He)}}else if("layerId"in ae.target){const{layerId:pe}=ae.target,ke=this.getLayer(pe);if(!ke||mw.has(ke.type))continue;Z(ke,this.getLayerSourceCache(ke),ae)}const X=this._queryRenderedFeatures(w,V,F);return this._flattenAndSortRenderedFeatures(X)}_queryRenderedFeatures(w,A,F){const V=[],Z=!!this.map._showQueryGeometry,X=Co.createFromScreenPoints(w,F);for(const ae in A){const pe=Px(X,A[ae],this._availableImages,F,Z,this.getActualScope());Object.keys(pe).length&&V.push(pe)}if(this.placement)for(const ae in A){if(A[ae].sourceCache._renderSourceType!==o.b4.Symbol)continue;const pe=Do(X.screenGeometry,A[ae],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(pe).length&&V.push(pe)}return V}querySourceFeatures(w,A){const F=A&&A.filter;F&&this._validate(Ms,"querySourceFeatures.filter",F,null,A);let V=[];const Z=this.getOwnSourceCaches(w);for(const X of Z)V=V.concat(go(X,A));return V}addSourceType(w,A,F){return yu.getSourceType(w)?F(new Error(`A source type called "${w}" already exists.`)):(yu.setSourceType(w,A),A.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:w,url:A.workerSourceURL},F):F(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(w,A,F={}){this._checkLoaded();const V=this.light.getLight();let Z=!1;for(const ae in w)if(!o.b6(w[ae],V[ae])){Z=!0;break}if(!Z)return;const X=this._getTransitionParameters();this.light.setLight(w,A,F),this.light.updateTransitions(X)}getTerrain(){return this.terrain&&this.terrain.drapeRenderMode===1?this.terrain.get():null}setTerrainForDraping(){this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){this.disableElevatedTerrain===void 0&&(this.disableElevatedTerrain=o.o.hasCanvasFingerprintNoise(),this.disableElevatedTerrain&&o.w("Terrain and hillshade are disabled because of Canvas2D limitations when fingerprinting protection is enabled (e.g. in private browsing mode)."))}setTerrain(w,A=1){if(this._checkLoaded(),!w)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),A===0&&delete this.terrain,w===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let F=w;const V=!("source"in w)||w.source==null;if(A===1){if(this.disableElevatedTerrain)return;if("source"in F&&typeof F.source=="object"){const ae="terrain-dem-src";this.addSource(ae,F.source),F=o.d9(F),F=Object.assign(F,{source:ae})}const Z=Object.assign({},F),X={};if(this.terrain&&V){Z.source=this.terrain.get().source;const ae=this.terrain?this.getFragmentStyle(this.terrain.scope):null;ae&&(X.style=ae.serialize())}if(this._validate(it,"terrain",Z,X))return}if(!this.terrain||this.terrain.scope!==this.scope&&!V||this.terrain&&A!==this.terrain.drapeRenderMode){if(!F)return;this._createTerrain(F,A),this.fire(new o.C("data",{dataType:"style"}))}else{const Z=this.terrain,X=Z.get();for(const ae of Object.keys(o.a8.terrain))!F.hasOwnProperty(ae)&&o.a8.terrain[ae].default&&(F[ae]=o.a8.terrain[ae].default);for(const ae in w)if(!o.b6(w[ae],X[ae])){Z.set(w,this.options),this.stylesheet.terrain=w;const pe=this._getTransitionParameters({duration:0});Z.updateTransitions(pe),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(w){const A=this.fog=new ao(w,this.map.transform,this.scope,this.options);this.stylesheet.fog=A.get();const F=this._getTransitionParameters({duration:0});A.updateTransitions(F)}_createSnow(w){const A=this.snow=new $a(w,this.map.transform,this.scope,this.options);this.stylesheet.snow=A.get();const F=this._getTransitionParameters({duration:0});A.updateTransitions(F)}_createRain(w){const A=this.rain=new Gr(w,this.map.transform,this.scope,this.options);this.stylesheet.rain=A.get();const F=this._getTransitionParameters({duration:0});A.updateTransitions(F)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const w of this.map._markers)w._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(w){if(this._checkLoaded(),!w)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const A=this.fog;if(!o.b6(A.get(),w)){A.set(w,this.options),this.stylesheet.fog=A.get();const F=this._getTransitionParameters({duration:0});A.updateTransitions(F)}}else this._createFog(w);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(w){if(this._checkLoaded(),!w)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const A=this.snow;if(!o.b6(A.get(),w)){A.set(w,this.options),this.stylesheet.snow=A.get();const F=this._getTransitionParameters({duration:0});A.updateTransitions(F)}}else this._createSnow(w);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(w){if(this._checkLoaded(),!w)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const A=this.rain;if(!o.b6(A.get(),w)){A.set(w,this.options),this.stylesheet.rain=A.get();const F=this._getTransitionParameters({duration:0});A.updateTransitions(F)}}else this._createRain(w);this._markersNeedUpdate=!0}_reloadColorTheme(){const w=()=>{for(const V in this._layers)this._layers[V].lut=this._styleColorTheme.lut;for(const V in this._sourceCaches)this._sourceCaches[V].clearTiles()},A=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!A)return this._styleColorTheme.lut=null,void w();const F=this._evaluateColorThemeData(A);this._loadColorTheme(F).then(()=>{this.fire(new o.C("colorthemeset")),w()}).catch(V=>{o.w(`Couldn't set color theme: ${V}`)})}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,A){const F=this.getFragmentStyle(w);F&&(F._styleColorTheme.colorThemeOverride=A,F._reloadColorTheme())}_getTransitionParameters(w){return{now:o.o.now(),transition:Object.assign(this.transition,w)}}updateDrapeFirstLayers(){if(!this.terrain)return;const w=[],A=[];for(const F of this._mergedOrder)this.isLayerDraped(this._mergedLayers[F])?w.push(F):A.push(F);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...w),this._drapedFirstOrder.push(...A)}_createTerrain(w,A){const F=this.terrain=new Qt(w,A,this.scope,this.options,this.map.getWorldview());A===1&&(this.stylesheet.terrain=w),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const V=this._getTransitionParameters({duration:0});F.updateTransitions(V)}_force3DLayerUpdate(){for(const w in this._layers){const A=this._layers[w];A.type==="fill-extrusion"&&this._updateLayer(A)}}_forceSymbolLayerUpdate(){for(const w in this._layers){const A=this._layers[w];A.type==="symbol"&&this._updateLayer(A)}}_validate(w,A,F,V,Z={}){if(Z&&Z.validate===!1)return!1;const X=Object.assign({},this.serialize());return w0(this,w.call(Jn,Object.assign({key:A,style:X,value:F,styleSpec:o.a8},V)))}_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 A=this.getSourceCaches(w);for(const F of A)F.clearTiles()}clearSources(){for(const w in this._mergedSourceCaches)this._mergedSourceCaches[w].clearTiles()}clearLayers(){for(const w in this._mergedLayers){const A=this._mergedLayers[w];A._clear&&A._clear()}}reloadSource(w){const A=this.getSourceCaches(w);for(const F of A)F.resume(),F.reload()}reloadSources(){for(const w of this.getSources())w.reload&&w.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(w=>{w.modelManager.reloadModels(w.scope)})}updateSources(w){let A;this.directionalLight&&(A=_0(this.directionalLight));const F=new Set,V=new Set,Z=new Set;for(const X in this._mergedLayers){const ae=this._mergedLayers[X];ae.type==="building"?F.add(ae.source):ae.type==="raster"&&ae.paint&&ae.paint.get("raster-elevation-reference")==="ground"&&Z.add(ae.source),ae.hasElevation()&&!V.has(ae.source)&&V.add(ae.source)}for(const X in this._mergedSourceCaches){const ae=this._mergedSourceCaches[X],pe=V.has(ae._source.id);ae._isRasterElevatedOverTerrain=Z.has(ae._source.id),F.has(ae._source.id)&&(ae._source.reparseOverscaled=!1),ae.update(w,void 0,void 0,A,pe)}}_generateCollisionBoxes(){for(const w in this._sourceCaches){const A=this._sourceCaches[w];A.resume(),A.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new yy),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(w,A,F,V,Z){this.pauseablePlacement||(this.pauseablePlacement=new yy);let X=!1,ae=!1;const pe={},ke={};for(const ot of this._mergedOrder){const wt=this._mergedLayers[ot];if(wt.type!=="symbol")continue;const _t=o.F(wt.source,wt.scope);let Rt=pe[_t];if(!Rt){const kt=this.getLayerSourceCache(wt);if(!kt)continue;const ks=kt.getRenderableIds(!0).map(Jt=>kt.getTileByID(Jt));ke[_t]=ks.slice(),Rt=pe[_t]=ks.sort((Jt,ws)=>ws.tileID.overscaledZ-Jt.tileID.overscaledZ||(Jt.tileID.isLessThan(ws.tileID)?-1:1))}const $t=this.crossTileSymbolIndex.addLayer(wt,Rt,w.center.lng,w.projection);X=X||$t}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const Me=!!(this.placement&&!w.equals(this.placement.transform)),Ke=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!Z||this.placement.lastReplacementSourceUpdateTime!==Z.updateTime)),He=Me||Ke||X,tt=(He||this.pauseablePlacement.isStale())&&F===0,ct=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),w.zoom)&&F!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||tt||ct)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(w,this._mergedOrder,A,F,V,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 wt=180*w.pitch/Math.PI;if(wt>=15){const _t=Math.min(1,Math.max(0,(wt-15)/5)),Rt=_t*_t*(3-2*_t);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-Rt)+ot*Rt}}}if(this.pauseablePlacement.isDone()?He&&F!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,pe,ke,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),ae=!0),X&&this.pauseablePlacement.setStale()),ae||X){this._buildingIndex.onNewFrame(w.zoom);for(let ot=0;otZ===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(!A)return F.push(w),this._loadImports([w],!0);const V=F.findIndex(({id:Z})=>Z===A);return V===-1&&this.fire(new o.B(new Error(`Import with id "${A}" does not exist on this map.`))),this.stylesheet.imports=F.slice(0,V).concat(w).concat(F.slice(V)),this._loadImports([w],!0,A)}updateImport(w,A){this._checkLoaded();const F=this.stylesheet.imports||[],V=this.getImportIndex(w);return V===-1?this:typeof A=="string"?(this.setImportUrl(w,A),this):(A.url&&A.url!==F[V].url&&this.setImportUrl(w,A.url),o.b6(A.config,F[V].config)||this.setImportConfig(w,A.config,A.data.schema),o.b6(A.data,F[V].data)||this.setImportData(w,A.data),this)}moveImport(w,A){this._checkLoaded();let F=this.stylesheet.imports||[];const V=this.getImportIndex(w);if(V===-1)return this;const Z=this.getImportIndex(A);if(Z===-1)return this;const X=F[V],ae=this.fragments[V];return F=F.filter(({id:pe})=>pe!==w),this.fragments=this.fragments.filter(({id:pe})=>pe!==w),this.stylesheet.imports=F.slice(0,Z).concat(X).concat(F.slice(Z)),this.fragments=this.fragments.slice(0,Z).concat(ae).concat(this.fragments.slice(Z)),this.mergeLayers(),this}setImportUrl(w,A){this._checkLoaded();const F=this.stylesheet.imports||[],V=this.getImportIndex(w);if(V===-1)return this;F[V].url=A;const Z=this.fragments[V];return Z.style=this._createFragmentStyle(F[V]),Z.style.on("style.import.load",()=>this.mergeAll()),Z.style.loadURL(A),this}setImportData(w,A){this._checkLoaded();const F=this.getImportIndex(w),V=this.stylesheet.imports||[];return F===-1?this:A?(this.fragments[F].style.setState(A),this._reloadImports(),this):(delete V[F].data,this.setImportUrl(w,V[F].url))}setImportConfig(w,A,F){this._checkLoaded();const V=this.getImportIndex(w),Z=this.stylesheet.imports||[];if(V===-1)return this;A?Z[V].config=A:delete Z[V].config;const X=this.fragments[V];F&&X.style.stylesheet&&(X.style.stylesheet.schema=F);const ae=X.style.stylesheet&&X.style.stylesheet.schema;return X.config=A,X.style.updateConfig(A,ae),this.updateConfigDependencies(),this}removeImport(w){this._checkLoaded();const A=this.stylesheet.imports||[],F=this.getImportIndex(w);F!==-1&&(A.splice(F,1),this.fragments[F].style._remove(),this.fragments.splice(F,1),this._reloadImports())}getImportIndex(w){const A=(this.stylesheet.imports||[]).findIndex(F=>F.id===w);return A===-1&&this.fire(new o.B(new Error(`Import '${w}' does not exist in the map's style and cannot be updated.`))),A}getLayer(w){return this._mergedLayers[w]}getSources(){const w=[];for(const A in this._mergedOtherSourceCaches){const F=this._mergedOtherSourceCaches[A];F&&w.push(F.getSource())}return w}getSource(w,A){const F=this.getSourceCache(w,A);return F&&F.getSource()}getLayerSource(w){const A=this.getLayerSourceCache(w);return A&&A.getSource()}getSourceCache(w,A){const F=o.F(w,A);return this._mergedOtherSourceCaches[F]}getLayerSourceCache(w){const A=o.F(w.source,w.scope);return w.type==="symbol"?this._mergedSymbolSourceCaches[A]:w.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[A]||this._mergedOtherSourceCaches[A]}getSourceCaches(w){if(w==null)return Object.values(this._mergedSourceCaches);const A=[];return this._mergedOtherSourceCaches[w]&&A.push(this._mergedOtherSourceCaches[w]),this._mergedSymbolSourceCaches[w]&&A.push(this._mergedSymbolSourceCaches[w]),this._mergedFillExtrusionSourceCaches[w]&&A.push(this._mergedFillExtrusionSourceCaches[w]),A}updateSourceCaches(){const w=this._changes.getUpdatedSourceCaches();for(const A in w){const F=w[A];F==="reload"?this.reloadSource(A):F==="clear"&&this.clearSource(A)}}updateLayers(w){const A=this._changes.getUpdatedPaintProperties();for(const F of A){const V=this.getLayer(F);V&&V.updateTransitions(w)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(w){this.stylesheet.glyphs=w,this.glyphManager.setURL(w)}getImages(w,A,F){this.imageManager.getImages(A.images,A.scope,F),this._updateTilesForChangedImages();const V=X=>{if(X){const ae=A.images.map(pe=>o.I.toString(pe));X.setDependencies(A.tileID.key,A.type,ae)}},Z=o.F(A.source,A.scope);V(this._mergedOtherSourceCaches[Z]),V(this._mergedSymbolSourceCaches[Z]),A.images.some(X=>X.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(w,A,F){this.imageManager.rasterizeImages(A,F)}checkAtlasCache(w,A,F){const V=this.imageManager.imageAtlasCache.findCachedAtlas(A.descriptor);F(null,V&&V.contentDescriptor?{iconPositions:V.iconPositions,patternPositions:V.patternPositions,sourceHash:V.contentDescriptor.hash}:null)}getGlyphs(w,A,F){this.glyphManager.getGlyphs(A.stacks,F)}getOwnSourceCache(w){return this._otherSourceCaches[w]}getOwnLayerSourceCache(w){return w.type==="symbol"?this._symbolSourceCaches[w.source]:w.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[w.source]||this._otherSourceCaches[w.source]}getOwnSourceCaches(w){const A=[];return this._otherSourceCaches[w]&&A.push(this._otherSourceCaches[w]),this._symbolSourceCaches[w]&&A.push(this._symbolSourceCaches[w]),this._fillExtrusionSourceCaches[w]&&A.push(this._fillExtrusionSourceCaches[w]),A}_isSourceCacheLoaded(w){const A=this.getOwnSourceCaches(w);return A.length===0?(this.fire(new o.B(new Error(`There is no source with ID '${w}'`))),!1):A.every(F=>F.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(w,A){if(!this._clipLayerPresent&&w.type!=="fill-extrusion"&&w.type!=="building")return!1;const F=w.type==="fill-extrusion"&&(w.sourceLayer==="building"||w.sourceLayer==="procedural_buildings"),V=w.type==="building";if(w.is3D(!!this.terrain)){if(F||V||A&&A.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)}}yu.getSourceType=function(R){return xy[R]},yu.setSourceType=function(R,w){xy[R]=w},yu.registerForPluginStateChange=o.dk;var j0=` #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`,pw=` #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;}`,N0=` #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`,qb="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;}",e2=` #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`,t2=`#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`,w1=`#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`,j1=`#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`,s2=`#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;}`,Vb=`#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`,up=`#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 hh=/#include\s+"([^"]+)"/g,nr=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,N1=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,k1=new Set(["ifdef","ifndef","elif","if","defined"]),pv=new Set;kg(j0,pv),kg(N0,pv),kg(pw,pv);const Wp={"_prelude_fog.vertex.glsl":t2,"_prelude_terrain.vertex.glsl":e2,"_prelude_shadow.vertex.glsl":Vb,"_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":w1,"_prelude_shadow.fragment.glsl":up,"_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":j1,"_prelude_raster_particle.glsl":s2},vy={};oo("",e2),oo(w1,t2),oo(up,Vb),oo(j1,""),oo(s2,"");const k0=oo(pw,N0),Hb=j0,fv=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",Hb,k0.fragmentSource].join(` `),n2=["precision highp float;",Hb,k0.vertexSource].join(` `);var fw={background:oo(`#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:oo(`#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:oo(`#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:oo(`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:oo("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:oo(`#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:oo("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:oo(`#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:oo(`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:oo("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:oo("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:oo("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:oo("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:oo(`#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:oo(`#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:oo(`#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:oo(`#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:oo(`#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:oo(`#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:oo(`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:oo(`#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:oo("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:oo(`#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:oo(`#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:oo(`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:oo(`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:oo(`#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:oo(`#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:oo(`#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:oo(`#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:oo(`#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:oo("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:oo("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:oo(`#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:oo(`#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:oo(`#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:oo("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:oo(`#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 }`,qb),skyboxGradient:oo(`#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 }`,qb),skyboxCapture:oo(` 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:oo(`#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:oo(`#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:oo(`#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:oo("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:oo(`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:oo("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:oo("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:oo("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:oo("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 kg(R,w){const A=R.split(` `);for(let F of A){if(F=F.trimStart(),F[0]!=="#"||!F.includes("if")||F.startsWith("#endif"))continue;const V=F.match(N1);if(V)for(const Z of V)k1.has(Z)||w.add(Z)}}function _S(R){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(R)}function oo(R,w){const A=new Set,F=[],V=[];R=R.replace(hh,(X,ae)=>(V.push(ae),"")),w=w.replace(hh,(X,ae)=>(F.push(ae),""));let Z=new Set(pv);kg(R,Z),kg(w,Z);for(const X of[...F,...V])vy[X]||(vy[X]=new Set,kg(Wp[X],vy[X])),Z=new Set([...Z,...vy[X]]);return{fragmentSource:R=R.replace(nr,(X,ae,pe,ke,Me)=>(A.add(Me),ae==="define"?` #ifndef HAS_UNIFORM_u_${Me} ${_S(ke)?"flat ":""}in ${pe} ${ke} ${Me}; #else uniform ${pe} ${ke} u_${Me}; #endif `:ae==="initialize"?` #ifdef HAS_UNIFORM_u_${Me} ${pe} ${ke} ${Me} = u_${Me}; #endif `:ae==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Me} in ${pe} ${ke} ${Me}; #endif `:ae==="initialize-attribute"?"":void 0)),vertexSource:w=w.replace(nr,(X,ae,pe,ke,Me)=>{const Ke=`MATERIAL_ATTRIBUTE_OFFSET_${Me}`,He=ke==="float"?"vec2":ke,tt=`GET_ATTRIBUTE_${He}(a_${Me}, materialInfo, ${Ke})`,ct=Me.match(/color/)?"color":He;return ae==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${Me} in ${pe} ${ke} a_${Me}; #endif `:A.has(Me)?ae==="define"?` #ifndef HAS_UNIFORM_u_${Me} uniform lowp float u_${Me}_t; #if !defined(${Ke}) in ${pe} ${He} a_${Me}; #endif ${_S(ke)?"flat ":""}out ${pe} ${ke} ${Me}; #else uniform ${pe} ${ke} u_${Me}; #endif `:ae==="initialize"?ct==="vec4"||ct==="uvec4"?` #ifndef HAS_UNIFORM_u_${Me} ${Me} = a_${Me}; #else ${pe} ${ke} ${Me} = u_${Me}; #endif `:` #if !defined(HAS_UNIFORM_u_${Me}) #ifdef ${Ke} ${Me} = unpack_mix_${ct}(${tt}, u_${Me}_t); #else ${Me} = unpack_mix_${ct}(a_${Me}, u_${Me}_t); #endif #else ${pe} ${ke} ${Me} = u_${Me}; #endif `:ae==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Me} in ${pe} ${ke} a_${Me}; out ${pe} ${ke} ${Me}; #endif `:ae==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${Me} ${Me} = a_${Me}; #endif `:void 0:ae==="define"?` #ifndef HAS_UNIFORM_u_${Me} uniform lowp float u_${Me}_t; #if !defined(${Ke}) in ${pe} ${He} a_${Me}; #endif #else uniform ${pe} ${ke} u_${Me}; #endif `:ae==="define-instanced"?ct==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${Me}0; in vec4 a_${Me}1; in vec4 a_${Me}2; in vec4 a_${Me}3; #else uniform ${pe} ${ke} u_${Me}; #endif `:` #ifdef INSTANCED_ARRAYS in ${pe} ${He} a_${Me}; #else uniform ${pe} ${ke} u_${Me}; #endif `:ae==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${Me} ${pe} ${ke} ${Me} = a_${Me}; #endif `:ct==="vec4"||ct==="uvec4"?` #ifndef HAS_UNIFORM_u_${Me} #ifdef ${Ke} ${pe} ${ke} ${Me} = ${tt}; #else ${pe} ${ke} ${Me} = a_${Me}; #endif #else ${pe} ${ke} ${Me} = u_${Me}; #endif `:` #ifndef HAS_UNIFORM_u_${Me} #ifdef ${Ke} ${pe} ${ke} ${Me} = unpack_mix_${ct}(${tt}, u_${Me}_t); #else ${pe} ${ke} ${Me} = unpack_mix_${ct}(a_${Me}, u_${Me}_t); #endif #else ${pe} ${ke} ${Me} = u_${Me}; #endif `}),usedDefines:Z,vertexIncludes:F,fragmentIncludes:V}}class WN{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(w,A,F,V,Z,X,ae,pe){this.context=w;let ke=this.boundPaintVertexBuffers.length!==V.length;for(let Ke=0;!ke&&Ke{const ks=$t.paint.get("hillshade-shadow-color"),Jt=$t.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",ws=$t.paint.get("hillshade-highlight-color"),Vt=$t.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Xt=$t.paint.get("hillshade-accent-color"),ms=$t.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",Us=$t.paint.get("hillshade-emissive-strength");let Cs=o.ap($t.paint.get("hillshade-illumination-direction"));if($t.paint.get("hillshade-illumination-anchor")==="viewport")Cs-=_t.transform.angle;else if(_t.style&&_t.style.enable3dLights()&&_t.style.directionalLight){const an=_t.style.directionalLight.properties.get("direction"),Ln=o.cP(an.x,an.y,an.z);Cs=o.ap(Ln[1])}const pn=!_t.options.moving;return{u_matrix:kt||_t.transform.calculateProjMatrix(Rt.tileID.toUnwrapped(),pn),u_image:0,u_latrange:wS(0,Rt.tileID),u_light:[$t.paint.get("hillshade-exaggeration"),Cs],u_shadow:ks.toPremultipliedRenderColor(Jt?null:$t.lut),u_highlight:ws.toPremultipliedRenderColor(Vt?null:$t.lut),u_emissive_strength:Us,u_accent:Xt.toPremultipliedRenderColor(ms?null:$t.lut)}})(R,A,F,R.terrain?w.projMatrix:null);R.uploadCommonUniforms(ae,He,w.toUnwrapped());const{tileBoundsBuffer:ct,tileBoundsIndexBuffer:ot,tileBoundsSegments:wt}=R.getTileBoundsBuffers(A);He.draw(R,pe.TRIANGLES,V,Z,X,la.disabled,tt,F.id,ct,ot,wt)}function jS(R,w,A){if(!w.needsDEMTextureUpload)return;const F=R.context,V=F.gl;F.pixelStoreUnpackPremultiplyAlpha.set(!1),w.demTexture=w.demTexture||R.getTileTexture(A.stride);const Z=A.getPixels();w.demTexture?w.demTexture.update(Z,{premultiply:!1}):w.demTexture=new o.T(F,Z,V.R32F,{premultiply:!1}),w.needsDEMTextureUpload=!1}function iC(R,w,A){const F=R.context,V=F.gl;if(!w.dem)return;const Z=w.dem;if(F.activeTexture.set(V.TEXTURE1),jS(R,w,Z),!w.demTexture)return;w.demTexture.bind(V.NEAREST,V.CLAMP_TO_EDGE);const X=Z.dim;F.activeTexture.set(V.TEXTURE0);let ae=w.hillshadeFBO;if(!ae){const He=new o.T(F,{width:X,height:X,data:null},V.RGBA8);He.bind(V.LINEAR,V.CLAMP_TO_EDGE),ae=w.hillshadeFBO=F.createFramebuffer(X,X,1,"renderbuffer"),ae.colorAttachment0.set(He.texture)}F.bindFramebuffer.set(ae.framebuffer),F.viewport.set([0,0,X,X]);const{tileBoundsBuffer:pe,tileBoundsIndexBuffer:ke,tileBoundsSegments:Me}=R.getMercatorTileBoundsBuffers(),Ke=[];R.linearFloatFilteringSupported()&&Ke.push("TERRAIN_DEM_FLOAT_FORMAT"),R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback"&&Ke.push("USE_MRT1"),R.getOrCreateProgram("hillshadePrepare",{defines:Ke}).draw(R,V.TRIANGLES,Ir.disabled,Sa.disabled,ka.unblended,la.disabled,((He,tt)=>{const ct=tt.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:He.overscaledZ}})(w.tileID,Z),A.id,pe,ke,Me),w.needsHillshadePrepare=!1}class wc{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 Gb extends wc{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(w){const A=this.current;(w.r!==A.r||w.g!==A.g||w.b!==A.b||w.a!==A.a||this.dirty)&&(this.gl.clearColor(w.r,w.g,w.b,w.a),this.current=w,this.dirty=!1)}}class NS extends wc{getDefault(){return 1}set(w){(w!==this.current||this.dirty)&&(this.gl.clearDepth(w),this.current=w,this.dirty=!1)}}class S1 extends wc{getDefault(){return 0}set(w){(w!==this.current||this.dirty)&&(this.gl.clearStencil(w),this.current=w,this.dirty=!1)}}class M6 extends wc{getDefault(){return[!0,!0,!0,!0]}set(w){const A=this.current;(w[0]!==A[0]||w[1]!==A[1]||w[2]!==A[2]||w[3]!==A[3]||this.dirty)&&(this.gl.colorMask(w[0],w[1],w[2],w[3]),this.current=w,this.dirty=!1)}}class Sg extends wc{getDefault(){return!0}set(w){(w!==this.current||this.dirty)&&(this.gl.depthMask(w),this.current=w,this.dirty=!1)}}class xw extends wc{getDefault(){return 255}set(w){(w!==this.current||this.dirty)&&(this.gl.stencilMask(w),this.current=w,this.dirty=!1)}}class Wb extends wc{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(w){const A=this.current;(w.func!==A.func||w.ref!==A.ref||w.mask!==A.mask||this.dirty)&&(this.gl.stencilFunc(w.func,w.ref,w.mask),this.current=w,this.dirty=!1)}}class KN extends wc{getDefault(){const w=this.gl;return[w.KEEP,w.KEEP,w.KEEP]}set(w){const A=this.current;(w[0]!==A[0]||w[1]!==A[1]||w[2]!==A[2]||this.dirty)&&(this.gl.stencilOp(w[0],w[1],w[2]),this.current=w,this.dirty=!1)}}class C1 extends wc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const A=this.gl;w?A.enable(A.STENCIL_TEST):A.disable(A.STENCIL_TEST),this.current=w,this.dirty=!1}}class A1 extends wc{getDefault(){return[0,1]}set(w){const A=this.current;(w[0]!==A[0]||w[1]!==A[1]||this.dirty)&&(this.gl.depthRange(w[0],w[1]),this.current=w,this.dirty=!1)}}class Rf extends wc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const A=this.gl;w?A.enable(A.DEPTH_TEST):A.disable(A.DEPTH_TEST),this.current=w,this.dirty=!1}}class Xd extends wc{getDefault(){return this.gl.LESS}set(w){(w!==this.current||this.dirty)&&(this.gl.depthFunc(w),this.current=w,this.dirty=!1)}}class Cg extends wc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const A=this.gl;w?A.enable(A.BLEND):A.disable(A.BLEND),this.current=w,this.dirty=!1}}class r2 extends wc{getDefault(){const w=this.gl;return[w.ONE,w.ZERO,w.ONE,w.ZERO]}set(w){const A=this.current;(w[0]!==A[0]||w[1]!==A[1]||w[2]!==A[2]||w[3]!==A[3]||this.dirty)&&(this.gl.blendFuncSeparate(w[0],w[1],w[2],w[3]),this.current=w,this.dirty=!1)}}class kS extends wc{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(w){const A=this.current;(w.r!==A.r||w.g!==A.g||w.b!==A.b||w.a!==A.a||this.dirty)&&(this.gl.blendColor(w.r,w.g,w.b,w.a),this.current=w,this.dirty=!1)}}class lx extends wc{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 Kp extends wc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const A=this.gl;w?A.enable(A.CULL_FACE):A.disable(A.CULL_FACE),this.current=w,this.dirty=!1}}class a2 extends wc{getDefault(){return this.gl.BACK}set(w){(w!==this.current||this.dirty)&&(this.gl.cullFace(w),this.current=w,this.dirty=!1)}}class YN extends wc{getDefault(){return this.gl.CCW}set(w){(w!==this.current||this.dirty)&&(this.gl.frontFace(w),this.current=w,this.dirty=!1)}}let gw=class extends wc{getDefault(){return null}set(R){(R!==this.current||this.dirty)&&(this.gl.useProgram(R),this.current=R,this.dirty=!1)}};class yw extends wc{getDefault(){return this.gl.TEXTURE0}set(w){(w!==this.current||this.dirty)&&(this.gl.activeTexture(w),this.current=w,this.dirty=!1)}}class Yp extends wc{getDefault(){const w=this.gl;return[0,0,w.drawingBufferWidth,w.drawingBufferHeight]}set(w){const A=this.current;(w[0]!==A[0]||w[1]!==A[1]||w[2]!==A[2]||w[3]!==A[3]||this.dirty)&&(this.gl.viewport(w[0],w[1],w[2],w[3]),this.current=w,this.dirty=!1)}}class hp extends wc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const A=this.gl;A.bindFramebuffer(A.FRAMEBUFFER,w),this.current=w,this.dirty=!1}}class SS extends wc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const A=this.gl;A.bindRenderbuffer(A.RENDERBUFFER,w),this.current=w,this.dirty=!1}}class by extends wc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const A=this.gl;A.bindTexture(A.TEXTURE_2D,w),this.current=w,this.dirty=!1}}class vw extends wc{getDefault(){return null}set(w){if(w===this.current&&!this.dirty)return;const A=this.gl;A.bindBuffer(A.ARRAY_BUFFER,w),this.current=w,this.dirty=!1}}class bw extends wc{getDefault(){return null}set(w){const A=this.gl;A.bindBuffer(A.ELEMENT_ARRAY_BUFFER,w),this.current=w,this.dirty=!1}}class ZN extends wc{getDefault(){return null}set(w){this.gl&&(w!==this.current||this.dirty)&&(this.gl.bindVertexArray(w),this.current=w,this.dirty=!1)}}class XN extends wc{getDefault(){return 4}set(w){if(w===this.current&&!this.dirty)return;const A=this.gl;A.pixelStorei(A.UNPACK_ALIGNMENT,w),this.current=w,this.dirty=!1}}class QN extends wc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const A=this.gl;A.pixelStorei(A.UNPACK_PREMULTIPLY_ALPHA_WEBGL,w),this.current=w,this.dirty=!1}}class _w extends wc{getDefault(){return!1}set(w){if(w===this.current&&!this.dirty)return;const A=this.gl;A.pixelStorei(A.UNPACK_FLIP_Y_WEBGL,w),this.current=w,this.dirty=!1}}class ww extends wc{constructor(w,A){super(w),this.context=w,this.parent=A}getDefault(){return null}}class Kb extends ww{constructor(w,A,F=0){super(w,A),this.attachmentPoint=w.gl.COLOR_ATTACHMENT0+F}setDirty(){this.dirty=!0}set(w){if(w===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const A=this.gl;A.framebufferTexture2D(A.FRAMEBUFFER,this.attachmentPoint,A.TEXTURE_2D,w,0),this.current=w,this.dirty=!1}}class i2 extends ww{attachment(){return this.gl.DEPTH_ATTACHMENT}set(w){if(w===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const A=this.gl;A.framebufferRenderbuffer(A.FRAMEBUFFER,this.attachment(),A.RENDERBUFFER,w),this.current=w,this.dirty=!1}}class JN extends ww{attachment(){return this.gl.DEPTH_ATTACHMENT}set(w){if(w===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const A=this.gl;A.framebufferTexture2D(A.FRAMEBUFFER,this.attachment(),A.TEXTURE_2D,w,0),this.current=w,this.dirty=!1}}class oC extends i2{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const Yb=(R,w,A,F)=>({u_matrix:R,u_image0:0,u_image1:1,u_skirt_height:w,u_ground_shadow_factor:A,u_emissive_texture_available:F}),_y=(R,w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt,ct,ot,wt)=>({u_proj_matrix:Float32Array.from(R),u_globe_matrix:w,u_normalize_matrix:Float32Array.from(F),u_merc_matrix:A,u_zoom_transition:V,u_merc_center:Z,u_image0:0,u_image1:1,u_frustum_tl:X,u_frustum_tr:ae,u_frustum_br:pe,u_frustum_bl:ke,u_globe_pos:Me,u_globe_radius:Ke,u_viewport:He,u_grid_matrix:wt?Float32Array.from(wt):new Float32Array(9),u_skirt_height:tt,u_far_z_cutoff:ct,u_emissive_texture_available:ot});function jw(R,w){return R!=null&&w!=null&&!(!R.hasData()||!w.hasData())&&R.demTexture!=null&&w.demTexture!=null&&R.tileID.key!==w.tileID.key}const Jh=new class{constructor(){this.operations={}}newMorphing(R,w,A,F,V){if(R in this.operations){const Z=this.operations[R];Z.to.tileID.key!==A.tileID.key&&(Z.queued=A)}else this.operations[R]={startTime:F,phase:0,duration:V,from:w,to:A,queued:null}}getMorphValuesForProxy(R){if(!(R in this.operations))return null;const w=this.operations[R];return{from:w.from,to:w.to,phase:w.phase}}update(R){for(const w in this.operations){const A=this.operations[w];for(A.phase=(R-A.startTime)/A.duration;A.phase>=1||!this._validOp(A);)if(!this._nextOp(A,R)){delete this.operations[w];break}}}_nextOp(R,w){return!!R.queued&&(R.from=R.to,R.to=R.queued,R.queued=null,R.phase=0,R.startTime=w,!0)}_validOp(R){return R.from.hasData()&&R.to.hasData()}},Nw={0:null,1:"TERRAIN_VERTEX_MORPHING"};function Zb(R,w,A){if(w===0)return 0;const F=w<1&&A===514?.25/w:1;return 6*Math.pow(1.5,22-R)*Math.max(w,1)*F}function Ce(R,w){const A=1<({u_matrix:R});function bt(R,w,A,F,V){if(V>0){const Z=o.o.now(),X=(Z-R.timeAdded)/V,ae=w?(Z-w.timeAdded)/V:-1,pe=A.getSource(),ke=F.coveringZoomLevel({tileSize:pe.tileSize,roundZoom:pe.roundZoom}),Me=!w||Math.abs(w.tileID.overscaledZ-ke)>Math.abs(R.tileID.overscaledZ-ke),Ke=Me&&R.refreshedUponExpiration?1:o.aC(Me?X:1-ae,0,1);return w?{opacity:1,mix:1-Ke,isFading:X<1}:{opacity:Ke,mix:0,isFading:X<1}}return{opacity:1,mix:0,isFading:!1}}class Yt extends Vl{constructor(w){const A={type:"raster-dem",maxzoom:Math.ceil(w.transform.maxZoom)},F=Ef("mock-dem",A,w.style.dispatcher,w.style);super("mock-dem",F,null),F.setEventedParent(this),this._sourceLoaded=!0}_loadTile(w,A){w.state="loaded",A(null)}}class ls extends Vl{constructor(w){const A=Ef("proxy",{type:"geojson",maxzoom:Math.ceil(w.transform.maxZoom)},w.style.dispatcher,w.style);super("proxy",A,null),A.setEventedParent(this),this.map=this.getSource().map=w,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(w,A,F){if(w.freezeTileCoverage)return;this.transform=w;const V=w.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((Z,X)=>{if(Z[X.key]="",!this._tiles[X.key]){const ae=new o.b0(X,this._source.tileSize*X.overscaleFactor(),w.tileZoom,void 0,void 0,this._source.worldview);ae.state="loaded",this._tiles[X.key]=ae}return Z},{});for(const Z in this._tiles)Z in V||(this.freeFBO(Z),this._tiles[Z].unloadVectorData(),delete this._tiles[Z])}freeFBO(w){const A=this.proxyCachedFBO[w];if(A!==void 0){const F=Object.values(A);this.renderCachePool.push(...F),delete this.proxyCachedFBO[w]}}deallocRenderCache(){this.renderCache.forEach(w=>w.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class hs extends o.aR{constructor(w,A,F){super(w.overscaledZ,w.wrap,w.canonical.z,w.canonical.x,w.canonical.y),this.proxyTileKey=A,this.projMatrix=F}}class Ss extends o.bu{constructor(w,A){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=w,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[F,V,Z]=function(){const pe=new o.dB,ke=new o.dC,Me=131;pe.reserve(17161),ke.reserve(33800);const Ke=o.an/128,He=o.an+Ke/2,tt=He+Ke;for(let ot=-Ke;otHe||ot<0||ot>He?24575:0,Rt=o.aC(Math.round(wt),0,o.an),$t=o.aC(Math.round(ot),0,o.an);pe.emplaceBack(Rt+_t,$t)}const ct=(ot,wt)=>{const _t=wt*Me+ot;ke.emplaceBack(_t+1,_t,_t+Me),ke.emplaceBack(_t+Me,_t+Me+1,_t+1)};for(let ot=1;ot<129;ot++)for(let wt=1;wt<129;wt++)ct(wt,ot);return[0,129].forEach(ot=>{for(let wt=0;wt<130;wt++)ct(wt,ot),ct(ot,wt)}),[pe,ke,32768]}(),X=w.context;this.gridBuffer=X.createVertexBuffer(F,o.dx.members),this.gridIndexBuffer=X.createIndexBuffer(V),this.gridSegments=o.dy.simpleSegment(0,0,F.length,V.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,F.length,Z),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new ls(A.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 ae=X.gl;this._overlapStencilMode=new Sa({func:ae.GEQUAL,mask:255},0,255,ae.KEEP,ae.KEEP,ae.REPLACE),this._previousZoom=w.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=A,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Yt(A.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,A,F){if(w&&w.terrain){this._style!==w&&(this.style=w,this._evaluationZoom=void 0);const V=w.terrain.properties,Z=w.terrain.drapeRenderMode===0,X=w.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const ae=w.terrain&&w.terrain.scope,pe=V.get("source"),ke=Z?this._mockSourceCache:w.getSourceCache(pe,ae);if(!ke)return void o.w(`Couldn't find terrain source "${pe}".`);if(this.sourceCache=ke,this._attenuationRange=w.terrain.getAttenuationRange(),this._exaggeration=X?this.calculateExaggeration(A):V.get("exaggeration"),!A.projection.requiresDraping&&X&&this._exaggeration===0)return void this._disable();this.enabled=!0;const Me=()=>{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 Ke=this.getScaledDemTileSize();this.sourceCache.update(A,Ke,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,Me(),this._initializing=!0),Me(),A.updateElevation(!0,F),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(A),this._emptyDEMTextureDirty=!0,this._previousZoom=A.zoom}else this._disable()}calculateExaggeration(w){if(this._attenuationRange&&w.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(w.zoom);const A=this._previousCameraAltitude,F=w.getFreeCameraOptions().position.z/w.pixelsPerMeter*w.worldSize;this._previousCameraAltitude=F;const V=A!=null?F-A:Number.MAX_VALUE;if(Math.abs(V)<2)return this._exaggeration;const Z=w.zoom,X=this._style.terrain;if(!this._previousUpdateTimestamp)return X.getExaggeration(Z);let ae=Z-this._previousZoom;const pe=this._previousUpdateTimestamp;let ke=Z;this._evaluationZoom!=null&&(ke=this._evaluationZoom,Math.abs(Z-ke)>.5&&(ae=.5*(Z-ke+ae)),ae*V<0&&(ke+=ae)),this._evaluationZoom=ke;const Me=X.getExaggeration(ke),Ke=Me===X.getExaggeration(Math.max(0,ke-.1));if(Ke&&Math.abs(Me-this._exaggeration)<.01)return Me;let He=Math.min(.1,.00375*(this._updateTimestamp-pe));return(Ke||Me<.1||Math.abs(ae)<1e-4)&&(He=Math.min(.2,4*He)),o.am(this._exaggeration,Me,He)}resetTileLookupCache(w){this._findCoveringTileCache[w]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(w){w.dataType==="source"&&w.coord?this._clearRenderCacheForTile(w.sourceCacheId,w.coord):w.dataType==="style"&&(this.invalidateRenderCache=!0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this._previousCameraAltitude=void 0)}_disable(){if(this.enabled&&(this.enabled=!1,this._emptyDEMTextureDirty=!0,this._sharedDepthStencil=void 0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this.proxySourceCache.deallocRenderCache(),this._style))for(const w in this._style._mergedSourceCaches)this._style._mergedSourceCaches[w].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(w=>w.fb.destroy()),this.pool=[],this.framebufferCopyTexture&&this.framebufferCopyTexture.destroy()}_source(){return this.enabled?this.sourceCache:null}isUsingMockSource(){return this.sourceCache===this._mockSourceCache}exaggeration(){return this.enabled?this._exaggeration:0}get visibleDemTiles(){return this._visibleDemTiles}get drapeBufferSize(){const w=2*this.proxySourceCache.getSource().tileSize;return[w,w]}set useVertexMorphing(w){this._useVertexMorphing=w}updateTileBinding(w){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const A=this.proxySourceCache,F=this.painter.transform;this._initializing&&(this._initializing=F._centerAltitude===0&&this.getAtPointOrZero(o.ag.fromLngLat(F.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const V=this.proxyCoords=A.getIds().map(pe=>{const ke=A.getTileByID(pe).tileID;return ke.projMatrix=F.calculateProjMatrix(ke.toUnwrapped()),ke});(function(pe,ke){const Me=ke.transform.pointCoordinate(ke.transform.getCameraPoint()),Ke=new o.P(Me.x,Me.y);pe.sort((He,tt)=>{if(tt.overscaledZ-He.overscaledZ)return tt.overscaledZ-He.overscaledZ;const ct=new o.P(He.canonical.x+(1<{this.proxyToSource[pe.key]={}}),this.terrainTileForTile={};const X=this._style._mergedSourceCaches;for(const pe in X){const ke=X[pe];if(!ke.used||(ke!==this.sourceCache&&this.resetTileLookupCache(ke.id),this._setupProxiedCoordsForOrtho(ke,w[pe],Z),ke.usedForTerrain))continue;const Me=w[pe];(ke.getSource().reparseOverscaled||ke._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Me)}this.proxiedCoords[A.id]=V.map(pe=>new hs(pe,pe.key,this.orthoMatrix)),this._assignTerrainTiles(V),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(Z),this.renderingToTexture=!1;const ae={};this._visibleDemTiles=[];for(const pe of this.proxyCoords){const ke=this.terrainTileForTile[pe.key];if(!ke)continue;const Me=ke.tileID.key;Me in ae||(this._visibleDemTiles.push(ke),ae[Me]=Me)}}_assignTerrainTiles(w){this._initializing||w.forEach(A=>{if(this.terrainTileForTile[A.key])return;const F=this._findTileCoveringTileID(A,this.sourceCache);F&&(this.terrainTileForTile[A.key]=F)})}_prepareDEMTextures(){const w=this.painter.context,A=w.gl;for(const F in this.terrainTileForTile){const V=this.terrainTileForTile[F],Z=V.dem;!Z||V.demTexture&&!V.needsDEMTextureUpload||(w.activeTexture.set(A.TEXTURE1),jS(this.painter,V,Z))}}_prepareDemTileUniforms(w,A,F,V){if(!A||A.demTexture==null)return!1;const Z=w.tileID.canonical,X=Math.pow(2,A.tileID.canonical.z-Z.z),ae=V||"";return F[`u_dem_tl${ae}`]=[Z.x*X%1,Z.y*X%1],F[`u_dem_scale${ae}`]=X,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let w=0;const A=this._visibleDemTiles.reduce((F,V)=>{if(!V.dem)return F;const Z=V.dem.tree.minimums[0];return Z>0&&w++,F+Z},0);return w?A/w:0}_updateEmptyDEMTexture(){const w=this.painter.context,A=w.gl;w.activeTexture.set(A.TEXTURE2);const F=this._getLoadedAreaMinimum(),V=new o.dz({width:1,height:1},new Float32Array([F]));this._emptyDEMTextureDirty=!1;let Z=this._emptyDEMTexture;return Z?Z.update(V,{premultiply:!1}):Z=this._emptyDEMTexture=new o.T(w,V,A.R32F,{premultiply:!1}),Z}setupElevationDraw(w,A,F){const V=this.painter.context,Z=V.gl,X={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0};X.u_exaggeration=this.exaggeration();let ae=null,pe=null,ke=1;if(F&&F.morphing&&this._useVertexMorphing){const tt=F.morphing.srcDemTile,ct=F.morphing.dstDemTile;ke=F.morphing.phase,tt&&ct&&(this._prepareDemTileUniforms(w,tt,X,"_prev")&&(pe=tt),this._prepareDemTileUniforms(w,ct,X)&&(ae=ct))}const Me=tt=>tt&&tt.demTexture&&this.painter.linearFloatFilteringSupported()?Z.LINEAR:Z.NEAREST;let Ke=null;var He;if(this.enabled?pe&&ae?(Ke=ae.demTexture,V.activeTexture.set(Z.TEXTURE4),pe.demTexture.bind(Me(pe),Z.CLAMP_TO_EDGE),X.u_dem_lerp=ke):(ae=this.terrainTileForTile[w.tileID.key],Ke=this._prepareDemTileUniforms(w,ae,X)?ae.demTexture:this.emptyDEMTexture):Ke=this.emptyDEMTexture,V.activeTexture.set(Z.TEXTURE2),Ke&&(X.u_dem_size=(He=Ke).size[0]===1?1:He.size[0]-2,Ke.bind(Me(ae),Z.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(F&&F.useDepthForOcclusion,A,X),F&&F.useMeterToDem&&ae){const tt=(1<{if(_t===an)return;const Ln=[Nw[an],"PROJECTION_GLOBE_VIEW"];$t&&Ln.push("CUSTOM_ANTIALIASING");const $n=ke.isTileAffectedByFog(pn);wt=ke.getOrCreateProgram("globeRaster",{defines:Ln,overrideFog:$n}),_t=an},ks=ke.colorModeForRenderPass(),Jt=new Ir(ot.LEQUAL,Ir.ReadWrite,ke.depthRangeFor3D);Jh.update(tt);const ws=o.dq(Rt),Vt=[o.aH(Rt.center.lng),o.aL(Rt.center.lat)],Xt=ke.globeSharedBuffers,ms=[Rt.width*o.o.devicePixelRatio,Rt.height*o.o.devicePixelRatio],Us=Float32Array.from(Rt.globeMatrix),Cs={useDenormalizedUpVectorScale:!0};{const pn=ke.transform,an=Zb(pn.zoom,Me.exaggeration(),Me.sourceCache._source.tileSize);_t=-1;const Ln=ot.TRIANGLES;for(const $n of He){const Ys=Ke.getTile($n),Es=Sa.disabled,hn=Me.prevTerrainTileForTile[$n.key],fn=Me.terrainTileForTile[$n.key];jw(hn,fn)&&Jh.newMorphing($n.key,hn,fn,tt,250),ze(ke,Ys.emissiveTexture),ct.activeTexture.set(ot.TEXTURE0),Ys.texture&&Ys.texture.bind(ot.LINEAR,ot.CLAMP_TO_EDGE);const jn=Jh.getMorphValuesForProxy($n.key),yr=jn?1:0;jn&&Object.assign(Cs,{morphing:{srcDemTile:jn.from,dstDemTile:jn.to,phase:o.dn(jn.phase)}});const rr=o.dr($n.canonical),ar=o.ds(rr.getCenter().lat),zn=o.dt($n.canonical,rr,ar,pn.worldSize/pn._pixelsPerMercatorPixel),ta=o.du(o.dv($n.canonical)),va=ke.emissiveMode==="mrt-fallback"?1:0,Br=_y(pn.expandedFarZProjMatrix,Us,ws,ta,o.al(pn.zoom),Vt,pn.frustumCorners.TL,pn.frustumCorners.TR,pn.frustumCorners.BR,pn.frustumCorners.BL,pn.globeCenterInViewSpace,pn.globeRadius,ms,an,pn._farZ,va,zn);if(kt($n,yr),wt&&(Me.setupElevationDraw(Ys,wt,Cs),ke.uploadCommonUniforms(ct,wt,$n.toUnwrapped()),Xt)){const[Qr,Ga,li]=Xt.getGridBuffers(ar,an!==0);wt.draw(ke,Ln,Jt,Es,ks,la.backCCW,Br,"globe_raster",Qr,Ga,li)}}}if(Xt&&(ke.renderDefaultNorthPole||ke.renderDefaultSouthPole)){const pn=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];$t&&pn.push("CUSTOM_ANTIALIASING"),wt=ke.getOrCreateProgram("globeRaster",{defines:pn});for(const an of He){const{x:Ln,y:$n,z:Ys}=an.canonical,Es=$n===0,hn=$n===(1<Qr.draw(ke,ot.TRIANGLES,Jt,Sa.disabled,ks,la.disabled,_y(Rt.expandedFarZProjMatrix,zn,zn,ta,0,Vt,Rt.frustumCorners.TL,Rt.frustumCorners.TR,Rt.frustumCorners.BR,Rt.frustumCorners.BL,Rt.globeCenterInViewSpace,Rt.globeRadius,ms,0,Rt._farZ,va),"globe_pole_raster",Ga,yr,rr);Me.setupElevationDraw(ar,wt,Cs),ke.uploadCommonUniforms(ct,wt,an.toUnwrapped()),Es&&ke.renderDefaultNorthPole&&Br(wt,fn),hn&&ke.renderDefaultSouthPole&&(zn=o.cC(o.bb(),zn,[1,-1,1]),Br(wt,jn))}}}})(V,Z,X,ae,pe);else{const ke=V.context,Me=ke.gl;let Ke,He;const tt=V.shadowRenderer,ct=Kc(V,V.longestCutoffRange),ot=ks=>{if(He===ks)return;const Jt=[];Jt.push(Nw[ks]),ct.shouldRenderCutoff&&Jt.push("RENDER_CUTOFF"),tt&&(Jt.push("RENDER_SHADOWS"),tt.useNormalOffset&&Jt.push("NORMAL_OFFSET")),Ke=V.getOrCreateProgram("terrainRaster",{defines:Jt}),He=ks},wt=V.colorModeForRenderPass(),_t=new Ir(Me.LEQUAL,Ir.ReadWrite,V.depthRangeFor3D);Jh.update(pe);const Rt=V.transform,$t=Zb(Rt.zoom,Z.exaggeration(),Z.sourceCache._source.tileSize);let kt=[0,0,0];if(tt){const ks=V.style.directionalLight,Jt=V.style.ambientLight;ks&&Jt&&(kt=dh(V.style,ks,Jt))}{He=-1;const ks=Me.TRIANGLES,[Jt,ws]=[Z.gridIndexBuffer,Z.gridSegments];for(const Vt of ae){const Xt=X.getTile(Vt),ms=Sa.disabled,Us=Z.prevTerrainTileForTile[Vt.key],Cs=Z.terrainTileForTile[Vt.key];jw(Us,Cs)&&Jh.newMorphing(Vt.key,Us,Cs,pe,250),ze(V,Xt.emissiveTexture),ke.activeTexture.set(Me.TEXTURE0),Xt.texture&&Xt.texture.bind(Me.LINEAR,Me.CLAMP_TO_EDGE);const pn=Jh.getMorphValuesForProxy(Vt.key),an=pn?1:0;let Ln;pn&&(Ln={morphing:{srcDemTile:pn.from,dstDemTile:pn.to,phase:o.dn(pn.phase)}});const $n=V.emissiveMode==="mrt-fallback"?1:0,Ys=Yb(Vt.projMatrix,Ce(Vt.canonical,Rt.renderWorldCopies)?$t/10:$t,kt,$n);if(ot(an),!Ke)continue;Z.setupElevationDraw(Xt,Ke,Ln);const Es=Vt.toUnwrapped();tt&&tt.setupShadows(Es,Ke),V.uploadCommonUniforms(ke,Ke,Es,null,ct),Ke.draw(V,ks,_t,ms,wt,la.backCCW,Ys,"terrain_raster",Z.gridBuffer,Jt,ws)}}}}(A,this,this.proxySourceCache,w,this._updateTimestamp),this.renderingToTexture=!0,A.gpuTimingDeferredRenderEnd(),w.splice(0,w.length))}renderBatch(w){if(this._drapedRenderBatches.length===0)return w+1;this.renderingToTexture=!0;const A=this.painter,F=this.painter.context,V=this.proxySourceCache,Z=this.proxiedCoords[V.id],X=this._drapedRenderBatches.shift(),ae=A.style.order,pe=[];this._updateFBOs(A.emissiveMode==="mrt-fallback");let ke=0;for(const Me of Z){const Ke=V.getTileByID(Me.proxyTileKey),He=V.proxyCachedFBO[Me.key]?V.proxyCachedFBO[Me.key][w]:void 0,tt=He!==void 0?V.renderCache[He]:this.pool[ke++],ct=He!==void 0;if(Ke.texture=tt.tex,Ke.emissiveTexture=tt.emissiveTex,ct&&!tt.dirty){pe.push(Ke.tileID);continue}F.bindFramebuffer.set(tt.fb.framebuffer);const ot=F.gl;let wt;ot.drawBuffers(A.emissiveMode==="mrt-fallback"?[ot.COLOR_ATTACHMENT0,ot.COLOR_ATTACHMENT1]:[ot.COLOR_ATTACHMENT0]),this.renderedToTile=!1,tt.dirty&&(F.clear({color:o.aq.transparent,stencil:0}),tt.dirty=!1);for(let _t=X.start;_t<=X.end;++_t){const Rt=A.style._mergedLayers[ae[_t]];if(Rt.isHidden(A.transform.zoom))continue;const $t=A.style.getLayerSourceCache(Rt),kt=$t?this.proxyToSource[Me.key][$t.id]:[Me];if(!kt)continue;const ks=kt;F.viewport.set([0,0,tt.fb.width,tt.fb.height]),wt!==($t?$t.id:null)&&(this._setupStencil(tt,kt,Rt,$t),wt=$t?$t.id:null),A.renderLayer(A,$t,Rt,ks)}if(ot.drawBuffers([ot.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const _t of this._pendingGroundEffectLayers){const Rt=A.style._mergedLayers[ae[_t]];if(Rt.isHidden(A.transform.zoom))continue;const $t=A.style.getLayerSourceCache(Rt),kt=$t?this.proxyToSource[Me.key][$t.id]:[Me];if(!kt)continue;const ks=kt;F.viewport.set([0,0,tt.fb.width,tt.fb.height]),wt!==($t?$t.id:null)&&(this._setupStencil(tt,kt,Rt,$t),wt=$t?$t.id:null),A.renderLayer(A,$t,Rt,ks)}this.renderedToTile?(tt.dirty=!0,pe.push(Ke.tileID)):ct||--ke,ke===5&&(ke=0,this.renderToBackBuffer(pe))}return this.renderToBackBuffer(pe),this.renderingToTexture=!1,F.bindFramebuffer.set(null),F.viewport.set([0,0,A.width,A.height]),X.end+1}postRender(){}isLayerOrderingCorrect(w){const A=w.order.length;let F=-1,V=A;for(let Z=0;ZF}getMinElevationBelowMSL(){let w=0;return this._visibleDemTiles.filter(A=>A.dem).forEach(A=>{w=Math.min(w,A.dem.tree.minimums[0])}),w===0?w:(w-30)*this._exaggeration}raycast(w,A,F){if(!this._visibleDemTiles)return null;const V=this._visibleDemTiles.filter(Z=>Z.dem).map(Z=>{const X=Z.tileID,ae=1<(Z.t!==null?Z.t:Number.MAX_VALUE)-(X.t!==null?X.t:Number.MAX_VALUE));for(const Z of V){if(Z.t==null)return null;const X=Z.tile.dem.tree.raycast(Z.minx,Z.miny,Z.maxx,Z.maxy,w,A,F);if(X!=null)return X}return null}_createFBO(){const w=this.painter.context,A=w.gl,F=this.drapeBufferSize;w.activeTexture.set(A.TEXTURE0);const V=new o.T(w,{width:F[0],height:F[1],data:null},A.RGBA8);V.bind(A.LINEAR,A.CLAMP_TO_EDGE);const Z=w.createFramebuffer(F[0],F[1],1,null);let X;return Z.colorAttachment0.set(V.texture),this._emissiveTexture&&(X=new o.T(w,{width:F[0],height:F[1],data:null},A.R8),X.bind(A.LINEAR,A.CLAMP_TO_EDGE),Z.createColorAttachment(w,1),Z.colorAttachment1.set(X.texture)),Z.depthAttachment=new oC(w,Z.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=w.createRenderbuffer(w.gl.DEPTH_STENCIL,F[0],F[1]),this._stencilRef=0,Z.depthAttachment.set(this._sharedDepthStencil),w.clear({stencil:0})):Z.depthAttachment.set(this._sharedDepthStencil),w.extTextureFilterAnisotropic&&A.texParameterf(A.TEXTURE_2D,w.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,w.extTextureFilterAnisotropicMax),{fb:Z,tex:V,emissiveTex:X,dirty:!1}}_updateFBOs(w){if(this._emissiveTexture!==w){for(const A of this.pool)this._updateFBO(A,w);for(const A of this.proxySourceCache.renderCache)this._updateFBO(A,w);this._emissiveTexture=w}}_updateFBO(w,A){const F=w.fb,V=this.painter.context,Z=V.gl,X=this.drapeBufferSize;if(A){const ae=new o.T(V,{width:X[0],height:X[1],data:null},Z.R8);ae.bind(Z.LINEAR,Z.CLAMP_TO_EDGE),w.emissiveTex=ae,F.createColorAttachment(V,1),F.colorAttachment1.set(ae.texture)}else w.emissiveTex=void 0,F.removeColorAttachment(V,1);w.dirty=!0}_initFBOPool(){for(;this.pool.length{const A=this._style._mergedLayers[w],F=A.isHidden(this.painter.transform.zoom);return A.type==="hillshade"||A.type==="custom"?!F&&A.shouldRedrape():!F&&A.hasTransition()})}_clearLineLayersFromRenderCache(){let w=!1;for(const F of this._style.getSources())if(F instanceof Wc){w=!0;break}if(!w)return;const A={};for(let F=0;Fpe>ae.end)||o.w("fill-extrusion with flood lighting and/or ground ambient occlusion should be moved to be on top of all draped layers.")}this._drapedRenderBatches=F}_setupRenderCache(w){const A=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,A.renderCache.length>A.renderCachePool.length){const X=Object.values(A.proxyCachedFBO);A.proxyCachedFBO={};for(let ae=0;ae=0;X--){const ae=F[X];if(A.getTileByID(ae.key),A.proxyCachedFBO[ae.key]!==void 0){const pe=w[ae.key],ke=this.proxyToSource[ae.key];let Me=0;for(const Ke in ke){const He=ke[Ke],tt=pe[Ke];if(!tt||tt.length!==He.length||He.some((ct,ot)=>ct!==tt[ot]||V[Ke]&&V[Ke].hasOwnProperty(ct.key))){Me=-1;break}++Me}for(const Ke in A.proxyCachedFBO[ae.key])A.renderCache[A.proxyCachedFBO[ae.key][Ke]].dirty=Me<0||Me!==Object.values(pe).length}}const Z=[...this._drapedRenderBatches];Z.sort((X,ae)=>ae.end-ae.start-(X.end-X.start));for(const X of Z)for(const ae of F){if(A.proxyCachedFBO[ae.key])continue;let pe=A.renderCachePool.pop();pe===void 0&&A.renderCache.length<50&&(pe=A.renderCache.length,A.renderCache.push(this._createFBO())),pe!==void 0&&(A.proxyCachedFBO[ae.key]={},A.proxyCachedFBO[ae.key][X.start]=pe,A.renderCache[pe].dirty=!0)}this._tilesDirty={}}_setupStencil(w,A,F,V){if(!V||!this._sourceTilesOverlap[V.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const Z=this.painter.context,X=Z.gl;if(A.length<=1)return void(this._overlapStencilType=!1);let ae;if(F.isTileClipped())ae=A.length,this._overlapStencilMode.test={func:X.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(A[0].overscaledZ>A[A.length-1].overscaledZ))return void(this._overlapStencilType=!1);ae=1,this._overlapStencilMode.test={func:X.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+ae>255&&(Z.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=ae,this._overlapStencilMode.ref=this._stencilRef,F.isTileClipped()&&this._renderTileClippingMasks(A,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):Sa.disabled}_renderTileClippingMasks(w,A){const F=this.painter,V=this.painter.context,Z=V.gl;F._tileClippingMaskIDs={},V.setColorMode(ka.disabled),V.setDepthMode(Ir.disabled);const X=F.getOrCreateProgram("clippingMask");for(const ae of w){const pe=F._tileClippingMaskIDs[ae.key]=--A;X.draw(F,Z.TRIANGLES,Ir.disabled,new Sa({func:Z.ALWAYS,mask:0},pe,255,Z.KEEP,Z.KEEP,Z.REPLACE),ka.disabled,la.disabled,ht(ae.projMatrix),"$clipping",F.tileExtentBuffer,F.quadTriangleIndexBuffer,F.tileExtentSegments)}}pointCoordinate(w){const A=this.painter.transform;if(w.x<0||w.x>A.width||w.y<0||w.y>A.height)return null;const F=[w.x,w.y,1,1];o.aE(F,F,A.pixelMatrixInverse),o.cu(F,F,1/F[3]),F[0]/=A.worldSize,F[1]/=A.worldSize;const V=A._camera.position,Z=o.bU(1,A.center.lat),X=[V[0],V[1],V[2]/Z,0],ae=o.cV([],F.slice(0,3),X);o.ay(ae,ae);const pe=this.raycast(X,ae,this._exaggeration);return pe!==null&&pe?(o.bg(X,X,ae,pe),X[3]=X[2],X[2]*=Z,X):null}_setupProxiedCoordsForOrtho(w,A,F){if(w.getSource()instanceof o.aV)return this._setupProxiedCoordsForImageSource(w,A,F);this._findCoveringTileCache[w.id]=this._findCoveringTileCache[w.id]||{};const V=this.proxiedCoords[w.id]=[],Z=this.proxyCoords;for(let pe=0;peMe.overscaledZ-ke.overscaledZ)}_setupProxiedCoordsForImageSource(w,A,F){if(!w.getSource().loaded())return;const V=this.proxiedCoords[w.id]=[],Z=this.proxyCoords,X=w.getSource(),ae=X.tileID;if(!ae)return;const pe=new o.P(ae.x,ae.y)._div(1<(Ke.min.x=Math.min(Ke.min.x,He.x-pe.x),Ke.min.y=Math.min(Ke.min.y,He.y-pe.y),Ke.max.x=Math.max(Ke.max.x,He.x-pe.x),Ke.max.y=Math.max(Ke.max.y,He.y-pe.y),Ke),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),Me=(Ke,He)=>{const tt=Ke.wrap+Ke.canonical.x/(1<wt+ke.max.x||ct+ot<_t+ke.min.y||ct>_t+ke.max.y};for(let Ke=0;KeX.key===A.tileID.key);if(Z)return Z}if(A.tileID.key!==w.key){const Z=w.canonical.z-A.tileID.canonical.z;let X,ae,pe;V=o.bb();const ke=A.tileID.wrap-w.wrap<0?(X=o.an>>Z,ae=X*((A.tileID.canonical.x<=Ke){const He=w.canonical.z-Ke;A.getSource().reparseOverscaled?(ae=Math.max(w.canonical.z+2,A.transform.tileZoom),X=new o.aR(ae,w.wrap,Ke,w.canonical.x>>He,w.canonical.y>>He)):He!==0&&(ae=Ke,X=new o.aR(ae,w.wrap,Ke,w.canonical.x>>He,w.canonical.y>>He))}X.key!==w.key&&(ke.push(X.key),F=A.getTile(X))}const Me=Ke=>{ke.forEach(He=>{V[He]=Ke}),ke.length=0};for(ae-=1;ae>=pe&&(!F||!F.hasData());ae--){F&&Me(F.tileID.key);const Ke=X.calculateScaledKey(ae);if(F=A.getTileByID(Ke),F&&F.hasData())break;const He=V[Ke];if(He===null)break;He===void 0?ke.push(Ke):F=A.getTileByID(He)}return Me(F?F.tileID.key:null),F&&F.hasData()?F:null}findDEMTileFor(w){return this.enabled?this._findTileCoveringTileID(w,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(w,A){let F=this._tilesDirty[w];F||(F=this._tilesDirty[w]={}),F[A.key]=!0}}function Ts(R,w,A){const F=function(ae,pe,ke){const Me=o.bi(pe,ae),Ke=o.bi(ke,[.2126,.7152,.0722]),He=(ct,ot,wt)=>(1-wt)*ct+wt*ot,tt=He(1-.3*Math.min(Ke,1),1,Math.min(Me+1,1));return He(.92,1,Math.asin(o.aC(pe[2],-1,1))/Math.PI+.5)*tt}(R,[0,0,1],w),V=[0,0,0];o.bJ(V,A.slice(0,3),F);const Z=[0,0,0];o.bJ(Z,w.slice(0,3),R[2]);const X=[0,0,0];return o.cT(X,V,Z),o.cW(X)}const Ws=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],Nn=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Vn{static cacheKey(w,A,F,V){const Z=[A];V&&Z.push(V.cacheKey);for(const X of F)(typeof X=="string"&&X.includes(" ")||w.usedDefines.has(X))&&Z.push(X);return Z.join("/")}constructor(w,A,F,V,Z,X){const ae=w.gl;this.program=ae.createProgram(),this.configuration=V,this.name=A,this.fixedDefines=[...X];const pe=`#version 300 es ${(V?V.defines():[]).concat(X.map(ot=>`#define ${ot}`)).join(` `)}`,ke=[pe,fv];for(const ot of F.fragmentIncludes)ke.push(Wp[ot]);ke.push(F.fragmentSource);const Me=ke.join(` `),Ke=[pe,n2];for(const ot of F.vertexIncludes)Ke.push(Wp[ot]);this.forceManualRenderingForInstanceIDShaders=w.forceManualRenderingForInstanceIDShaders&&F.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Ke.push("uniform int u_instanceID;"),Ke.push(F.vertexSource);let He=Ke.join(` `);this.forceManualRenderingForInstanceIDShaders&&(He=He.replaceAll("gl_InstanceID","u_instanceID"));const tt=ae.createShader(ae.FRAGMENT_SHADER);if(ae.isContextLost())return void(this.failedToCreate=!0);ae.shaderSource(tt,Me),ae.compileShader(tt),ae.attachShader(this.program,tt);const ct=ae.createShader(ae.VERTEX_SHADER);ae.isContextLost()?this.failedToCreate=!0:(ae.shaderSource(ct,He),ae.compileShader(ct),ae.attachShader(this.program,ct),this.attributes={},ae.linkProgram(this.program),ae.deleteShader(ct),ae.deleteShader(tt),this.fixedUniforms=Z(w),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=V?V.getUniforms(w):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(ot=>({u_instanceID:new o.bX(ot)}))(w)),(X.includes("TERRAIN")||X.includes("ELEVATED")||A.includes("symbol")||A.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)),X.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)),X.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)),X.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(ot=>({u_cutoff_params:new o.cO(ot)}))(w)),X.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)),X.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,A){let F=this.attributes[A];return F===void 0&&(F=this.attributes[A]=w.getAttribLocation(this.program,A)),F}setTerrainUniformValues(w,A){if(!this.terrainUniforms)return;const F=this.terrainUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const V in A)F[V]&&F[V].set(this.program,V,A[V])}}setGlobeUniformValues(w,A){if(!this.globeUniforms)return;const F=this.globeUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const V in A)F[V]&&F[V].set(this.program,V,A[V])}}setFogUniformValues(w,A){if(!this.fogUniforms)return;const F=this.fogUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const V in A)F[V].set(this.program,V,A[V])}}setCutoffUniformValues(w,A){if(!this.cutoffUniforms)return;const F=this.cutoffUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const V in A)F[V].set(this.program,V,A[V])}}setLightsUniformValues(w,A){if(!this.lightsUniforms)return;const F=this.lightsUniforms;if(!this.failedToCreate){w.program.set(this.program);for(const V in A)F[V].set(this.program,V,A[V])}}setShadowUniformValues(w,A){if(this.failedToCreate||!this.shadowUniforms)return;const F=this.shadowUniforms;w.program.set(this.program);for(const V in A)F[V].set(this.program,V,A[V])}_drawDebugWireframe(w,A,F,V,Z,X,ae,pe,ke,Me){const Ke=w.options.wireframe;if(Ke.terrain===!1&&Ke.layers2D===!1&&Ke.layers3D===!1)return;const He=w.context;if(!(!(!Ke.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Ke.layers2D||w._terrain&&w._terrain.renderingToTexture||!Ws.includes(this.name))||!(!Ke.layers3D||!Nn.includes(this.name))))return;const tt=He.gl,ct=w.wireframeDebugCache.getLinesFromTrianglesBuffer(w.frameCounter,Z,He);if(!ct)return;const ot=[...this.fixedDefines,"DEBUG_WIREFRAME"],wt=w.getOrCreateProgram(this.name,{config:this.configuration,defines:ot});He.program.set(wt.program);const _t=(kt,ks,Jt)=>{if(ks[kt]&&Jt[kt])for(const ws in ks[kt])Jt[kt][ws]&&Jt[kt][ws].set(Jt.program,ws,ks[kt][ws].current)};ke&&ke.setUniforms(wt.program,He,wt.binderUniforms,ae,{zoom:pe}),_t("fixedUniforms",this,wt),_t("terrainUniforms",this,wt),_t("globeUniforms",this,wt),_t("fogUniforms",this,wt),_t("lightsUniforms",this,wt),_t("shadowUniforms",this,wt),ct.bind(),He.setColorMode(new ka([tt.ONE,tt.ONE_MINUS_SRC_ALPHA,tt.ZERO,tt.ONE],o.aq.transparent,[!0,!0,!0,!1])),He.setDepthMode(new Ir(A.func===tt.LESS?tt.LEQUAL:A.func,Ir.ReadOnly,A.range)),He.setStencilMode(Sa.disabled);const Rt=3*X.primitiveLength*2,$t=3*X.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const kt=Me||1;for(let ks=0;ks1?tt.drawElementsInstanced(tt.LINES,Rt,tt.UNSIGNED_SHORT,$t,Me):tt.drawElements(tt.LINES,Rt,tt.UNSIGNED_SHORT,$t);Z.bind(),He.program.set(this.program),He.setDepthMode(A),He.setStencilMode(F),He.setColorMode(V)}checkUniforms(w,A,F){if(this.fixedDefines.includes(A)){for(const V of Object.keys(F))if(!F[V].initialized)throw new Error(`Program '${this.name}', from draw '${w}': uniform ${V} not set but required by ${A} being defined`)}}draw(w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt,ct,ot,wt){const _t=w.context,Rt=_t.gl;if(this.failedToCreate)return;_t.program.set(this.program),_t.setDepthMode(F),_t.setStencilMode(V),_t.setColorMode(Z),_t.setCullFace(X);for(const[Vt,Xt]of this.fixedUniformsEntries)Xt.set(this.program,Vt,ae[Vt]);ct&&ct.setUniforms(this.program,_t,this.binderUniforms,He,{zoom:tt});const $t={[Rt.POINTS]:1,[Rt.LINES]:2,[Rt.TRIANGLES]:3,[Rt.LINE_STRIP]:1}[A];this.checkUniforms(pe,"RENDER_SHADOWS",this.shadowUniforms);const kt=ot||[],ks=ct?ct.getPaintVertexBuffers():[],Jt=A===Rt.TRIANGLES&&Me,ws=wt&&wt>0?1:void 0;for(const Vt of Ke.get()){const Xt=Vt.vaos||(Vt.vaos={});if((Xt[pe]||(Xt[pe]=new WN)).bind(_t,this,ke,ks,Me,Vt.vertexOffset,kt,ws),this.forceManualRenderingForInstanceIDShaders){const ms=wt||1;for(let Us=0;Us1?Rt.drawElementsInstanced(A,Vt.primitiveLength*$t,Rt.UNSIGNED_SHORT,Vt.primitiveOffset*$t*2,wt):Me?Rt.drawElements(A,Vt.primitiveLength*$t,Rt.UNSIGNED_SHORT,Vt.primitiveOffset*$t*2):Rt.drawArrays(A,Vt.vertexOffset,Vt.vertexLength);Jt&&this._drawDebugWireframe(w,F,V,Z,Me,Vt,He,tt,ct,wt)}}}function Ks(R,w,A=0){const F=Math.pow(2,w.tileID.overscaledZ),V=w.tileSize*Math.pow(2,R.transform.tileZoom)/F,Z=V*(w.tileID.canonical.x+w.tileID.wrap*F),X=V*w.tileID.canonical.y;return{u_image:0,u_texsize:w.imageAtlasTexture?w.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/o.aA(w,1,R.transform.tileZoom),u_pixel_coord_upper:[Z>>16,X>>16],u_pixel_coord_lower:[65535&Z,65535&X],u_pattern_transition:A}}const In={terrain:0,flat:1},Xn=o.bb(),Cr=(R,w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt,ct,ot,wt,_t,Rt=[0,0,1])=>{const $t=w.style.light,kt=$t.properties.get("position"),ks=[kt.x,kt.y,kt.z],Jt=o.dE();$t.properties.get("anchor")==="viewport"&&(o.dF(Jt,-w.transform.angle),o.dG(ks,ks,Jt));const ws=$t.properties.get("color").toPremultipliedRenderColor(null),Vt=w.transform,Xt={u_matrix:R,u_lightpos:ks,u_lightintensity:$t.properties.get("intensity"),u_lightcolor:[ws.r,ws.g,ws.b],u_vertical_gradient:+A,u_opacity:F,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Xn,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:In[ke],u_base_type:In[Me],u_ao:V,u_edge_radius:Z,u_width_scale:X,u_flood_light_color:ct,u_vertical_scale:ot,u_flood_light_intensity:wt,u_ground_shadow_factor:_t,u_front_cutoff_params:Rt};return Vt.projection.name==="globe"&&(Xt.u_tile_id=[ae.canonical.x,ae.canonical.y,1<({u_matrix:R,u_edge_radius:w,u_width_scale:A,u_vertical_scale:F,u_height_type:In[V],u_base_type:In[Z]}),On=(R,w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt,ct,ot,wt,_t)=>{const Rt=Cr(R,w,A,F,V,Z,X,ae,ke,Me,Ke,He,tt,ct,ot,wt,1,[0,0,0]),$t={u_height_factor:-Math.pow(2,ae.overscaledZ)/pe.tileSize/8};return Object.assign(Rt,Ks(w,pe,_t),$t)},Pr=(R,w,A)=>({u_matrix:R,u_emissive_strength:w,u_ground_shadow_factor:A}),ga=(R,w,A,F,V,Z=0)=>Object.assign(Pr(R,w,V),Ks(A,F,Z)),ca=(R,w,A,F)=>({u_matrix:R,u_world:A,u_emissive_strength:w,u_ground_shadow_factor:F}),Li=(R,w,A,F,V,Z,X=0)=>Object.assign(ga(R,w,A,F,Z,X),{u_world:V}),fi=(R,w)=>({u_matrix:R,u_depth_bias:w}),Zo=(R,w)=>({u_matrix:R,u_ground_shadow_factor:w}),Si=(R,w,A,F,V)=>({u_matrix:R,u_camera_pos:[w[0],w[1],w[2]],u_depth_bias:A,u_height_scale:F,u_reset_depth:V}),Tl=(R,w,A)=>({u_image:R,u_opacity:w,u_blend_mode:A}),Ad=(R,w,A,F,V,Z,X,ae,pe,ke=[0,0,1])=>({u_matrix:R,u_normal_matrix:w,u_opacity:A,u_faux_facade_ao_intensity:F,u_camera_pos:V,u_tile_to_meter:Z,u_facade_emissive_chance:X,u_flood_light_color:ae,u_flood_light_intensity:pe,u_front_cutoff_params:ke}),Xo=R=>({u_matrix:R}),Ti=R=>({u_matrix:R}),Ya=(R,w,A,F,V,Z,X,ae)=>{const pe=o.an/Z.tileSize;return{u_matrix:R,u_inv_rot_matrix:w,u_camera_to_center_distance:A.getCameraToCenterDistance(ae),u_extrude_scale:[A.pixelsToGLUnits[0]/pe,A.pixelsToGLUnits[1]/pe],u_zoom_transition:F,u_tile_id:X,u_merc_center:V}},el=(R,w,A,F)=>({u_matrix:R,u_inv_matrix:w,u_camera_to_center_distance:A.getCameraToCenterDistance(F),u_viewport_size:[A.width,A.height]}),io=(R,w,A=1)=>({u_matrix:R,u_color:w,u_overlay:0,u_overlay_scale:A}),qo=o.bb(),yd=(R,w,A,F,V,Z,X)=>{const ae=R.transform,pe=ae.projection.name==="globe",ke=pe?o.dH(ae.zoom,w.canonical)*ae._pixelsPerMercatorPixel:o.aA(A,1,Z),Me={u_matrix:w.projMatrix,u_extrude_scale:ke,u_intensity:X,u_inv_rot_matrix:qo,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(pe){Me.u_inv_rot_matrix=F,Me.u_merc_center=V,Me.u_tile_id=[w.canonical.x,w.canonical.y,1<({u_matrix:w,u_normalize_matrix:A,u_globe_matrix:F,u_merc_matrix:V,u_grid_matrix:Z,u_tl_parent:X,u_scale_parent:Me,u_fade_t:Ke.mix,u_opacity:Ke.opacity*He.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:He.paint.get("raster-brightness-min"),u_brightness_high:He.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(He.paint.get("raster-saturation")),u_contrast_factor:o.dI(He.paint.get("raster-contrast")),u_spin_weights:Zp(He.paint.get("raster-hue-rotate")),u_perspective_transform:tt,u_raster_elevation:ct,u_zoom_transition:ae,u_merc_center:pe,u_cutoff_params:ke,u_colorization_mix:Th(o.dK,wt,Rt),u_colorization_offset:vd(o.dK,_t,Rt),u_color_ramp:ot,u_texture_offset:[kt/($t+2*kt),$t/($t+2*kt)],u_texture_res:[$t+2*kt,$t+2*kt],u_emissive_strength:ks,u_zbias_factor:Qd(R)});function Zp(R){R*=Math.PI/180;const w=Math.sin(R),A=Math.cos(R);return[(2*A+1)/3,(-Math.sqrt(3)*w-A+1)/3,(Math.sqrt(3)*w-A+1)/3]}const od=.05,uc=(R,w,A,F,V,Z,X,ae,pe,ke,Me,Ke)=>({u_matrix:R,u_normalize_matrix:w,u_globe_matrix:A,u_merc_matrix:F,u_grid_matrix:V,u_tl_parent:Z,u_scale_parent:ke,u_fade_t:Me.mix,u_opacity:Me.opacity,u_image0:0,u_image1:1,u_raster_elevation:Ke,u_zoom_transition:X,u_merc_center:ae,u_cutoff_params:pe}),Zc=(R,w,A,F,V,Z,X,ae,pe,ke)=>({u_particle_texture:R,u_particle_texture_side_len:w,u_tile_offset:A,u_velocity:F,u_color_ramp:Z,u_velocity_res:V,u_max_speed:X,u_uv_offset:ae,u_data_scale:[255*pe[0],255*pe[1]],u_data_offset:ke,u_particle_pos_scale:1.1,u_particle_pos_offset:[od,od]}),vu=(R,w,A,F,V,Z,X,ae,pe,ke)=>({u_particle_texture:R,u_particle_texture_side_len:w,u_velocity:A,u_velocity_res:F,u_max_speed:V,u_speed_factor:Z,u_reset_rate:X,u_rand_seed:Math.random(),u_uv_offset:ae,u_data_scale:[255*pe[0],255*pe[1]],u_data_offset:ke,u_particle_pos_scale:1.1,u_particle_pos_offset:[od,od]}),jc=o.bb(),Pu=(R,w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt,ct,ot,wt,_t,Rt,$t,kt,ks,Jt,ws)=>{const Vt=V.transform,Xt={u_is_size_zoom_constant:+(R==="constant"||R==="source"),u_is_size_feature_constant:+(R==="constant"||R==="camera"),u_size_t:w?w.uSizeT:0,u_size:w?w.uSize:0,u_camera_to_center_distance:Vt.getCameraToCenterDistance(Rt),u_rotate_symbol:+A,u_aspect_ratio:Vt.width/Vt.height,u_fade_change:V.options.fadeDuration?V.symbolFadeChange:1,u_matrix:Z,u_label_plane_matrix:X,u_coord_matrix:ae,u_is_text:+ke,u_elevation_from_sea:pe?1:0,u_pitch_with_map:+F,u_texsize:Me,u_texsize_icon:Ke,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:jc,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:jc,u_up_vector:[0,-1,0],u_color_adj_mat:ks,u_icon_transition:Jt||0,u_gamma_scale:F?V.transform.getCameraToCenterDistance(Rt)*Math.cos(V.terrain?0:V.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:ws||1,u_ground_shadow_factor:$t,u_inv_matrix:o.b7(o.bb(),X),u_normal_scale:kt,u_lutTexture:10,u_zoom:Vt.zoom-Math.floor(Vt.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 Rt.name==="globe"&&(Xt.u_tile_id=[tt.canonical.x,tt.canonical.y,1<({u_matrix:R,u_emissive_strength:w,u_opacity:A,u_color:F}),Fc=(R,w,A,F,V,Z,X,ae,pe)=>Object.assign(function(ke,Me,Ke,He,tt,ct){const{width:ot,height:wt}=He.imageManager.getPixelSize(Me),_t=Math.pow(2,ct.tileID.overscaledZ),Rt=ct.tileSize*Math.pow(2,He.transform.tileZoom)/_t,$t=Rt*(ct.tileID.canonical.x+ct.tileID.wrap*_t),kt=Rt*ct.tileID.canonical.y;return{u_image:0,u_pattern_tl:Ke.tl,u_pattern_br:Ke.br,u_texsize:[ot,wt],u_pattern_size:Ke.displaySize,u_pattern_units_to_pixels:tt?[He.transform.width,-1*He.transform.height]:[1/o.aA(ct,1,He.transform.tileZoom),1/o.aA(ct,1,He.transform.tileZoom)],u_pixel_coord_upper:[$t>>16,kt>>16],u_pixel_coord_lower:[65535&$t,65535&kt]}}(0,Z,X,F,ae,pe),{u_matrix:R,u_emissive_strength:w,u_opacity:A}),Xu=new Float32Array(o.b9([])),Bl=(R,w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt=[0,0,0],ct,ot,wt)=>{const _t=V.style.light,Rt=_t.properties.get("position"),$t=[-Rt.x,-Rt.y,Rt.z],kt=o.dE();_t.properties.get("anchor")==="viewport"&&(o.dF(kt,-V.transform.angle),o.dG($t,$t,kt));const ks=Me.alphaMode==="MASK",Jt=_t.properties.get("color").toNonPremultipliedRenderColor(null),ws=He.paint.get("model-ambient-occlusion-intensity"),Vt=He.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return Vt.a=He.paint.get("model-color-mix-intensity").constantOr(0),wt&&(Vt.r=wt[0],Vt.g=wt[1],Vt.b=wt[2],Vt.a=wt[3]),ot&&(Vt.r=ot.color.r,Vt.g=ot.color.g,Vt.b=ot.color.b,Vt.a=ot.colorMix,Ke=ot.emissionStrength,Z*=ot.opacity),{u_matrix:R,u_lighting_matrix:w,u_normal_matrix:A,u_node_matrix:F||Xu,u_lightpos:$t,u_lightintensity:_t.properties.get("intensity"),u_lightcolor:[Jt.r,Jt.g,Jt.b],u_camera_pos:tt,u_opacity:Z,u_baseTextureIsAlpha:0,u_alphaMask:+ks,u_alphaCutoff:Me.alphaCutoff,u_baseColorFactor:X.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:ae.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:pe,u_roughnessFactor:ke,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:Vt.toArray01(),u_aoIntensity:ws,u_emissive_strength:Ke,u_occlusionTextureTransform:ct||[0,0,0,0]}},Iu=(R,w=Xu,A=Xu)=>({u_matrix:R,u_instance:w,u_node_matrix:A}),Sm={fillExtrusion:R=>({u_matrix:new o.b$(R),u_lightpos:new o.bY(R),u_lightintensity:new o.bZ(R),u_lightcolor:new o.bY(R),u_vertical_gradient:new o.bZ(R),u_opacity:new o.bZ(R),u_edge_radius:new o.bZ(R),u_width_scale:new o.bZ(R),u_ao:new o.b_(R),u_height_type:new o.bX(R),u_base_type:new o.bX(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_up_dir:new o.bY(R),u_height_lift:new o.bZ(R),u_flood_light_color:new o.bY(R),u_vertical_scale:new o.bZ(R),u_flood_light_intensity:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_front_cutoff_params:new o.bY(R)}),fillExtrusionDepth:R=>({u_matrix:new o.b$(R),u_edge_radius:new o.bZ(R),u_width_scale:new o.bZ(R),u_vertical_scale:new o.bZ(R),u_height_type:new o.bX(R),u_base_type:new o.bX(R)}),fillExtrusionPattern:R=>({u_matrix:new o.b$(R),u_lightpos:new o.bY(R),u_lightintensity:new o.bZ(R),u_lightcolor:new o.bY(R),u_vertical_gradient:new o.bZ(R),u_height_factor:new o.bZ(R),u_edge_radius:new o.bZ(R),u_width_scale:new o.bZ(R),u_ao:new o.b_(R),u_height_type:new o.bX(R),u_base_type:new o.bX(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_up_dir:new o.bY(R),u_height_lift:new o.bZ(R),u_image:new o.bX(R),u_texsize:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_tile_units_to_pixels:new o.bZ(R),u_opacity:new o.bZ(R),u_pattern_transition:new o.bZ(R)}),fillExtrusionGroundEffect:R=>({u_matrix:new o.b$(R),u_opacity:new o.bZ(R),u_ao_pass:new o.bZ(R),u_meter_to_tile:new o.bZ(R),u_ao:new o.b_(R),u_flood_light_intensity:new o.bZ(R),u_flood_light_color:new o.bY(R),u_attenuation:new o.bZ(R),u_edge_radius:new o.bZ(R),u_fb:new o.bX(R),u_fb_size:new o.bZ(R),u_dynamic_offset:new o.bZ(R)}),fill:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_ground_shadow_factor:new o.bY(R)}),fillPattern:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_image:new o.bX(R),u_texsize:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_tile_units_to_pixels:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_pattern_transition:new o.bZ(R)}),fillOutline:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_world:new o.b_(R),u_ground_shadow_factor:new o.bY(R)}),fillOutlinePattern:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_world:new o.b_(R),u_image:new o.bX(R),u_texsize:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_tile_units_to_pixels:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_pattern_transition:new o.bZ(R)}),lineBlendComposite:R=>({u_image:new o.bX(R),u_opacity:new o.bZ(R),u_blend_mode:new o.bX(R)}),building:R=>({u_matrix:new o.b$(R),u_normal_matrix:new o.b$(R),u_opacity:new o.bZ(R),u_faux_facade_ao_intensity:new o.bZ(R),u_camera_pos:new o.bY(R),u_tile_to_meter:new o.bZ(R),u_facade_emissive_chance:new o.bZ(R),u_flood_light_color:new o.bY(R),u_flood_light_intensity:new o.bZ(R),u_front_cutoff_params:new o.bY(R)}),buildingBloom:R=>({u_matrix:new o.b$(R)}),buildingDepth:R=>({u_matrix:new o.b$(R)}),elevatedStructuresDepth:R=>({u_matrix:new o.b$(R),u_depth_bias:new o.bZ(R)}),elevatedStructures:R=>({u_matrix:new o.b$(R),u_ground_shadow_factor:new o.bY(R)}),elevatedStructuresDepthReconstruct:R=>({u_matrix:new o.b$(R),u_camera_pos:new o.bY(R),u_depth_bias:new o.bZ(R),u_height_scale:new o.bZ(R),u_reset_depth:new o.bZ(R)}),circle:o.dO,collisionBox:R=>({u_matrix:new o.b$(R),u_inv_rot_matrix:new o.b$(R),u_camera_to_center_distance:new o.bZ(R),u_extrude_scale:new o.b_(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_tile_id:new o.bY(R)}),collisionCircle:R=>({u_matrix:new o.b$(R),u_inv_matrix:new o.b$(R),u_camera_to_center_distance:new o.bZ(R),u_viewport_size:new o.b_(R)}),debug:R=>({u_color:new o.dl(R),u_matrix:new o.b$(R),u_overlay:new o.bX(R),u_overlay_scale:new o.bZ(R)}),clippingMask:R=>({u_matrix:new o.b$(R)}),heatmap:R=>({u_extrude_scale:new o.bZ(R),u_intensity:new o.bZ(R),u_matrix:new o.b$(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_up_dir:new o.bY(R)}),heatmapTexture:R=>({u_image:new o.bX(R),u_color_ramp:new o.bX(R),u_opacity:new o.bZ(R)}),hillshade:R=>({u_matrix:new o.b$(R),u_image:new o.bX(R),u_latrange:new o.b_(R),u_light:new o.b_(R),u_shadow:new o.dl(R),u_highlight:new o.dl(R),u_emissive_strength:new o.bZ(R),u_accent:new o.dl(R)}),hillshadePrepare:R=>({u_matrix:new o.b$(R),u_image:new o.bX(R),u_dimension:new o.b_(R),u_zoom:new o.bZ(R)}),line:o.dN,linePattern:o.dM,raster:R=>({u_matrix:new o.b$(R),u_normalize_matrix:new o.b$(R),u_globe_matrix:new o.b$(R),u_merc_matrix:new o.b$(R),u_grid_matrix:new o.dm(R),u_tl_parent:new o.b_(R),u_scale_parent:new o.bZ(R),u_fade_t:new o.bZ(R),u_opacity:new o.bZ(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_brightness_low:new o.bZ(R),u_brightness_high:new o.bZ(R),u_saturation_factor:new o.bZ(R),u_contrast_factor:new o.bZ(R),u_spin_weights:new o.bY(R),u_perspective_transform:new o.b_(R),u_raster_elevation:new o.bZ(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_cutoff_params:new o.cO(R),u_colorization_mix:new o.cO(R),u_colorization_offset:new o.bZ(R),u_color_ramp:new o.bX(R),u_texture_offset:new o.b_(R),u_texture_res:new o.b_(R),u_emissive_strength:new o.bZ(R),u_zbias_factor:new o.bZ(R)}),rasterParticle:R=>({u_matrix:new o.b$(R),u_normalize_matrix:new o.b$(R),u_globe_matrix:new o.b$(R),u_merc_matrix:new o.b$(R),u_grid_matrix:new o.dm(R),u_tl_parent:new o.b_(R),u_scale_parent:new o.bZ(R),u_fade_t:new o.bZ(R),u_opacity:new o.bZ(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_raster_elevation:new o.bZ(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_cutoff_params:new o.cO(R)}),rasterParticleTexture:R=>({u_texture:new o.bX(R),u_opacity:new o.bZ(R)}),rasterParticleDraw:R=>({u_particle_texture:new o.bX(R),u_particle_texture_side_len:new o.bZ(R),u_tile_offset:new o.b_(R),u_velocity:new o.bX(R),u_color_ramp:new o.bX(R),u_velocity_res:new o.b_(R),u_max_speed:new o.bZ(R),u_uv_offset:new o.b_(R),u_data_scale:new o.b_(R),u_data_offset:new o.bZ(R),u_particle_pos_scale:new o.bZ(R),u_particle_pos_offset:new o.b_(R)}),rasterParticleUpdate:R=>({u_particle_texture:new o.bX(R),u_particle_texture_side_len:new o.bZ(R),u_velocity:new o.bX(R),u_velocity_res:new o.b_(R),u_max_speed:new o.bZ(R),u_speed_factor:new o.bZ(R),u_reset_rate:new o.bZ(R),u_rand_seed:new o.bZ(R),u_uv_offset:new o.b_(R),u_data_scale:new o.b_(R),u_data_offset:new o.bZ(R),u_particle_pos_scale:new o.bZ(R),u_particle_pos_offset:new o.b_(R)}),symbol:R=>({u_is_size_zoom_constant:new o.bX(R),u_is_size_feature_constant:new o.bX(R),u_size_t:new o.bZ(R),u_size:new o.bZ(R),u_camera_to_center_distance:new o.bZ(R),u_rotate_symbol:new o.bX(R),u_aspect_ratio:new o.bZ(R),u_fade_change:new o.bZ(R),u_matrix:new o.b$(R),u_label_plane_matrix:new o.b$(R),u_coord_matrix:new o.b$(R),u_is_text:new o.bX(R),u_elevation_from_sea:new o.bX(R),u_pitch_with_map:new o.bX(R),u_texsize:new o.b_(R),u_texsize_icon:new o.b_(R),u_texture:new o.bX(R),u_texture_icon:new o.bX(R),u_gamma_scale:new o.bZ(R),u_device_pixel_ratio:new o.bZ(R),u_tile_id:new o.bY(R),u_zoom_transition:new o.bZ(R),u_inv_rot_matrix:new o.b$(R),u_merc_center:new o.b_(R),u_camera_forward:new o.bY(R),u_tile_matrix:new o.b$(R),u_up_vector:new o.bY(R),u_ecef_origin:new o.bY(R),u_is_halo:new o.bX(R),u_icon_transition:new o.bZ(R),u_color_adj_mat:new o.b$(R),u_scale_factor:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_inv_matrix:new o.b$(R),u_normal_scale:new o.bZ(R),u_lutTexture:new o.bX(R),u_zoom:new o.bZ(R),u_spp_fill_np_color:new o.cO(R),u_spp_halo_np_color:new o.cO(R),u_spp_opacity:new o.bZ(R),u_spp_halo_width:new o.bZ(R),u_spp_halo_blur:new o.bZ(R),u_spp_emissive_strength:new o.bZ(R),u_spp_occlusion_opacity:new o.bZ(R),u_spp_z_offset:new o.bZ(R),u_spp_translate_rotation:new o.b_(R)}),background:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_opacity:new o.bZ(R),u_color:new o.dl(R)}),backgroundPattern:R=>({u_matrix:new o.b$(R),u_emissive_strength:new o.bZ(R),u_opacity:new o.bZ(R),u_image:new o.bX(R),u_pattern_tl:new o.b_(R),u_pattern_br:new o.b_(R),u_texsize:new o.b_(R),u_pattern_size:new o.b_(R),u_pixel_coord_upper:new o.b_(R),u_pixel_coord_lower:new o.b_(R),u_pattern_units_to_pixels:new o.b_(R)}),terrainRaster:R=>({u_matrix:new o.b$(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_skirt_height:new o.bZ(R),u_ground_shadow_factor:new o.bY(R),u_emissive_texture_available:new o.bZ(R)}),skybox:R=>({u_matrix:new o.b$(R),u_sun_direction:new o.bY(R),u_cubemap:new o.bX(R),u_opacity:new o.bZ(R),u_temporal_offset:new o.bZ(R)}),skyboxGradient:R=>({u_matrix:new o.b$(R),u_color_ramp:new o.bX(R),u_center_direction:new o.bY(R),u_radius:new o.bZ(R),u_opacity:new o.bZ(R),u_temporal_offset:new o.bZ(R)}),skyboxCapture:R=>({u_matrix_3f:new o.dm(R),u_sun_direction:new o.bY(R),u_sun_intensity:new o.bZ(R),u_color_tint_r:new o.cO(R),u_color_tint_m:new o.cO(R),u_luminance:new o.bZ(R)}),globeRaster:R=>({u_proj_matrix:new o.b$(R),u_globe_matrix:new o.b$(R),u_normalize_matrix:new o.b$(R),u_merc_matrix:new o.b$(R),u_zoom_transition:new o.bZ(R),u_merc_center:new o.b_(R),u_image0:new o.bX(R),u_image1:new o.bX(R),u_grid_matrix:new o.dm(R),u_skirt_height:new o.bZ(R),u_far_z_cutoff:new o.bZ(R),u_frustum_tl:new o.bY(R),u_frustum_tr:new o.bY(R),u_frustum_br:new o.bY(R),u_frustum_bl:new o.bY(R),u_globe_pos:new o.bY(R),u_globe_radius:new o.bZ(R),u_viewport:new o.b_(R),u_emissive_texture_available:new o.bZ(R)}),globeAtmosphere:R=>({u_frustum_tl:new o.bY(R),u_frustum_tr:new o.bY(R),u_frustum_br:new o.bY(R),u_frustum_bl:new o.bY(R),u_horizon:new o.bZ(R),u_transition:new o.bZ(R),u_fadeout_range:new o.bZ(R),u_atmosphere_fog_color:new o.cO(R),u_high_color:new o.cO(R),u_space_color:new o.cO(R),u_temporal_offset:new o.bZ(R),u_horizon_angle:new o.bZ(R)}),model:R=>({u_matrix:new o.b$(R),u_lighting_matrix:new o.b$(R),u_normal_matrix:new o.b$(R),u_node_matrix:new o.b$(R),u_lightpos:new o.bY(R),u_lightintensity:new o.bZ(R),u_lightcolor:new o.bY(R),u_camera_pos:new o.bY(R),u_opacity:new o.bZ(R),u_baseColorFactor:new o.cO(R),u_emissiveFactor:new o.cO(R),u_metallicFactor:new o.bZ(R),u_roughnessFactor:new o.bZ(R),u_baseTextureIsAlpha:new o.bX(R),u_alphaMask:new o.bX(R),u_alphaCutoff:new o.bZ(R),u_baseColorTexture:new o.bX(R),u_metallicRoughnessTexture:new o.bX(R),u_normalTexture:new o.bX(R),u_occlusionTexture:new o.bX(R),u_emissionTexture:new o.bX(R),u_lutTexture:new o.bX(R),u_color_mix:new o.cO(R),u_aoIntensity:new o.bZ(R),u_emissive_strength:new o.bZ(R),u_occlusionTextureTransform:new o.cO(R)}),modelDepth:R=>({u_matrix:new o.b$(R),u_instance:new o.b$(R),u_node_matrix:new o.b$(R)}),groundShadow:R=>({u_matrix:new o.b$(R),u_ground_shadow_factor:new o.bY(R)}),stars:R=>({u_matrix:new o.b$(R),u_up:new o.bY(R),u_right:new o.bY(R),u_intensity_multiplier:new o.bZ(R)}),snowParticle:R=>({u_modelview:new o.b$(R),u_projection:new o.b$(R),u_time:new o.bZ(R),u_cam_pos:new o.bY(R),u_velocityConeAperture:new o.bZ(R),u_velocity:new o.bZ(R),u_horizontalOscillationRadius:new o.bZ(R),u_horizontalOscillationRate:new o.bZ(R),u_boxSize:new o.bZ(R),u_billboardSize:new o.bZ(R),u_simpleShapeParameters:new o.b_(R),u_screenSize:new o.b_(R),u_thinningCenterPos:new o.b_(R),u_thinningShape:new o.bY(R),u_thinningAffectedRatio:new o.bZ(R),u_thinningParticleOffset:new o.bZ(R),u_particleColor:new o.cO(R),u_direction:new o.bY(R)}),rainParticle:R=>({u_modelview:new o.b$(R),u_projection:new o.b$(R),u_time:new o.bZ(R),u_cam_pos:new o.bY(R),u_texScreen:new o.bX(R),u_velocityConeAperture:new o.bZ(R),u_velocity:new o.bZ(R),u_boxSize:new o.bZ(R),u_rainDropletSize:new o.b_(R),u_distortionStrength:new o.bZ(R),u_rainDirection:new o.bY(R),u_color:new o.cO(R),u_screenSize:new o.b_(R),u_thinningCenterPos:new o.b_(R),u_thinningShape:new o.bY(R),u_thinningAffectedRatio:new o.bZ(R),u_thinningParticleOffset:new o.bZ(R),u_shapeDirectionalPower:new o.bZ(R),u_shapeNormalPower:new o.bZ(R),u_mode:new o.bZ(R)}),vignette:R=>({u_vignetteShape:new o.bY(R),u_vignetteColor:new o.cO(R)}),occlusion:R=>({u_matrix:new o.b$(R),u_anchorPos:new o.bY(R),u_screenSizePx:new o.b_(R),u_occluderSizePx:new o.b_(R),u_color:new o.cO(R)})};class Td{constructor(w,A,F,V){this.id=Td.uniqueIdxCounter,Td.uniqueIdxCounter++,this.context=w;const Z=w.gl;this.buffer=Z.createBuffer(),this.dynamicDraw=!!F,this.context.unbindVAO(),w.bindElementBuffer.set(this.buffer),Z.bufferData(Z.ELEMENT_ARRAY_BUFFER,A.arrayBuffer,this.dynamicDraw?Z.DYNAMIC_DRAW:Z.STATIC_DRAW),this.dynamicDraw||V||A.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(w){this.id=Td.uniqueIdxCounter,Td.uniqueIdxCounter++;const A=this.context.gl;this.context.unbindVAO(),this.bind(),A.bufferSubData(A.ELEMENT_ARRAY_BUFFER,0,w.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}Td.uniqueIdxCounter=0;const Xp={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Qp{constructor(w,A,F,V,Z,X){this.length=A.length,this.attributes=F,this.itemSize=A.bytesPerElement,this.dynamicDraw=V,this.instanceCount=X,this.context=w;const ae=w.gl;this.buffer=ae.createBuffer(),w.bindVertexBuffer.set(this.buffer),ae.bufferData(ae.ARRAY_BUFFER,A.arrayBuffer,this.dynamicDraw?ae.DYNAMIC_DRAW:ae.STATIC_DRAW),this.dynamicDraw||Z||A.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(w){const A=this.context.gl;this.bind(),A.bufferSubData(A.ARRAY_BUFFER,0,w.arrayBuffer)}enableAttributes(w,A){for(const F of this.attributes){const V=A.getAttributeLocation(w,F.name);V!==-1&&w.enableVertexAttribArray(V)}}setVertexAttribPointers(w,A,F){for(const V of this.attributes){const Z=A.getAttributeLocation(w,V.name);if(Z!==-1){const X=V.offset+this.itemSize*(F||0);V.type==="Float32"?w.vertexAttribPointer(Z,V.components,w.FLOAT,!1,this.itemSize,X):w.vertexAttribIPointer(Z,V.components,w[Xp[V.type]],this.itemSize,X)}}}setVertexAttribDivisor(w,A,F){for(let V=0;V0&&w.vertexAttribDivisor(Z,F)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Cm{constructor(w,A,F,V,Z){this.context=w,this.width=A,this.height=F;const X=this.framebuffer=w.gl.createFramebuffer();V>0&&(this.colorAttachment0=new Kb(w,X,0)),V>1&&(this.colorAttachment1=new Kb(w,X,1)),Z&&(this.depthAttachmentType=Z,this.depthAttachment=Z==="renderbuffer"?new i2(w,X):new JN(w,X))}static createWithTexture(w,A,F,V,Z){const X=w.gl;if(w.activeTexture.set(X.TEXTURE1),w.viewport.set([0,0,F,V]),A&&A.width===F&&A.height===V)return X.bindTexture(X.TEXTURE_2D,A.colorAttachment0.get()),w.bindFramebuffer.set(A.framebuffer),A;A&&A.destroy();const ae=new o.T(w,{width:F,height:V,data:null},w.extRenderToTextureHalfFloat?w.gl.RGBA16F:w.gl.RGBA8);ae.bind(X.LINEAR,X.CLAMP_TO_EDGE);const pe=w.createFramebuffer(F,V,1,null);if(pe.colorAttachment0.set(ae.texture),Z){const ke=w.createRenderbuffer(X.DEPTH24_STENCIL8,F,V);w.bindFramebuffer.set(pe.framebuffer),X.framebufferRenderbuffer(X.FRAMEBUFFER,X.DEPTH_STENCIL_ATTACHMENT,X.RENDERBUFFER,ke),pe._stencilRbo=ke}return pe}createColorAttachment(w,A){A===0?this.colorAttachment0=new Kb(w,this.framebuffer,0):A===1&&(this.colorAttachment1=new Kb(w,this.framebuffer,1))}removeColorAttachment(w,A){const F=this.context.gl;let V;A===0?(V=this.colorAttachment0.get(),this.colorAttachment0=void 0):A===1&&(V=this.colorAttachment1.get(),this.colorAttachment1=void 0),V&&F.deleteTexture(V)}destroy(){const w=this.context.gl;if(this.colorAttachment0){const A=this.colorAttachment0.get();A&&w.deleteTexture(A)}if(this.colorAttachment1){const A=this.colorAttachment1.get();A&&w.deleteTexture(A)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const A=this.depthAttachment.get();A&&w.deleteRenderbuffer(A)}else{const A=this.depthAttachment.get();A&&w.deleteTexture(A)}this._stencilRbo&&(w.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),w.deleteFramebuffer(this.framebuffer)}}class mh{constructor(w,A){this.gl=w,this.clearColor=new Gb(this),this.clearDepth=new NS(this),this.clearStencil=new S1(this),this.colorMask=new M6(this),this.depthMask=new Sg(this),this.stencilMask=new xw(this),this.stencilFunc=new Wb(this),this.stencilOp=new KN(this),this.stencilTest=new C1(this),this.depthRange=new A1(this),this.depthTest=new Rf(this),this.depthFunc=new Xd(this),this.blend=new Cg(this),this.blendFunc=new r2(this),this.blendColor=new kS(this),this.blendEquation=new lx(this),this.cullFace=new Kp(this),this.cullFaceSide=new a2(this),this.frontFace=new YN(this),this.program=new gw(this),this.activeTexture=new yw(this),this.viewport=new Yp(this),this.bindFramebuffer=new hp(this),this.bindRenderbuffer=new SS(this),this.bindTexture=new by(this),this.bindVertexBuffer=new vw(this),this.bindElementBuffer=new bw(this),this.bindVertexArrayOES=new ZN(this),this.pixelStoreUnpack=new XN(this),this.pixelStoreUnpackPremultiplyAlpha=new QN(this),this.pixelStoreUnpackFlipY=new _w(this),this.options=A?Object.assign({},A):{},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=A&&!!A.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=A&&!!A.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,A,F){return new Td(this,w,A,F)}createVertexBuffer(w,A,F,V,Z){return new Qp(this,w,A,F,V,Z)}createRenderbuffer(w,A,F){const V=this.gl,Z=V.createRenderbuffer();return this.bindRenderbuffer.set(Z),V.renderbufferStorage(V.RENDERBUFFER,w,A,F),this.bindRenderbuffer.set(null),Z}createFramebuffer(w,A,F,V){return new Cm(this,w,A,F,V)}clear({color:w,depth:A,stencil:F,colorMask:V}){const Z=this.gl;let X=0;w&&(X|=Z.COLOR_BUFFER_BIT,this.clearColor.set(w.toNonPremultipliedRenderColor(null)),this.colorMask.set(V||[!0,!0,!0,!0])),A!==void 0&&(X|=Z.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(A),this.depthMask.set(!0)),F!==void 0&&(X|=Z.STENCIL_BUFFER_BIT,this.clearStencil.set(F),this.stencilMask.set(255)),Z.clear(X)}setCullFace(w){w.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(w.mode),this.frontFace.set(w.frontFace))}setDepthMode(w){w.func!==this.gl.ALWAYS||w.mask?(this.depthTest.set(!0),this.depthFunc.set(w.func),this.depthMask.set(w.mask),this.depthRange.set(w.range)):this.depthTest.set(!1)}setStencilMode(w){w.test.func!==this.gl.ALWAYS||w.mask?(this.stencilTest.set(!0),this.stencilMask.set(w.mask),this.stencilOp.set([w.fail,w.depthFail,w.pass]),this.stencilFunc.set({func:w.test.func,ref:w.ref,mask:w.test.mask})):this.stencilTest.set(!1)}setColorMode(w){o.b6(w.blendFunction,ka.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(w.blendFunction),this.blendColor.set(w.blendColor),w.blendEquation?this.blendEquation.set(w.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(w.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let hc;function gr(R,w,A,F,V,Z,X){const ae=R.context,pe=ae.gl,ke=R.transform,Me=[o.aH(ke.center.lng),o.aL(ke.center.lat)],Ke=A.layout.get("symbol-placement"),He=A.layout.get("text-variable-anchor"),tt=A.layout.get("icon-rotation-alignment")==="map",ct=A.layout.get("text-rotation-alignment")==="map",ot=Ke!=="point",wt=[];let _t=0,Rt=0;for(let Vt=0;Vt0){const va=o.bb(),Br=rr;o.cz(va,Us.placementInvProjMatrix,ke.glCoordMatrix),o.cz(va,va,Us.placementViewportMatrix),wt.push({circleArray:zn,circleOffset:Rt,transform:Br,invTransform:va,projection:Us.getProjection()}),_t+=zn.length/4,Rt=_t}if(!ar)continue;R.terrain&&R.terrain.setupElevationDraw(ms,yr);const ta=fn?[Xt.canonical.x,Xt.canonical.y,1<=0&&(tt[$t.associatedIconIndex]={x:Cs,y:pn,z:an,angle:hn})}else er(Jt,Ke)}if(ke){He.clear();const Rt=R.icon.placedSymbolArray;for(let $t=0;$t{let mi=[0,0,0];if(Ho){const zc=R.style.directionalLight,Ml=R.style.ambientLight;zc&&Ml&&(mi=dh(R.style,zc,Ml))}return mi},Ri=Ho=>{if(R.context.disableSymbolUBO)return;Ho.push("USE_PAINT_PROPERTIES_UBO");const mi=Math.floor(R.context.maxUniformBlockSize/4),zc=Math.floor(mi/4);Ho.push(`MAX_UBO_SIZE_VEC4 ${zc}u`)},ri=Ho=>{Xt.depthOcclusionForSymbolsAndCircles&&(A.hasOcclusionOpacityProperties||R.terrain)&&(Ho.push("DEPTH_D24"),Ho.push("DEPTH_OCCLUSION"))},Mo=Ho=>{A.lut&&!Jt&&(A.lut.texture||(A.lut.texture=new o.dR(R.context,A.lut.image,[A.lut.image.height,A.lut.image.height,A.lut.image.height],ws.gl.RGBA8)),ws.activeTexture.set(ws.gl.TEXTURE0+10),A.lut.texture&&A.lut.texture.bind(ws.gl.LINEAR,ws.gl.CLAMP_TO_EDGE),Ho.push("APPLY_LUT_ON_GPU"))},El=()=>{const Ho=ms&&A.layout.get("symbol-placement")!=="point",mi=[];ri(mi),Mo(mi);const zc=Ho||li,Ml=zn.elevationType==="road",Ou=R.shadowRenderer,Ji=Ml&&Cs&&!!Ou&&Ou.enabled,$l=Ea(Ji),ph=Ml&&Cs&&!R.terrain?Ys:$n,Ff=A.paint.get("icon-image-cross-fade");R.terrainRenderModeElevated()&&Cs&&mi.push("PITCH_WITH_MAP_TERRAIN"),ta&&(mi.push("PROJECTION_GLOBE_VIEW"),zc&&mi.push("PROJECTED_POS_ON_VIEWPORT")),Ff>0&&zn.hasAnySecondaryIcon&&mi.push("ICON_TRANSITION"),!zn.icon.zOffsetVertexBuffer||Ml&&R.terrain||mi.push("Z_OFFSET"),_t===0&&Rt===0&&$t===0&&kt===1||mi.push("COLOR_ADJUSTMENT"),zn.sdfIcons&&mi.push("RENDER_SDF"),Ji&&mi.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ml&&Cs&&!R.terrain&&zn.icon.orientationVertexBuffer&&mi.push("ELEVATED_ROADS"),Ri(mi);const Mh=ws.disableSymbolUBO?zn.icon.programConfigurations.get(A.id):null,pp=R.getOrCreateProgram("symbol",{config:Mh,defines:mi}),Ny=ar.imageAtlasTexture?ar.imageAtlasTexture.size:[0,0],al=zn.iconSizeData,wv=o.bj(al,Xt.zoom),jv=Cs||!Xt.isOrthographic,tc=rd(Br,ar.tileID.canonical,Cs,ms,Xt,zn.getProjection(),Qr),fc=ip(Br,ar.tileID.canonical,Cs,ms,Xt,zn.getProjection(),Qr),_l=zn.icon.uboBinder&&zn.icon.uboBinder.cachedHeader&&256&zn.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:ae,_u=R.translatePosMatrix(fc,ar,_l,ke,!0),ux=R.translatePosMatrix(Br,ar,_l,ke),Md=zc?yo:tc,ky=ms&&!Cs&&!Ho;let ok=yr;!fn&&!Xt.mercatorFromTransition||ms||(ok=Ec(Xt));const DS=ta?ok:yr,OS=A.getColorAdjustmentMatrix(_t,Rt,$t,kt),fC=Pu(al.kind,wv,ky,Cs,R,ux,Md,_u,ks,!1,Ny,[0,0],0,rr,va,Es,ni,DS,zn.getProjection(),$l,Ii,OS,Ff,null),h2=ar.imageAtlasTexture?ar.imageAtlasTexture:null,Ew=A.layout.get("icon-size").constantOr(0)!==1||zn.iconsNeedLinear,xC=zn.sdfIcons||R.options.rotating||R.options.zooming||Ew||jv?Vt.LINEAR:Vt.NEAREST,L0=zn.sdfIcons&&A.paint.get("icon-halo-width").constantOr(1)!==0,lk=R.terrain&&Cs&&Ho?o.b7(o.bb(),tc):yo;if(Ho&&zn.icon){const ck=o.bu.getAtTileOffsetFunc(rr,Xt.center.lat,Xt.worldSize,zn.getProjection()),dk=Tc(Br,ar.tileID.canonical,Cs,ms,Xt,zn.getProjection(),Qr),sF=A.layout.get("icon-size-scale-range"),gC=o.aC(R.scaleFactor,sF[0],sF[1]);Zt(zn,Br,R,!1,dk,fc,Cs,ot,ck,rr,gC)}return{program:pp,buffers:zn.icon,uniformValues:fC,atlasTexture:h2,atlasTextureIcon:null,atlasInterpolation:xC,atlasInterpolationIcon:null,isSDF:zn.sdfIcons,hasHalo:L0,depthMode:ph,tile:ar,renderWithShadows:Ji,labelPlaneMatrixInv:lk}},Xc=()=>{const Ho=Us&&A.layout.get("symbol-placement")!=="point",mi=[],zc=Ho||hn||li,Ml=zn.elevationType==="road",Ou=R.shadowRenderer,Ji=Ml&&pn&&!!Ou&&Ou.enabled,$l=Ea(Ji),ph=Ml&&pn&&!R.terrain?Ys:$n;R.terrainRenderModeElevated()&&pn&&mi.push("PITCH_WITH_MAP_TERRAIN"),ta&&(mi.push("PROJECTION_GLOBE_VIEW"),zc&&mi.push("PROJECTED_POS_ON_VIEWPORT")),!zn.text.zOffsetVertexBuffer||Ml&&R.terrain||mi.push("Z_OFFSET"),zn.iconsInText&&mi.push("RENDER_TEXT_AND_SYMBOL"),mi.push("RENDER_SDF"),Ji&&mi.push("RENDER_SHADOWS","NORMAL_OFFSET"),Ml&&pn&&!R.terrain&&zn.text.orientationVertexBuffer&&mi.push("ELEVATED_ROADS"),ri(mi),Ri(mi);const Ff=ws.disableSymbolUBO?zn.text.programConfigurations.get(A.id):null,Mh=R.getOrCreateProgram("symbol",{config:Ff,defines:mi});let pp,Ny=[0,0],al=null;const wv=zn.textSizeData;zn.iconsInText&&(Ny=ar.imageAtlasTexture?ar.imageAtlasTexture.size:[0,0],al=ar.imageAtlasTexture?ar.imageAtlasTexture:null,pp=pn||!Xt.isOrthographic||R.options.rotating||R.options.zooming||wv.kind==="composite"||wv.kind==="camera"?Vt.LINEAR:Vt.NEAREST);const jv=ar.glyphAtlasTexture?ar.glyphAtlasTexture.size:[0,0],tc=A.layout.get("text-size-scale-range"),fc=o.aC(R.scaleFactor,tc[0],tc[1]),_l=o.bj(wv,Xt.zoom,fc),_u=rd(Br,ar.tileID.canonical,pn,Us,Xt,zn.getProjection(),Qr),ux=ip(Br,ar.tileID.canonical,pn,Us,Xt,zn.getProjection(),Qr),Md=zn.text.uboBinder&&zn.text.uboBinder.cachedHeader&&256&zn.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:pe,ky=R.translatePosMatrix(ux,ar,Md,Me,!0),ok=R.translatePosMatrix(Br,ar,Md,Me),DS=zc?yo:_u,OS=Us&&!pn&&!Ho;let fC=yr;!fn&&!Xt.mercatorFromTransition||Us||(fC=Ec(Xt));const h2=Pu(wv.kind,_l,OS,pn,R,ok,DS,ky,ks,!0,jv,Ny,0,rr,va,Es,ni,ta?fC:yr,zn.getProjection(),$l,Ii,null,null,fc),Ew=ar.glyphAtlasTexture?ar.glyphAtlasTexture:null,xC=Vt.LINEAR,L0=A.paint.get("text-halo-width").constantOr(1)!==0,lk=R.terrain&&pn&&Ho?o.b7(o.bb(),_u):yo;if(Ho&&zn.text){const ck=o.bu.getAtTileOffsetFunc(rr,Xt.center.lat,Xt.worldSize,zn.getProjection()),dk=Tc(Br,ar.tileID.canonical,pn,Us,Xt,zn.getProjection(),Qr);Zt(zn,Br,R,!0,dk,ux,pn,wt,ck,rr,fc)}return{program:Mh,buffers:zn.text,uniformValues:h2,atlasTexture:Ew,atlasTextureIcon:al,atlasInterpolation:xC,atlasInterpolationIcon:pp,isSDF:!0,hasHalo:L0,depthMode:ph,tile:ar,renderWithShadows:Ji,labelPlaneMatrixInv:lk}},Wl=zn.icon.segments.get().length,Vo=zn.text.segments.get().length,Ci=Wl&&!X.onlyText?El():null,Ai=Vo&&!X.onlyIcons?Xc():null,Kl=A.paint.get("icon-opacity").constantOr(1),ld=A.paint.get("text-opacity").constantOr(1);if(an&&zn.canOverlap){Ln=!0;const Ho=Kl&&!X.onlyText?zn.icon.segments.get():[],mi=ld&&!X.onlyIcons?zn.text.segments.get():[];for(const zc of Ho)jn.push({segments:new o.dy([zc]),sortKey:zc.sortKey,state:Ci});for(const zc of mi)jn.push({segments:new o.dy([zc]),sortKey:zc.sortKey,state:Ai})}else X.onlyText||jn.push({segments:Kl?zn.icon.segments:new o.dy([]),sortKey:0,state:Ci}),X.onlyIcons||jn.push({segments:ld?zn.text.segments:new o.dy([]),sortKey:0,state:Ai})}Ln&&jn.sort((rr,ar)=>rr.sortKey-ar.sortKey);for(const rr of jn){const ar=rr.state;if(ar)if(R.terrain?R.terrain.setupElevationDraw(ar.tile,ar.program,{useDepthForOcclusion:Xt.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:ar.labelPlaneMatrixInv}):R.setupDepthForOcclusion(Xt.depthOcclusionForSymbolsAndCircles,ar.program),ws.activeTexture.set(Vt.TEXTURE0),ar.atlasTexture&&ar.atlasTexture.bind(ar.atlasInterpolation,Vt.CLAMP_TO_EDGE,!0),ar.atlasTextureIcon&&(ws.activeTexture.set(Vt.TEXTURE1),ar.atlasTextureIcon&&ar.atlasTextureIcon.bind(ar.atlasInterpolationIcon,Vt.CLAMP_TO_EDGE,!0)),ar.renderWithShadows&&R.shadowRenderer.setupShadows(ar.tile.tileID.toUnwrapped(),ar.program,"vector-tile"),R.uploadCommonLightUniforms(R.context,ar.program),ar.hasHalo){const zn=ar.uniformValues;zn.u_is_halo=1,S0(ar.buffers,rr.segments,A,R,ar.program,ar.depthMode,V,Z,zn,2),zn.u_is_halo=0}else{if(ar.isSDF){const zn=ar.uniformValues;ar.hasHalo&&(zn.u_is_halo=1,S0(ar.buffers,rr.segments,A,R,ar.program,ar.depthMode,V,Z,zn,1)),zn.u_is_halo=0}S0(ar.buffers,rr.segments,A,R,ar.program,ar.depthMode,V,Z,ar.uniformValues,1)}}}function S0(R,w,A,F,V,Z,X,ae,pe,ke){const Me=F.context,Ke=Me.gl,He=[R.dynamicLayoutVertexBuffer,R.opacityVertexBuffer,R.iconTransitioningVertexBuffer,R.globeExtVertexBuffer,R.zOffsetVertexBuffer,R.orientationVertexBuffer];R.featureIdBuffer&&He.push(R.featureIdBuffer);const tt=R.uboBinder?null:R.programConfigurations.get(A.id);if(R.uboBinder){R.uboBinder.layer=A;const wt=F.transform.zoom,_t=F.style.getBrightness?F.style.getBrightness():null,Rt=R.uboBinder.getConstantUniformValues(wt,_t);pe.u_spp_fill_np_color=Rt.fill_np_color,pe.u_spp_halo_np_color=Rt.halo_np_color,pe.u_spp_opacity=Rt.opacity,pe.u_spp_halo_width=Rt.halo_width,pe.u_spp_halo_blur=Rt.halo_blur,pe.u_spp_emissive_strength=Rt.emissive_strength,pe.u_spp_occlusion_opacity=Rt.occlusion_opacity,pe.u_spp_z_offset=Rt.z_offset;const $t=A.paint.get(R.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),kt=R.uboBinder.cachedHeader&&256&R.uboBinder.cachedHeader.dataDrivenMask&&$t==="map"?F.transform.angle:0;pe.u_spp_translate_rotation=[Math.cos(kt),Math.sin(kt)]}const{batchIndices:ct,batchSegments:ot}=R.getBatchGrouping(w);for(const wt of ct){const _t=ot.get(wt);R.uboBinder&&R.uboBinder.bind(Me,V.program,wt),V.draw(F,Ke.TRIANGLES,Z,X,ae,la.disabled,pe,A.id,R.layoutVertexBuffer,R.indexBuffer,_t,A.paint,F.transform.zoom,tt,He,ke)}}function Jd(R,w,A,F,V,Z){const X=A.paint.get("line-width"),ae=A.paint.get("line-emissive-strength").isConstant(),pe=A.paint.get("line-emissive-strength").constantOr(0),ke=A.paint.get("line-occlusion-opacity"),Me=A.layout.get("line-elevation-reference"),Ke=A.layout.get("line-width-unit")==="meters",He=Me==="sea",tt=!(!R.terrain||!R.terrain.enabled),ct=R.context,ot=ct.gl;if(A.hasElevatedBuckets&&R.transform.projection.name==="globe")return;const wt=A.layout.get("line-cross-slope"),_t=wt!==void 0,Rt=wt<1,$t=V||R.colorModeForDrapableLayerRenderPass(ae?pe:null),kt=R.terrain&&R.terrain.renderingToTexture||Z,ks=kt?1:o.o.devicePixelRatio,Jt=A.paint.get("line-dasharray"),ws=Jt.constantOr(1),Vt=A.layout.get("line-cap"),Xt=Jt.constantOr(null),ms=Vt.constantOr(null),Us=A.paint.get("line-pattern"),Cs=Us.constantOr(1),pn=A.paint.get("line-pattern-cross-fade"),an=Us.constantOr(null),Ln=A.paint.get("line-opacity").constantOr(1);let $n=!Cs&&Ln!==1||R.depthOcclusion&&ke>0&&ke<1;const Ys=A.paint.get("line-gradient"),Es=Cs?"linePattern":"line",hn=o.dU(A);let fn;if(kt&&R.terrain&&R.terrain.clipOrMaskOverlapStencilType()&&($n=!1),ke!==0&&R.depthOcclusion){const zn=A.paint._values["line-opacity"];zn&&zn.value&&zn.value.kind==="constant"?fn=zn.value:o.w(`Occlusion opacity for layer ${A.id} is supported only when line-opacity isn't data-driven.`)}X.value.kind!=="constant"&&X.value.isLineProgressConstant===!1&&hn.push("VARIABLE_LINE_WIDTH"),kt&&(R.emissiveMode!=="dual-source-blending"||ae?R.emissiveMode==="mrt-fallback"&&hn.push("USE_MRT1"):hn.push("DUAL_SOURCE_BLENDING"));const jn={},yr=(zn,ta,va,Br,Qr,Ga)=>{for(const li of zn){const ni=w.getTile(li);if(Cs&&!ni.patternsLoaded())continue;const Ii=ni.getBucket(A);if(!Ii||Ii.elevationType!=="none"&&!Qr||Ii.elevationType==="none"&&Qr)continue;R.prepareDrawTile();const Ea=[...ta],Ri=R.shadowRenderer,ri=Ii.elevationType==="road"&&!!Ri&&Ri.enabled;let Mo=[0,0,0];if(ri){const Ji=R.style.directionalLight,$l=R.style.ambientLight;Ji&&$l&&(Mo=dh(R.style,Ji,$l)),Ea.push("RENDER_SHADOWS","NORMAL_OFFSET")}const El=Ii.programConfigurations.get(A.id);let Xc=!1;if(an&&ni.imageAtlas){const Ji=o.dV.from(an),$l=Ji.getPrimary().scaleSelf(ks).toString(),ph=ni.imageAtlas.patternPositions.get($l),Ff=Ji.getSecondary(),Mh=Ff?ni.imageAtlas.patternPositions.get(Ff.scaleSelf(ks).toString()):null;Xc=!!ph&&!!Mh,ph&&El.setConstantPatternPositions(ph,Mh)}pn>0&&(Xc||El.getPatternTransitionVertexBuffer("line-pattern"))&&Ea.push("LINE_PATTERN_TRANSITION"),Ii.elevationGroundScaleVertexBuffer&&Ea.push("ELEVATION_GROUND_SCALE");const Wl=R.isTileAffectedByFog(li),Vo=R.getOrCreateProgram(Es,{config:El,defines:Ea,overrideFog:Wl});if(!Cs&&Xt&&ms&&ni.lineAtlas){const Ji=ni.lineAtlas.getDash(Xt,ms);Ji&&El.setConstantPatternPositions(Ji)}ri&&Ri.setupShadows(ni.tileID.toUnwrapped(),Vo,"vector-tile");let[Ci,Ai]=A.paint.get("line-trim-offset");(ms==="round"||ms==="square")&&Ci!==Ai&&(Ci===0&&(Ci-=1),Ai===1&&(Ai+=1));const Kl=kt?li.projMatrix:null,ld=Ke?1/Ii.tileToMeter/o.aA(ni,1,R.transform.zoom):1,Ho=Ke?1/Ii.tileToMeter/o.aA(ni,1,Math.floor(R.transform.zoom)):1,mi=ws?A.paint._values["line-floorwidth"]:null;let zc;if(mi&&mi.value.kind==="constant"){const Ji=Ii.zoom;Ji in jn||(jn[Ji]=Math.max(.01,A.widthExpression().evaluate({zoom:Ji}))),zc=mi.value.value;const $l=Math.floor(R.transform.zoom);mi.value.value=jn[Ji]*Math.pow(2,$l-ni.tileID.overscaledZ)}const Ml=Cs?o.dW(R,ni,A,Kl,ks,ld,Ho,[Ci,Ai],Mo,pn):o.dX(R,ni,A,Kl,Ii.lineClipsArray.length,ks,ld,Ho,[Ci,Ai],Mo);if(Ys){const Ji=Ii.gradients[A.id];let $l=Ji.texture;if(A.gradientVersion!==Ji.version){let ph=256;if(A.stepInterpolant){const Ff=w.getSource().maxzoom,Mh=li.canonical.z===Ff?Math.ceil(1<{fn!=null&&(fn.value=Ln*ke),Vo.draw(R,ot.TRIANGLES,va,Ji,$t,la.disabled,Ml,A.id,Ii.layoutVertexBuffer,Ii.indexBuffer,Ii.segments,A.paint,R.transform.zoom,El,[Ii.layoutVertexBuffer2,Ii.patternVertexBuffer,Ii.zOffsetVertexBuffer,Ii.elevationGroundScaleVertexBuffer]),fn!=null&&(fn.value=Ln)};if($n&&!Qr){const Ji=R.stencilModeForClipping(li).ref;Ji===0&&kt&&ct.clear({stencil:0});const $l={func:ot.EQUAL,mask:255};Ml.u_alpha_discard_threshold=.8,Ou(new Sa($l,Ji,255,ot.KEEP,ot.KEEP,ot.INVERT)),Ml.u_alpha_discard_threshold=0,Ou(new Sa($l,Ji,255,ot.KEEP,ot.KEEP,ot.KEEP))}else Ml.u_alpha_discard_threshold=$n&&Qr&&Ga?.8:0,Ou(Qr?Br:R.stencilModeForClipping(li));zc!==void 0&&(mi.value.value=zc)}};let rr=R.depthModeForSublayer(0,Ir.ReadOnly);const ar=new Ir(R.depthOcclusion?ot.GREATER:ot.LEQUAL,Ir.ReadOnly,R.depthRangeFor3D);if(A.hasNonElevatedBuckets){const zn=!kt&&R.terrain;ke!==0&&zn?o.w(`Occlusion opacity for layer ${A.id} is supported on terrain only if the layer has line-z-offset enabled.`):zn?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${A.id}.`):yr(F,hn,rr,Sa.disabled,!1,!0)}if(A.hasElevatedBuckets){Me==="hd-road-markup"?tt||(rr=ar,hn.push("ELEVATED_ROADS")):(hn.push("ELEVATED"),rr=ar,_t&&hn.push(Rt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),He&&hn.push("ELEVATION_REFERENCE_SEA"));const zn=$n?R.stencilModeFor3D():Sa.disabled;R.forceTerrainMode=!0,yr(F,hn,rr,zn,!0,!0),$n&&yr(F,hn,rr,zn,!0,!1),R.forceTerrainMode=!1}$n&&(R.resetStencilClippingMasks(),kt&&ct.clear({stencil:0})),ke===0||R.depthOcclusion||kt||R.layersWithOcclusionOpacity.push(R.currentLayer)}const mp={additive:{clearColor:new o.aq(0,0,0,0),colorMode:ka.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:ka.multiply,compositeUniformValue:0}};function xv(R,w){const A=1<=ch?1:tt.pitch/ch))),2*ct}(R.transform),ke=R.transform.getFreeCameraOptions().position,Me="elevatedStructuresDepthReconstruct",Ke=R.getOrCreateProgram(Me,{defines:["DEPTH_RECONSTRUCTION"]}),He=R.getOrCreateProgram(Me);for(const tt of F){const ct=w.getTile(tt),ot=ct.getBucket(A);if(!ot)continue;const wt=ot.elevatedStructures;if(!wt)continue;const _t=ot.elevationBufferData.heightRange,Rt=xv(tt.toUnwrapped(),ke),$t=R.translatePosMatrix(tt.projMatrix,ct,A.paint.get("fill-translate"),A.paint.get("fill-translate-anchor"));let kt,ks,Jt,ws;if(V==="initialize"){if(!_t||_t.min>=1||wt.depthSegments.segments[0].primitiveLength===0)continue;kt=Si($t,Rt,pe,1,0),ks=X,Jt=wt.depthSegments,ws=Ke}else if(V==="reset"){if(!_t||_t.min>=0||wt.maskSegments.segments[0].primitiveLength===0)continue;kt=Si($t,Rt,0,0,1),ks=ae,Jt=wt.maskSegments,ws=Ke}else if(V==="geometry"){if(wt.depthSegments.segments[0].primitiveLength===0)continue;kt=Si($t,Rt,pe,1,0),ks=X,Jt=wt.depthSegments,ws=He}ws.draw(R,Z.TRIANGLES,ks,Sa.disabled,ka.disabled,la.disabled,kt,A.id,wt.vertexBuffer,wt.indexBuffer,Jt,A.paint,R.transform.zoom)}}function gv(R,w,A,F){const{painter:V,sourceCache:Z,layer:X,coords:ae,colorMode:pe,elevationType:ke,terrainEnabled:Me,pass:Ke}=R,He=V.context.gl,tt=X.paint.get("fill-pattern"),ct=X.paint.get("fill-pattern-cross-fade"),ot=tt.constantOr(null);let wt=ke;ke!=="road"||w&&!Me||(wt="none");const _t=wt==="road",Rt=R.painter.shadowRenderer,$t=_t&&!!Rt&&Rt.enabled,kt=new Ir(V.context.gl.LEQUAL,Ir.ReadOnly,V.depthRangeFor3D);let ks=[0,0,0];if($t){const Xt=V.style.directionalLight,ms=V.style.ambientLight;Xt&&ms&&(ks=dh(V.style,Xt,ms))}const Jt=tt&&tt.constantOr(1),ws=V.terrain&&V.terrain.renderingToTexture,Vt=(Xt,ms)=>{let Us,Cs,pn,an,Ln;ms?(Us=Jt&&!X.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",pn=He.LINES):(Us=Jt?"fillPattern":"fill",pn=He.TRIANGLES);for(const $n of ae){const Ys=Z.getTile($n);if(Jt&&!Ys.patternsLoaded())continue;const Es=Ys.getBucket(X);if(!Es)continue;const hn=w?Es.elevationBufferData:Es.bufferData;if(hn.isEmpty())continue;V.prepareDrawTile();const fn=hn.programConfigurations.get(X.id),jn=V.isTileAffectedByFog($n),yr=[],rr=[];_t&&(yr.push("ELEVATED_ROADS"),rr.push(hn.elevatedLayoutVertexBuffer)),$t&&yr.push("RENDER_SHADOWS","NORMAL_OFFSET"),ws&&A&&yr.push("USE_MRT1"),Jt&&(V.context.activeTexture.set(He.TEXTURE0),Ys.imageAtlasTexture&&Ys.imageAtlasTexture.bind(He.LINEAR,He.CLAMP_TO_EDGE),fn.updatePaintBuffers());let ar=!1;if(ot&&Ys.imageAtlas){const Qr=Ys.imageAtlas,Ga=o.dV.from(ot),li=Ga.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),ni=Ga.getSecondary(),Ii=Qr.patternPositions.get(li),Ea=ni?Qr.patternPositions.get(ni.scaleSelf(o.o.devicePixelRatio).toString()):null;ar=!!Ii&&!!Ea,Ii&&fn.setConstantPatternPositions(Ii,Ea)}ct>0&&(ar||fn.getPatternTransitionVertexBuffer("fill-pattern"))&&yr.push("FILL_PATTERN_TRANSITION");const zn=V.getOrCreateProgram(Us,{config:fn,overrideFog:jn,defines:yr}),ta=V.translatePosMatrix($n.projMatrix,Ys,X.paint.get("fill-translate"),X.paint.get("fill-translate-anchor"));$t&&Rt.setupShadows(Ys.tileID.toUnwrapped(),zn,"vector-tile");const va=X.paint.get("fill-emissive-strength");if(ms){an=hn.lineIndexBuffer,Ln=hn.lineSegments;const Qr=V.terrain&&V.terrain.renderingToTexture?V.terrain.drapeBufferSize:[He.drawingBufferWidth,He.drawingBufferHeight];Cs=Us==="fillOutlinePattern"&&Jt?Li(ta,va,V,Ys,Qr,ks,ct):ca(ta,va,Qr,ks)}else an=hn.indexBuffer,Ln=hn.triangleSegments,Cs=Jt?ga(ta,va,V,Ys,ks,ct):Pr(ta,va,ks);V.uploadCommonUniforms(V.context,zn,$n.toUnwrapped());let Br=Xt;(ke==="road"&&!Me||ke==="offset")&&(Br=kt),zn.draw(V,pn,Br,F||V.stencilModeForClipping($n),pe,la.disabled,Cs,X.id,hn.layoutVertexBuffer,an,Ln,X.paint,V.transform.zoom,fn,rr)}};V.renderPass===Ke&&Vt(V.depthModeForSublayer(1,V.renderPass==="opaque"?Ir.ReadWrite:Ir.ReadOnly),!1),wt==="none"&&V.renderPass==="translucent"&&X.paint.get("fill-antialias")&&Vt(V.depthModeForSublayer(X.getPaintProperty("fill-outline-color")?2:0,Ir.ReadOnly),!0)}function Am(R,w,A,F,V,Z,X,ae){A.resetLayerRenderingStats(R);const pe=R.context,ke=pe.gl,Me=R.transform,Ke=A.paint.get("fill-extrusion-pattern"),He=A.paint.get("fill-extrusion-pattern-cross-fade"),tt=Ke.constantOr(null),ct=Ke.constantOr(1),ot=A.paint.get("fill-extrusion-opacity"),wt=R.style.enable3dLights(),_t=A.paint.get(wt&&!ct?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Rt=[A.paint.get("fill-extrusion-ambient-occlusion-intensity"),_t],$t=A.layout.get("fill-extrusion-edge-radius"),kt=$t>0&&!A.paint.get("fill-extrusion-rounded-roof"),ks=kt?0:$t,Jt=Me.projection.name==="globe"?o.e1():0,ws=Me.projection.name==="globe",Vt=ws?o.al(Me.zoom):0,Xt=[o.aH(Me.center.lng),o.aL(Me.center.lat)],ms=A.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Us=A.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(ms?null:A.lut).toArray01().slice(0,3),Cs=A.paint.get("fill-extrusion-flood-light-intensity"),pn=A.paint.get("fill-extrusion-vertical-scale"),an=A.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Ln=A.paint.get("fill-extrusion-height-alignment"),$n=A.paint.get("fill-extrusion-base-alignment"),Ys=Kc(R,A.paint.get("fill-extrusion-cutoff-fade-range")),Es=A.paint.get("fill-extrusion-front-cutoff"),hn=kw(Me.pitch,Es,!!R.terrain),fn=hn[2]<1;fn&&(R.maxFrontCutoffRawStart=Math.max(R.maxFrontCutoffRawStart,Es[0]));const jn=[];let yr;ws&&jn.push("PROJECTION_GLOBE_VIEW"),Rt[0]>0&&jn.push("FAUX_AO"),kt&&jn.push("ZERO_ROOF_RADIUS"),ae&&jn.push("HAS_CENTROID"),Cs>0&&jn.push("FLOOD_LIGHT"),Ys.shouldRenderCutoff&&jn.push("RENDER_CUTOFF"),fn&&jn.push("RENDER_FRONT_CUTOFF"),an&&jn.push("RENDER_WALL_MODE");const rr=R.renderPass==="shadow",ar=R.shadowRenderer,zn=rr&&!!ar,ta=rr?la.disabled:la.backCCW;R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!0);let va=[0,0,0];if(ar){const Ga=R.style.directionalLight,li=R.style.ambientLight;Ga&&li&&(va=dh(R.style,Ga,li)),rr||(jn.push("RENDER_SHADOWS"),ar.useNormalOffset&&jn.push("NORMAL_OFFSET")),yr=jn.concat(["SHADOWS_SINGLE_CASCADE"])}const Br=zn?"fillExtrusionDepth":ct?"fillExtrusionPattern":"fillExtrusion",Qr=A.getLayerRenderingStats();for(const Ga of F){const li=w.getTile(Ga),ni=li.getBucket(A);if(!ni||ni.projection.name!==Me.projection.name)continue;let Ii=!1;ar&&(Ii=ar.getMaxCascadeForTile(Ga.toUnwrapped())===0);const Ea=R.isTileAffectedByFog(Ga),Ri=ni.programConfigurations.get(A.id);let ri=!1;if(tt&&li.imageAtlas){const Ai=li.imageAtlas,Kl=o.dV.from(tt),ld=Kl.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),Ho=Kl.getSecondary(),mi=Ai.patternPositions.get(ld),zc=Ho?Ai.patternPositions.get(Ho.scaleSelf(o.o.devicePixelRatio).toString()):null;ri=!!mi&&!!zc,mi&&Ri.setConstantPatternPositions(mi,zc)}He>0&&(ri||Ri.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&jn.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Mo=R.getOrCreateProgram(Br,{config:Ri,defines:Ii?yr:jn,overrideFog:Ea});if(R.terrain&&R.terrain.setupElevationDraw(li,Mo,{useMeterToDem:!0}),!ni.centroidVertexBuffer){const Ai=Mo.getAttributeLocation(ke,"a_centroid_pos");Ai!==-1&&ke.vertexAttribI4ui(Ai,0,0,0,0)}!rr&&ar&&ar.setupShadows(li.tileID.toUnwrapped(),Mo,"vector-tile"),ct&&(R.context.activeTexture.set(ke.TEXTURE0),li.imageAtlasTexture&&li.imageAtlasTexture.bind(ke.LINEAR,ke.CLAMP_TO_EDGE),Ri.updatePaintBuffers());const El=A.paint.get("fill-extrusion-vertical-gradient"),Xc=1/ni.tileToMeter;let Wl;if(rr&&ar){if(cx(li.tileID,ni.maxHeight,R))continue;const Ai=ar.calculateShadowPassMatrixFromTile(li.tileID.toUnwrapped());Wl=hr(Ai,ks,Xc,pn,Ln,$n)}else{const Ai=R.translatePosMatrix(Ga.expandedProjMatrix,li,A.paint.get("fill-extrusion-translate"),A.paint.get("fill-extrusion-translate-anchor")),Kl=Me.projection.createInversionMatrix(Me,Ga.canonical);Wl=ct?On(Ai,R,El,ot,Rt,ks,Xc,Ga,li,Jt,Ln,$n,Vt,Xt,Kl,Us,pn,He):Cr(Ai,R,El,ot,Rt,ks,Xc,Ga,Jt,Ln,$n,Vt,Xt,Kl,Us,pn,Cs,va,hn)}R.uploadCommonUniforms(pe,Mo,Ga.toUnwrapped(),null,Ys);let Vo=ni.segments;if(Me.projection.name==="mercator"&&!rr&&(Vo=ni.getVisibleSegments(li.tileID,R.terrain,R.transform.getFrustum(0)),!Vo.get().length))continue;if(Qr)if(rr)for(const Ai of Vo.get())Qr.numRenderedVerticesInShadowPass+=Ai.primitiveLength;else for(const Ai of Vo.get())Qr.numRenderedVerticesInTransparentPass+=Ai.primitiveLength;const Ci=[];(R.terrain||ae)&&Ci.push(ni.centroidVertexBuffer),ws&&Ci.push(ni.layoutVertexExtBuffer),an&&Ci.push(ni.wallVertexBuffer),Mo.draw(R,pe.gl.TRIANGLES,V,Z,X,ta,Wl,A.id,ni.layoutVertexBuffer,ni.indexBuffer,Vo,A.paint,R.transform.zoom,Ri,Ci)}R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!1)}class Jp{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function kw(R,w,A){if(!(w[2]<1)||A)return[0,0,1];const F=180*R/Math.PI;if(F<15)return[-.5,w[1],w[2]];const V=Math.min(1,Math.max(0,(F-15)/5)),Z=V*V*(3-2*V);return[-.5*(1-Z)+w[0]*Z,w[1],w[2]]}function Ag(R,w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt,ct,ot,wt,_t,Rt,$t,kt){const ks=w.context,Jt=ks.gl,ws=w.transform,Vt=w.transform.zoom,Xt=[],ms=R.translate,Us=R.translateAnchor,Cs=R.edgeRadius,pn=Kc(w,R.cutoffFadeRange);Me==="clear"?(Xt.push("CLEAR_SUBPASS"),$t&&(Xt.push("CLEAR_FROM_TEXTURE"),ks.activeTexture.set(Jt.TEXTURE0),$t.bind(Jt.LINEAR,Jt.CLAMP_TO_EDGE))):Me==="sdf"?Xt.push("SDF_SUBPASS"):Me==="emissive"&&(Xt.push("USE_MRT1"),ks.activeTexture.set(Jt.TEXTURE0),$t.bind(Jt.LINEAR,Jt.CLAMP_TO_EDGE)),_t&&Xt.push("HAS_CENTROID"),pn.shouldRenderCutoff&&Xt.push("RENDER_CUTOFF");const an=(Ln,$n,Ys,Es,hn)=>{let fn=Xt;$n.groundRadiusBuffer!=null&&(fn=Xt.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const jn=$n.programConfigurations.get(F.id),yr=w.isTileAffectedByFog(Ln),rr=w.getOrCreateProgram("fillExtrusionGroundEffect",{config:jn,defines:fn,overrideFog:yr}),ar=((ta,va,Br,Qr,Ga,li,ni,Ii,Ea,Ri,ri)=>({u_matrix:va,u_opacity:Br,u_ao_pass:Qr?1:0,u_meter_to_tile:Ga,u_ao:li,u_flood_light_intensity:ni,u_flood_light_color:Ii,u_attenuation:Ea,u_edge_radius:Ri,u_fb:0,u_fb_size:ri,u_dynamic_offset:1}))(0,Es,Ke,ke,hn,[He,tt*hn],ct,ot,wt,Vt>=17?0:Cs*hn,$t?$t.size[0]:0),zn=[];_t&&zn.push($n.hiddenByLandmarkVertexBuffer),$n.groundRadiusBuffer!=null&&zn.push($n.groundRadiusBuffer),w.uploadCommonUniforms(ks,rr,Ln.toUnwrapped(),null,pn),rr.draw(w,ks.gl.TRIANGLES,Z,X,ae,pe,ar,F.id,$n.vertexBuffer,$n.indexBuffer,Ys,F.paint,Vt,jn,zn)};for(const Ln of V){const $n=A.getTile(Ln),Ys=$n.getBucket(F);if(!Ys||Ys.projection.name!==ws.projection.name||!Ys.groundEffect||Ys.groundEffect&&!Ys.groundEffect.hasData())continue;const Es=Ys.groundEffect,hn=1/Ys.tileToMeter;{const fn=w.translatePosMatrix(Ln.projMatrix,$n,ms,Us),jn=Es.getDefaultSegment();an(Ln,Es,jn,fn,hn)}if(Rt)for(let fn=0;fn<4;fn++){const jn=o.d$[fn](Ln),yr=A.getTile(jn);if(!yr)continue;const rr=yr.getBucket(F);if(!rr||rr.projection.name!==ws.projection.name||!rr.groundEffect||rr.groundEffect&&!rr.groundEffect.hasData())continue;const ar=rr.groundEffect;let zn,ta;fn===0?(zn=[-o.an,0,0],ta=1):fn===1?(zn=[o.an,0,0],ta=0):fn===2?(zn=[0,-o.an,0],ta=3):(zn=[0,o.an,0],ta=2);const va=ar.regionSegments[ta];if(!va)continue;const Br=new Float32Array(16);o.bx(Br,Ln.projMatrix,zn),an(Ln,ar,va,w.translatePosMatrix(Br,$n,ms,Us),hn)}}}function C0(R,w,A,F,V,Z,X){F.centroidVertexArray.length===0&&F.createCentroidsBuffer();const ae=Z?Z.findDEMTileFor(A):null;if(!(ae&&ae.dem||X))return;Z&&ae&&ae.dem&&F.selfDEMTileTimestamp!==ae.dem._timestamp&&(F.borderDoneWithNeighborZ=[-1,-1,-1,-1],F.selfDEMTileTimestamp=ae.dem._timestamp);const pe=(_t,Rt)=>{(_t.flags|Rt.flags)&o.e3?(_t.flags|=o.e3,Rt.flags|=o.e3):(_t.flags&=~o.e3,Rt.flags&=~o.e3)},ke=_t=>new o.P(Math.ceil((_t+o.e4)*o.e5),0),Me=(_t,Rt,$t)=>{const kt=Math.ceil((_t+o.e4)*o.e5),ks=Math.floor(Math.max(0,Math.min(o.an-1,$t))/4);return new o.P(kt,ks<<5|(3&Rt)<<3|7)},Ke=_t=>{const Rt=w.getSource().minzoom,$t=ks=>{const Jt=w.getTileByID(ks);if(Jt&&Jt.hasData())return Jt.getBucket(V)},kt=[0,-1,1];for(const ks of kt){if(_t.overscaledZ+ks(He[0]=Math.min(_t.min.y,Rt.min.y),He[1]=Math.max(_t.max.y,Rt.max.y),He[2]=o.an-Rt.min.x>_t.max.x?Rt.min.x-o.an:_t.max.x,He),ct=(_t,Rt)=>(He[0]=Math.min(_t.min.x,Rt.min.x),He[1]=Math.max(_t.max.x,Rt.max.x),He[2]=o.an-Rt.min.y>_t.max.y?Rt.min.y-o.an:_t.max.y,He),ot=[(_t,Rt)=>tt(_t,Rt),(_t,Rt)=>tt(Rt,_t),(_t,Rt)=>ct(_t,Rt),(_t,Rt)=>ct(Rt,_t)],wt=(_t,Rt,$t,kt,ks,Jt,ws)=>{if(!Z)return 0;const Vt=[[Jt?$t:_t,Jt?_t:$t,0],[Jt?$t:Rt,Jt?Rt:$t,0]],Xt=ws<0?o.an+ws:ws,ms=[Jt?Xt:(_t+Rt)/2,Jt?(_t+Rt)/2:Xt,0];return $t===0&&ws<0||$t!==0&&ws>0?Z.getForTilePoints(ks,[ms],!0,kt):Vt.push(ms),Z.getForTilePoints(A,Vt,!0,ae),Math.max(Vt[0][2],Vt[1][2],ms[2])/Z.exaggeration()};for(let _t=0;_t<4;_t++){const Rt=F.borderFeatureIndices[_t];if(Rt.length===0)continue;const $t=o.d$[_t](A),kt=Ke($t);if(!(kt&&kt instanceof o.e0))continue;const ks=Z?Z.findDEMTileFor($t):null;if(!(ks&&ks.dem||X)||(Z&&ks&&ks.dem&&F.borderDEMTileTimestamp[_t]!==ks.dem._timestamp&&(F.borderDoneWithNeighborZ[_t]=-1,F.borderDEMTileTimestamp[_t]=ks.dem._timestamp),F.borderDoneWithNeighborZ[_t]===kt.canonical.z))continue;kt.centroidVertexArray.length===0&&kt.createCentroidsBuffer();const Jt=(_t<2?1:5)-_t,ws=kt.borderDoneWithNeighborZ[Jt]!==F.canonical.z,Vt=kt.borderFeatureIndices[Jt];let Xt=0;if(F.canonical.z!==kt.canonical.z){for(const pn of Rt)F.showCentroid(F.featuresOnBorder[pn]);if(ws)for(const pn of Vt)kt.showCentroid(kt.featuresOnBorder[pn]);F.borderDoneWithNeighborZ[_t]=kt.canonical.z,kt.borderDoneWithNeighborZ[Jt]=F.canonical.z;continue}const ms=new Map,Us=new Set,Cs=new Set;for(let pn=0;pn1||Ys.intersectsCount()>1;{let rr=0;if(ks&&ks.dem&&!yr){const ar=ot[_t](Ln,Es),zn=_t%2?o.an-1:0;rr=wt(ar[0],Math.min(o.an-1,ar[1]),zn,ks,$t,_t<2,ar[2])}Ln.centroidXY=Me(rr,_t,jn),Es.centroidXY=Me(rr,Jt,jn)}if(F.writeCentroidToBuffer(Ln),kt.writeCentroidToBuffer(Es),an.buildingId!==void 0){for(const rr of F.centroidData)rr.buildingId===an.buildingId&&rr!==Ln&&(rr.centroidXY=Ln.centroidXY,F.writeCentroidToBuffer(rr));for(const rr of kt.centroidData)rr.buildingId===an.buildingId&&rr!==Es&&(rr.centroidXY=Es.centroidXY,kt.writeCentroidToBuffer(rr))}}for(const pn of Rt){if(Us.has(pn))continue;const an=F.featuresOnBorder[pn],Ln=F.centroidData[an.centroidDataIndex],$n=an.borders[_t];let Ys;for(;Xt$n[0]+3||Es[0]>$n[0]-3)break;kt.showCentroid(Ys),Xt++}if(Ys&&Xt$n[1]-3||(hn++,++Xt===Vt.length))break;Ys=kt.featuresOnBorder[Vt[Xt]]}for(;Es=Vt.length){F.showCentroid(an);continue}Ys=kt.featuresOnBorder[Vt[Es]];let fn=!1;if(hn>=1){const rr=Ys.borders[Jt];Math.abs($n[0]-rr[0])<3&&Math.abs($n[1]-rr[1])<3&&(hn=1,fn=!0,Xt=Es+1)}else if(hn===0){F.showCentroid(an);continue}const jn=kt.centroidData[Ys.centroidDataIndex];X&&fn&&pe(Ln,jn);const yr=an.intersectsCount()>1||Ys.intersectsCount()>1;if(hn>1)Xt=Es,Ln.centroidXY=jn.centroidXY=new o.P(0,0);else if(ks&&ks.dem&&!yr){const rr=ot[_t](Ln,jn),ar=_t%2?o.an-1:0,zn=wt(rr[0],Math.min(o.an-1,rr[1]),ar,ks,$t,_t<2,rr[2]);Ln.centroidXY=jn.centroidXY=ke(zn)}else yr?Ln.centroidXY=jn.centroidXY=new o.P(0,0):(Ln.centroidXY=F.encodeBorderCentroid(an),jn.centroidXY=kt.encodeBorderCentroid(Ys));F.writeCentroidToBuffer(Ln),kt.writeCentroidToBuffer(jn)}else F.showCentroid(an)}F.borderDoneWithNeighborZ[_t]=kt.canonical.z,kt.borderDoneWithNeighborZ[Jt]=F.canonical.z}(F.needsCentroidUpdate||!F.centroidVertexBuffer&&F.centroidVertexArray.length!==0)&&F.uploadCentroid(R)}const wy=[1,0,0],Sw=[0,1,0],Cw=[0,0,1];function cx(R,w,A){const F=A.transform,V=A.shadowRenderer;if(!V)return!0;const Z=R.toUnwrapped(),X=F.tileSize*V._cascades[A.currentShadowCascade].scale;let ae=w;if(F.elevation){const ct=F.elevation.getMinMaxForTile(R);ct&&(ae+=ct.max)}const pe=F.scaleZoom(X);ae/=o.e2(F.center.lat,pe);const ke=[...V.shadowDirection];ke[2]=-ke[2];const Me=V.computeSimplifiedTileShadowVolume(Z,ae,X,ke);if(!Me)return!1;const Ke=[wy,Sw,Cw,ke,[ke[0],0,ke[2]],[0,ke[1],ke[2]]],He=o.cl.fromInvProjectionMatrix(F.invProjMatrix,F.worldSize,pe,F.projection.name!=="globe"),tt=V.getCurrentCascadeFrustum();return He.intersectsPrecise(Me.vertices,Me.planes,Ke)===0||tt.intersectsPrecise(Me.vertices,Me.planes,Ke)===0}function jy(R){const{painter:w,source:A,layer:F,coords:V}=R;let Z=R.defines;const X=w.context,ae=w.renderPass==="shadow",pe=w.renderPass==="light-beam",ke=w.shadowRenderer,Me=o.e2(w.transform.center.lat,w.transform.zoom),Ke=Kc(w,F.paint.get("building-cutoff-fade-range"));Ke.shouldRenderCutoff&&(Z=Z.concat("RENDER_CUTOFF"));const He=F.paint.get("building-front-cutoff"),tt=He[2]<1&&!w.terrain,ct=kw(w.transform.pitch,He,!!w.terrain);tt&&(Z=Z.concat("RENDER_FRONT_CUTOFF"),w.maxFrontCutoffRawStart=Math.max(w.maxFrontCutoffRawStart,He[0])),R.floodLightIntensity>0&&(Z=Z.concat("FLOOD_LIGHT"));for(const ot of V){const wt=A.getTile(ot),_t=wt.getBucket(F);if(!_t)continue;ke&&ke.getMaxCascadeForTile(ot.toUnwrapped())===0&&(Z=Z.concat("SHADOWS_SINGLE_CASCADE"));const Rt=_t.programConfigurations.get(F.id);let $t,kt,ks,Jt=w.translatePosMatrix(ot.expandedProjMatrix,wt,[0,0],"map");if(Jt=o.cC(o.bb(),Jt,[1,1,R.verticalScale]),ae&&ke){if(cx(wt.tileID,_t.maxHeight*Me,w))continue;let Vt=ke.calculateShadowPassMatrixFromTile(wt.tileID.toUnwrapped());Vt=o.cC(o.bb(),Vt,[1,1,R.verticalScale]),ks=Ti(Vt),$t=kt=w.getOrCreateProgram("buildingDepth",{config:Rt,defines:Z,overrideFog:!1})}else if(pe)$t=kt=w.getOrCreateProgram("buildingBloom",{config:Rt,defines:Z,overrideFog:!1}),ks=Xo(Jt);else{const Vt=w.transform.calculatePosMatrix(ot.toUnwrapped(),w.transform.worldSize);o.cC(Vt,Vt,[1,1,R.verticalScale]);const Xt=o.bb();o.cC(Xt,Vt,[1,-1,1/Me]),o.b7(Xt,Xt),o.e6(Xt,Xt);const ms=w.transform.getFreeCameraOptions().position,Us=1<{if(pe){const ms=Vt.entranceBloom;Xt.draw(w,X.gl.TRIANGLES,R.depthMode,Sa.disabled,R.blendMode,la.disabled,ks,F.id,ms.layoutVertexBuffer,ms.indexBuffer,ms.segmentsBucket,F.paint,w.transform.zoom,Rt,[ms.layoutAttenuationBuffer,ms.layoutColorBuffer])}else{const ms=Vt.segmentsBucket;let Us=[Vt.layoutNormalBuffer,Vt.layoutCentroidBuffer,Vt.layoutColorBuffer,Vt.layoutFloodLightDataBuffer];Vt.layoutFacadePaintBuffer&&(Us=Us.concat([Vt.layoutFacadeDataBuffer,Vt.layoutFacadeVerticalRangeBuffer,Vt.layoutFacadePaintBuffer])),Xt.draw(w,X.gl.TRIANGLES,R.depthMode,Sa.disabled,R.blendMode,ae?la.disabled:la.backCW,ks,F.id,Vt.layoutVertexBuffer,Vt.indexBuffer,ms,F.paint,w.transform.zoom,Rt,Us)}};w.uploadCommonUniforms(X,kt,ot.toUnwrapped(),null,Ke),_t.buildingWithoutFacade&&ws(_t.buildingWithoutFacade,kt),_t.buildingWithFacade&&($t!==kt&&w.uploadCommonUniforms(X,$t,ot.toUnwrapped(),null,Ke),ws(_t.buildingWithFacade,$t))}}function dx(R,w,A,F,V,Z,X,ae,pe,ke,Me,Ke,He,tt){const ct=R.context.gl,ot=R.depthModeForSublayer(1,Ir.ReadOnly,ct.LEQUAL,!0),wt=.1*(1-(_t=Me))+3*_t;var _t;const Rt=R._showOverdrawInspector,$t=Ke,kt=new Jp;Rt||Ag(kt,R,w,A,F,ot,new Sa({func:ct.ALWAYS,mask:255},255,255,ct.KEEP,ct.KEEP,ct.REPLACE),new ka([ct.ONE,ct.ONE,ct.ONE,ct.ONE],o.aq.transparent,[!1,!1,!1,!0],ct.MIN),la.disabled,V,"sdf",Z,X,ae,pe,ke,wt,$t,!1,void 0);{const ks=Rt?Sa.disabled:new Sa({func:ct.EQUAL,mask:255},255,255,ct.KEEP,ct.DECR,ct.DECR),Jt=Rt?R.colorModeForRenderPass():new ka([ct.ONE_MINUS_DST_ALPHA,ct.DST_ALPHA,ct.ONE,ct.ONE],o.aq.transparent,[!0,!0,!0,!0]);Ag(kt,R,w,A,F,ot,ks,Jt,la.disabled,V,"color",Z,X,ae,pe,ke,wt,$t,!1,void 0)}}function Xb(R){return[R[0]*o.e7,R[1]*o.e7,R[2]*o.e7,0]}function E1(R,w,A,F,V,Z,X,ae,pe){const ke=F.getSource(),Me=A.globeSharedBuffers;if(!Me)return;let Ke,He,tt;if(w&&(Ke=F.getTile(w)),ke instanceof o.aV?(He=ke.texture,tt=o.dw(0,0,A.transform)):Ke&&w&&(He=Ke.texture,tt=o.dw(w.canonical.z,w.canonical.x,A.transform)),!He||!tt)return;R||(tt=o.cC(o.bb(),tt,[1,-1,1]));const ct=A.context,ot=ct.gl,wt=V.paint.get("raster-resampling")==="nearest"?ot.NEAREST:ot.LINEAR,_t=A.colorModeForDrapableLayerRenderPass(Z),Rt=X.defines;Rt.push("GLOBE_POLES");const $t=new Ir(ot.LEQUAL,Ir.ReadWrite,A.depthRangeFor3D),kt=Float32Array.from(A.transform.expandedFarZProjMatrix),ks=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));A.terrain&&A.terrain.prepareDrawTile(),ct.activeTexture.set(ot.TEXTURE0),He.bind(wt,ot.CLAMP_TO_EDGE),ct.activeTexture.set(ot.TEXTURE1),He.bind(wt,ot.CLAMP_TO_EDGE),"useMipmap"in He&&ct.extTextureFilterAnisotropic&&A.transform.pitch>20&&ot.texParameterf(ot.TEXTURE_2D,ct.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,ct.extTextureFilterAnisotropicMax);const[Jt,ws,Vt,Xt]=w?Me.getPoleBuffers(w.canonical.z,!1):Me.getPoleBuffers(0,!0),ms=V.paint.get("raster-elevation");let Us;R?(Us=Jt,A.renderDefaultNorthPole=ms!==0):(Us=ws,A.renderDefaultSouthPole=ms!==0);const Cs=Xb(X.mix),pn=((Ln,$n,Ys,Es,hn,fn,jn,yr,rr,ar,zn,ta,va,Br)=>Wd(Ln,$n,Ys,Es,new Float32Array(16),new Float32Array(9),[0,0],hn,[0,0],[0,0,0,0],1,{opacity:1,mix:0},jn,[0,0],rr,2,zn,ta,va,1,0,Br))(A,kt,ks,tt,o.al(A.transform.zoom),0,V,0,ms,0,Cs,X.offset,X.range,Z),an=A.getOrCreateProgram("raster",{defines:Rt});A.uploadCommonUniforms(ct,an,null),an.draw(A,ot.TRIANGLES,$t,pe,_t,ae,pn,V.id,Us,Vt,Xt)}function M1(R){if(R.isOrthographic)return[0,0,0,0];const w=R._nearZ,A=R.projection.farthestPixelDistance(R),F=A-w,V=.2*R.height,Z=w+V;return[w,A,(Z-V-w)/F,(Z-w)/F]}function Aw(R,w,A,F){if(R)return w instanceof Jm&&R instanceof _m?w.getTextureDescriptor(R,A,!0):{texture:R.texture,mix:Xb(F.mix),offset:F.offset,buffer:0,tileSize:1}}var L1=o.e8([{name:"a_index",type:"Int16",components:1}]);class bu{constructor(w,A,F,V){const Z={width:F[0],height:F[1],data:null},X=w.gl;this.targetColorTexture=new o.T(w,Z,X.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(w,Z,X.RGBA8,{useMipmap:!1}),this.context=w,this.updateParticleTexture(A,V),this.lastInvalidatedAt=0}updateParticleTexture(w,A){if(this.particleTextureDimension===A.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const F=this.context.gl,V=A.width*A.height;this.particleTexture0=new o.T(this.context,A,F.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,A,F.RGBA8,{premultiply:!1,useMipmap:!1});const Z=new o.e9;Z.reserve(V);for(let X=0;X0){const Cs=o.ec(A.canonical,pe),pn=o.ed(Cs);He=o.aD(new Float32Array(16),pe.globeMatrix,pn),o.aD(He,pe.projMatrix,He)}const tt=o.bb();tt[12]+=2*V/(o.o.devicePixelRatio*pe.width),tt[13]+=2*Z/(o.o.devicePixelRatio*pe.height),o.aD(He,tt,He);const ct=R.getOrCreateProgram("debug",{defines:Ke}),ot=w.getTileByID(A.key);R.terrain&&R.terrain.setupElevationDraw(ot,ct);const wt=Ir.disabled,_t=Sa.disabled,Rt=R.colorModeForRenderPass(),$t="$debug";ae.activeTexture.set(ke.TEXTURE0),R.emptyTexture.bind(ke.LINEAR,ke.CLAMP_TO_EDGE),Me?ot._makeGlobeTileDebugBuffers(R.context,pe):ot._makeDebugTileBoundsBuffers(R.context,pe.projection);const kt=ot._tileDebugBuffer||R.debugBuffer,ks=ot._tileDebugIndexBuffer||R.debugIndexBuffer,Jt=ot._tileDebugSegments||R.debugSegments;if(ct.draw(R,ke.LINE_STRIP,wt,_t,Rt,la.disabled,io(He,F.toPremultipliedRenderColor(null)),$t,kt,ks,Jt,null,null,null,[ot._globeTileDebugBorderBuffer]),X){const Cs=ot.latestRawTileData,pn=Math.floor((Cs&&Cs.byteLength||0)/1024);let an=A.canonical.toString();A.overscaledZ!==A.canonical.z&&(an+=` => ${A.overscaledZ}`),an+=` ${ot.state}`,an+=` ${pn}kb`,function(Ln,$n){Ln.initDebugOverlayCanvas();const Ys=Ln.debugOverlayCanvas,Es=Ln.context.gl,hn=Ln.debugOverlayCanvas.getContext("2d");hn.clearRect(0,0,Ys.width,Ys.height),hn.shadowColor="white",hn.shadowBlur=2,hn.lineWidth=1.5,hn.strokeStyle="white",hn.textBaseline="top",hn.font="bold 36px Open Sans, sans-serif",hn.fillText($n,5,5),hn.strokeText($n,5,5),Ln.debugOverlayTexture.update(Ys),Ln.debugOverlayTexture.bind(Es.LINEAR,Es.CLAMP_TO_EDGE)}(R,an)}const ws=w.getTile(A).tileSize,Vt=512/Math.min(ws,512)*(A.overscaledZ/pe.zoom)*.5,Xt=ot._tileDebugTextBuffer||R.debugBuffer,ms=ot._tileDebugTextIndexBuffer||R.quadTriangleIndexBuffer,Us=ot._tileDebugTextSegments||R.debugSegments;ct.draw(R,ke.TRIANGLES,wt,_t,ka.alphaBlended,la.disabled,io(He,o.aq.transparent.toPremultipliedRenderColor(null),Vt),$t,Xt,ms,Us,null,null,null,[ot._globeTileDebugTextBuffer])}function TS(R,w,A,F){Tg(R,0,w+A/2,R.transform.width,A,F)}function bv(R,w,A,F){Tg(R,w-A/2,0,A,R.transform.height,F)}function Tg(R,w,A,F,V,Z){const X=R.context,ae=X.gl;ae.enable(ae.SCISSOR_TEST),ae.scissor(w*o.o.devicePixelRatio,A*o.o.devicePixelRatio,F*o.o.devicePixelRatio,V*o.o.devicePixelRatio),X.clear({color:Z}),ae.disable(ae.SCISSOR_TEST)}const o2=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:Ru}=o2;function tm(R,w,A,F){R.emplaceBack(w,A,F)}class Ed{constructor(w){this.vertexArray=new o.ee,this.indices=new o.dC,tm(this.vertexArray,-1,-1,1),tm(this.vertexArray,1,-1,1),tm(this.vertexArray,-1,1,1),tm(this.vertexArray,1,1,1),tm(this.vertexArray,-1,-1,-1),tm(this.vertexArray,1,-1,-1),tm(this.vertexArray,-1,1,-1),tm(this.vertexArray,1,1,-1),this.indices.emplaceBack(5,1,3),this.indices.emplaceBack(3,7,5),this.indices.emplaceBack(6,2,0),this.indices.emplaceBack(0,4,6),this.indices.emplaceBack(2,6,7),this.indices.emplaceBack(7,3,2),this.indices.emplaceBack(5,4,0),this.indices.emplaceBack(0,1,5),this.indices.emplaceBack(0,2,3),this.indices.emplaceBack(3,1,0),this.indices.emplaceBack(7,6,4),this.indices.emplaceBack(4,5,7),this.vertexBuffer=w.createVertexBuffer(this.vertexArray,Ru),this.indexBuffer=w.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function tf(R,w,A,F,V,Z){const X=R.context.gl,ae=w.paint.get("sky-atmosphere-color"),pe=w.paint.get("sky-atmosphere-halo-color"),ke=w.paint.get("sky-atmosphere-sun-intensity"),Me=((Ke,He,tt,ct,ot)=>({u_matrix_3f:Ke,u_sun_direction:He,u_sun_intensity:tt,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(),F),V,ke,ae.toPremultipliedRenderColor(null),pe.toPremultipliedRenderColor(null));X.framebufferTexture2D(X.FRAMEBUFFER,X.COLOR_ATTACHMENT0,X.TEXTURE_CUBE_MAP_POSITIVE_X+Z,w.skyboxTexture,0),A.draw(R,X.TRIANGLES,Ir.disabled,Sa.disabled,ka.unblended,la.frontCW,Me,"skyboxCapture",w.skyboxGeometry.vertexBuffer,w.skyboxGeometry.indexBuffer,w.skyboxGeometry.segment)}const tk=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class l2{constructor(w){const A=new o.eh;A.emplaceBack(-1,1,1,0,0),A.emplaceBack(1,1,1,1,0),A.emplaceBack(1,-1,1,1,1),A.emplaceBack(-1,-1,1,0,1);const F=new o.dC;F.emplaceBack(0,1,2),F.emplaceBack(2,3,0),this.vertexBuffer=w.createVertexBuffer(A,tk.members),this.indexBuffer=w.createIndexBuffer(F),this.segments=o.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const sk=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 T0{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class nk{constructor(w){this.colorModeAlphaBlendedWriteRGB=new ka([1,yl,1,yl],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new ka([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new T0,this.updateNeeded=!0}update(w){const A=w.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new l2(A);const F=this.params.sizeRange,V=this.params.intensityRange,Z=function(Me){const Ke=o.em(30),He=[];for(let tt=0;tt{const Vt=Z.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];ws&&Vt.push("ALPHA_PASS");const Xt=w.getOrCreateProgram("globeAtmosphere",{defines:Vt}),ms=((Cs,pn,an,Ln,$n,Ys,Es,hn,fn,jn,yr,rr)=>({u_frustum_tl:Cs,u_frustum_tr:pn,u_frustum_br:an,u_frustum_bl:Ln,u_horizon:$n,u_transition:Ys,u_fadeout_range:Es,u_atmosphere_fog_color:hn.toArray01(),u_high_color:fn.toArray01(),u_space_color:jn.toArray01(),u_temporal_offset:yr,u_horizon_angle:rr}))(Z.frustumCorners.TL,Z.frustumCorners.TR,Z.frustumCorners.BR,Z.frustumCorners.BL,Z.frustumCorners.horizon,ae,wt,Me,He,ct,Rt,ks);w.uploadCommonUniforms(F,Xt);const Us=this.atmosphereBuffer;Us&&Xt.draw(w,V.TRIANGLES,X,Sa.disabled,ws?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,la.backCW,ms,ws?"atmosphere_glow_alpha":"atmosphere_glow",Us.vertexBuffer,Us.indexBuffer,Us.segments)};Jt(!1),Jt(!0)}drawStars(w,A){const F=o.aC(A.properties.get("star-intensity"),0,1);if(F===0)return;const V=w.context,Z=V.gl,X=w.transform,ae=w.getOrCreateProgram("stars"),pe=o.bL([]);o.bN(pe,pe,-X._pitch),o.bM(pe,pe,-X.angle),o.bN(pe,pe,o.ap(X._center.lat)),o.ek(pe,pe,-o.ap(X._center.lng));const ke=o.bR(new Float32Array(16),pe),Me=o.aD([],X.starsProjMatrix,ke),Ke=o.eg([],ke),He=o.el([],Ke),tt=[0,1,0];o.dG(tt,tt,He),o.bJ(tt,tt,this.params.sizeMultiplier);const ct=[1,0,0];o.dG(ct,ct,He),o.bJ(ct,ct,this.params.sizeMultiplier);const ot=(wt=tt,_t=ct,Rt=F,{u_matrix:Float32Array.from(Me),u_up:wt,u_right:_t,u_intensity_multiplier:Rt});var wt,_t,Rt;w.uploadCommonUniforms(V,ae),this.starsVx&&this.starsIdx&&ae.draw(w,Z.TRIANGLES,Ir.disabled,Sa.disabled,this.colorModeAlphaBlendedWriteRGB,la.disabled,ot,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class $x{constructor(){this.visibleTiles=[]}updateBorders(w,A){const F=[],V=[],Z=w._getRenderableCoordinates(!1,!0);for(const pe of Z){const ke=w.getTile(pe);if(!ke.hasData())continue;const Me=ke.getBucket(A);Me&&(Me.isEmpty()||(F.push(pe.key),V.push({bucket:Me,tileID:pe.canonical})))}let X=F.length!==this.visibleTiles.length;if(!X){F.sort();for(let pe=0;pepe.tileID.z-ke.tileID.z||pe.tileID.x-ke.tileID.x||pe.tileID.y-ke.tileID.y);for(const pe of V){const ke=new Array,Me=new Array,Ke=pe.bucket;for(const He of Ke.featuresOnBorder)ae.has(He.featureId)?Me.push(He.footprintIndex):(ae.add(He.featureId),ke.push(He.footprintIndex));Ke.updateFootprintHiddenFlags(ke,o.en,!1),Ke.updateFootprintHiddenFlags(Me,o.en,!0)}}}function L6(R,w){const A=[...R],F=w.cameraWorldSizeForFog/w.worldSize,V=o.b9([]);return o.cC(V,V,[F,F,1]),o.aD(A,V,A),o.aD(A,w.worldToFogMatrix,A),A}function bi(R,w,A,F,V){const Z=A.material,X=F.context,{baseColorTexture:ae,metallicRoughnessTexture:pe}=Z.pbrMetallicRoughness,{normalTexture:ke,occlusionTexture:Me,emissionTexture:Ke}=Z;function He(ct,ot,wt){if(ct&&(R.push(ot),X.activeTexture.set(X.gl.TEXTURE0+wt),ct.gfxTexture)){const{minFilter:_t,magFilter:Rt,wrapS:$t,wrapT:kt}=ct.sampler;ct.gfxTexture.bindExtraParam(_t,Rt,$t,kt)}}He(ae,"HAS_TEXTURE_u_baseColorTexture",5),He(pe,"HAS_TEXTURE_u_metallicRoughnessTexture",6),He(ke,"HAS_TEXTURE_u_normalTexture",7),He(Me,"HAS_TEXTURE_u_occlusionTexture",8),He(Ke,"HAS_TEXTURE_u_emissionTexture",9),V&&(V.texture||(V.texture=new o.dR(F.context,V.image,[V.image.height,V.image.height,V.image.height],X.gl.RGBA8)),X.activeTexture.set(X.gl.TEXTURE0+10),V.texture&&V.texture.bind(X.gl.LINEAR,X.gl.CLAMP_TO_EDGE),R.push("APPLY_LUT_ON_GPU")),A.texcoordBuffer&&(R.push("HAS_ATTRIBUTE_a_uv_2f"),w.push(A.texcoordBuffer)),A.colorBuffer&&(R.push(A.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),w.push(A.colorBuffer)),A.normalBuffer&&(R.push("HAS_ATTRIBUTE_a_normal_3f"),w.push(A.normalBuffer)),A.pbrBuffer&&(R.push("HAS_ATTRIBUTE_a_pbr"),R.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),w.push(A.pbrBuffer)),Z.alphaMode!=="OPAQUE"&&Z.alphaMode!=="MASK"||R.push("UNPREMULT_TEXTURE_IN_SHADER"),Z.defined||R.push("DIFFUSE_SHADED");const tt=F.shadowRenderer;tt&&(R.push("RENDER_SHADOWS"),tt.useNormalOffset&&R.push("NORMAL_OFFSET"))}function rk(R,w,A,F,V,Z){const X=R.modelOpacity,ae=w.context,pe=new Ir(w.context.gl.LEQUAL,R.isLightMesh?Ir.ReadOnly:Ir.ReadWrite,w.depthRangeFor3D),ke=w.transform,Me=R.mesh,Ke=Me.material,He=Ke.pbrMetallicRoughness,tt=w.style.fog;let ct;ct=w.transform.projection.zAxisUnit==="pixels"?[...R.nodeModelMatrix]:o.aD([],F.zScaleMatrix,R.nodeModelMatrix),o.aD(ct,F.negCameraPosMatrix,ct);const ot=o.b7([],ct);o.e6(ot,ot);const wt=A.paint.get("model-color-use-theme").constantOr("default")==="none",_t=A.paint.get("model-emissive-strength").constantOr(0),Rt=Bl(new Float32Array(R.worldViewProjection),new Float32Array(ct),new Float32Array(ot),null,w,X,He.baseColorFactor,Ke.emissiveFactor,He.metallicFactor,He.roughnessFactor,Ke,_t,A,void 0,void 0,R.materialOverride,R.modelColor),$t={defines:[]},kt=[],ks=w.shadowRenderer;ks&&(ks.useNormalOffset=!1),bi($t.defines,kt,Me,w,wt?null:A.lut);let Jt=null;if(tt){const Xt=L6(R.nodeModelMatrix,w.transform);if(Jt=new Float32Array(Xt),ke.projection.name!=="globe"){const ms=Me.aabb.min,Us=Me.aabb.max,[Cs,pn]=tt.getOpacityForBounds(Xt,ms[0],ms[1],Us[0],Us[1]);$t.overrideFog=Cs>=Zn||pn>=Zn}}const ws=Kc(w,A.paint.get("model-cutoff-fade-range"));ws.shouldRenderCutoff&&$t.defines.push("RENDER_CUTOFF");const Vt=w.getOrCreateProgram("model",$t);w.uploadCommonUniforms(ae,Vt,null,Jt,ws),w.renderPass!=="shadow"&&ks&&ks.setupShadowsFromMatrix(R.nodeModelMatrix,Vt),Vt.draw(w,ae.gl.TRIANGLES,pe,V,Z,Me.material.doubleSided?la.disabled:la.backCCW,Rt,A.id,Me.vertexBuffer,Me.indexBuffer,Me.segments,A.paint,w.transform.zoom,void 0,kt)}function ES(R,w){return R.style._importedAsBasemap?"basemap":w.scope}function lC(R,w,A,F,V,Z,X,ae,pe,ke){const Me=R.transform,Ke=!!w.isGeometryBloom&&w.isGeometryBloom;if(Ke&&R.renderPass==="shadow")return;const He=Me.projection.name==="globe"?o.ev(A,Me):[...A];o.aD(He,He,w.globalMatrix);const tt=o.aD([],F,He);if(w.meshes)for(const ct of w.meshes){const ot=ae.get(ct.material.name);if(ot&&ot.opacity<=0)continue;if(ct.material.alphaMode!=="BLEND"){X.push({mesh:ct,depth:0,modelIndex:V,worldViewProjection:tt,nodeModelMatrix:He,isLightMesh:Ke,materialOverride:ot,modelOpacity:pe,modelColor:ke,node:w,modelMatrix:A});continue}const wt=o.ah([],ct.centroid,tt);!Me.isOrthographic&&wt[2]<=0||Z.push({mesh:ct,depth:wt[2],modelIndex:V,worldViewProjection:tt,nodeModelMatrix:He,isLightMesh:Ke,materialOverride:ot,modelOpacity:pe,modelColor:ke,node:w,modelMatrix:A})}if(w.children)for(const ct of w.children)lC(R,ct,A,F,V,Z,X,ae,pe,ke)}function ak(R,w,A,F){const V=A.shadowRenderer;if(!V)return;const Z=V.getShadowPassDepthMode(),X=V.calculateShadowPassMatrixFromMatrix(w),ae=Iu(X);A.getOrCreateProgram("modelDepth").draw(A,A.context.gl.TRIANGLES,Z,Sa.disabled,ka.disabled,la.disabled,ae,F.id,R.vertexBuffer,R.indexBuffer,R.segments,F.paint,A.transform.zoom,void 0,void 0)}function cC(R,w,A,F){const V=function(Me,Ke){if(Ke.footprintDebugMesh)return Ke.footprintDebugMesh;if(!Ke.footprint)return null;const He=Me.context,tt=Ke.footprint.vertices,ct=Ke.footprint.indices,ot=new o.dB;ot.reserve(tt.length);for(const ms of tt)ot.emplaceBack(ms.x,ms.y);const wt=new o.dC;wt.reserve(ct.length);for(let ms=0;ms0){const He=Z.terrain,tt=He.findDEMTileFor(ae);tt&&tt.dem?pe=o.ex.create(He,ae,tt):Ke=0}if(Ke===0&&(X.terrainElevationMin=0,X.terrainElevationMax=0),Ke===X.validForExaggeration&&(Ke===0||pe&&pe._demTile&&pe._demTile.tileID===X.validForDEMTile.id&&pe._dem._timestamp===X.validForDEMTile.timestamp))return!1;for(const He in X.instancesPerModel){const tt=X.instancesPerModel[He];for(let ct=0;ctke&&(ke=tt.max)}const Me=o.aC(F.x,Z,X)-F.x,Ke=o.aC(F.y,ae,pe)-F.y,He=o.bU(ke,w.center.lat)-F.z;return w._zoomFromMercatorZ(Math.sqrt(Me*Me+Ke*Ke+He*He))}function pc(R,w,A,F,V,Z,X){const ae=R.context,pe=R.renderPass==="shadow",ke=R.shadowRenderer,Me=pe&&ke?ke.getShadowPassDepthMode():new Ir(ae.gl.LEQUAL,Ir.ReadWrite,R.depthRangeFor3D),Ke=R.isTileAffectedByFog(Z),He=R.transform.projection.name==="globe";if(A.meshes)for(const tt of A.meshes){const ct=He?[]:["MODEL_POSITION_ON_GPU"],ot=[];let wt,_t,Rt;const $t=!He&&F.instancedDataArray.length>20;$t&&ct.push("INSTANCED_ARRAYS");const kt=Kc(R,w.paint.get("model-cutoff-fade-range"));if(kt.shouldRenderCutoff&&ct.push("RENDER_CUTOFF"),pe&&ke)wt=R.getOrCreateProgram("modelDepth",{defines:ct}),_t=Iu(X.shadowTileMatrix,X.shadowTileMatrix,Float32Array.from(A.globalMatrix)),Rt=ka.disabled;else{bi(ct,ot,tt,R,w.paint.get("model-color-use-theme").constantOr("default")==="none"?null:w.lut),wt=R.getOrCreateProgram("model",{defines:ct,overrideFog:Ke});const Jt=tt.material,ws=Jt.pbrMetallicRoughness,Vt=w.paint.get("model-opacity").constantOr(1),Xt=w.paint.get("model-emissive-strength").constantOr(0);_t=Bl(Z.expandedProjMatrix,Float32Array.from(A.globalMatrix),new Float32Array(16),null,R,Vt,ws.baseColorFactor,Jt.emissiveFactor,ws.metallicFactor,ws.roughnessFactor,Jt,Xt,w,V),ke&&(X.shadowUniformsInitialized?wt.setShadowUniformValues(ae,ke.getShadowUniformValues()):(ke.setupShadows(Z.toUnwrapped(),wt,"model-tile"),X.shadowUniformsInitialized=!0)),Rt=kt.shouldRenderCutoff||Vt<1||Jt.alphaMode!=="OPAQUE"?ka.alphaBlended:ka.unblended}R.uploadCommonUniforms(ae,wt,Z.toUnwrapped(),null,kt);const ks=tt.material.doubleSided?la.disabled:la.backCCW;if($t)ot.push(F.instancedDataBuffer),wt.draw(R,ae.gl.TRIANGLES,Me,Sa.disabled,Rt,ks,_t,w.id,tt.vertexBuffer,tt.indexBuffer,tt.segments,w.paint,R.transform.zoom,void 0,ot,F.instancedDataArray.length);else{const Jt=pe?"u_instance":"u_normal_matrix";for(let ws=0;wspe[1]?X:pe,Z[0]=A.max[0],X=o.aE(o.bE(),Z,V),ae=X[1]pe[1]?X:pe,Z[1]=A.min[1],X=o.aE(o.bE(),Z,V),ae=X[1]pe[1]?X:pe;const ke=o.aC(F[0],0,1),Me=100*w.pixelsPerMeter*o.aC(F[1],0,1),Ke=o.aC(F[2],0,1),He=o.ey(o.bE(),ae,pe,ke),tt=Math.tan(.5*w.fovX),ct=-He[2]*tt;if(Me===0)return He[1]<-Math.abs(ct)?Ke:1;const ot=(-Math.abs(ct)-He[1])/Me,wt=(Rt,$t,kt)=>(1-kt)*Rt+kt*$t,_t=o.aC(wt(1,Ke,ot),Ke,1);return wt(1,_t,o.aC((w.pitch-20)/20,0,1))}class uC{}class P6{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(w,A,F){{const Ke=this._storage.get(A.id);if(Ke)return Ke.lastUsedFrameIdx=w,Ke.buf}const V=F.gl,Z=V.getBufferParameter(V.ELEMENT_ARRAY_BUFFER,V.BUFFER_SIZE),X=new ArrayBuffer(Z),ae=new Int16Array(X);V.getBufferSubData(V.ELEMENT_ARRAY_BUFFER,0,new Int16Array(X));const pe=new o.eA;for(let Ke=0;Ke30&&(F.buf.destroy(),this._storage.delete(A))}destroy(){for(const[w,A]of this._storage)A.buf.destroy(),this._storage.delete(w)}}class I6{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const d2=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 R6{constructor(w){this.revealStart=11,this.revealRange=2}}const hC=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class GO{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(w,A){const F=w.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const X=new o.eB,ae=new o.dC;X.emplaceBack(-1,-1),X.emplaceBack(1,-1),X.emplaceBack(1,1),X.emplaceBack(-1,1),ae.emplaceBack(0,1,2),ae.emplaceBack(0,2,3),this.vignetteVx=w.context.createVertexBuffer(X,hC.members),this.vignetteIdx=w.context.createIndexBuffer(ae)}const V=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){w.uploadCommonUniforms(w.context,F);const X={u_vignetteShape:(Z={vignetteShape:[A.start,A.range,Math.pow(10,A.fadePower)],vignetteColor:[A.color.r,A.color.g,A.color.b,A.color.a*A.strength]}).vignetteShape,u_vignetteColor:Z.vignetteColor};F.draw(w,w.context.gl.TRIANGLES,Ir.disabled,Sa.disabled,ka.alphaBlended,la.disabled,X,"vignette",this.vignetteVx,this.vignetteIdx,V)}var Z}}class mC{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(w,A){const F=w.getFreeCameraOptions().position,V=F.toAltitude(),Z=F.toLngLat(),X=o.ap(Z.lng),ae=o.ap(Z.lat),pe=w.pixelsPerMeter/A,ke=X*o.eD,Me=o.eD*Math.log(Math.tan(Math.PI/4+ae/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 Ke=-this._offsetYPrev+Me,He=-this._elevationPrev+V;this._accumulatedOffsetX+=(-this._offsetXPrev+ke)*pe,this._accumulatedOffsetY+=Ke*pe,this._accumulatedElevation+=He*pe,this._offsetXPrev=ke,this._offsetYPrev=Me,this._elevationPrev=V}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Q(R,w){return[-(R[0]-Math.floor(R[0]/w)*w),-(R[1]-Math.floor(R[1]/w)*w),-(R[2]-Math.floor(R[2]/w)*w)]}function ne(R){const w=o.em(1323123451230),A=[];for(let F=0;F Rain"),this._vignetteParams={strength:1,start:.7,range:1,fadePower:.4,color:{r:.27,g:.27,b:.27,a:1}},this.particlesCount=16e3}update(w){const A=w.context;if(!this.particlesVx){const F=ne(this.particlesCount),V=new o.eE,Z=new o.dC;let X=0;const ae=o.em(1323123451230);for(let pe=0;peF)return;const V=Pe(0,1,A.revealStart,A.revealStart+A.revealRange,F);if(!this.particlesVx||!this.particlesIdx)return;const Z=structuredClone(this._params);let X=[-Z.direction.x,Z.direction.y,-100];o.ay(X,X);const ae=structuredClone(this._vignetteParams);ae.strength*=V,Z.overrideStyleParameters||(Z.intensity=w.style.rain.state.density,Z.timeFactor=w.style.rain.state.intensity,Z.color=structuredClone(w.style.rain.state.color),X=structuredClone(w.style.rain.state.direction),Z.screenThinning.intensity=w.style.rain.state.centerThinning,Z.dropletSizeX=w.style.rain.state.dropletSize[0],Z.dropletSizeYScale=w.style.rain.state.dropletSize[1]/w.style.rain.state.dropletSize[0],Z.distortionStrength=100*w.style.rain.state.distortionStrength,ae.strength=1,ae.color=structuredClone(w.style.rain.state.vignetteColor));const pe=this.updateOnRender(w,Z.timeFactor),ke=w.context,Me=ke.gl,Ke=w.transform;this.screenTexture&&this.screenTexture.size[0]===w.width&&this.screenTexture.size[1]===w.height||(this.screenTexture=new o.T(ke,{width:w.width,height:w.height,data:null},Me.RGBA8)),Z.distortionStrength>0&&(ke.activeTexture.set(Me.TEXTURE0),this.screenTexture.bind(Me.LINEAR,Me.CLAMP_TO_EDGE),Me.copyTexSubImage2D(Me.TEXTURE_2D,0,0,0,0,0,w.width,w.height));const He=w.getOrCreateProgram("rainParticle");w.uploadCommonUniforms(ke,He),ke.activeTexture.set(Me.TEXTURE0),this.screenTexture.bind(Me.LINEAR,Me.CLAMP_TO_EDGE);const tt=[Z.color.r,Z.color.g,Z.color.b,Z.color.a],ct=(ot,wt)=>{const _t=Q(this._movement.getPosition(),ot),Rt=Z.dropletSizeX,$t=Z.dropletSizeX*Z.dropletSizeYScale,kt=w.width/2,ks=w.height/2,Jt=Pe(0,Z.screenThinning.start,0,1,Z.screenThinning.intensity),ws=Pe(.001,Z.screenThinning.range,0,1,Z.screenThinning.intensity),Vt=Pe(0,Z.screenThinning.particleOffset,0,1,Z.screenThinning.intensity),Xt=(ms={modelview:pe.modelviewMatrix,projection:pe.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:_t,velocityConeAperture:Z.velocityConeAperture,velocity:Z.velocity,boxSize:ot,rainDropletSize:[Rt,$t],distortionStrength:Z.distortionStrength,rainDirection:X,color:tt,screenSize:[Ke.width,Ke.height],thinningCenterPos:[kt,ks],thinningShape:[Jt,ws,Math.pow(10,Z.screenThinning.fadePower)],thinningAffectedRatio:Z.screenThinning.affectedRatio,thinningParticleOffset:Vt,shapeDirectionalPower:Z.shapeDirPower,shapeNormalPower:Z.shapeNormalPower,mode:wt?0:1},{u_modelview:Float32Array.from(ms.modelview),u_projection:Float32Array.from(ms.projection),u_time:ms.time,u_cam_pos:ms.camPos,u_texScreen:0,u_velocityConeAperture:ms.velocityConeAperture,u_velocity:ms.velocity,u_boxSize:ms.boxSize,u_rainDropletSize:ms.rainDropletSize,u_distortionStrength:ms.distortionStrength,u_rainDirection:ms.rainDirection,u_color:ms.color,u_screenSize:ms.screenSize,u_thinningCenterPos:ms.thinningCenterPos,u_thinningShape:ms.thinningShape,u_thinningAffectedRatio:ms.thinningAffectedRatio,u_thinningParticleOffset:ms.thinningParticleOffset,u_shapeDirectionalPower:ms.shapeDirectionalPower,u_shapeNormalPower:ms.shapeNormalPower,u_mode:ms.mode});var ms;const Us=Math.round(Z.intensity*this.particlesCount),Cs=o.dy.simpleSegment(0,0,4*Us,2*Us);He.draw(w,Me.TRIANGLES,Ir.disabled,Sa.disabled,ka.alphaBlended,la.disabled,Xt,"rain_particles",this.particlesVx,this.particlesIdx,Cs)};Z.distortionStrength>0&&ct(Z.boxSize,!0),ct(Z.boxSize,!1),this._vignette.draw(w,ae)}}const Ct=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 st{constructor(w){super(2.25),this._params={overrideStyleParameters:!1,intensity:.85,timeFactor:.75,velocityConeAperture:70,velocity:40,horizontalOscillationRadius:4,horizontalOscillationRate:1.5,boxSize:2e3,billboardSize:2,shapeFadeStart:.27,shapeFadePower:.21,screenThinning:{intensity:.4,start:.15,range:1.4,fadePower:.24,affectedRatio:1,particleOffset:-.2},color:{r:1,g:1,b:1,a:1},direction:{x:-50,y:-35}},this._revealParams=new R6("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 A=w.context;if(!this.particlesVx){const F=ne(this.particlesCount),V=new o.eF,Z=new o.dC;let X=0;const ae=o.em(1323123451230);for(let pe=0;peX)return;const ae=Pe(0,1,Z.revealStart,Z.revealStart+Z.revealRange,X);V.strength*=ae,A.overrideStyleParameters||(A.intensity=w.style.snow.state.density,A.timeFactor=w.style.snow.state.intensity,A.color=structuredClone(w.style.snow.state.color),F=structuredClone(w.style.snow.state.direction),A.screenThinning.intensity=w.style.snow.state.centerThinning,A.billboardSize=2.79*w.style.snow.state.flakeSize,V.strength=1,V.color=structuredClone(w.style.snow.state.vignetteColor));const pe=this.updateOnRender(w,A.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const ke=w.context,Me=ke.gl,Ke=w.transform,He=w.getOrCreateProgram("snowParticle");w.uploadCommonUniforms(ke,He),((tt,ct,ot)=>{const wt=Q(this._movement.getPosition(),tt),_t=Ke.width/2,Rt=Ke.height/2,$t=Pe(0,ot.screenThinning.start,0,1,ot.screenThinning.intensity),kt=Pe(.001,ot.screenThinning.range,0,1,ot.screenThinning.intensity),ks=Pe(0,ot.screenThinning.particleOffset,0,1,ot.screenThinning.intensity),Jt=(ws={modelview:pe.modelviewMatrix,projection:pe.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:wt,velocityConeAperture:ot.velocityConeAperture,velocity:ot.velocity,horizontalOscillationRadius:ot.horizontalOscillationRadius,horizontalOscillationRate:ot.horizontalOscillationRate,boxSize:tt,billboardSize:1*ot.billboardSize,simpleShapeParameters:[ot.shapeFadeStart,ot.shapeFadePower],screenSize:[Ke.width,Ke.height],thinningCenterPos:[_t,Rt],thinningShape:[$t,kt,Math.pow(10,ot.screenThinning.fadePower)],thinningAffectedRatio:ot.screenThinning.affectedRatio,thinningParticleOffset:ks,color:[ot.color.r,ot.color.g,ot.color.b,ot.color.a],direction:F},{u_modelview:Float32Array.from(ws.modelview),u_projection:Float32Array.from(ws.projection),u_time:ws.time,u_cam_pos:ws.camPos,u_velocityConeAperture:ws.velocityConeAperture,u_velocity:ws.velocity,u_horizontalOscillationRadius:ws.horizontalOscillationRadius,u_horizontalOscillationRate:ws.horizontalOscillationRate,u_boxSize:ws.boxSize,u_billboardSize:ws.billboardSize,u_simpleShapeParameters:ws.simpleShapeParameters,u_screenSize:ws.screenSize,u_thinningCenterPos:ws.thinningCenterPos,u_thinningShape:ws.thinningShape,u_thinningAffectedRatio:ws.thinningAffectedRatio,u_thinningParticleOffset:ws.thinningParticleOffset,u_particleColor:ws.color,u_direction:ws.direction});var ws;const Vt=Math.round(ot.intensity*this.particlesCount),Xt=o.dy.simpleSegment(0,0,4*Vt,2*Vt);this.particlesVx&&this.particlesIdx&&He.draw(w,Me.TRIANGLES,Ir.disabled,Sa.disabled,ka.alphaBlended,la.disabled,Jt,"snow_particles",this.particlesVx,this.particlesIdx,Xt)})(A.boxSize,0,A),this._vignette.draw(w,V)}}const qn={symbol:function(R,w,A,F,V){if(R.renderPass!=="translucent")return;const Z=Sa.disabled,X=R.colorModeForRenderPass(),ae=A.layout.get("text-variable-anchor"),pe=A.layout.get("text-size-scale-range"),ke=o.aC(R.scaleFactor,pe[0],pe[1]);ae&&function(He,tt,ct,ot,wt,_t,Rt,$t){const kt=tt.transform,ks=wt==="map",Jt=_t==="map";for(const ws of He){const Vt=ot.getTile(ws),Xt=Vt.getBucket(ct);if(!Xt||!Xt.text||!Xt.text.segments.get().length)continue;const ms=o.bj(Xt.textSizeData,kt.zoom,$t),Us=Zh(ws,Xt.getProjection(),kt),Cs=kt.calculatePixelsToTileUnitsMatrix(Vt),pn=rd(Us,Vt.tileID.canonical,Jt,ks,kt,Xt.getProjection(),Cs),an=Xt.hasIconTextFit()&&Xt.hasIconData();ms&&mc(Xt,ks,Jt,Rt,kt,pn,ws,Math.pow(2,kt.zoom-Vt.tileID.overscaledZ),ms,an)}}(F,R,A,w,A.layout.get("text-rotation-alignment"),A.layout.get("text-pitch-alignment"),V,ke);const Me=A.paint.get("icon-opacity").constantOr(1)!==0,Ke=A.paint.get("text-opacity").constantOr(1)!==0;A.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(Me||Ke)?em(R,w,A,F,Z,X):(Me&&em(R,w,A,F,Z,X,{onlyIcons:!0}),Ke&&em(R,w,A,F,Z,X,{onlyText:!0})),w.map.showCollisionBoxes&&(gr(R,w,A,F,A.paint.get("text-translate"),A.paint.get("text-translate-anchor"),!0),gr(R,w,A,F,A.paint.get("icon-translate"),A.paint.get("icon-translate-anchor"),!1))},circle:function(R,w,A,F){if(R.renderPass!=="translucent")return;const V=A.paint.get("circle-opacity"),Z=A.paint.get("circle-stroke-width"),X=A.paint.get("circle-stroke-opacity"),ae=A.layout.get("circle-sort-key").constantOr(1)!==void 0,pe=A.paint.get("circle-emissive-strength");if(V.constantOr(1)===0&&(Z.constantOr(1)===0||X.constantOr(1)===0))return;const ke=R.context,Me=ke.gl,Ke=R.transform,He=!(!R.terrain||!R.terrain.enabled),tt=A.layout.get("circle-elevation-reference"),ct=R.depthModeForSublayer(0,Ir.ReadOnly),ot=new Ir(R.context.gl.LEQUAL,Ir.ReadOnly,R.depthRangeFor3D),wt=tt==="none"||He?ct:ot,_t=Sa.disabled,Rt=R.colorModeForDrapableLayerRenderPass(pe),$t=Ke.projection.name==="globe",kt=[o.aH(Ke.center.lng),o.aL(Ke.center.lat)],ks=[];for(let ws=0;wsws.sortKey-Vt.sortKey);const Jt={useDepthForOcclusion:Ke.depthOcclusionForSymbolsAndCircles};for(const ws of ks){const{programConfiguration:Vt,program:Xt,layoutVertexBuffer:ms,dynamicBuffers:Us,indexBuffer:Cs,uniformValues:pn,tile:an}=ws.state,Ln=ws.segments;R.terrain&&R.terrain.setupElevationDraw(an,Xt,Jt),R.uploadCommonUniforms(ke,Xt,an.tileID.toUnwrapped()),Xt.draw(R,Me.TRIANGLES,wt,_t,Rt,la.disabled,pn,A.id,ms,Cs,Ln,A.paint,Ke.zoom,Vt,Us)}},heatmap:function(R,w,A,F){if(A.paint.get("heatmap-opacity")!==0)if(R.renderPass==="offscreen"){const V=R.context,Z=V.gl,X=Sa.disabled,ae=new ka([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.aq.transparent,[!0,!0,!0,!0]),pe=R.transform.projection.name==="globe"?.5:.25;A.heatmapFbo=Cm.createWithTexture(V,A.heatmapFbo,R.width*pe,R.height*pe),V.clear({color:o.aq.transparent});const ke=R.transform,Me=ke.projection.name==="globe",Ke=Me?["PROJECTION_GLOBE_VIEW"]:[],He=Me?la.frontCCW:la.disabled,tt=[o.aH(ke.center.lng),o.aL(ke.center.lat)];for(let ct=0;ct({u_image:0,u_color_ramp:1,u_opacity:Ke.paint.get("heatmap-opacity")}))(0,Z),Z.id,V.viewportBuffer,V.quadTriangleIndexBuffer,V.viewportSegments,Z.paint,V.transform.zoom)}(R,A))},line:function(R,w,A,F){const V=A.paint.get("line-opacity"),Z=A.paint.get("line-width");if(V.constantOr(1)===0||Z.constantOr(1)===0)return;const X=A.paint.get("line-blend-mode");if(X!=="default"&&R.transform.projection.name!=="globe")return R.terrain&&R.terrain.renderingToTexture?void function(ae,pe,ke,Me,Ke){if(ae.renderPass!=="translucent")return;const He=ae.context,tt=He.gl,ct=ae.terrain;if(!ct)return;const ot=He.bindFramebuffer.current,wt=ae.emissiveMode==="mrt-fallback";ke.lineBlendDrapeFbo=Cm.createWithTexture(He,ke.lineBlendDrapeFbo,ct.drapeBufferSize[0],ct.drapeBufferSize[1],!0),ke.lineBlendDrapeStencil=ke.lineBlendDrapeFbo._stencilRbo,wt&&tt.drawBuffers([tt.COLOR_ATTACHMENT0]),He.clear({color:mp[Ke].clearColor,depth:1,stencil:0});const _t=ae.currentStencilSource,Rt=ae._tileClippingMaskIDs,$t=ae.nextStencilID;ae.currentStencilSource=void 0,ae._tileClippingMaskIDs={},ae.nextStencilID=1;const kt=ae._terrain;ae._terrain=null,ae._renderTileClippingMasks(ke,pe,Me),Jd(ae,pe,ke,Me,mp[Ke].colorMode,!0),ae._terrain=kt,ae.currentStencilSource=_t,ae._tileClippingMaskIDs=Rt,ae.nextStencilID=$t,He.bindFramebuffer.set(ot),wt&&tt.drawBuffers([tt.COLOR_ATTACHMENT0,tt.COLOR_ATTACHMENT1]);const ks=ct.drapeBufferSize;He.viewport.set([0,0,ks[0],ks[1]]);const Jt=ke.lineBlendDrapeFbo;if(!Jt)return;He.activeTexture.set(tt.TEXTURE0),tt.bindTexture(tt.TEXTURE_2D,Jt.colorAttachment0.get());const ws=Ke==="additive"?1:ke.paint.get("line-opacity").constantOr(1),Vt=ke.paint.get("line-emissive-strength").constantOr(0),Xt=Ke==="additive"?ae.colorModeForDrapableLayerRenderPass(Vt):mp[Ke].colorMode;ae.getOrCreateProgram("lineBlendComposite").draw(ae,tt.TRIANGLES,Ir.disabled,Sa.disabled,Xt,la.disabled,Tl(0,ws,mp[Ke].compositeUniformValue),ke.id,ae.viewportBuffer,ae.quadTriangleIndexBuffer,ae.viewportSegments,ke.paint,ae.transform.zoom)}(R,w,A,F,X):R.renderPass==="offscreen"?void function(ae,pe,ke,Me,Ke){const He=ae.context,tt=Math.ceil(ae.width),ct=Math.ceil(ae.height);ke.lineBlendFbo=Cm.createWithTexture(He,ke.lineBlendFbo,tt,ct,!0),ke.lineBlendStencil=ke.lineBlendFbo._stencilRbo,He.clear({color:mp[Ke].clearColor,depth:1,stencil:0});const ot=ae.currentStencilSource,wt=ae._tileClippingMaskIDs,_t=ae.nextStencilID;ae.currentStencilSource=void 0,ae._tileClippingMaskIDs={},ae.nextStencilID=1,ae._renderTileClippingMasks(ke,pe,Me);const Rt=ae.renderPass;ae.renderPass="translucent",Jd(ae,pe,ke,Me,mp[Ke].colorMode),ae.renderPass=Rt,ae.currentStencilSource=ot,ae._tileClippingMaskIDs=wt,ae.nextStencilID=_t,He.viewport.set([0,0,ae.width,ae.height])}(R,w,A,F,X):R.renderPass==="translucent"?void function(ae,pe,ke){const Me=ae.context,Ke=Me.gl,He=pe.lineBlendFbo;if(!He)return;Me.activeTexture.set(Ke.TEXTURE0),Ke.bindTexture(Ke.TEXTURE_2D,He.colorAttachment0.get());const tt=ke==="additive"?1:pe.paint.get("line-opacity").constantOr(1),ct=ke==="additive"?ae.colorModeForDrapableLayerRenderPass(pe.paint.get("line-emissive-strength").constantOr(0)):mp[ke].colorMode;ae.getOrCreateProgram("lineBlendComposite").draw(ae,Ke.TRIANGLES,Ir.disabled,Sa.disabled,ct,la.disabled,Tl(0,tt,mp[ke].compositeUniformValue),pe.id,ae.viewportBuffer,ae.quadTriangleIndexBuffer,ae.viewportSegments,pe.paint,ae.transform.zoom)}(R,A,X):void 0;R.renderPass==="translucent"&&Jd(R,w,A,F)},fill:function(R,w,A,F){const V=A.paint.get("fill-color"),Z=A.paint.get("fill-opacity");if(Z.constantOr(1)===0)return;const X=A.paint.get("fill-emissive-strength"),ae=R.colorModeForDrapableLayerRenderPass(X),pe=A.paint.get("fill-pattern"),ke=R.opaquePassEnabledForLayer()&&!pe.constantOr(1)&&V.constantOr(o.aq.transparent).a===1&&Z.constantOr(0)===1?"opaque":"translucent";let Me="none";A.layout.get("fill-elevation-reference")!=="none"?Me="road":A.paint.get("fill-z-offset").constantOr(1)!==0&&(Me="offset");const Ke=!(!R.terrain||!R.terrain.enabled),He={painter:R,sourceCache:w,layer:A,coords:F,colorMode:ae,elevationType:Me,terrainEnabled:Ke,pass:ke};if(R.renderPass==="shadow")return void(R.shadowRenderer&&Me==="road"&&!Ke&&function(ct){const{painter:ot,sourceCache:wt,layer:_t,coords:Rt}=ct,$t=ot.context.gl,kt=ct.painter.shadowRenderer;for(const ks of Rt){const Jt=wt.getTile(ks),ws=Jt.getBucket(_t);if(!ws)continue;const Vt=ws.elevatedStructures;if(!Vt||!Vt.shadowCasterSegments||Vt.shadowCasterSegments.segments[0].primitiveLength===0)continue;ot.prepareDrawTile();const Xt=ws.bufferData.programConfigurations.get(_t.id),ms=ot.isTileAffectedByFog(ks),Us=ot.getOrCreateProgram("elevatedStructuresDepth",{config:Xt,overrideFog:ms}),Cs=kt.calculateShadowPassMatrixFromTile(Jt.tileID.toUnwrapped());ot.uploadCommonUniforms(ot.context,Us,ks.toUnwrapped());const pn=fi(Cs,0);Us.draw(ot,$t.TRIANGLES,kt.getShadowPassDepthMode(),Sa.disabled,ka.disabled,la.disabled,pn,_t.id,Vt.vertexBuffer,Vt.indexBuffer,Vt.shadowCasterSegments,_t.paint,ot.transform.zoom,Xt)}}(He));const tt=R.emissiveMode==="mrt-fallback";if(Me!=="offset"){if(gv(He,!1,tt),Me==="road"){const ct=!Ke&&R.renderPass==="translucent";ct&&T1(R,w,A,F,"geometry"),gv(He,!0,tt,Sa.disabled),ct&&function(ot){const{painter:wt,sourceCache:_t,layer:Rt,coords:$t,colorMode:kt}=ot,ks=wt.context.gl,Jt=ot.painter.shadowRenderer,ws=!!Jt&&Jt.enabled,Vt=new Ir(wt.context.gl.LEQUAL,Ir.ReadOnly,wt.depthRangeFor3D);let Xt=[0,0,0];if(ws){const Us=wt.style.directionalLight,Cs=wt.style.ambientLight;Us&&Cs&&(Xt=dh(wt.style,Us,Cs))}const ms=Us=>{for(const Cs of $t){const pn=_t.getTile(Cs),an=pn.getBucket(Rt);if(!an)continue;const Ln=an.elevatedStructures;if(!Ln)continue;let $n,Ys;if(Us?($n=Ln.renderableBridgeSegments,Ys=Ln.bridgeProgramConfigurations.get(Rt.id)):($n=Ln.renderableTunnelSegments,Ys=Ln.tunnelProgramConfigurations.get(Rt.id)),!$n||$n.segments[0].primitiveLength===0)continue;Ys.updatePaintBuffers(),wt.prepareDrawTile();const Es=wt.isTileAffectedByFog(Cs),hn=[];ws&&hn.push("RENDER_SHADOWS","NORMAL_OFFSET");const fn=wt.getOrCreateProgram("elevatedStructures",{config:Ys,overrideFog:Es,defines:hn}),jn=wt.translatePosMatrix(Cs.projMatrix,pn,Rt.paint.get("fill-translate"),Rt.paint.get("fill-translate-anchor"));ws&&Jt.setupShadows(pn.tileID.toUnwrapped(),fn,"vector-tile");const yr=Zo(jn,Xt);wt.uploadCommonUniforms(wt.context,fn,Cs.toUnwrapped()),fn.draw(wt,ks.TRIANGLES,Vt,Sa.disabled,kt,la.backCCW,yr,Rt.id,Ln.vertexBuffer,Ln.indexBuffer,$n,Rt.paint,wt.transform.zoom,Ys,[Ln.vertexBufferNormal])}};ms(!0),ms(!1)}(He)}}else gv(He,!1,tt,R.stencilModeFor3D())},"fill-extrusion":function(R,w,A,F){const V=A.paint.get("fill-extrusion-opacity"),Z=R.context,X=Z.gl,ae=R.terrain,pe=ae&&ae.renderingToTexture;if(V===0)return;const ke=R.emissiveMode==="mrt-fallback",Me=R.conflationActive&&R.style.isLayerClipped(A,w.getSource()),Ke=R.style.order.indexOf(A.fqid);if(Me&&function(He,tt,ct,ot,wt){for(const _t of ot){const Rt=tt.getTile(_t).getBucket(ct);Rt&&(Rt.updateReplacement(_t,He.replacementSource,wt),Rt.uploadCentroid(He.context))}}(R,w,A,F,Ke),ae||Me)for(const He of F){const tt=w.getTile(He).getBucket(A);tt&&C0(R.context,w,He,tt,A,ae,Me)}if(R.renderPass==="shadow"&&R.shadowRenderer){if(ae&&V<.65&&A._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const He=R.shadowRenderer.getShadowPassDepthMode();Am(R,w,A,F,He,Sa.disabled,ka.disabled,Me)}else if(R.renderPass==="translucent"){const He=!A.paint.get("fill-extrusion-pattern").constantOr(1),tt=A.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!pe&&tt.a!==0){const ct=new Ir(R.context.gl.LEQUAL,Ir.ReadWrite,R.depthRangeFor3D);V===1&&He?Am(R,w,A,F,ct,Sa.disabled,ka.unblended,Me):(Am(R,w,A,F,ct,Sa.disabled,ka.disabled,Me),Am(R,w,A,F,ct,R.stencilModeFor3D(),R.colorModeForRenderPass(),Me),R.resetStencilClippingMasks())}if(R.style.enable3dLights()&&He&&(!ae&&R.transform.projection.name!=="globe"||pe)){const ct=A.paint.get("fill-extrusion-opacity"),ot=A.paint.get("fill-extrusion-ambient-occlusion-intensity"),wt=A.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),_t=A.paint.get("fill-extrusion-flood-light-intensity"),Rt=A.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",$t=A.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Rt?null:A.lut).toArray01().slice(0,3),kt=ot>0&&wt>0,ks=_t>0,Jt=(Xt,ms,Us)=>(1-Us)*Xt+Us*ms,ws=new Jp;ws.translate=A.paint.get("fill-extrusion-translate"),ws.translateAnchor=A.paint.get("fill-extrusion-translate-anchor"),ws.edgeRadius=A.layout.get("fill-extrusion-edge-radius"),ws.cutoffFadeRange=A.paint.get("fill-extrusion-cutoff-fade-range");const Vt=Xt=>{const ms=R.depthModeForSublayer(1,Ir.ReadOnly,X.LEQUAL,!0),Us=A.paint.get(Xt?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Cs=Jt(.1,3,Us),pn=R._showOverdrawInspector;if(!pn){const an=new Sa({func:X.ALWAYS,mask:255},255,255,X.KEEP,X.KEEP,X.REPLACE),Ln=new ka([X.ONE,X.ONE,X.ONE,X.ONE],o.aq.transparent,[!1,!1,!1,!0],X.MIN);Ag(ws,R,w,A,F,ms,an,Ln,la.disabled,Xt,"sdf",ct,ot,wt,_t,$t,Cs,Me,!1)}{const an=pn?Sa.disabled:new Sa({func:X.EQUAL,mask:255},255,255,X.KEEP,X.DECR,X.DECR),Ln=pn?R.colorModeForRenderPass():new ka([X.ONE_MINUS_DST_ALPHA,X.DST_ALPHA,X.ONE,X.ONE],o.aq.transparent,[!0,!0,!0,!0]);Ag(ws,R,w,A,F,ms,an,Ln,la.disabled,Xt,"color",ct,ot,wt,_t,$t,Cs,Me,!1)}};if(pe){const Xt=()=>{const Us=ae.drapeBufferSize[0],Cs=ae.drapeBufferSize[1];let pn=ae.framebufferCopyTexture;return pn&&(!pn||pn.size[0]===Us&&pn.size[1]===Cs)||(pn&&pn.destroy(),pn=ae.framebufferCopyTexture=new o.T(Z,new o.q({width:Us,height:Cs}),X.RGBA8)),pn.bind(X.LINEAR,X.CLAMP_TO_EDGE),X.copyTexSubImage2D(X.TEXTURE_2D,0,0,0,0,0,Us,Cs),pn},ms=(Us,Cs,pn)=>{const an=R.depthModeForSublayer(1,Ir.ReadOnly,X.LEQUAL,!1),Ln=A.paint.get(Us?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),$n=Jt(.1,3,Ln);{const Ys=new ka([X.ONE,X.ONE,X.ONE,X.ONE],o.aq.transparent,[!1,!1,!1,!0]);Ag(ws,R,w,A,F,an,Sa.disabled,Ys,la.disabled,Us,"clear",ct,ot,wt,_t,$t,$n,Me,Cs)}{const Ys=new Sa({func:X.ALWAYS,mask:255},255,255,X.KEEP,X.KEEP,X.REPLACE),Es=new ka([X.ONE,X.ONE,X.ONE,X.ONE],o.aq.transparent,[!1,!1,!1,!0],X.MIN);Ag(ws,R,w,A,F,an,Ys,Es,la.disabled,Us,"sdf",ct,ot,wt,_t,$t,$n,Me,Cs)}ke&&!Us&&(pn=Xt());{const Ys=Us?X.ZERO:X.ONE_MINUS_DST_ALPHA,Es=new Sa({func:X.EQUAL,mask:255},255,255,X.KEEP,X.DECR,X.DECR),hn=new ka([Ys,X.DST_ALPHA,X.ONE_MINUS_DST_ALPHA,X.ZERO],o.aq.transparent,[!0,!0,!0,!0]);Ag(ws,R,w,A,F,an,Es,hn,la.disabled,Us,"color",ct,ot,wt,_t,$t,$n,Me,Cs)}if(!ke||Us){const Ys=new ka([X.ONE,X.ONE,X.ONE,Us?X.ZERO:X.ONE],o.aq.transparent,[!1,!1,!1,!0],Us?X.FUNC_ADD:X.MAX);Ag(ws,R,w,A,F,an,Sa.disabled,Ys,la.disabled,Us,"clear",ct,ot,wt,_t,$t,$n,Me,Cs,pn)}else{X.drawBuffers([X.NONE,X.COLOR_ATTACHMENT1]);const Ys=new Sa({func:X.EQUAL,mask:255},254,255,X.KEEP,X.DECR,X.DECR),Es=new ka([X.ONE,X.ONE,X.ONE,X.ONE],o.aq.transparent,[!0,!1,!1,!1],X.MAX);Ag(ws,R,w,A,F,an,Ys,Es,la.disabled,Us,"emissive",ct,ot,wt,_t,$t,$n,Me,Cs,pn),X.drawBuffers([X.COLOR_ATTACHMENT0])}};if(kt||ks){let Us;R.prepareDrawTile(),ke&&!kt||(Us=Xt()),kt&&ms(!0,!1,Us),ks&&ms(!1,!0,Us)}}else kt&&Vt(!0),ks&&Vt(!1),(kt||ks)&&R.resetStencilClippingMasks()}}},building:function(R,w,A,F){R.currentLayer0&&Z>0,ke=!0;const Me=A.paint.get("building-vertical-scale");if(Me<=0)return;R.shadowRenderer||(ke=!1);const Ke=R.conflationActive&&R.style.isLayerClipped(A,w.getSource()),He=R.style.order.indexOf(A.fqid);if(function(tt,ct,ot,wt,_t,Rt){for(const $t of Rt){const kt=ct.getTile($t).getBucket(ot);kt&&(_t&&kt.updateReplacement($t,tt.replacementSource,wt),kt.uploadUpdatedIndexBuffer(tt.context))}}(R,w,A,He,Ke,F),function(tt,ct,ot,wt){for(const _t of wt){const Rt=ct.getTile(_t).getBucket(ot);Rt&&Rt.needsEvaluation()&&Rt.uploadUpdatedColorBuffer(tt.context)}}(R,w,A,F),A.resetLayerRenderingStats(R),R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!0),R.renderPass==="shadow"&&R.shadowRenderer){const tt=[],ct=R.shadowRenderer.getShadowPassDepthMode();jy({painter:R,source:w,layer:A,coords:F,defines:tt,blendMode:ka.disabled,depthMode:ct,opacity:ae,verticalScale:Me,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(R.renderPass==="translucent"){let tt=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];ke&&(tt=tt.concat("RENDER_SHADOWS")),R.shadowRenderer&&R.shadowRenderer.useNormalOffset&&(tt=tt.concat("NORMAL_OFFSET"));const ct=A.paint.get("building-facade-emissive-chance"),ot=A.paint.get("building-ambient-occlusion-intensity"),wt=A.paint.get("building-flood-light-intensity"),_t=A.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Rt=A.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(_t?null:A.lut).toArray01().slice(0,3),$t=A.paint.get("building-flood-light-ground-attenuation"),kt=wt>0,ks=new Ir(R.context.gl.LEQUAL,Ir.ReadWrite,R.depthRangeFor3D);ae<1&&jy({painter:R,source:w,layer:A,coords:F,defines:tt,blendMode:ka.disabled,depthMode:ks,opacity:ae,verticalScale:Me,facadeEmissiveChance:ct,facadeAOIntensity:ot,floodLightIntensity:wt,floodLightColor:Rt,depthOnly:!0});const Jt=R.colorModeForRenderPass();jy({painter:R,source:w,layer:A,coords:F,defines:tt,blendMode:Jt,depthMode:ks,opacity:ae,verticalScale:Me,facadeEmissiveChance:ct,facadeAOIntensity:ot,floodLightIntensity:wt,floodLightColor:Rt});const ws=A.paint.get("building-front-cutoff");kw(R.transform.pitch,ws,!!R.terrain),pe&&dx(R,w,A,F,!0,ae,V,Z,wt,Rt,X,Ke),kt&&dx(R,w,A,F,!1,ae,V,Z,wt,Rt,$t,Ke)}else if(R.renderPass==="light-beam"){const tt=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],ct=new Ir(R.context.gl.LEQUAL,Ir.ReadOnly,R.depthRangeFor3D);jy({painter:R,source:w,layer:A,coords:F,defines:tt,blendMode:ka.alphaBlended,depthMode:ct,opacity:ae,verticalScale:Me,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}R.shadowRenderer&&(R.shadowRenderer.useNormalOffset=!1),R.resetStencilClippingMasks()},hillshade:function(R,w,A,F){if(R.renderPass!=="offscreen"&&R.renderPass!=="translucent"||R.style.disableElevatedTerrain)return;const V=R.context,Z=R.terrain&&R.terrain.renderingToTexture,[X,ae]=R.renderPass!=="translucent"||Z?[{},F]:R.stencilConfigForOverlap(F);for(const pe of ae){const ke=w.getTile(pe);if(ke.needsHillshadePrepare&&R.renderPass==="offscreen")iC(R,ke,A);else if(R.renderPass==="translucent"){const Me=R.depthModeForSublayer(0,Ir.ReadOnly),Ke=A.paint.get("hillshade-emissive-strength"),He=R.colorModeForDrapableLayerRenderPass(Ke),tt=Z&&R.terrain?R.terrain.stencilModeForRTTOverlap(pe):X[pe.overscaledZ];E6(R,pe,ke,A,Me,tt,He)}}V.viewport.set([0,0,R.width,R.height]),R.resetStencilClippingMasks()},raster:function(R,w,A,F,V,Z){if(R.renderPass!=="translucent")return;const X=A.paint.get("raster-opacity");if(X===0)return;const ae=R.transform.projection.name==="globe",pe=A.paint.get("raster-elevation")!==0,ke=pe&&ae,Me=R.terrain&&R.terrain.exaggeration()>0&&pe&&A.paint.get("raster-elevation-reference")==="ground",Ke=!ae&&Me;if(R.renderElevatedRasterBackface&&!ke)return;const He=R.context,tt=He.gl,ct=w.getSource(),ot=function(Xt,ms,Us,Cs,pn){const an=ms.paint.get("raster-color"),Ln=Xt.type==="raster-array",$n=[],Ys=ms.paint.get("raster-resampling"),Es=ms.paint.get("raster-color-mix");let hn=ms.paint.get("raster-color-range");const fn=[Es[0],Es[1],Es[2],0],jn=Es[3];let yr=Ys==="nearest"?Cs.NEAREST:Cs.LINEAR;if(Ln&&($n.push("RASTER_ARRAY"),an||$n.push("RASTER_COLOR"),Ys==="linear"&&$n.push("RASTER_ARRAY_LINEAR"),yr=Cs.NEAREST,!hn&&Xt.rasterLayers)){const rr=Xt.rasterLayers.find(({id:ar})=>ar===ms.sourceLayer);rr&&rr.fields&&rr.fields.range&&(hn=rr.fields.range)}if(hn=hn||[0,1],an){$n.push("RASTER_COLOR"),Us.activeTexture.set(Cs.TEXTURE2),ms.updateColorRamp(hn);let rr=ms.colorRampTexture;rr||(rr=ms.colorRampTexture=new o.T(Us,ms.colorRamp,Cs.RGBA8)),rr.bind(yr,Cs.CLAMP_TO_EDGE)}return pn&&$n.push("USE_MRT1"),{mix:fn,range:hn,offset:jn,defines:$n,resampling:yr}}(ct,A,He,tt,R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback");if(ct instanceof o.aV&&!F.length&&!ae)return;const wt=A.paint.get("raster-emissive-strength"),_t=R.colorModeForDrapableLayerRenderPass(wt),Rt=R.terrain&&R.terrain.renderingToTexture,$t=!R.options.moving,kt=A.paint.get("raster-resampling")==="nearest"?tt.NEAREST:tt.LINEAR;if(ct instanceof o.aV&&!F.length&&(ct.onNorthPole||ct.onSouthPole)){const Xt=pe?R.stencilModeFor3D():Sa.disabled;return void E1(!!ct.onNorthPole,null,R,w,A,wt,ot,la.disabled,Xt)}if(!F.length)return;const[ks,Jt]=ct instanceof o.aV||Rt?[{},F]:R.stencilConfigForOverlap(F),ws=Jt[Jt.length-1].overscaledZ;ke&&ot.defines.push("PROJECTION_GLOBE_VIEW"),pe&&ot.defines.push("RENDER_CUTOFF","ELEVATED"),Me&&ot.defines.push("ELEVATION_REFERENCE_GROUND");const Vt=(Xt,ms,Us)=>{for(const Cs of Xt){const pn=Cs.toUnwrapped(),an=w.getTile(Cs);if(Rt&&(!an||!an.hasData()))continue;He.activeTexture.set(tt.TEXTURE0);const Ln=Aw(an,ct,A,ot);if(!Ln||!Ln.texture)continue;const{texture:$n,mix:Ys,offset:Es,tileSize:hn,buffer:fn}=Ln;let jn,yr;Rt?(jn=Ir.disabled,yr=Cs.projMatrix):pe?(jn=new Ir(tt.LEQUAL,Ir.ReadWrite,R.depthRangeFor3D),yr=ae?Float32Array.from(R.transform.expandedFarZProjMatrix):R.transform.calculateProjMatrix(pn,$t)):(jn=R.depthModeForSublayer(Cs.overscaledZ-ws,X===1?Ir.ReadWrite:Ir.ReadOnly,tt.LESS),yr=R.transform.calculateProjMatrix(pn,$t));const rr=R.terrain&&Rt?R.terrain.stencilModeForRTTOverlap(Cs):ks[Cs.overscaledZ],ar=Z?0:A.paint.get("raster-fade-duration");an.registerFadeDuration(ar);const zn=w.findLoadedParent(Cs,0),ta=bt(an,zn,w,R.transform,ar);let va,Br;!ta.isFading&&an.refreshedUponExpiration&&(an.refreshedUponExpiration=!1),R.terrain&&R.terrain.prepareDrawTile(),He.activeTexture.set(tt.TEXTURE0),$n.bind(kt,tt.CLAMP_TO_EDGE),He.activeTexture.set(tt.TEXTURE1),zn?(zn.texture&&zn.texture.bind(kt,tt.CLAMP_TO_EDGE),va=Math.pow(2,zn.tileID.overscaledZ-an.tileID.overscaledZ),Br=[an.tileID.canonical.x*va%1,an.tileID.canonical.y*va%1]):$n.bind(kt,tt.CLAMP_TO_EDGE),"useMipmap"in $n&&He.extTextureFilterAnisotropic&&R.transform.pitch>20&&tt.texParameterf(tt.TEXTURE_2D,He.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,He.extTextureFilterAnisotropicMax);const Qr=R.transform;let Ga;const li=pe?M1(Qr):[0,0,0,0];let ni,Ii,Ea,Ri,ri,Mo=0;if(ke&&ct instanceof o.aV&&ct.coordinates.length>3)ni=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),Ii=Float32Array.from(Qr.globeMatrix),Ea=Float32Array.from(o.dq(Qr)),Ri=[o.aH(Qr.center.lng),o.aL(Qr.center.lat)],Ga=ct.elevatedGlobePerspectiveTransform,ri=ct.elevatedGlobeGridMatrix||new Float32Array(9);else if(ke){const Vo=o.dr(Cs.canonical);Mo=o.ds(Vo.getCenter().lat),ni=Float32Array.from(o.du(o.dv(Cs.canonical))),Ii=Float32Array.from(Qr.globeMatrix),Ea=Float32Array.from(o.dq(Qr)),Ri=[o.aH(Qr.center.lng),o.aL(Qr.center.lat)],Ga=[0,0],ri=Float32Array.from(o.dt(Cs.canonical,Vo,Mo,Qr.worldSize/Qr._pixelsPerMercatorPixel))}else Ga=ct instanceof o.aV?ct.perspectiveTransform:[0,0],ni=new Float32Array(16),Ii=new Float32Array(9),Ea=new Float32Array(16),Ri=[0,0],ri=new Float32Array(9);const El=Wd(R,yr,ni,Ii,Ea,ri,Br||[0,0],o.al(R.transform.zoom),Ri,li,va||1,ta,A,Ga,pe?A.paint.get("raster-elevation"):0,2,Ys,Es,ot.range,hn,fn,wt),Xc=R.isTileAffectedByFog(Cs),Wl=R.getOrCreateProgram("raster",{defines:ot.defines,overrideFog:Xc});if(R.uploadCommonUniforms(He,Wl,pn),ct instanceof o.aV){const Vo=ct.elevatedGlobeVertexBuffer,Ci=ct.elevatedGlobeIndexBuffer;if(Rt||!ae)ct.boundsBuffer&&ct.boundsSegments&&Wl.draw(R,tt.TRIANGLES,jn,Sa.disabled,_t,la.disabled,El,A.id,ct.boundsBuffer,R.quadTriangleIndexBuffer,ct.boundsSegments);else if(Vo&&Ci){const Ai=Qr.zoom<=o.cJ?ct.elevatedGlobeSegments:ct.getSegmentsForLongitude(Qr.center.lng);Ai&&Wl.draw(R,tt.TRIANGLES,jn,Sa.disabled,_t,ms,El,A.id,Vo,Ci,Ai)}}else if(ke){jn=new Ir(tt.LEQUAL,Ir.ReadOnly,R.depthRangeFor3D);const Vo=R.globeSharedBuffers;if(Vo){Me&&(R.terrain.setupElevationDraw(an,Wl),R.uploadCommonUniforms(He,Wl,an.tileID.toUnwrapped()));const[Ci,Ai,Kl]=Vo.getGridBuffers(Mo,!1),ld=Wl.getAttributeLocation(tt,"a_texture_pos");ld!==-1&&tt.vertexAttribI4ui(ld,0,0,0,0),Wl.draw(R,tt.TRIANGLES,jn,Us||rr,R.colorModeForRenderPass(),ms,El,A.id,Ci,Ai,Kl)}}else if(Ke)jn=new Ir(tt.LEQUAL,Ir.ReadWrite,R.depthRangeFor3D),R.terrain.setupElevationDraw(an,Wl),R.uploadCommonUniforms(He,Wl,an.tileID.toUnwrapped()),Qr.pitch>20&&Wl.draw(R,tt.TRIANGLES,jn,Sa.disabled,ka.disabled,la.frontCCW,El,A.id,R.terrain.gridBuffer,R.terrain.gridIndexBuffer,R.terrain.gridSegments),Wl.draw(R,tt.TRIANGLES,jn,rr,_t,la.backCCW,El,A.id,R.terrain.gridBuffer,R.terrain.gridIndexBuffer,R.terrain.gridSegments);else{const{tileBoundsBuffer:Vo,tileBoundsIndexBuffer:Ci,tileBoundsSegments:Ai}=R.getTileBoundsBuffers(an);Wl.draw(R,tt.TRIANGLES,jn,rr,_t,la.disabled,El,A.id,Vo,Ci,Ai)}}if(!(ct instanceof o.aV)&&ke)for(const Cs of Xt){const pn=Cs.canonical.y===(1<o.d$[fn](pn));Ys.push(pn);const Es=pn.canonical.x,hn=pn.canonical.y;for(const fn of Ys){const jn=kt.getTile(ms?fn.wrapped():fn);if(!jn)continue;const yr=jn.rasterParticleState;if(!yr)continue;const rr=fn.canonical.x+(1<ws.tileID)),tt&&(ke.activeTexture.set(Me.TEXTURE0),R.imageManager.bind(R.context,A.scope));const Jt=[];if(R.terrain&&R.terrain.renderingToTexture&&R.emissiveMode==="mrt-fallback"&&Jt.push("USE_MRT1"),pe){const ws=R.getOrCreateProgram($t,{overrideFog:!1,overrideRtt:!0,defines:Jt}),Vt=new Float32Array(o.b9([])),Xt=new o.aR(0,0,0,0,0),ms=tt?Fc(Vt,ae,X,R,0,A.scope,ct,pe,{tileID:Xt,tileSize:He}):km(Vt,ae,X,V.toPremultipliedRenderColor(Z?null:A.lut));return void ws.draw(R,Me.TRIANGLES,_t,wt,Rt,la.disabled,ms,A.id,R.viewportBuffer,R.quadTriangleIndexBuffer,R.viewportSegments)}for(const ws of ks){const Vt=R.isTileAffectedByFog(ws),Xt=R.getOrCreateProgram($t,{overrideFog:Vt,defines:Jt}),ms=ws.toUnwrapped(),Us=F?ws.projMatrix:R.transform.calculateProjMatrix(ms);R.prepareDrawTile();const Cs=w?w.getTile(ws):kt?kt[ws.key]:new o.b0(ws,He,Ke.zoom,R),pn=tt?Fc(Us,ae,X,R,0,A.scope,ct,pe,{tileID:ws,tileSize:He}):km(Us,ae,X,V.toPremultipliedRenderColor(Z?null:A.lut));R.uploadCommonUniforms(ke,Xt,ms);const{tileBoundsBuffer:an,tileBoundsIndexBuffer:Ln,tileBoundsSegments:$n}=R.getTileBoundsBuffers(Cs);Xt.draw(R,Me.TRIANGLES,_t,wt,Rt,la.disabled,pn,A.id,an,Ln,$n)}},sky:function(R,w,A){const F=R._atmosphere?o.al(R.transform.zoom):1,V=A.paint.get("sky-opacity")*F;if(V===0)return;const Z=R.context,X=A.paint.get("sky-type"),ae=new Ir(Z.gl.LEQUAL,Ir.ReadOnly,[0,1]),pe=R.frameCounter/1e3%1;X==="atmosphere"?R.renderPass==="offscreen"?A.needsSkyboxCapture(R)&&(function(ke,Me){const Ke=ke.context,He=Ke.gl;let tt=Me.skyboxFbo;if(!tt){tt=Me.skyboxFbo=Ke.createFramebuffer(32,32,1,null),Me.skyboxGeometry=new Ed(Ke),Me.skyboxTexture=Ke.gl.createTexture(),He.bindTexture(He.TEXTURE_CUBE_MAP,Me.skyboxTexture),He.texParameteri(He.TEXTURE_CUBE_MAP,He.TEXTURE_WRAP_S,He.CLAMP_TO_EDGE),He.texParameteri(He.TEXTURE_CUBE_MAP,He.TEXTURE_WRAP_T,He.CLAMP_TO_EDGE),He.texParameteri(He.TEXTURE_CUBE_MAP,He.TEXTURE_MIN_FILTER,He.LINEAR),He.texParameteri(He.TEXTURE_CUBE_MAP,He.TEXTURE_MAG_FILTER,He.LINEAR);for(let _t=0;_t<6;++_t)He.texImage2D(He.TEXTURE_CUBE_MAP_POSITIVE_X+_t,0,He.RGBA,32,32,0,He.RGBA,He.UNSIGNED_BYTE,null)}Ke.bindFramebuffer.set(tt.framebuffer),Ke.viewport.set([0,0,32,32]);const ct=Me.getCenter(ke,!0),ot=ke.getOrCreateProgram("skyboxCapture"),wt=new Float64Array(16);o.b9(wt),o.ef(wt,wt,.5*-Math.PI),tf(ke,Me,ot,wt,ct,0),o.b9(wt),o.ef(wt,wt,.5*Math.PI),tf(ke,Me,ot,wt,ct,1),o.b9(wt),o.cE(wt,wt,.5*-Math.PI),tf(ke,Me,ot,wt,ct,2),o.b9(wt),o.cE(wt,wt,.5*Math.PI),tf(ke,Me,ot,wt,ct,3),o.b9(wt),tf(ke,Me,ot,wt,ct,4),o.b9(wt),o.ef(wt,wt,Math.PI),tf(ke,Me,ot,wt,ct,5),Ke.viewport.set([0,0,ke.width,ke.height])}(R,A),A.markSkyboxValid(R)):R.renderPass==="sky"&&function(ke,Me,Ke,He,tt){const ct=ke.context,ot=ct.gl,wt=ke.transform,_t=ke.getOrCreateProgram("skybox");ct.activeTexture.set(ot.TEXTURE0),ot.bindTexture(ot.TEXTURE_CUBE_MAP,Me.skyboxTexture);const Rt=(($t,kt,ks,Jt,ws)=>({u_matrix:$t,u_sun_direction:kt,u_cubemap:0,u_opacity:Jt,u_temporal_offset:ws}))(wt.skyboxMatrix,Me.getCenter(ke,!1),0,He,tt);ke.uploadCommonUniforms(ct,_t),_t.draw(ke,ot.TRIANGLES,Ke,Sa.disabled,ke.colorModeForRenderPass(),la.backCW,Rt,"skybox",Me.skyboxGeometry.vertexBuffer,Me.skyboxGeometry.indexBuffer,Me.skyboxGeometry.segment)}(R,A,ae,V,pe):X==="gradient"&&R.renderPass==="sky"&&function(ke,Me,Ke,He,tt){const ct=ke.context,ot=ct.gl,wt=ke.transform,_t=ke.getOrCreateProgram("skyboxGradient");Me.skyboxGeometry||(Me.skyboxGeometry=new Ed(ct)),ct.activeTexture.set(ot.TEXTURE0);let Rt=Me.colorRampTexture;Rt||(Rt=Me.colorRampTexture=new o.T(ct,Me.colorRamp,ot.RGBA8)),Rt.bind(ot.LINEAR,ot.CLAMP_TO_EDGE);const $t=((kt,ks,Jt,ws,Vt)=>({u_matrix:kt,u_color_ramp:0,u_center_direction:ks,u_radius:o.ap(Jt),u_opacity:ws,u_temporal_offset:Vt}))(wt.skyboxMatrix,Me.getCenter(ke,!1),Me.paint.get("sky-gradient-radius"),He,tt);ke.uploadCommonUniforms(ct,_t),_t.draw(ke,ot.TRIANGLES,Ke,Sa.disabled,ke.colorModeForRenderPass(),la.backCW,$t,"skyboxGradient",Me.skyboxGeometry.vertexBuffer,Me.skyboxGeometry.indexBuffer,Me.skyboxGeometry.segment)}(R,A,ae,V,pe)},custom:function(R,w,A,F){const V=R.context,Z=A.implementation;if(!R.transform.projection.unsupportedLayers||!R.transform.projection.unsupportedLayers.includes("custom")||R.terrain&&(R.terrain.renderingToTexture||R.renderPass==="offscreen")&&A.isDraped(w)){if(R.renderPass==="offscreen"){const X=Z.prerender;if(X){if(R.setCustomLayerDefaults(),V.setColorMode(R.colorModeForRenderPass()),R.transform.projection.name==="globe"){const ae=R.transform.pointMerc;X.call(Z,V.gl,R.transform.customLayerMatrix(),R.transform.getProjection(),R.transform.globeToMercatorMatrix(),o.al(R.transform.zoom),[ae.x,ae.y],R.transform.pixelsPerMeterRatio)}else X.call(Z,V.gl,R.transform.customLayerMatrix());V.setDirty(),R.setBaseState()}}else if(R.renderPass==="translucent"){if(R.terrain&&R.terrain.renderingToTexture){const ae=Z.renderToTile;if(ae){const pe=F[0].canonical,ke={x:pe.x+F[0].wrap*(Z.wrapTileId?0:1<{ke&&(ke.useNormalOffset=!0,Me||(ke.enabled=!0))},He=w.getSource();if(R.renderPass==="light-beam"&&He.type!=="batched-model")return;if(He.type==="vector"||He.type==="geojson")return function(kt,ks,Jt,ws,Vt){const Xt=kt.transform,ms=Xt.projection.name==="globe",Us=Xt.getFreeCameraOptions().position;if(!kt.modelManager)return;const Cs=kt.modelManager;Jt.modelManager=Cs;const pn=kt.shadowRenderer;if(!Jt._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const an=Jt._unevaluatedLayout._values["model-id"],Ln=Object.assign({},Jt.layout.get("model-id").parameters),$n=kt.style.order.indexOf(Jt.fqid),Ys=Jt.paint.get("model-opacity").constantOr(1);for(const Es of ws){const hn=ks.getTile(Es).getBucket(Jt);if(!hn||hn.projection.name!==Xt.projection.name)continue;const fn=hn.getModelUris();if(fn&&!hn.modelsRequested&&(Cs.addModelsFromBucket(fn,Vt),hn.modelsRequested=!0),ms)Ln.zoom=Es.overscaledZ;else{const Br=E0(Es,Xt);Ln.zoom=Br}const jn=an.possiblyEvaluate(Ln);if(sr(kt,hn,Es),tr.shadowUniformsInitialized=!1,tr.useSingleShadowCascade=!!pn&&pn.getMaxCascadeForTile(Es.toUnwrapped())===0,kt.renderPass==="shadow"&&pn){if(kt.currentShadowCascade===1&&hn.isInsideFirstShadowMapFrustum)continue;const Br=Xt.calculatePosMatrix(Es.toUnwrapped(),Xt.worldSize);if(tr.tileMatrix.set(Br),tr.shadowTileMatrix=Float32Array.from(pn.calculateShadowPassMatrixFromMatrix(Br)),tr.aabb.min=[0,0,0],tr.aabb.max[0]=tr.aabb.max[1]=o.an,tr.aabb.max[2]=0,MS(hn,tr,kt,Jt.scope))continue}const yr=1<0&&kt.style.isLayerClipped(Jt,ks.getSource())&&hn.updateReplacement(Es,kt.replacementSource,$n,Jt.scope)&&(hn.uploaded=!1,hn.upload(kt.context));let ar=0;const zn=new Array,ta=new Array,va=new Array;for(let Br in hn.instancesPerModel){const Qr=hn.instancesPerModel[Br];Qr.features.length>0&&!ms&&(Br=jn.evaluate(Qr.features[0].feature,{}));const Ga=Cs.getModel(Br,Vt);if(Ga||Cs.hasURLBeenRequested(Br)||hn.modelUris.includes(Br)||(hn.modelUris.push(Br),hn.modelsRequested=!1),Ga&&Ga.uploaded)if(ms){const li=o.bJ([],[Us.x,Us.y,Us.z],kt.transform.worldSize);o.eo(li,li);for(let ni=0;ni0&&Ri.elevationUpdate(Br.terrain,ni,Ea,Ga.source),Ri.needsReEvaluation(Br,Ii,Ga)&&Ri.evaluate(Ga))}})(kt,ks,Jt,ws),function(){const Br=new Map;let Qr,Ga,li;zn?(Qr=ws.length-1,Ga=-1,li=-1):(Qr=0,Ga=ws.length,li=1);const ni=new Float64Array(16),Ii=o.ce(),Ea=new o.P(0,0);for(let Ri=Qr;Ri!==Ga;Ri+=li){const ri=ws[Ri],Mo=ks.getTile(ri).getBucket(Jt);if(!Mo||!Mo.uploaded)continue;let El=!1;Us&&(El=Us.getMaxCascadeForTile(ri.toUnwrapped())===0);const Xc=Xt.calculatePosMatrix(ri.toUnwrapped(),Xt.worldSize),Wl=Mo.modelTraits;!yr&&zn&&(o.b7(ni,Xc),o.ah(Ii,pn,ni),Ea.x=Ii[0],Ea.y=Ii[1]);const Vo=[];Mo.setFilter(Jt.filter);for(const Ci of Mo.getNodesInfo()){if(Ci.hiddenByReplacement||!Ci.node.meshes)continue;const Ai=Ci.node;let Kl=0;kt.terrain&&Ai.elevation&&(Kl=Ai.elevation*kt.terrain.exaggeration());const ld=(()=>{const pp=Ci.aabb;return jn.min=[...pp.min],jn.max=[...pp.max],jn.min[2]+=Kl,jn.max[2]+=Kl,o.ah(jn.min,jn.min,Xc),o.ah(jn.max,jn.max,Xc),jn})(),Ho=Ci.evaluatedScale;if(Ho[0]<=1&&Ho[1]<=1&&Ho[2]<=1&&ld.intersects(rr)===0)continue;if(!yr&&zn){const pp=.16666666666666666;Ci.cameraCollisionOpacity=pn[0]>ld.min[0]&&pn[0]ld.min[1]&&pn[1]!zn||Ci.opacity===1&&Ai.opacity===1?Ci.depthAi.depth?-1:1);for(const Ci of Vo){const Ai=Ci.nodeInfo,Kl=Ai.node;if(kt._debugParams.show3DModelFootprints&&Kl.footprint){const Ji=Kl.id||Kl.name||"footprint";Br.has(Ji)||Br.set(Ji,{node:Kl,mvp:Ci.wvpForTile})}let ld=o.aD([],Ys,Ci.tileModelMatrix);o.aD(ld,Ln,ld);const Ho=o.b7([],ld);o.e6(Ho,Ho),o.cC(Ho,Ho,Rs),ld=o.aD(ld,ld,Kl.globalMatrix);const mi=kt.renderPass==="light-beam",zc=Jt.paint.get("model-color-use-theme").constantOr("default")==="none",Ml=Wl&o.ez.HasMapboxMeshFeatures,Ou=Ml?0:Ai.evaluatedRMEA[0][2];for(let Ji=0;Ji=Zn||ky>=Zn}}const al=$l.material;let wv;al.occlusionTexture&&al.occlusionTexture.offsetScale&&(wv=al.occlusionTexture.offsetScale,Mh.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const jv=kt.getOrCreateProgram("model",Mh);!yr&&Us&&Us.setupShadowsFromMatrix(Ci.tileModelMatrix,jv,Us.useNormalOffset),kt.uploadCommonUniforms(Vt,jv,null,Ny);const tc=al.pbrMetallicRoughness;tc.metallicFactor=.9,tc.roughnessFactor=.5;const fc=Bl(new Float32Array(Ff),new Float32Array(ld),new Float32Array(Ho),new Float32Array(Kl.globalMatrix),kt,Ci.opacity,tc.baseColorFactor,al.emissiveFactor,tc.metallicFactor,tc.roughnessFactor,al,Ou,Jt,[0,0,0],wv);!ph&&(Ai.hasTranslucentParts||Ci.opacity<1)&&jv.draw(kt,Vt.gl.TRIANGLES,hn,Sa.disabled,ka.disabled,la.backCCW,fc,Jt.id,$l.vertexBuffer,$l.indexBuffer,$l.segments,Jt.paint,kt.transform.zoom,void 0,pp),jv.draw(kt,Vt.gl.TRIANGLES,ph?fn:hn,Sa.disabled,ph||Ci.opacity<1||Ai.hasTranslucentParts?ka.alphaBlended:ka.unblended,la.backCCW,fc,Jt.id,$l.vertexBuffer,$l.indexBuffer,$l.segments,Jt.paint,kt.transform.zoom,void 0,pp)}}}if(kt._debugParams.show3DModelFootprints&&Br.size>0){const Ri=Array.from(Br.keys()).sort();for(const ri of Ri){const{node:Mo,mvp:El}=Br.get(ri);cC(kt,0,Mo,El)}}}()}(R,w,A,F),void Ke();if(He.type!=="model")return;const tt=He.getModels(),ct=[],ot=R.transform.getFreeCameraOptions().position,wt=o.bJ([],[ot.x,ot.y,ot.z],R.transform.worldSize);o.eo(wt,wt);const _t=[],Rt=[];let $t=0;for(const kt of tt){const ks=w.getFeatureState("",kt.id),Jt={type:"Unknown",id:kt.id,properties:kt.featureProperties},ws=A.paint.get("model-rotation").evaluate(Jt,ks),Vt=A.paint.get("model-scale").evaluate(Jt,ks),Xt=A.paint.get("model-translation").evaluate(Jt,ks),ms=A.paint.get("model-opacity").evaluate(Jt,ks);dC(A,kt.id,ks,kt.featureProperties,kt.nodeOverrideNames,kt.nodeOverrides),c2(A,kt.id,ks,kt.featureProperties,kt.materialOverrideNames,kt.materialOverrides),kt.nodeOverrides.size>0&&kt.computeBoundsAndApplyParent(),kt.computeModelMatrix(R,ws,Vt,Xt,ae,X,!1);const Us=o.b9([]),Cs=o.e2(kt.position.lat,R.transform.zoom),pn=o.bP([],[1,1,1/Cs]);o.bx(Us,Us,wt),ct.push({zScaleMatrix:pn,negCameraPosMatrix:Us});for(const an of kt.nodes)lC(R,an,kt.matrix,R.transform.expandedFarZProjMatrix,$t,_t,Rt,kt.materialOverrides,ms);$t++}if(_t.sort((kt,ks)=>ks.depth-kt.depth),R.renderPass!=="shadow"){if(R._debugParams.show3DModelFootprints){const kt=R.transform.projMatrix,ks=new Map,Jt=(Vt,Xt)=>{if(Vt.footprint){const ms=Vt.id||Vt.name||"footprint";if(!ks.has(ms)){const Us=o.aD([],kt,Xt);ks.set(ms,{node:Vt,mvp:Us})}}};for(const Vt of Rt)Jt(Vt.node,Vt.modelMatrix);for(const Vt of _t)Jt(Vt.node,Vt.modelMatrix);const ws=Array.from(ks.keys()).sort();for(const Vt of ws){const{node:Xt,mvp:ms}=ks.get(Vt);cC(R,0,Xt,ms)}}Tm(R,A,_t,Rt,ct),Ke()}else{for(const kt of Rt)ak(kt.mesh,kt.nodeModelMatrix,R,A);for(const kt of _t)ak(kt.mesh,kt.nodeModelMatrix,R,A);Ke()}}},Er={line:function(R,w,A){if(R.hasElevatedBuckets=!1,R.hasNonElevatedBuckets=!1,R._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||R._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(w){const F=w.getVisibleCoordinates();for(const V of F){const Z=w.getTile(V).getBucket(R);if(Z&&(Z.elevationType!=="none"?R.hasElevatedBuckets=!0:R.hasNonElevatedBuckets=!0,R.hasElevatedBuckets&&R.hasNonElevatedBuckets))break}}}else R.hasNonElevatedBuckets=!0},model:function(R,w,A){const F=w.getSource();if(!F.loaded())return;if(F.type==="vector"||F.type==="geojson")return void(A.modelManager&&A.modelManager.upload(A,ES(A,R)));if(F.type==="batched-model"||F.type!=="model")return;const V=F.getModels();for(const Z of V)Z.upload(A.context)},raster:function(R,w,A){const F=w.getSource();if(!(F instanceof Jm&&F.loaded()))return;const V=R.sourceLayer||F.rasterLayerIds&&F.rasterLayerIds[0];if(!V)return;const Z=R.paint.get("raster-array-band")||F.getInitialBand(V);if(Z==null)return;const X=w.getIds().map(ae=>w.getTileByID(ae));for(const ae of X)ae.updateNeeded(R.id,Z)&&F.prepareTile(ae,V,R.id,Z)},"raster-particle":function(R,w,A){const F=w.getSource();if(!(F instanceof Jm&&F.loaded()))return;const V=R.sourceLayer||F.rasterLayerIds&&F.rasterLayerIds[0];if(!V)return;const Z=R.paint.get("raster-particle-array-band")||F.getInitialBand(V);if(Z==null)return;const X=w.getIds().map(ae=>w.getTileByID(ae));for(const ae of X)ae.updateNeeded(R.id,Z)&&F.prepareTile(ae,V,R.id,Z)}},Ca={fill:T1},Ei={fill:function(R,w,A,F){if(!A.layout||A.layout.get("fill-elevation-reference")==="none"||A.paint.get("fill-opacity").constantOr(1)===0)return;const V=R.context.gl,Z=new Ir(V.LEQUAL,Ir.ReadOnly,R.depthRangeFor3D),X=new Sa({func:V.ALWAYS,mask:255},255,255,V.KEEP,V.KEEP,V.REPLACE),ae=R.transform.getFreeCameraOptions().position,pe=R.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const ke of F){const Me=w.getTile(ke),Ke=Me.getBucket(A);if(!Ke)continue;const He=Ke.elevatedStructures;if(!He||He.depthSegments.segments[0].primitiveLength===0)continue;const tt=xv(ke.toUnwrapped(),ae),ct=R.translatePosMatrix(ke.projMatrix,Me,A.paint.get("fill-translate"),A.paint.get("fill-translate-anchor")),ot=Si(ct,tt,0,1,0);pe.draw(R,V.TRIANGLES,Z,X,ka.disabled,la.disabled,ot,A.id,He.vertexBuffer,He.indexBuffer,He.depthSegments,A.paint,R.transform.zoom)}}};class vl{constructor(w,A,F,V,Z){this.context=new mh(w,A),this.transform=F,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this._timeStamp=o.o.now(),this._averageFPS=0,this._fpsHistory=[],this._dt=0,this._debugParams={forceEnablePrecipitation:!1,showTerrainProxyTiles:!1,fpsWindow:30,continousRedraw:!1,show3DModelFootprints:!1,enabledLayers:{}};const X=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const pe of X)this._debugParams.enabledLayers[pe]=!0;for(const pe of X);this.occlusionParams=new I6,this.setup(),this.numSublayers=Vl.maxUnderzooming+Vl.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new o.eG,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._shadowRenderer=new _c(this),this._wireframeDebugCache=new P6,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const ae=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,ae,w.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=V,this.maxFrontCutoffRawStart=0,this.worldview=Z,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(w,A){const F=!!w&&!!w.terrain&&this.transform.projection.supportsTerrain;if(!(F||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new Ss(this,w));const V=this._terrain;this.transform.elevation=F?V:null,V.update(w,this.transform,A),this.transform.elevation&&!V.enabled&&(this.transform.elevation=null)}_updateFog(w){const A=w.fog;if(!A||this.transform.projection.name==="globe"||A.getOpacity(this.transform.pitch)<1||A.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[F,V]=A.getFovAdjustedRange(this.transform._fov);if(F>V)return void(this.transform.fogCullDistSq=null);const Z=F+.78*(V-F);this.transform.fogCullDistSq=Z*Z}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(w){w&&!this._terrain&&(this._terrain=new Ss(this,this.style)),this._forceTerrainMode=w}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(w,A){if(this.width=w*o.o.devicePixelRatio,this.height=A*o.o.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const F of this.style.order)this.style._mergedLayers[F].resize()}setup(){const w=this.context,A=new o.dB;A.emplaceBack(0,0),A.emplaceBack(o.an,0),A.emplaceBack(0,o.an),A.emplaceBack(o.an,o.an),this.tileExtentBuffer=w.createVertexBuffer(A,o.dx.members),this.tileExtentSegments=o.dy.simpleSegment(0,0,4,2);const F=new o.dB;F.emplaceBack(0,0),F.emplaceBack(o.an,0),F.emplaceBack(0,o.an),F.emplaceBack(o.an,o.an),this.debugBuffer=w.createVertexBuffer(F,o.dx.members),this.debugSegments=o.dy.simpleSegment(0,0,4,5);const V=new o.dB;V.emplaceBack(-1,-1),V.emplaceBack(1,-1),V.emplaceBack(-1,1),V.emplaceBack(1,1),this.viewportBuffer=w.createVertexBuffer(V,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const Z=new o.eH;Z.emplaceBack(0,0,0,0),Z.emplaceBack(o.an,0,o.an,0),Z.emplaceBack(0,o.an,0,o.an),Z.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=w.createVertexBuffer(Z,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const X=new o.dC;X.emplaceBack(0,1,2),X.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=w.createIndexBuffer(X);const ae=new o.eJ;for(const ke of[0,1,3,2,0])ae.emplaceBack(ke);this.debugIndexBuffer=w.createIndexBuffer(ae),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 Sa({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,ka.disabled,la.disabled,ht(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(w,A,F){if(!A||this.currentStencilSource===A.id||!w.isTileClipped()||!F||F.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let ae=!1;for(const pe of F)if(this._tileClippingMaskIDs[pe.key]===void 0){ae=!0;break}if(!ae)return}this.currentStencilSource=A.id;const V=this.context,Z=V.gl;this.nextStencilID+F.length>256&&this.clearStencil(),V.setColorMode(ka.disabled),V.setDepthMode(Ir.disabled);const X=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const ae of F){const pe=A.getTile(ae),ke=this._tileClippingMaskIDs[ae.key]=this.nextStencilID++,{tileBoundsBuffer:Me,tileBoundsIndexBuffer:Ke,tileBoundsSegments:He}=this.getTileBoundsBuffers(pe);X.draw(this,Z.TRIANGLES,Ir.disabled,new Sa({func:Z.ALWAYS,mask:0},ke,255,Z.KEEP,Z.KEEP,Z.REPLACE),ka.disabled,la.disabled,ht(ae.projMatrix),"$clipping",Me,Ke,He)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const w=this.nextStencilID++,A=this.context.gl;return new Sa({func:A.NOTEQUAL,mask:255},w,255,A.KEEP,A.KEEP,A.REPLACE)}stencilModeForClipping(w){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(w);const A=this.context.gl;return new Sa({func:A.EQUAL,mask:255},this._tileClippingMaskIDs[w.key],0,A.KEEP,A.KEEP,A.REPLACE)}stencilConfigForOverlap(w){const A=this.context.gl,F=w.sort((X,ae)=>ae.overscaledZ-X.overscaledZ),V=F[F.length-1].overscaledZ,Z=F[0].overscaledZ-V+1;if(Z>1){this.currentStencilSource=void 0,this.nextStencilID+Z>256&&this.clearStencil();const X={};for(let ae=0;aethis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((w,A)=>w+A/this._fpsHistory.length,0))}render(w,A){const F=o.o.now();this._dt=F-this._timeStamp,this._timeStamp=F,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=w.map.repaint,this.style=w,this.options=A;const V=this.style._mergedLayers,Z=!(!this.terrain||!this.terrain.enabled),X=()=>this.style._getOrder(Z).filter(Ys=>{const Es=V[Ys];return!(Es.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[Es.type]});let ae=X(),pe=!1,ke=!1,Me=null,Ke=0,He=!1;for(const Ys of ae){const Es=V[Ys];Es.visibility!=="none"&&(Es.type==="circle"?pe=!0:Es.type==="building"?(Me=Es,++Ke):Es.type==="symbol"&&(Es.hasOcclusionOpacityProperties?ke=!0:pe=!0))}this.updateEmissiveMode();let tt=ae.map(Ys=>V[Ys]);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 Ys in ct){const Es=ct[Ys];Es.used&&(Es.prepare(this.context),Es.getSource().usedInConflation&&++Ke)}let ot=!1;for(const Ys of tt)Ys.isHidden(this.transform.zoom)||(Ys.type==="clip"&&(ot=!0),this.prepareLayer(Ys));const wt={},_t={},Rt={},$t={},kt={};for(const Ys in ct){const Es=ct[Ys];wt[Ys]=Es.getVisibleCoordinates(),_t[Ys]=wt[Ys].slice().reverse(),Rt[Ys]=Es.getVisibleCoordinates(!0).reverse(),$t[Ys]=Es.getShadowCasterCoordinates(),kt[Ys]=Es.sortCoordinatesByDistance(wt[Ys])}const ks=Ys=>{const Es=this.style.getLayerSourceCache(Ys);return Es&&Es.used?Es.getSource():null};if(Ke||ot||this._clippingActiveLastFrame){const Ys=[],Es=[];let hn=0;for(const fn of tt)this.isSourceForClippingOrConflation(fn,ks(fn))&&(Ys.push(fn),Es.push(hn)),hn++;if(Ys&&(ot||Ys.length>1)||this._clippingActiveLastFrame){ot=!1;const fn=[];for(let jn=0;jn0){const fn=ks(Es);fn&&(this.minCutoffZoom=Math.max(fn.minzoom,this.minCutoffZoom)),Es.minzoom&&(this.minCutoffZoom=Math.max(Es.minzoom,this.minCutoffZoom))}Es.is3D(Z)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=Ys),this._lastOcclusionLayer=Ys)}const Jt=this.style&&this.style.fog;Jt?(this._fogVisible=Jt.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Jt.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(Rt),this.opaquePassCutoff=0,ae=X(),tt=ae.map(Ys=>V[Ys]));const ws=this._shadowRenderer;if(ws){ws.updateShadowParameters(this.transform,this.style.directionalLight);for(const Ys in ct)for(const Es of wt[Ys]){let hn={min:0,max:0};this.terrain&&(hn=this.terrain.getMinMaxForTile(Es)||hn),ws.addShadowReceiver(Es.toUnwrapped(),hn.min,hn.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 nk(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const Vt=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),Xt=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(Vt&&!this._snow&&(this._snow=new Ps(this)),!Vt&&this._snow&&(this._snow.destroy(),delete this._snow),Xt&&!this._rain&&(this._rain=new lt(this)),!Xt&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),Me){this.buildingTileBorderManager||(this.buildingTileBorderManager=new $x);const Ys=this.style.getLayerSourceCache(Me);this.buildingTileBorderManager.updateBorders(Ys,Me)}if(!Xe.has(this.context.gl))return;this.renderPass="offscreen";for(const Ys of tt){const Es=w.getLayerSourceCache(Ys);if(!Ys.hasOffscreenPass()||Ys.isHidden(this.transform.zoom))continue;const hn=Es?_t[Es.id]:void 0;(Ys.type==="custom"||Ys.type==="raster"||Ys.type==="raster-particle"||Ys.isSky()||hn&&hn.length)&&this.renderLayer(this,Es,Ys,hn)}this.depthRangeFor3D=[0,1-(tt.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,$t)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const ms=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),Us=(()=>{if(A.showOverdrawInspector)return o.aq.black;const Ys=this.style.fog;if(Ys&&this.transform.projection.supportsFog){const Es=this.style.getLut(Ys.scope);if(!ms){const hn=Ys.properties.get("color-use-theme")==="none",fn=Ys.properties.get("color").toNonPremultipliedRenderColor(hn?null:Es).toArray01();return new o.aq(...fn)}if(ms){const hn=Ys.properties.get("space-color-use-theme")==="none",fn=Ys.properties.get("space-color").toNonPremultipliedRenderColor(hn?null:Es).toArray01();return new o.aq(...fn)}}return o.aq.transparent})();if(this.context.clear({color:Us,depth:1}),this.clearStencil(),this._showOverdrawInspector=A.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&ms&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=ae.length-1;this.currentLayer>=0;this.currentLayer--){const Ys=tt[this.currentLayer],Es=w.getLayerSourceCache(Ys);if(Ys.isSky())continue;const hn=Es?(Ys.is3D(Z)?kt:_t)[Es.id]:void 0;this._renderTileClippingMasks(Ys,Es,hn),this.renderLayer(this,Es,Ys,hn)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&ms&&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 hn=this.currentLayer;this.depthOcclusion=!0;for(const fn of this.layersWithOcclusionOpacity){this.currentLayer=fn;const jn=tt[this.currentLayer],yr=w.getLayerSourceCache(jn),rr=yr?_t[yr.id]:void 0;this.terrain||this._renderTileClippingMasks(jn,yr,yr?wt[yr.id]:void 0),this.renderLayer(this,yr,jn,rr)}this.depthOcclusion=!1,this.currentLayer=hn,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 Ys=null;tt.forEach(Es=>{const hn=w.getLayerSourceCache(Es);hn&&!Es.isHidden(this.transform.zoom)&&hn.getVisibleCoordinates().length&&(!Ys||Ys.getSource().maxzoom0?A.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(w,A,F){const V=F===void 0?this.terrain&&this.terrain.renderingToTexture:F,Z=[];return this.style&&this.style.enable3dLights()&&(w==="globeRaster"||w==="terrainRaster"?(Z.push("LIGHTING_3D_MODE"),Z.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):V||Z.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(Z.push("TERRAIN"),this.linearFloatFilteringSupported()&&Z.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&Z.push("GLOBE"),!this._fogVisible||V||A!==void 0&&!A||Z.push("FOG"),V&&Z.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&Z.push("OVERDRAW_INSPECTOR"),Z}getOrCreateProgram(w,A){this.cache=this.cache||{};const F=A&&A.defines||[],V=A&&A.config,Z=this.currentGlobalDefines(w,A&&A.overrideFog,A&&A.overrideRtt).concat(F),X=Vn.cacheKey(fw[w],w,Z,V);return this.cache[X]||(this.cache[X]=new Vn(this.context,w,fw[w],V,Sm[w],Z)),this.cache[X]}setCustomLayerDefaults(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.frontFace.setDefault(),this.context.cullFaceSide.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault()}setBaseState(){const w=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(w.FUNC_ADD)}initDebugOverlayCanvas(){this.debugOverlayCanvas==null&&(this.debugOverlayCanvas=document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new o.T(this.context,this.debugOverlayCanvas,this.context.gl.RGBA8))}destroy(){this._terrain&&this._terrain.destroy(),this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0),this.globeSharedBuffers&&this.globeSharedBuffers.destroy(),this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy(),this._wireframeDebugCache.destroy(),this.depthFBO&&(this.depthFBO.destroy(),this.depthFBO=void 0,this.depthTexture=void 0),this.emptyDepthTexture&&this.emptyDepthTexture.destroy()}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(w,A){if(this.style.enable3dLights()){const F=this.style.directionalLight,V=this.style.ambientLight;if(F&&V){const Z=((X,ae,pe)=>{const ke=X.properties.get("direction"),Me=X.properties.get("color-use-theme")==="none",Ke=X.properties.get("color").toNonPremultipliedRenderColor(Me?null:pe.getLut(X.scope)).toArray01(),He=X.properties.get("intensity"),tt=ae.properties.get("color-use-theme")==="none",ct=ae.properties.get("color").toNonPremultipliedRenderColor(tt?null:pe.getLut(ae.scope)).toArray01(),ot=ae.properties.get("intensity"),wt=[ke.x,ke.y,ke.z],_t=o.dD(ct,ot),Rt=o.dD(Ke,He);return{u_lighting_ambient_color:_t,u_lighting_directional_dir:wt,u_lighting_directional_color:Rt,u_ground_radiance:Ts(wt,Rt,_t)}})(F,V,this.style);A.setLightsUniformValues(w,Z)}}}uploadCommonUniforms(w,A,F,V,Z){if(this.uploadCommonLightUniforms(w,A),this.terrain&&this.terrain.renderingToTexture)return;const X=this.style.fog;if(X){const ae=X.getOpacity(this.transform.pitch),pe=((ke,Me,Ke,He,tt,ct,ot,wt,_t,Rt,$t,kt)=>{const ks=ke.transform,Jt=Me.properties.get("color-use-theme")==="none",ws=Me.properties.get("color").toNonPremultipliedRenderColor(Jt?null:ke.style.getLut(Me.scope)).toArray01();ws[3]=He;const Vt=ke.frameCounter/1e3%1,[Xt,ms]=Me.properties.get("vertical-range");return{u_fog_matrix:Ke?ks.calculateFogTileMatrix(Ke):kt||ke.identityMat,u_fog_range:Me.getFovAdjustedRange(ks._fov),u_fog_color:ws,u_fog_horizon_blend:Me.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(Xt,ms),ms],u_fog_temporal_offset:Vt,u_frustum_tl:tt,u_frustum_tr:ct,u_frustum_br:ot,u_frustum_bl:wt,u_globe_pos:_t,u_globe_radius:Rt,u_viewport:$t,u_globe_transition:o.al(ks.zoom),u_is_globe:+(ks.projection.name==="globe")}})(this,X,F,ae,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],V);A.setFogUniformValues(w,pe)}Z&&A.setCutoffUniformValues(w,Z.uniformValues)}setTileLoadedFlag(w){this.tileLoaded=w}saveCanvasCopy(){const w=this.canvasCopy();w&&(this.frameCopies.push(w),this.tileLoaded=!1)}canvasCopy(){const w=this.context.gl,A=w.createTexture();return w.bindTexture(w.TEXTURE_2D,A),w.copyTexImage2D(w.TEXTURE_2D,0,w.RGBA,0,0,w.drawingBufferWidth,w.drawingBufferHeight,0),A}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,A=this._backgroundTiles={},F=this.transform.coveringTiles({tileSize:512});for(const V of F)A[V.key]=w[V.key]||new o.b0(V,512,this.transform.tileZoom,this,void 0,this.worldview);return A}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(w,A){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")&&(!A||A.type!=="batched-model")))}isTileAffectedByFog(w){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let A=this._cachedTileFogOpacities[w.key];return A||(this._cachedTileFogOpacities[w.key]=A=this.style.fog.getOpacityForTile(w)),A[0]>=Zn||A[1]>=Zn}setupDepthForOcclusion(w,A,F){const V=this.context,Z=V.gl,X=!!F;var ae;F||(F={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),V.activeTexture.set(Z.TEXTURE3),w&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(Z.NEAREST,Z.CLAMP_TO_EDGE),F.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],F.u_depth_range_unpack=[2/((ae=this.depthRangeFor3D)[1]-ae[0]),-1-2*ae[0]/(ae[1]-ae[0])],F.u_occluder_half_size=.5*this.occlusionParams.occluderSize,F.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(Z.NEAREST,Z.CLAMP_TO_EDGE),V.activeTexture.set(Z.TEXTURE0),X||A.setTerrainUniformValues(V,F)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const w=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=w?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function hi(R,w){let A=!1,F=null;const V=()=>{F=null,A&&(R(),F=setTimeout(V,w),A=!1)};return()=>(A=!0,F||V(),F)}class Du{constructor(w){this._hashName=w&&encodeURIComponent(w),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=hi(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 A=bl(w);if(this._hashName){const F=this._hashName;let V=!1;const Z=location.hash.slice(1).split("&").map(X=>{const ae=X.split("=")[0];return ae===F?(V=!0,`${ae}=${A}`):X}).filter(X=>X);return V||Z.push(`${F}=${A}`),`#${Z.join("&")}`}return`#${A}`}_getCurrentHash(){const w=location.hash.replace("#","");if(this._hashName){let A;return w.split("&").map(F=>F.split("=")).forEach(F=>{F[0]===this._hashName&&(A=F)}),(A&&A[1]||"").split("/")}return w.split("/")}_onHashChange(){const w=this._map;if(!w)return!1;const A=this._getCurrentHash();if(A.length>=3&&!A.some(F=>isNaN(Number(F)))){const F=w.dragRotate.isEnabled()&&w.touchZoomRotate.isEnabled()?+(A[3]||0):w.getBearing();return w.jumpTo({center:[+A[2],+A[1]],zoom:+A[0],bearing:F,pitch:+(A[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function bl(R,w){const A=R.getCenter(),F=Math.round(100*R.getZoom())/100,V=Math.ceil((F*Math.LN2+Math.log(512/360/.5))/Math.LN10),Z=Math.pow(10,V),X=Math.round(A.lng*Z)/Z,ae=Math.round(A.lat*Z)/Z,pe=R.getBearing(),ke=R.getPitch();let Me=w?`/${X}/${ae}/${F}`:`${F}/${ae}/${X}`;return(pe||ke)&&(Me+="/"+Math.round(10*pe)/10),ke&&(Me+=`/${Math.round(ke)}`),Me}const Of={linearity:.3,easing:o.eN(0,0,.3,1)},M0=Object.assign({deceleration:2500,maxSpeed:1400},Of),Sr=Object.assign({deceleration:20,maxSpeed:1400},Of),wn=Object.assign({deceleration:1e3,maxSpeed:360},Of),Fn=Object.assign({deceleration:1e3,maxSpeed:90},Of);class _i{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,A=o.o.now();for(;w.length>0&&A-w[0].time>160;)w.shift()}_onMoveEnd(w){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const A={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:Z}of this._inertiaBuffer)A.zoom+=Z.zoomDelta||0,A.bearing+=Z.bearingDelta||0,A.pitch+=Z.pitchDelta||0,Z.panDelta&&A.pan._add(Z.panDelta),Z.around&&(A.around=Z.around),Z.pinchAround&&(A.pinchAround=Z.pinchAround);const F=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,V={};if(A.pan.mag()){const Z=Uo(A.pan.mag(),F,Object.assign({},M0,w||{}));V.offset=A.pan.mult(Z.amount/A.pan.mag()),V.center=this._map.transform.center,Pi(V,Z)}if(A.zoom){const Z=Uo(A.zoom,F,Sr);V.zoom=this._map.transform.zoom+Z.amount,Pi(V,Z)}if(A.bearing){const Z=Uo(A.bearing,F,wn);V.bearing=this._map.transform.bearing+o.aC(Z.amount,-179,179),Pi(V,Z)}if(A.pitch){const Z=Uo(A.pitch,F,Fn);V.pitch=this._map.transform.pitch+Z.amount,Pi(V,Z)}if(V.zoom||V.bearing){const Z=A.pinchAround===void 0?A.around:A.pinchAround;V.around=Z?this._map.unproject(Z):this._map.getCenter()}return this.clear(),V.noMoveStart=!0,V}}function Pi(R,w){(!R.duration||R.durationA.unproject(pe)),ae=Z.reduce((pe,ke,Me,Ke)=>pe.add(ke.div(Ke.length)),new o.P(0,0));super(w,{points:Z,point:ae,lngLats:X,lngLat:A.unproject(ae),originalEvent:F}),this._defaultPrevented=!1}}class Em extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(w,A){super("wheel",{originalEvent:A}),this._defaultPrevented=!1}}class Mc{constructor(w,A){this._map=w,this._clickTolerance=A.clickTolerance}reset(){this._mousedownPos=void 0}wheel(w){return this._firePreventable(new Em(this._map,w))}mousedown(w,A){return this._mousedownPos=A,this._firePreventable(new Xi(w.type,this._map,w))}mouseup(w){this._map.fire(new Xi(w.type,this._map,w))}preclick(w){const A=new MouseEvent("preclick",w);this._map.fire(new Xi(A.type,this._map,A))}click(w,A){this._mousedownPos&&this._mousedownPos.dist(A)>=this._clickTolerance||(this.preclick(w),this._map.fire(new Xi(w.type,this._map,w)))}dblclick(w){return this._firePreventable(new Xi(w.type,this._map,w))}mouseover(w){this._map.fire(new Xi(w.type,this._map,w))}mouseout(w){this._map.fire(new Xi(w.type,this._map,w))}touchstart(w){return this._firePreventable(new dl(w.type,this._map,w))}touchmove(w){this._map.fire(new dl(w.type,this._map,w))}touchend(w){this._map.fire(new dl(w.type,this._map,w))}touchcancel(w){this._map.fire(new dl(w.type,this._map,w))}_firePreventable(w){if(this._map.fire(w),w.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class I1{constructor(w){this._map=w}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(w){this._map.fire(new Xi(w.type,this._map,w))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Xi("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(w){this._delayContextMenu?this._contextMenuEvent=w:this._map.fire(new Xi(w.type,this._map,w)),this._map.listens("contextmenu")&&w.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class D6{constructor(w,A){this._map=w,this._el=w.getCanvasContainer(),this._container=w.getContainer(),this._clickTolerance=A.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(w,A){this.isEnabled()&&w.shiftKey&&w.button===0&&(C(),this._startPos=this._lastPos=A,this._active=!0)}mousemoveWindow(w,A){if(!this._active)return;const F=A,V=this._startPos,Z=this._lastPos;if(!V||!Z||Z.equals(F)||!this._box&&F.dist(V){this._box&&(this._box.style.transform=`translate(${X}px,${pe}px)`,this._box.style.width=ae-X+"px",this._box.style.height=ke-pe+"px")})}mouseupWindow(w,A){if(!this._active)return;const F=this._startPos,V=A;if(F&&w.button===0){if(this.reset(),P(),F.x!==V.x||F.y!==V.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:w})),{cameraAnimation:Z=>Z.fitScreenCoordinates(F,V,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,A){return this._map.fire(new o.C(w,{originalEvent:A}))}}function O6(R,w){const A={};for(let F=0;Fthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=w.timeStamp),F.length===this.numTouches&&(this.centroid=function(V){const Z=new o.P(0,0);for(const X of V)Z._add(X);return Z.div(V.length)}(A),this.touches=O6(F,A)))}touchmove(w,A,F){if(this.aborted||!this.centroid)return;const V=O6(F,A);for(const Z in this.touches){const X=V[Z];(!X||X.dist(this.touches[Z])>30)&&(this.aborted=!0)}}touchend(w,A,F){if((!this.centroid||w.timeStamp-this.startTime>500)&&(this.aborted=!0),F.length===0){const V=!this.aborted&&this.centroid;if(this.reset(),V)return V}}}class Tw{constructor(w){this.singleTap=new R1(w),this.numTaps=w.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(w,A,F){this.singleTap.touchstart(w,A,F)}touchmove(w,A,F){this.singleTap.touchmove(w,A,F)}touchend(w,A,F){const V=this.singleTap.touchend(w,A,F);if(V){const Z=w.timeStamp-this.lastTime<500,X=!this.lastTap||this.lastTap.dist(V)<30;if(Z&&X||this.reset(),this.count++,this.lastTime=w.timeStamp,this.lastTap=V,this.count===this.numTaps)return this.reset(),V}}}class pC{constructor(){this._zoomIn=new Tw({numTouches:1,numTaps:2}),this._zoomOut=new Tw({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(w,A,F){this._zoomIn.touchstart(w,A,F),this._zoomOut.touchstart(w,A,F)}touchmove(w,A,F){this._zoomIn.touchmove(w,A,F),this._zoomOut.touchmove(w,A,F)}touchend(w,A,F){const V=this._zoomIn.touchend(w,A,F),Z=this._zoomOut.touchend(w,A,F);return V?(this._active=!0,w.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:X=>X.easeTo({duration:300,zoom:X.getZoom()+1,around:X.unproject(V)},{originalEvent:w})}):Z?(this._active=!0,w.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:X=>X.easeTo({duration:300,zoom:X.getZoom()-1,around:X.unproject(Z)},{originalEvent:w})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const WO=0,Jq=2,eV={[WO]:1,[Jq]:2},u2={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class F6{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,A){return!1}_move(w,A){return{}}mousedown(w,A){if(this._lastPoint)return;const F=O(w);this._correctButton(w,F)&&(this._lastPoint=A,this._eventButton=F)}mousemoveWindow(w,A){const F=this._lastPoint;if(F){if(w.preventDefault(),this._eventButton!=null&&function(V,Z){const X=eV[Z];return V.buttons===void 0||(V.buttons&X)!==X}(w,this._eventButton))this.reset();else if(this._moved||!(A.dist(F)0&&(this._active=!0);const V=O6(F,A),Z=new o.P(0,0),X=new o.P(0,0);let ae=0;for(const ke in V){const Me=V[ke],Ke=this._touches[ke];Ke&&(Z._add(Me),X._add(Me.sub(Ke)),ae++,V[ke]=Me)}if(this._touches=V,ae{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class B6{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(w){}_move(w,A,F){return{}}touchstart(w,A,F){this._firstTwoTouches||F.length<2||(this._firstTwoTouches=[F[0].identifier,F[1].identifier],this._start([A[0],A[1]]))}touchmove(w,A,F){const V=this._firstTwoTouches;if(!V)return;w.preventDefault();const[Z,X]=V,ae=eu(F,A,Z),pe=eu(F,A,X);if(!ae||!pe)return;const ke=this._aroundCenter?null:ae.add(pe).div(2);return this._move([ae,pe],ke,w)}touchend(w,A,F){if(!this._firstTwoTouches)return;const[V,Z]=this._firstTwoTouches,X=eu(F,A,V),ae=eu(F,A,Z);X&&ae||(this._active&&P(),this.reset())}touchcancel(){this.reset()}enable(w){this._enabled=!0,this._aroundCenter=!!w&&w.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function eu(R,w,A){for(let F=0;FMath.abs(R.x)}class nV extends B6{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,$6(w[0].sub(w[1]))&&(this._valid=!1)}_move(w,A,F){const V=this._lastPoints;if(!V)return;const Z=w[0].sub(V[0]),X=w[1].sub(V[1]);return this._map._cooperativeGestures&&!o.eO()&&F.touches.length<3||(this._valid=this.gestureBeginsVertically(Z,X,F.timeStamp),!this._valid)?void 0:(this._lastPoints=w,this._active=!0,{pitchDelta:(Z.y+X.y)/2*-.5})}gestureBeginsVertically(w,A,F){if(this._valid!==void 0)return this._valid;const V=w.mag()>=2,Z=A.mag()>=2;if(!V&&!Z)return;if(!V||!Z)return this._firstMove==null&&(this._firstMove=F),F-this._firstMove<100&&void 0;const X=w.y>0==A.y>0;return $6(w)&&$6(A)&&X}}const rV={panStep:100,bearingStep:15,pitchStep:10};class IS{constructor(){const w=rV;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 A=0,F=0,V=0,Z=0,X=0;switch(w.keyCode){case 61:case 107:case 171:case 187:A=1;break;case 189:case 109:case 173:A=-1;break;case 37:w.shiftKey?F=-1:(w.preventDefault(),Z=-1);break;case 39:w.shiftKey?F=1:(w.preventDefault(),Z=1);break;case 38:w.shiftKey?V=1:(w.preventDefault(),X=-1);break;case 40:w.shiftKey?V=-1:(w.preventDefault(),X=1);break;default:return}return this._rotationDisabled&&(F=0,V=0),{cameraAnimation:ae=>{const pe=ae.getZoom();ae.easeTo({duration:300,easeId:"keyboardHandler",easing:aV,zoom:A?Math.round(pe)+A*(w.shiftKey?2:1):pe,bearing:ae.getBearing()+F*this._bearingStep,pitch:ae.getPitch()+V*this._pitchStep,offset:[-Z*this._panStep,-X*this._panStep],center:ae.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 aV(R){return R*(2-R)}const RS=4.000244140625,iV=1/450;class XO{constructor(w,A){this._map=w,this._el=w.getCanvasContainer(),this._handler=A,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=iV,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 A=w.deltaMode===WheelEvent.DOM_DELTA_LINE?40*w.deltaY:w.deltaY;const F=o.o.now(),V=F-(this._lastWheelEventTime||0);this._lastWheelEventTime=F,A!==0&&A%RS===0?this._type="wheel":A!==0&&Math.abs(A)<4?this._type="trackpad":V>400?(this._type=null,this._lastValue=A,this._timeout=window.setTimeout(this._onTimeout,40,w)):this._type||(this._type=Math.abs(V*A)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,A+=this._lastValue)),w.shiftKey&&A&&(A/=4),this._type&&(this._lastWheelEvent=w,this._delta-=A,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 A=L(this._el,w);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:A,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 A=()=>w._terrainEnabled()&&this._aroundCoord?w.computeZoomRelativeTo(this._aroundCoord):w.zoom;if(this._delta!==0){const ke=this._type==="wheel"&&Math.abs(this._delta)>RS?this._wheelZoomRate:this._defaultZoomRate;let Me=2/(1+Math.exp(-Math.abs(this._delta*ke)));this._delta<0&&Me!==0&&(Me=1/Me);const Ke=A(),He=Math.pow(2,Ke),tt=typeof this._targetZoom=="number"?w.zoomScale(this._targetZoom):He;this._targetZoom=Math.min(w.maxZoom,Math.max(w.minZoom,w.scaleZoom(tt*Me))),this._type==="wheel"&&(this._startZoom=Ke,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const F=typeof this._targetZoom=="number"?this._targetZoom:A(),V=this._startZoom,Z=this._easing;let X,ae=!1;if(this._type==="wheel"&&V&&Z){const ke=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),Me=Z(ke);X=o.am(V,F,Me),ke<1?this._frameId||(this._frameId=!0):ae=!0}else X=F,ae=!0;this._active=!0,ae&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let pe=X-A();return pe*this._lastDelta<0&&(pe=0),{noInertia:!0,needsRenderFrame:!ae,zoomDelta:pe,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(w){let A=o.eP;if(this._prevEase){const F=this._prevEase,V=(o.o.now()-F.start)/F.duration,Z=F.easing(V+.01)-F.easing(V),X=.27/Math.sqrt(Z*Z+1e-4)*.01,ae=Math.sqrt(.0729-X*X);A=o.eN(X,ae,.25,1)}return this._prevEase={start:o.o.now(),duration:w,easing:A},A}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 QO{constructor(w,A){this._clickZoom=w,this._tapZoom=A}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 JO{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(w,A){return w.preventDefault(),{cameraAnimation:F=>{F.easeTo({duration:300,zoom:F.getZoom()+(w.shiftKey?-1:1),around:F.unproject(A)},{originalEvent:w})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Nee{constructor(){this._tap=new Tw({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,A,F){this._swipePoint||(this._tapTime&&w.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?F.length>0&&(this._swipePoint=A[0],this._swipeTouch=F[0].identifier):this._tap.touchstart(w,A,F))}touchmove(w,A,F){if(this._tapTime){if(this._swipePoint){if(F[0].identifier!==this._swipeTouch)return;const V=A[0],Z=V.y-this._swipePoint.y;return this._swipePoint=V,w.preventDefault(),this._active=!0,{zoomDelta:Z/128}}}else this._tap.touchmove(w,A,F)}touchend(w,A,F){this._tapTime?this._swipePoint&&F.length===0&&this.reset():this._tap.touchend(w,A,F)&&(this._tapTime=w.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class oV{constructor(w,A,F){this._el=w,this._mousePan=A,this._touchPan=F}enable(w){this._inertiaOptions=w||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("mapboxgl-touch-drag-pan")}disable(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan")}isEnabled(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()}isActive(){return this._mousePan.isActive()||this._touchPan.isActive()}}class kee{constructor(w,A,F){this._pitchWithRotate=w.pitchWithRotate,this._mouseRotate=A,this._mousePitch=F}enable(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}}class See{constructor(w,A,F,V){this._el=w,this._touchZoom=A,this._touchRotate=F,this._tapDragZoom=V,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 U6=R=>R.zoom||R.drag||R.pitch||R.rotate;class Cee extends o.C{}class Aee{constructor(){this.constants=[1,1,.01],this.radius=0}setup(w,A){const F=o.ax([],A,w);this.radius=o.ai(F[2]<0?o.eR([],F,this.constants):[F[0],F[1],0])}projectRay(w){o.eR(w,w,this.constants),o.ay(w,w),o.eS(w,w,this.constants);const A=o.bJ([],w,this.radius);if(A[2]>0){const F=o.bJ([],[0,0,1],o.bi(A,[0,0,1])),V=o.bJ([],o.ay([],[A[0],A[1],0]),this.radius),Z=o.cT([],A,o.bJ([],o.ax([],o.cT([],V,F),A),2));A[0]=Z[0],A[1]=Z[1]}return A}}function q6(R){return R.panDelta&&R.panDelta.mag()||R.zoomDelta||R.bearingDelta||R.pitchDelta}class Tee{constructor(w,A){this._map=w,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new _i(w),this._bearingSnap=A.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new Aee,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(A),o.aZ(["handleEvent","handleWindowEvent"],this);const F=this._el;this._listeners=[[F,"touchstart",{passive:!0}],[F,"touchmove",{passive:!1}],[F,"touchend",void 0],[F,"touchcancel",void 0],[F,"mousedown",void 0],[F,"mousemove",void 0],[F,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[F,"mouseover",void 0],[F,"mouseout",void 0],[F,"dblclick",void 0],[F,"click",void 0],[F,"keydown",{capture:!1}],[F,"keyup",void 0],[F,"wheel",{passive:!1}],[F,"contextmenu",void 0],[window,"blur",void 0]];for(const[V,Z,X]of this._listeners){const ae=V===document?this.handleWindowEvent:this.handleEvent;V.addEventListener(Z,ae,X)}}destroy(){for(const[w,A,F]of this._listeners){const V=w===document?this.handleWindowEvent:this.handleEvent;w.removeEventListener(A,V,F)}}_addDefaultHandlers(w){const A=this._map,F=A.getCanvasContainer();this._add("mapEvent",new Mc(A,w));const V=A.boxZoom=new D6(A,w);this._add("boxZoom",V);const Z=new pC,X=new JO;A.doubleClickZoom=new QO(X,Z),this._add("tapZoom",Z),this._add("clickZoom",X);const ae=new Nee;this._add("tapDragZoom",ae);const pe=A.touchPitch=new nV(A);this._add("touchPitch",pe);const ke=new KO(w),Me=new z6(w);A.dragRotate=new kee(w,ke,Me),this._add("mouseRotate",ke,["mousePitch"]),this._add("mousePitch",Me,["mouseRotate"]);const Ke=new D1(w),He=new tV(A,w);A.dragPan=new oV(F,Ke,He),this._add("mousePan",Ke),this._add("touchPan",He,["touchZoom","touchRotate"]);const tt=new PS,ct=new sV;A.touchZoomRotate=new See(F,ct,tt,ae),this._add("touchRotate",tt,["touchPan","touchZoom"]),this._add("touchZoom",ct,["touchPan","touchRotate"]),this._add("blockableMapEvent",new I1(A));const ot=A.scrollZoom=new XO(A,this);this._add("scrollZoom",ot,["mousePan"]);const wt=A.keyboard=new IS;this._add("keyboard",wt);for(const _t of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])w.interactive&&w[_t]&&A[_t].enable(w[_t])}_add(w,A,F){this._handlers.push({handlerName:w,handler:A,allowed:F}),this._handlersById[w]=A}stop(w){if(!this._updatingCamera){for(const{handler:A}of this._handlers)A.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!!U6(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(w,A,F){for(const V in w)if(V!==F&&(!A||A.indexOf(V)<0))return!0;return!1}handleWindowEvent(w){this.handleEvent(w,`${w.type}Window`)}_getMapTouches(w){const A=[];for(const F of w)this._el.contains(F.target)&&A.push(F);return A}handleEvent(w,A){this._updatingCamera=!0;const F=w.type==="renderFrame",V=F?void 0:w,Z={needsRenderFrame:!1},X={},ae={},pe=w.touches?this._getMapTouches(w.touches):void 0,ke=pe?I(this._el,pe):F?void 0:L(this._el,w);for(const{handlerName:He,handler:tt,allowed:ct}of this._handlers){if(!tt.isEnabled())continue;let ot;this._blockedByActive(ae,ct,He)?tt.reset():tt[A||w.type]&&(ot=tt[A||w.type](w,ke,pe),this.mergeHandlerResult(Z,X,ot,He,V),ot&&ot.needsRenderFrame&&this._triggerRenderFrame()),(ot||tt.isActive())&&(ae[He]=tt)}const Me={};for(const He in this._previousActiveHandlers)ae[He]||(Me[He]=V);this._previousActiveHandlers=ae,(Object.keys(Me).length||q6(Z))&&(this._changes.push([Z,X,Me]),this._triggerRenderFrame()),(Object.keys(ae).length||q6(Z))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:Ke}=Z;Ke&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Ke(this._map))}mergeHandlerResult(w,A,F,V,Z){if(!F)return;Object.assign(w,F);const X={handlerName:V,originalEvent:F.originalEvent||Z};F.zoomDelta!==void 0&&(A.zoom=X),F.panDelta!==void 0&&(A.drag=X),F.pitchDelta!==void 0&&(A.pitch=X),F.bearingDelta!==void 0&&(A.rotate=X)}_applyChanges(){const w={},A={},F={};for(const[V,Z,X]of this._changes)V.panDelta&&(w.panDelta=(w.panDelta||new o.P(0,0))._add(V.panDelta)),V.zoomDelta&&(w.zoomDelta=(w.zoomDelta||0)+V.zoomDelta),V.bearingDelta&&(w.bearingDelta=(w.bearingDelta||0)+V.bearingDelta),V.pitchDelta&&(w.pitchDelta=(w.pitchDelta||0)+V.pitchDelta),V.around!==void 0&&(w.around=V.around),V.aroundCoord!==void 0&&(w.aroundCoord=V.aroundCoord),V.pinchAround!==void 0&&(w.pinchAround=V.pinchAround),V.noInertia&&(w.noInertia=V.noInertia),Object.assign(A,Z),Object.assign(F,X);this._updateMapTransform(w,A,F),this._changes=[]}_updateMapTransform(w,A,F){const V=this._map,Z=V.transform,X=Rt=>[Rt.x,Rt.y,Rt.z];if((()=>{const Rt=this._eventsInProgress.drag;return Rt&&!this._handlersById[Rt.handlerName].isActive()})()&&!q6(w)){const Rt=Z.zoom;Z.cameraElevationReference="sea",this._originalZoom!=null&&Z._orthographicProjectionAtLowPitch&&Z.projection.name!=="globe"&&Z.pitch===0?(Z.cameraElevationReference="ground",Z.zoom=this._originalZoom):(Z.recenterOnTerrain(),Z.cameraElevationReference="ground"),Rt!==Z.zoom&&this._map._update(!0)}if(Z._isCameraConstrained&&V._stop(!0),!q6(w))return void this._fireEvents(A,F,!0);let{panDelta:ae,zoomDelta:pe,bearingDelta:ke,pitchDelta:Me,around:Ke,aroundCoord:He,pinchAround:tt}=w;Z._isCameraConstrained&&(pe>0&&(pe=0),Z._isCameraConstrained=!1),tt!==void 0&&(Ke=tt),(pe||(Rt=>A[Rt]&&!this._eventsInProgress[Rt])("drag"))&&Ke&&(this._dragOrigin=X(Z.pointCoordinate3D(Ke)),this._originalZoom=Z.zoom,this._trackingEllipsoid.setup(Z._camera.position,this._dragOrigin)),Z.cameraElevationReference="sea",V._stop(!0),Ke=Ke||V.transform.centerPoint,ke&&(Z.bearing+=ke),Me&&(Z.pitch+=Me),Z._updateCameraState();const ct=[0,0,0];if(ae)if(Z.projection.name==="mercator"){const Rt=this._trackingEllipsoid.projectRay(Z.screenPointToMercatorRay(Ke).dir),$t=this._trackingEllipsoid.projectRay(Z.screenPointToMercatorRay(Ke.sub(ae)).dir);ct[0]=$t[0]-Rt[0],ct[1]=$t[1]-Rt[1]}else{const Rt=Z.pointCoordinate(Ke);if(Z.projection.name==="globe"){ae=ae.rotate(-Z.angle);const $t=Z._pixelsPerMercatorPixel/Z.worldSize;ct[0]=-ae.x*o.eQ(o.bV(Rt.y))*$t,ct[1]=-ae.y*o.eQ(Z.center.lat)*$t}else{const $t=Z.pointCoordinate(Ke.sub(ae));Rt&&$t&&(ct[0]=$t.x-Rt.x,ct[1]=$t.y-Rt.y)}}const ot=Z.zoom,wt=[0,0,0];if(pe){const Rt=X(He||Z.pointCoordinate3D(Ke)),$t={dir:o.ay([],o.ax([],Rt,Z._camera.position))};if($t.dir[2]<0){const kt=Z.zoomDeltaToMovement(Rt,pe);o.bJ(wt,$t.dir,kt)}}const _t=o.cT(ct,ct,wt);Z._translateCameraConstrained(_t),pe&&Math.abs(Z.zoom-ot)>1e-4&&Z.recenterOnTerrain(),Z.cameraElevationReference="ground",this._map._update(),w.noInertia||this._inertia.record(w),this._fireEvents(A,F,!0)}_fireEvents(w,A,F){const V=U6(this._eventsInProgress),Z=U6(w),X={};for(const Me in w){const{originalEvent:Ke}=w[Me];this._eventsInProgress[Me]||(X[`${Me}start`]=Ke),this._eventsInProgress[Me]=w[Me]}!V&&Z&&this._fireEvent("movestart",Z.originalEvent);for(const Me in X)this._fireEvent(Me,X[Me]);Z&&this._fireEvent("move",Z.originalEvent);for(const Me in w){const{originalEvent:Ke}=w[Me];this._fireEvent(Me,Ke)}const ae={};let pe;for(const Me in this._eventsInProgress){const{handlerName:Ke,originalEvent:He}=this._eventsInProgress[Me];this._handlersById[Ke].isActive()||(delete this._eventsInProgress[Me],pe=A[Ke]||He,ae[`${Me}end`]=pe)}for(const Me in ae)this._fireEvent(Me,ae[Me]);const ke=U6(this._eventsInProgress);if(F&&(V||Z)&&!ke){this._updatingCamera=!0;const Me=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Ke=He=>He!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new Cee("renderFrame",{timeStamp:w})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const lV="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class Eee extends o.E{constructor(w,A){super(),this._moving=!1,this._zooming=!1,this.transform=w,this._bearingSnap=A.bearingSnap,this._respectPrefersReducedMotion=A.respectPrefersReducedMotion!==!1,o.aZ(["_renderFrameCallback"],this)}getCenter(){return new o.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(w,A){return this.jumpTo({center:w},A)}panBy(w,A,F){return w=o.P.convert(w).mult(-1),this.panTo(this.transform.center,Object.assign({offset:w},A),F)}panTo(w,A,F){return this.easeTo(Object.assign({center:w},A),F)}getZoom(){return this.transform.zoom}setZoom(w,A){return this.jumpTo({zoom:w},A),this}zoomTo(w,A,F){return this.easeTo(Object.assign({zoom:w},A),F)}zoomIn(w,A){return this.zoomTo(this.getZoom()+1,w,A),this}zoomOut(w,A){return this.zoomTo(this.getZoom()-1,w,A),this}getBearing(){return this.transform.bearing}setBearing(w,A){return this.jumpTo({bearing:w},A),this}getPadding(){return this.transform.padding}setPadding(w,A){return this.jumpTo({padding:w},A),this}rotateTo(w,A,F){return this.easeTo(Object.assign({bearing:w},A),F)}resetNorth(w,A){return this.rotateTo(0,Object.assign({duration:1e3},w),A),this}resetNorthPitch(w,A){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},w),A),this}snapToNorth(w,A){return Math.abs(this.getBearing())w.aspect?F/(2*Math.tan(.5*w.fovX)*w.aspect):V/(2*Math.tan(.5*w.fovY)*w.aspect)}_cameraForBoundsOnGlobe(w,A,F,V,Z,X){const ae=w.clone(),pe=this._extendCameraOptions(X);ae.bearing=V,ae.pitch=Z;const ke=o.aU.convert(A),Me=o.aU.convert(F),Ke=.5*(ke.lat+Me.lat),He=.5*(ke.lng+Me.lng),tt=o.eT(Ke,He),ct=o.ay([],tt),ot=o.ay([],o.bh([],ct,[0,1,0])),wt=o.bh([],ot,ct),_t=[ot[0],ot[1],ot[2],0,wt[0],wt[1],wt[2],0,ct[0],ct[1],ct[2],0,0,0,0,1],Rt=[tt,o.eT(ke.lat,ke.lng),o.eT(Me.lat,ke.lng),o.eT(Me.lat,Me.lng),o.eT(ke.lat,Me.lng),o.eT(Ke,ke.lng),o.eT(Ke,Me.lng),o.eT(ke.lat,He),o.eT(Me.lat,He)];let $t=o.cU.fromPoints(Rt.map(fn=>[o.bi(ot,fn),o.bi(wt,fn),o.bi(ct,fn)]));const kt=o.ah([],$t.center,_t);o.eU(kt)===0&&o.eV(kt,0,0,1),o.ay(kt,kt),o.bJ(kt,kt,o.aF),ae.center=o.eW(kt);const ks=ae.getWorldToCameraMatrix(),Jt=o.b7(new Float64Array(16),ks);$t=o.cU.applyTransform($t,o.aD([],ks,_t));const ws=this._extendAABB($t,ae,pe,V);if(!ws)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");$t=ws,o.ah(kt,kt,ks);const Vt=.5*($t.max[2]-$t.min[2]),Xt=this._minimumAABBFrustumDistance(ae,$t),ms=o.bJ([],[0,0,1],Vt),Us=o.cT(ms,kt,ms),Cs=Xt+(ae.pitch===0?0:o.bf(kt,Us)),pn=ae.globeCenterInViewSpace,an=o.ax([],kt,[pn[0],pn[1],pn[2]]);o.ay(an,an),o.bJ(an,an,Cs);const Ln=o.cT([],kt,an);o.ah(Ln,Ln,Jt);const $n=o.eD/o.aF,Ys=o.ai(Ln),Es=o.bU(Math.max(Ys*$n-o.eD,Number.EPSILON),0),hn=Math.min(ae.zoomFromMercatorZAdjusted(Es),pe.maxZoom);return hn>.5*(o.cJ+o.cv)?(ae.setProjection({name:"mercator"}),ae.zoom=hn,this._cameraForBounds(ae,A,F,V,Z,X)):{center:ae.center,zoom:hn,bearing:V,pitch:Z}}_extendAABB(w,A,F,V){const Z=.5*((F.padding.left||0)+(F.padding.right||0)),X=.5*((F.padding.top||0)+(F.padding.bottom||0)),ae=X,pe=Z,ke=Z,Me=X,Ke=A.width-(pe+ke),He=A.height-(ae+Me),tt=o.ax([],w.max,w.min),ct=Math.min(Ke/tt[0],He/tt[1]),ot=Math.min(A.scaleZoom(A.scale*ct),F.maxZoom);if(isNaN(ot))return null;const wt=A.scale/A.zoomScale(ot),_t=new o.cU([w.min[0]-pe*wt,w.min[1]-Me*wt,w.min[2]],[w.max[0]+ke*wt,w.max[1]+ae*wt,w.max[2]]),Rt=(typeof F.offset.x=="number"&&typeof F.offset.y=="number"?new o.P(F.offset.x,F.offset.y):o.P.convert(F.offset)).rotate(-o.ap(V));return _t.center[0]-=Rt.x*wt,_t.center[1]+=Rt.y*wt,_t}queryTerrainElevation(w,A){const F=this.transform.elevation;return F?(A=Object.assign({},{exaggerated:!0},A),F.getAtPoint(o.ag.fromLngLat(w),null,A.exaggerated)):null}_cameraForBounds(w,A,F,V,Z,X){if(w.projection.name==="globe")return this._cameraForBoundsOnGlobe(w,A,F,V,Z,X);const ae=w.clone(),pe=this._extendCameraOptions(X);ae.bearing=V,ae.pitch=Z;const ke=o.aU.convert(A),Me=o.aU.convert(F),Ke=new o.aU(ke.lng,Me.lat),He=new o.aU(Me.lng,ke.lat),tt=ae.project(ke),ct=ae.project(Me),ot=this.queryTerrainElevation(ke),wt=this.queryTerrainElevation(Me),_t=this.queryTerrainElevation(Ke),Rt=this.queryTerrainElevation(He),$t=[[tt.x,tt.y,Math.min(ot||0,wt||0,_t||0,Rt||0)],[ct.x,ct.y,Math.max(ot||0,wt||0,_t||0,Rt||0)]];let kt=o.cU.fromPoints($t);const ks=ae.getWorldToCameraMatrix(),Jt=o.b7(new Float64Array(16),ks);kt=o.cU.applyTransform(kt,ks);const ws=this._extendAABB(kt,ae,pe,V);if(!ws)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");kt=ws;const Vt=.5*o.ax([],kt.max,kt.min)[2],Xt=this._minimumAABBFrustumDistance(ae,kt),ms=[0,0,1,0];o.aE(ms,ms,ks),o.eX(ms,ms);const Us=o.bJ([],ms,Xt+Vt),Cs=o.cT([],kt.center,Us);o.ah(kt.center,kt.center,Jt),o.ah(Cs,Cs,Jt);const pn=ae.unproject(new o.P(kt.center[0],kt.center[1])),an=o.eY(ae.projection,pn),Ln=Math.pow(2,an),$n=Math.min(ae._zoomFromMercatorZ(Cs[2]*ae.pixelsPerMeter*Ln/ae.worldSize),pe.maxZoom);return ae.mercatorFromTransition&&$n<.5*(o.cJ+o.cv)?(ae.setProjection({name:"globe"}),ae.zoom=$n,this._cameraForBounds(ae,A,F,V,Z,X)):{center:pn,zoom:$n,bearing:V,pitch:Z}}fitBounds(w,A,F){const V=this.cameraForBounds(w,A);return this._fitInternal(V,A,F)}fitScreenCoordinates(w,A,F,V,Z){const X=o.P.convert(w),ae=o.P.convert(A),pe=new o.P(Math.min(X.x,ae.x),Math.min(X.y,ae.y)),ke=new o.P(Math.max(X.x,ae.x),Math.max(X.y,ae.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(X,ae))return this;const Me=this.transform.pointLocation3D(pe),Ke=this.transform.pointLocation3D(ke),He=this.transform.pointLocation3D(new o.P(pe.x,ke.y)),tt=this.transform.pointLocation3D(new o.P(ke.x,pe.y)),ct=[Math.min(Me.lng,Ke.lng,He.lng,tt.lng),Math.min(Me.lat,Ke.lat,He.lat,tt.lat)],ot=[Math.max(Me.lng,Ke.lng,He.lng,tt.lng),Math.max(Me.lat,Ke.lat,He.lat,tt.lat)],wt=V&&V.pitch?V.pitch:this.getPitch(),_t=this._cameraForBounds(this.transform,ct,ot,F,wt,V);return this._fitInternal(_t,V,Z)}_fitInternal(w,A,F){return w?(A=Object.assign(w,A)).linear?this.easeTo(A,F):this.flyTo(A,F):this}jumpTo(w,A){this.stop();const F=w.preloadOnly?this.transform.clone():this.transform;let V=!1,Z=!1,X=!1;"zoom"in w&&F.zoom!==+w.zoom&&(V=!0,F.zoom=+w.zoom),w.center!==void 0&&(F.center=o.aU.convert(w.center)),"bearing"in w&&F.bearing!==+w.bearing&&(Z=!0,F.bearing=+w.bearing),"pitch"in w&&F.pitch!==+w.pitch&&(X=!0,F.pitch=+w.pitch);const ae=typeof w.padding=="number"?this._extendPadding(w.padding):w.padding;if(w.padding!=null&&!F.isPaddingEqual(ae))if(w.retainPadding===!1){const pe=F.clone();pe.padding=ae,F.setLocationAtPoint(F.center,pe.centerPoint)}else F.padding=ae;return w.preloadOnly?(this._preloadTiles(F),this):(this.fire(new o.C("movestart",A)).fire(new o.C("move",A)),V&&this.fire(new o.C("zoomstart",A)).fire(new o.C("zoom",A)).fire(new o.C("zoomend",A)),Z&&this.fire(new o.C("rotatestart",A)).fire(new o.C("rotate",A)).fire(new o.C("rotateend",A)),X&&this.fire(new o.C("pitchstart",A)).fire(new o.C("pitch",A)).fire(new o.C("pitchend",A)),this.fire(new o.C("moveend",A)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(lV),this.transform.getFreeCameraOptions()}setFreeCameraOptions(w,A){const F=this.transform;if(!F.projection.supportsFreeCamera)return o.w(lV),this;this.stop();const V=F.zoom,Z=F.pitch,X=F.bearing;F.setFreeCameraOptions(w);const ae=V!==F.zoom,pe=Z!==F.pitch,ke=X!==F.bearing;return this.fire(new o.C("movestart",A)).fire(new o.C("move",A)),ae&&this.fire(new o.C("zoomstart",A)).fire(new o.C("zoom",A)).fire(new o.C("zoomend",A)),ke&&this.fire(new o.C("rotatestart",A)).fire(new o.C("rotate",A)).fire(new o.C("rotateend",A)),pe&&this.fire(new o.C("pitchstart",A)).fire(new o.C("pitch",A)).fire(new o.C("pitchend",A)),this.fire(new o.C("moveend",A)),this}easeTo(w,A){this._stop(!1,w.easeId),((w=Object.assign({offset:[0,0],duration:500,easing:o.eP},w)).animate===!1||this._prefersReducedMotion(w))&&(w.duration=0);const F=this.transform,V=this.getZoom(),Z=this.getBearing(),X=this.getPitch(),ae=this.getPadding(),pe="zoom"in w?+w.zoom:V,ke="bearing"in w?this._normalizeBearing(w.bearing,Z):Z,Me="pitch"in w?+w.pitch:X,Ke=this._extendPadding(w.padding),He=o.P.convert(w.offset);let tt,ct,ot;if(F.projection.name==="globe"){const ms=o.ag.fromLngLat(F.center),Us=He.rotate(-F.angle);ms.x+=Us.x/F.worldSize,ms.y+=Us.y/F.worldSize;const Cs=ms.toLngLat(),pn=o.aU.convert(w.center||Cs);this._normalizeCenter(pn),tt=F.centerPoint.add(Us),ct=new o.P(ms.x,ms.y).mult(F.worldSize),ot=new o.P(o.aH(pn.lng),o.aL(pn.lat)).mult(F.worldSize).sub(ct)}else{tt=F.centerPoint.add(He);const ms=F.pointLocation(tt),Us=o.aU.convert(w.center||ms);this._normalizeCenter(Us),ct=F.project(ms),ot=F.project(Us).sub(ct)}const wt=F.zoomScale(pe-V);let _t,Rt;w.around&&(_t=o.aU.convert(w.around),Rt=F.locationPoint(_t));const $t=this._zooming||pe!==V,kt=this._rotating||Z!==ke,ks=this._pitching||Me!==X,Jt=!F.isPaddingEqual(Ke),ws=w.retainPadding===!1?F.clone():F,Vt=ms=>Us=>{if($t&&(ms.zoom=o.am(V,pe,Us)),kt&&(ms.bearing=o.am(Z,ke,Us)),ks&&(ms.pitch=o.am(X,Me,Us)),Jt&&(ws.interpolatePadding(ae,Ke,Us),tt=ws.centerPoint.add(He)),_t)ms.setLocationAtPoint(_t,Rt);else{const Cs=ms.zoomScale(ms.zoom-V),pn=pe>V?Math.min(2,wt):Math.max(.5,wt),an=Math.pow(pn,1-Us),Ln=ms.unproject(ct.add(ot.mult(Us*an)).mult(Cs));ms.setLocationAtPoint(ms.renderWorldCopies?Ln.wrap():Ln,tt)}return w.preloadOnly||this._fireMoveEvents(A),ms};if(w.preloadOnly){const ms=this._emulate(Vt,w.duration,F);return this._preloadTiles(ms),this}const Xt={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=$t,this._rotating=kt,this._pitching=ks,this._padding=Jt,this._easeId=w.easeId,this._prepareEase(A,w.noMoveStart,Xt),this._ease(Vt(F),ms=>{F.cameraElevationReference==="sea"&&F.recenterOnTerrain(),this._afterEase(A,ms)},w),this}_prepareEase(w,A,F={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),A||F.moving||this.fire(new o.C("movestart",w)),this._zooming&&!F.zooming&&this.fire(new o.C("zoomstart",w)),this._rotating&&!F.rotating&&this.fire(new o.C("rotatestart",w)),this._pitching&&!F.pitching&&this.fire(new o.C("pitchstart",w))}_fireMoveEvents(w){this.fire(new o.C("move",w)),this._zooming&&this.fire(new o.C("zoom",w)),this._rotating&&this.fire(new o.C("rotate",w)),this._pitching&&this.fire(new o.C("pitch",w))}_afterEase(w,A){if(this._easeId&&A&&this._easeId===A)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const F=this._zooming,V=this._rotating,Z=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,F&&this.fire(new o.C("zoomend",w)),V&&this.fire(new o.C("rotateend",w)),Z&&this.fire(new o.C("pitchend",w)),this.fire(new o.C("moveend",w))}flyTo(w,A){if(this._prefersReducedMotion(w)){const fn=o.aJ(w,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(fn,A)}this.stop(),w=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},w);const F=this.transform,V=this.getZoom(),Z=this.getBearing(),X=this.getPitch(),ae=this.getPadding(),pe="zoom"in w?o.aC(+w.zoom,F.minZoom,F.maxZoom):V,ke="bearing"in w?this._normalizeBearing(w.bearing,Z):Z,Me="pitch"in w?+w.pitch:X,Ke=this._extendPadding(w.padding),He=F.zoomScale(pe-V),tt=o.P.convert(w.offset);let ct=F.centerPoint.add(tt);const ot=F.pointLocation(ct),wt=o.aU.convert(w.center||ot);this._normalizeCenter(wt);const _t=F.project(ot),Rt=F.project(wt).sub(_t);let $t=w.curve;const kt=Math.max(F.width,F.height),ks=kt/He,Jt=Rt.mag();if("minZoom"in w){const fn=o.aC(Math.min(w.minZoom,V,pe),F.minZoom,F.maxZoom),jn=kt/F.zoomScale(fn-V);$t=Math.sqrt(jn/Jt*2)}const ws=$t*$t;function Vt(fn){const jn=(ks*ks-kt*kt+(fn?-1:1)*ws*ws*Jt*Jt)/(2*(fn?ks:kt)*ws*Jt);return Math.log(Math.sqrt(jn*jn+1)-jn)}function Xt(fn){return(Math.exp(fn)-Math.exp(-fn))/2}function ms(fn){return(Math.exp(fn)+Math.exp(-fn))/2}const Us=Vt(0);let Cs=function(fn){return ms(Us)/ms(Us+$t*fn)},pn=function(fn){return kt*((ms(Us)*(Xt(jn=Us+$t*fn)/ms(jn))-Xt(Us))/ws)/Jt;var jn},an=(Vt(1)-Us)/$t;if(Math.abs(Jt)<1e-6||!isFinite(an)){if(Math.abs(kt-ks)<1e-6)return this.easeTo(w,A);const fn=ksw.maxDuration&&(w.duration=0);const Ln=Z!==ke,$n=Me!==X,Ys=!F.isPaddingEqual(Ke),Es=w.retainPadding===!1?F.clone():F,hn=fn=>jn=>{const yr=jn*an,rr=1/Cs(yr);fn.zoom=jn===1?pe:V+fn.scaleZoom(rr),Ln&&(fn.bearing=o.am(Z,ke,jn)),$n&&(fn.pitch=o.am(X,Me,jn)),Ys&&(Es.interpolatePadding(ae,Ke,jn),ct=Es.centerPoint.add(tt));const ar=jn===1?wt:fn.unproject(_t.add(Rt.mult(pn(yr))).mult(rr));return fn.setLocationAtPoint(fn.renderWorldCopies?ar.wrap():ar,ct),fn._updateCameraOnTerrain(),w.preloadOnly||this._fireMoveEvents(A),fn};if(w.preloadOnly){const fn=this._emulate(hn,w.duration,F);return this._preloadTiles(fn),this}return this._zooming=!0,this._rotating=Ln,this._pitching=$n,this._padding=Ys,this._prepareEase(A,!1),this._ease(hn(F),()=>this._afterEase(A),w),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(w){}_cancelRenderFrame(w){}_stop(w,A){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const F=this._onEaseEnd;this._onEaseEnd=void 0,F.call(this,A)}if(!w){const F=this.handlers;F&&F.stop(!1)}return this}_ease(w,A,F){F.animate===!1||F.duration===0?(w(1),A()):(this._easeStart=o.o.now(),this._easeOptions=F,this._onEaseFrame=w,this._onEaseEnd=A,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const w=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),A=this._onEaseFrame;A&&A(this._easeOptions.easing(w)),w<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(w,A){w=o.bs(w,-180,180);const F=Math.abs(w-A);return Math.abs(w-360-A)180?-360:F<-180?360:0}_prefersReducedMotion(w){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(w&&w.essential)}_emulate(w,A,F){const V=Math.ceil(15*A/1e3),Z=[],X=w(F.clone());for(let ae=0;ae<=V;ae++){const pe=X(ae/V);Z.push(pe.clone())}return Z}_preloadTiles(w,A){}}class cV{constructor(w={}){this.options=w,o.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(w){const A=this.options&&this.options.compact,F=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",F);const V=y("span","mapboxgl-ctrl-icon",this._compactButton);return V.setAttribute("aria-hidden","true"),V.setAttribute("title",F),this._innerContainer=y("div","mapboxgl-ctrl-attrib-inner",this._container),A&&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),A===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 A=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.g.ACCESS_TOKEN}];if(w){const F=A.reduce((V,Z,X)=>(Z.value&&(V+=`${Z.key}=${Z.value}${XV.length-Z.length),w=w.filter((V,Z)=>{for(let X=Z+1;X=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?w=[...this.options.customAttribution,...w]:w.unshift(this.options.customAttribution));const F=w.map(V=>function(Z){const X=new DOMParser().parseFromString(Z,"text/html");return Array.from(X.body.querySelectorAll("*")).reverse().forEach(ae=>{const pe=ae.textContent||"";if(ae.tagName!=="A")return void ae.replaceWith(...ae.childNodes);const ke=ae.getAttribute("href");if(!ke||!/^(https?:|mailto:)/i.test(ke))return void ae.replaceWith(X.createTextNode(pe));const Me=X.createElement("a");Me.href=ke,Me.textContent=pe,Me.rel="noopener nofollow";const Ke=ae.getAttribute("class");Ke&&(Me.className=Ke),ae.replaceWith(Me)}),X.body.innerHTML}(V)).join(" | ");F!==this._attribHTML&&(this._attribHTML=F,w.length?(this._innerContainer.innerHTML=F,this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null)}_updateCompact(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact","mapboxgl-compact-show")}}class dV{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(w){this._map=w,this._container=y("div","mapboxgl-ctrl");const A=y("a","mapboxgl-ctrl-logo");return A.target="_blank",A.rel="noopener nofollow",A.href="https://www.mapbox.com/",A.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),A.setAttribute("rel","noopener nofollow"),this._container.appendChild(A),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 A in w){const F=w[A].getSource();if(F.hasOwnProperty("mapbox_logo")&&!F.mapbox_logo)return!1}return!0}_updateCompact(){const w=this._container.children;if(w.length){const A=w[0];this._map.getCanvasContainer().offsetWidth<250?A.classList.add("mapboxgl-compact"):A.classList.remove("mapboxgl-compact")}}}class Mee{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(w){const A=++this._id;return this._queue.push({callback:w,id:A,cancelled:!1}),A}remove(w){const A=this._currentlyRunning,F=A?this._queue.concat(A):this._queue;for(const V of F)if(V.id===w)return void(V.cancelled=!0)}run(w=0){const A=this._currentlyRunning=this._queue;this._queue=[];for(const F of A)if(!F.cancelled&&(F.callback(w),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class OTe{constructor(w){this.jumpTo(w)}getValue(w){if(w<=this._startTime)return this._start;if(w>=this._endTime)return this._end;const A=o.dn((w-this._startTime)/(this._endTime-this._startTime));return this._start*(1-A)+this._end*A}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,A,F){this._start=this.getValue(A),this._end=w,this._startTime=A,this._endTime=A+F}}const FTe={"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 Gl extends o.C{constructor(w,A,F,V){const{point:Z,lngLat:X,originalEvent:ae,target:pe}=w;super(w.type,{point:Z,lngLat:X,originalEvent:ae,target:pe}),this.preventDefault=()=>{w.preventDefault()},this.id=A,this.interaction=F,this.feature=V}}class eF{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,A){if(this.typeById.has(w))throw new Error(`Interaction id "${w}" already exists.`);const F=A.filter;let V=A.type;F&&this.filters.set(w,o.dg(F)),V==="mouseover"&&(V="mouseenter"),V==="mouseout"&&(V="mouseleave");const Z=this.interactionsByType.get(V)||new Map;V==="mouseenter"||V==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(w,A)):Z.size===0&&this.map.on(V,this.handleType),Z.size===0&&this.interactionsByType.set(V,Z),Z.set(w,A),this.typeById.set(w,V)}get(w){const A=this.typeById.get(w);if(!A)return;const F=this.interactionsByType.get(A);return F?F.get(w):void 0}remove(w){const A=this.typeById.get(w);if(!A)return;this.typeById.delete(w),this.filters.delete(w);const F=this.interactionsByType.get(A);F&&(F.delete(w),A==="mouseenter"||A==="mouseleave"?(this.delegatedInteractions.delete(w),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):F.size===0&&this.map.off(A,this.handleType))}queryTargets(w,A){const F=[];for(const[V,Z]of A)Z.target&&F.push({targetId:V,target:Z.target,filter:this.filters.get(V)});return this.map.style.queryRenderedTargets(w,F,this.map.transform)}handleMove(w){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const A=this.queryTargets(w.point,Array.from(this.delegatedInteractions).reverse());A.length&&(w.type="mouseenter",this.handleType(w,A));const F=new Map;for(const[V,{feature:Z}]of this.prevHoveredFeatures)this.hoveredFeatures.has(V)||F.set(Z.id,Z);F.size&&(w.type="mouseleave",this.handleType(w,Array.from(F.values())))}handleOut(w){const A=Array.from(this.hoveredFeatures.values()).map(({feature:F})=>F);A.length&&(w.type="mouseleave",this.handleType(w,A)),this.hoveredFeatures.clear()}handleType(w,A){const F=w.type==="mouseenter";if(F&&!this.interactionsByType.has(w.type))return void o.w("mouseenter interaction required for mouseleave to work.");const V=Array.from(this.interactionsByType.get(w.type)).reverse(),Z=!!A;A=A||this.queryTargets(w.point,V);let X=!1;const ae=new Set;for(const pe of A){for(const[ke,Me]of V){if(!Me.target)continue;const Ke=pe.variants?pe.variants[ke]:null;if(Ke){for(const He of Ke){if(pu(He,pe,ae,ke))continue;const tt=new o.di(pe,He),ct=Mf(He,pe,ke);Z&&tt.id!==void 0&&(tt.state=this.map.getFeatureState(tt));const ot=F?this.prevHoveredFeatures.get(ct):null,wt=new Gl(w,ke,Me,tt),_t=ot?ot.stop:Me.handler(wt);if(F&&this.hoveredFeatures.set(ct,{feature:pe,stop:_t}),_t!==!1){X=!0;break}}if(X)break}}if(X)break}if(!X)for(const[pe,ke]of V){const{handler:Me,target:Ke}=ke;if(!Ke&&Me(new Gl(w,pe,ke,null))!==!1)break}}}function zTe(R,w){if(Array.isArray(R)&&Array.isArray(w)){const A=new Set(R),F=new Set(w);return A.size===F.size&&R.every(V=>F.has(V))}return o.b6(R,w)}const BTe={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},$Te={showCompass:!0,showZoom:!0,visualizePitch:!1};class V6{constructor(w,A,F=!1){this._clickTolerance=10,this.element=A,this.mouseRotate=new KO({clickTolerance:w.dragRotate._mouseRotate._clickTolerance}),this.map=w,F&&(this.mousePitch=new z6({clickTolerance:w.dragRotate._mousePitch._clickTolerance})),o.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),A.addEventListener("mousedown",this.mousedown),A.addEventListener("touchstart",this.touchstart,{passive:!1}),A.addEventListener("touchmove",this.touchmove),A.addEventListener("touchend",this.touchend),A.addEventListener("touchcancel",this.reset)}down(w,A){this.mouseRotate.mousedown(w,A),this.mousePitch&&this.mousePitch.mousedown(w,A),C()}move(w,A){const F=this.map,V=this.mouseRotate.mousemoveWindow(w,A),Z=V&&V.bearingDelta;if(Z&&F.setBearing(F.getBearing()+Z),this.mousePitch){const X=this.mousePitch.mousemoveWindow(w,A),ae=X&&X.pitchDelta;ae&&F.setPitch(F.getPitch()+ae)}}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()}),L(this.element,w)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(w){this.move(w,L(this.element,w))}mouseup(w){this.mouseRotate.mouseupWindow(w),this.mousePitch&&this.mousePitch.mouseupWindow(w),this.offTemp()}touchstart(w){w.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=I(this.element,w.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>w.preventDefault()},this._startPos))}touchmove(w){w.targetTouches.length!==1?this.reset():(this._lastPos=I(this.element,w.targetTouches)[0],this.move({buttons:1,preventDefault:()=>w.preventDefault()},this._lastPos))}touchend(w){w.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)A.width||w.y>A.height;A.locationPoint3D(F).distSqr(w)180;){const F=A.locationPoint3D(R);if(F.x>=0&&F.y>=0&&F.x<=A.width&&F.y<=A.height)break;R.lng>A.center.lng?R.lng-=360:R.lng+=360}return R}const H6={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%)"},_v={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class O1 extends o.E{constructor(w,A){super(),(w instanceof HTMLElement||A)&&(w=Object.assign({element:w},A)),o.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:F="center",color:V="#3FB1CE",scale:Z=1,draggable:X=!1,clickTolerance:ae=0,rotation:pe=_v.rotation,rotationAlignment:ke=_v.rotationAlignment,pitchAlignment:Me=_v.pitchAlignment,occludedOpacity:Ke=_v.occludedOpacity,altitude:He=_v.altitude}=w||{};this._anchor=F,this._color=V,this._scale=Z,this._draggable=X,this._clickTolerance=ae,this._rotation=pe,this._rotationAlignment=ke,this._pitchAlignment=Me,this._occludedOpacity=Ke,this._altitude=He,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),w&&w.element?(this._element=w.element,this._offset=o.P.convert(w&&w.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(w&&w.offset||[0,-14])),this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label","Map marker"),this._element.hasAttribute("role")||this._element.setAttribute("role","img"),this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",ot=>{ot.preventDefault()}),this._element.addEventListener("mousedown",ot=>{ot.preventDefault()});const tt=this._element.classList;for(const ot in H6)tt.remove(`mapboxgl-marker-anchor-${ot}`);tt.add(`mapboxgl-marker-anchor-${this._anchor}`);const ct=w&&w.className?w.className.trim().split(/\s+/):[];tt.add(...ct),this._popup=null}_createDefaultMarker(){const w=y("div"),A=g("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},w);if(this._altitude===0){const F=g("radialGradient",{id:"shadowGradient"},g("defs",{},A));g("stop",{offset:"10%","stop-opacity":.4},F),g("stop",{offset:"100%","stop-opacity":.05},F),g("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},A)}return g("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"},A),g("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"},A),g("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},A),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||_v.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 V=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":[V,-1*(38.1-13.5+V)],"bottom-right":[-V,-1*(38.1-13.5+V)],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 A=w.code,F=w.charCode||w.keyCode;A!=="Space"&&A!=="Enter"&&F!==32&&F!==13||this.togglePopup()}_onMapClick(w){const A=w.originalEvent.target,F=this._element;this._popup&&(A===F||F.contains(A))&&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,A=this._pos;if(!w||!A)return!1;const F=w.unproject(A,this._altitude),V=w.getFreeCameraOptions();if(!V.position)return!1;const Z=V.position.toLngLat();return Z.distanceTo(F)<.9*Z.distanceTo(this._lngLat)}_evaluateOpacity(){const w=this._map;if(!w)return;const A=this._pos;if(!A||A.x<0||A.x>w.transform.width||A.y<0||A.y>w.transform.height)return void this._clearFadeTimer();const F=w.unproject(A,this._altitude);let V;w._showingGlobe()&&o.e$(w.transform,this._lngLat)?V=0:(V=1-w._queryFogOpacity(F),w.transform._terrainEnabled()&&w.getTerrain()&&this._behindTerrain()&&(V*=this._occludedOpacity)),this._element.style.opacity=`${V}`,this._element.style.pointerEvents=V>0?"auto":"none",this._popup&&this._popup._setOpacity(V),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const w=this._pos;if(!w||!this._map)return;const A=this._offset.mult(this._scale);this._element.style.transform=` translate(${w.x}px,${w.y}px) ${H6[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${A.x}px,${A.y}px) `}_calculateXYTransform(){const w=this._pos,A=this._map,F=this.getPitchAlignment();if(!A||!w||F!=="map")return"";if(!A._showingGlobe()){const pe=A.getPitch();return pe?`rotateX(${pe}deg)`:""}const V=o.cH(o.f0(A.transform,this._lngLat)),Z=w.sub(o.f1(A.transform)),X=Math.abs(Z.x)+Math.abs(Z.y);if(X===0)return"";const ae=V/X;return`rotateX(${-Z.y*ae}deg) rotateY(${Z.x*ae}deg)`}_calculateZTransform(){const w=this._pos,A=this._map;if(!A||!w)return"";let F=0;const V=this.getRotationAlignment();if(V==="map")if(A._showingGlobe()){const Z=A.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),X=A.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(Z);F=o.cH(Math.atan2(X.y,X.x))-90}else F=-A.getBearing();else if(V==="horizon"){const Z=o.aj(4,6,A.getZoom()),X=o.f1(A.transform);X.y+=Z*A.transform.height;const ae=w.sub(X),pe=o.cH(Math.atan2(ae.y,ae.x));F=(pe>90?pe-270:pe+90)*(1-Z)}return F+=this._rotation,F?`rotateZ(${F}deg)`:""}_update(w){cancelAnimationFrame(this._updateFrameId);const A=this._map;A&&(A.transform.renderWorldCopies&&(this._lngLat=uV(this._lngLat,this._pos,A.transform)),this._pos=A.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(),A._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(A._showingGlobe()||A.getTerrain()||A.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 A=this._map;if(!A)return;const F=this._pointerdownPos,V=this._positionDelta;if(F&&V){if(!this._isDragging){const Z=this._clickTolerance||A._clickTolerance;if(w.point.dist(F)R.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(R.minPitch!=null&&R.maxPitch!=null&&R.minPitch>R.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(R.minPitch!=null&&R.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(R.maxPitch!=null&&R.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");R.antialias&&o.eZ(window)&&(R.antialias=!1,o.w("Antialiasing is disabled for this WebGL context to avoid browser bug: https://github.com/mapbox/mapbox-gl-js/issues/11609")),super(new xu(R.minZoom,R.maxZoom,R.minPitch,R.maxPitch,R.renderWorldCopies,null,null),R),this._repaint=!!R.repaint,this._interactive=R.interactive,this._minTileCacheSize=R.minTileCacheSize,this._maxTileCacheSize=R.maxTileCacheSize,this._failIfMajorPerformanceCaveat=R.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=R.preserveDrawingBuffer,this._antialias=R.antialias,this._trackResize=R.trackResize,this._bearingSnap=R.bearingSnap,this._refreshExpiredTiles=R.refreshExpiredTiles,this._fadeDuration=R.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=R.crossSourceCollisions,this._collectResourceTiming=R.collectResourceTiming,this._language=this._parseLanguage(R.language),this._worldview=R.worldview,this._renderTaskQueue=new Mee,this._domRenderTaskQueue=new Mee,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},FTe,R.locale),this._clickTolerance=R.clickTolerance,this._cooperativeGestures=R.cooperativeGestures,this._performanceMetricsCollection=R.performanceMetricsCollection,this._tessellationStep=R.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=R.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new OTe(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=R.scaleFactor,this._requestManager=new G(R.transformRequest,R.accessToken,R.testMode);const A=ue(R.accessToken||o.g.ACCESS_TOKEN);if(A&&"atlas"in A&&typeof A.atlas=="number"&&(this._tokenExpiration=A.atlas),this._silenceAuthErrors=!!R.testMode,this._contextCreateOptions=R.contextCreateOptions?Object.assign({},R.contextCreateOptions):{},typeof R.container=="string"){const F=document.getElementById(R.container);if(!F)throw new Error(`Container '${R.container.toString()}' not found.`);this._container=F}else{if(!(R.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=R.container}if(this._container.childNodes.length>0&&o.w("The map container element should be empty, otherwise the map's interactivity will be negatively impacted. If you want to display a message when WebGL is not supported, use the Mapbox GL Supported plugin instead."),R.maxBounds&&this.setMaxBounds(R.maxBounds),this._spriteFormat="auto",o.aZ(["_onWindowOnline","_onWindowResize","_onVisibilityChange","_onMapScroll","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),this.painter===void 0)throw new Error("Failed to initialize WebGL.");if(this.on("move",()=>this._update(!1)),this.on("moveend",()=>this._update(!1)),this.on("zoom",()=>this._update(!0)),this._fullscreenchangeEvent="onfullscreenchange"in document?"fullscreenchange":"webkitfullscreenchange",window.addEventListener("online",this._onWindowOnline,!1),window.addEventListener("resize",this._onWindowResize,!1),window.addEventListener("orientationchange",this._onWindowResize,!1),window.addEventListener(this._fullscreenchangeEvent,this._onWindowResize,!1),window.addEventListener("visibilitychange",this._onVisibilityChange,!1),this.handlers=new Tee(this,R),this._localFontFamily=R.localFontFamily,this._localIdeographFontFamily=R.localIdeographFontFamily,this._useServerFontComposition=R.useServerFontComposition,(R.style||!R.testMode)&&this.setStyle(R.style||o.g.DEFAULT_STYLE,{config:R.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),R.projection&&this.setProjection(R.projection),R.hash&&(this._hash=new Du(typeof R.hash=="string"&&R.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){w.center==null&&w.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:R.center,zoom:R.zoom,bearing:R.bearing,pitch:R.pitch});const F=R.bounds;F&&(this.resize(),this.fitBounds(F,Object.assign({},R.fitBoundsOptions,{duration:0})))}this.resize(),R.attributionControl&&this.addControl(new cV({customAttribution:R.customAttribution})),this._logoControl=new dV,this.addControl(this._logoControl,R.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",F=>{this._update(F.dataType==="style"),this.fire(new o.C(`${F.dataType}data`,F))}),this.on("dataloading",F=>{this.fire(new o.C(`${F.dataType}dataloading`,F))}),this._interactions=new eF(this)}_getMapId(){return this._mapId}addControl(R,w){if(w===void 0&&(w=R.getDefaultPosition?R.getDefaultPosition():"top-right"),!R||!R.onAdd)return this.fire(new o.B(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const A=R.onAdd(this);this._controls.push(R);const F=this._controlPositions[w];return w.indexOf("bottom")!==-1?F.insertBefore(A,F.firstChild):F.appendChild(A),this}removeControl(R){if(!R||!R.onRemove)return this.fire(new o.B(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const w=this._controls.indexOf(R);return w>-1&&this._controls.splice(w,1),R.onRemove(this),this}hasControl(R){return this._controls.indexOf(R)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(R){if(this._updateContainerDimensions(),this._containerWidth===this.transform.width&&this._containerHeight===this.transform.height)return this;this._resizeCanvas(this._containerWidth,this._containerHeight),this.transform.resize(this._containerWidth,this._containerHeight),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight));const w=!this._moving;return w&&this.fire(new o.C("movestart",R)).fire(new o.C("move",R)),this.fire(new o.C("resize",R)),w&&this.fire(new o.C("moveend",R)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(R){return this.transform.setMaxBounds(o.aK.convert(R)),this._update()}setMinZoom(R){if((R=R??-2)>=-2&&R<=this.transform.maxZoom)return this.transform.minZoom=R,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=R,this._update(),this.getZoom()>R?this.setZoom(R):this.fire(new o.C("zoomstart")).fire(new o.C("zoom")).fire(new o.C("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(R){if((R=R??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(R>=0&&R<=this.transform.maxPitch)return this.transform.minPitch=R,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(R>=this.transform.minPitch)return this.transform.maxPitch=R,this._update(),this.getPitch()>R?this.setPitch(R):this.fire(new o.C("pitchstart")).fire(new o.C("pitch")).fire(new o.C("pitchend")),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(R){return this._scaleFactor=R,this.painter.scaleFactor=R,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(w=>w.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(R){return this.transform.renderWorldCopies=R,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(R){return R==="auto"?navigator.language:Array.isArray(R)?R.length===0?void 0:R.map(w=>w==="auto"?navigator.language:w):R}setLanguage(R){const w=this._parseLanguage(R);if(!this.style||w===this._language)return this;this._language=w,this.style.reloadSources();for(const A of this._controls)A._setLanguage&&A._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(R){return this.style&&R!==this._worldview?(this._worldview=R,this._styleDirty=!0,this.style.setWorldview(R),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(R){return this._lazyInitEmptyStyle(),R?typeof R=="string"&&(R={name:R}):R=null,this._useExplicitProjection=!!R,this._prioritizeAndUpdateProjection(R,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const R=this.transform,w=R.projection.name;let A;w==="globe"&&R.zoom>=o.cv?(R.setMercatorFromTransition(),A=!0):w==="mercator"&&R.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(R),this.style.applyProjectionUpdate();const F=this.transform.getProjection().name==="mercator"&&A!==this.transform.mercatorFromTransition;return(w||F)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(R,w){return this.transform.locationPoint3D(o.aU.convert(R),w)}unproject(R,w){return this.transform.pointLocation3D(o.P.convert(R),w)}isMoving(){return this._moving||this.handlers&&this.handlers.isMoving()||!1}isZooming(){return this._zooming||this.handlers&&this.handlers.isZooming()||!1}isRotating(){return this._rotating||this.handlers&&this.handlers.isRotating()||!1}_isDragging(){return this.handlers&&this.handlers._isDragging()||!1}_createDelegatedListener(R,w,A){const F=V=>{let Z=[];if(Array.isArray(w)){const X=w.filter(ae=>this.getLayer(ae));Z=X.length?this.queryRenderedFeatures(V,{layers:X}):[]}else Z=this.queryRenderedFeatures(V,{target:w});return Z};if(R==="mouseenter"||R==="mouseover"){let V=!1;return{listener:A,targets:w,delegates:{mousemove:X=>{const ae=F(X.point);ae.length?V||(V=!0,A.call(this,new Xi(R,this,X.originalEvent,{features:ae}))):V=!1},mouseout:()=>{V=!1}}}}if(R==="mouseleave"||R==="mouseout"){let V=!1;return{listener:A,targets:w,delegates:{mousemove:ae=>{F(ae.point).length?V=!0:V&&(V=!1,A.call(this,new Xi(R,this,ae.originalEvent)))},mouseout:ae=>{V&&(V=!1,A.call(this,new Xi(R,this,ae.originalEvent)))}}}}{const V=Z=>{const X=F(Z.point);X.length&&(Z.features=X,A.call(this,Z),delete Z.features)};return{listener:A,targets:w,delegates:{[R]:V}}}}on(R,w,A){if(typeof w=="function"||A===void 0)return super.on(R,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const F=this._createDelegatedListener(R,w,A);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[R]=this._delegatedListeners[R]||[],this._delegatedListeners[R].push(F);for(const V in F.delegates)this.on(V,F.delegates[V]);return this}once(R,w,A){if(typeof w=="function"||A===void 0)return super.once(R,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const F=this._createDelegatedListener(R,w,A);for(const V in F.delegates)this.once(V,F.delegates[V]);return this}off(R,w,A){if(typeof w=="function"||A===void 0)return super.off(R,w);if(typeof w=="string"&&(w=[w]),!this._areTargetsValid(w))return this;const F=this._delegatedListeners?this._delegatedListeners[R]:void 0;return F&&(V=>{for(let Z=0;Z{if(A){const V=typeof A=="string"?A:A instanceof Error?A.message:A.error;o.w(`Unable to perform style diff: ${V}. Rebuilding the style from scratch.`),this._updateStyle(R,w)}else F&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=w.localIdeographFontFamily,this._localFontFamily=w.localFontFamily,this._updateStyle(R,w))}_getUIString(R){const w=this._locale[R];if(w==null)throw new Error(`Missing UI string '${R}'`);return w}_updateStyle(R,w){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),R){const A=Object.assign({},w);w&&w.config&&(A.initialConfig=w.config,delete A.config),this.style=new yu(this,A).load(R),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new yu(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():(o.w("There is no style added to the map."),!1)}_isValidId(R){return R==null?(this.fire(new o.B(new Error("IDs can't be empty."))),!1):!o.db(R)||(this.fire(new o.B(new Error(`IDs can't contain special symbols: "${R}".`))),!1)}_isTargetValid(R){return"featuresetId"in R?this._isValidId("importId"in R?R.importId:R.featuresetId):"layerId"in R&&this._isValidId(R.layerId)}_areTargetsValid(R){if(Array.isArray(R)){for(const w of R)if(!this._isValidId(w))return!1;return!0}return this._isTargetValid(R)}addSource(R,w){return this._isValidId(R)?(this._lazyInitEmptyStyle(),this.style.addSource(R,w),this._update(!0)):this}isSourceLoaded(R){return!!this._isValidId(R)&&!!this.style&&this.style._isSourceCacheLoaded(R)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(R,w,A){this._lazyInitEmptyStyle(),this.style.addSourceType(R,w,A)}removeSource(R){return this._isValidId(R)?(this.style.removeSource(R),this._updateTerrain(),this._update(!0)):this}getSource(R){return this._isValidId(R)?this.style.getOwnSource(R):null}addImage(R,w,{pixelRatio:A=1,sdf:F=!1,stretchX:V,stretchY:Z,content:X}={}){this._lazyInitEmptyStyle();const ae=o.I.from(R);if(w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap){const{width:pe,height:ke,data:Me}=o.o.getImageData(w);this.style.addImage(ae,{data:new o.q({width:pe,height:ke},Me),pixelRatio:A,stretchX:V,stretchY:Z,content:X,sdf:F,version:0,usvg:!1})}else if(w.width===void 0||w.height===void 0)this.fire(new o.B(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));else{const{width:pe,height:ke}=w,Me=w;this.style.addImage(ae,{data:new o.q({width:pe,height:ke},new Uint8Array(Me.data)),pixelRatio:A,stretchX:V,stretchY:Z,content:X,sdf:F,usvg:!1,version:0,userImage:Me}),Me.onAdd&&Me.onAdd(this,R)}}updateImage(R,w){this._lazyInitEmptyStyle();const A=o.I.from(R),F=this.style.getImage(A);if(!F)return void this.fire(new o.B(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const V=w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap?o.o.getImageData(w):w,{width:Z,height:X,data:ae}=V;if(Z===void 0||X===void 0)return void this.fire(new o.B(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(Z!==(F.usvg?F.icon.usvg_tree.width:F.data.width)||X!==(F.usvg?F.icon.usvg_tree.height:F.data.height))return void this.fire(new o.B(new Error(`The width and height of the updated image (${Z}, ${X}) must be that same as the previous version of the image (${F.data.width}, ${F.data.height})`)));const pe=!(w instanceof HTMLImageElement||ImageBitmap&&w instanceof ImageBitmap);let ke=!1;F.usvg?(F.data=new o.q({width:Z,height:X},new Uint8Array(ae)),F.usvg=!1,F.icon=void 0,ke=!0):F.data.replace(ae,pe),this.style.updateImage(A,F,ke)}hasImage(R){return R?!!this.style&&!!this.style.getImage(o.I.from(R)):(this.fire(new o.B(new Error("Missing required image id"))),!1)}removeImage(R){this.style.removeImage(o.I.from(R))}loadImage(R,w){o.n(this._requestManager.transformRequest(R,o.R.Image),(A,F)=>{w(A,F)})}listImages(){return this.style.listImages().map(R=>R.name)}addModel(R,w){this._lazyInitEmptyStyle(),this.style.addModel(R,w)}hasModel(R){return R?this.style.hasModel(R):(this.fire(new o.B(new Error("Missing required model id"))),!1)}removeModel(R){this.style.removeModel(R)}listModels(){return this.style.listModels()}addLayer(R,w){return this._isValidId(R.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(R,w),this._update(!0)):this}getSlot(R){const w=this.getLayer(R);return w&&w.slot||null}setSlot(R,w){return this.style.setSlot(R,w),this.style.mergeLayers(),this._update(!0)}addImport(R,w){return this.style.addImport(R,w).catch(A=>this.fire(new o.B(new Error("Failed to add import",A)))),this}updateImport(R,w){return typeof w!="string"&&w.id!==R?(this.removeImport(R),this.addImport(w)):(this.style.updateImport(R,w),this._update(!0))}removeImport(R){return this.style.removeImport(R),this}moveImport(R,w){return this.style.moveImport(R,w),this._update(!0)}moveLayer(R,w){return this._isValidId(R)?(this.style.moveLayer(R,w),this._update(!0)):this}removeLayer(R){return this._isValidId(R)?(this.style.removeLayer(R),this._update(!0)):this}getLayer(R){if(!this._isValidId(R))return null;const w=this.style.getOwnLayer(R);return w?w.type==="custom"?w.implementation:w.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(R,w,A){return this._isValidId(R)?(this.style.setLayerZoomRange(R,w,A),this._update(!0)):this}setFilter(R,w,A={}){return this._isValidId(R)?(this.style.setFilter(R,w,A),this._update(!0)):this}getFilter(R){return this._isValidId(R)?this.style.getFilter(R):null}setPaintProperty(R,w,A,F={}){return this._isValidId(R)?(this.style.setPaintProperty(R,w,A,F),this._update(!0)):this}getPaintProperty(R,w){return this._isValidId(R)?this.style.getPaintProperty(R,w):null}setLayoutProperty(R,w,A,F={}){return this._isValidId(R)?(this.style.setLayoutProperty(R,w,A,F),this._update(!0)):this}getLayoutProperty(R,w){return this._isValidId(R)?this.style.getLayoutProperty(R,w):null}setLayerProperty(R,w,A,F={}){return this._isValidId(R)?(w==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(R,w,A,F),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(R){return this.style.setGlyphsUrl(R),this._update(!0)}getSchema(R){return this.style.getSchema(R)}setSchema(R,w){return this.style.setSchema(R,w),this._update(!0)}getConfig(R){return this.style.getConfig(R)}setConfig(R,w){return this.style.setConfig(R,w),this._update(!0)}getConfigProperty(R,w){return this.style.getConfigProperty(R,w)}setConfigProperty(R,w,A){return this.style.setConfigProperty(R,w,A),this._update(!0)}getFeaturesetDescriptors(R){return this.style.getFeaturesetDescriptors(R)}setLights(R){if(this._lazyInitEmptyStyle(),R&&R.length===1&&R[0].type==="flat"){const w=R[0];w.properties?this.style.setFlatLight(w.properties,w.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(R),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const R=this.style.getLights()||[];return R.length===0&&R.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),R}setLight(R,w={}){return console.log("The `map.setLight` function is deprecated, prefer using `map.setLights` with `flat` light type instead."),this.setLights([{id:"flat",type:"flat",properties:R}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(R){return this._lazyInitEmptyStyle(),!R&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(R),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(R){return this._lazyInitEmptyStyle(),this.style.setFog(R),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(R){return this._lazyInitEmptyStyle(),this.style.setSnow(R),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(R){return this._lazyInitEmptyStyle(),this.style.setRain(R),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(R){return this._lazyInitEmptyStyle(),this.style.setColorTheme(R),this._update(!0)}setImportColorTheme(R,w){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(R,w),this._update(!0)}setCamera(R){return this.style.setCamera(R),this._triggerCameraUpdate(R)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(R){const w=this.transform.nearClipOffset!==R;return this.transform.nearClipOffset=R,this._update(w)}_triggerCameraUpdate(R){return this._update(this.transform.setOrthographicProjectionAtLowPitch(R["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(R){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.aU.convert(R),this.transform):0}setFeatureState(R,w){return R.source&&!this._isValidId(R.source)?this:(this.style.setFeatureState(R,w),this._update())}removeFeatureState(R,w){return R.source&&!this._isValidId(R.source)?this:(this.style.removeFeatureState(R,w),this._update())}getFeatureState(R){return R.source&&!this._isValidId(R.source)?null:this.style.getFeatureState(R)}_selectIndoorFloor(R){this.style.indoorManager.selectFloor(R)}_setIndoorActiveFloorsVisibility(R){this.style.indoorManager.setActiveFloorsVisibility(R)}getIndoorTileOptions(R,w){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(R,w):null}_updateContainerDimensions(){if(!this._container)return;const R=this._container.getBoundingClientRect().width||400,w=this._container.getBoundingClientRect().height||300;let A,F,V,Z=this._container;for(;Z&&(!F||!V);){const X=window.getComputedStyle(Z).transform;X&&X!=="none"&&(A=X.match(/matrix.*\((.+)\)/)[1].split(", "),A[0]&&A[0]!=="0"&&A[0]!=="1"&&(F=A[0]),A[3]&&A[3]!=="0"&&A[3]!=="1"&&(V=A[3])),Z=Z.parentElement}this._containerWidth=F?Math.abs(R/F):R,this._containerHeight=V?Math.abs(w/V):w}_detectMissingCSS(){window.getComputedStyle(this._missingCSSCanary).getPropertyValue("background-color")!=="rgb(250, 128, 114)"&&o.w("This page appears to be missing CSS declarations for Mapbox GL JS, which may cause the map to display incorrectly. Please ensure your page includes mapbox-gl.css, as described in https://www.mapbox.com/mapbox-gl-js/api/.")}_setupContainer(){const R=this._container;R.classList.add("mapboxgl-map"),(this._missingCSSCanary=y("div","mapboxgl-canary",R)).style.visibility="hidden",this._detectMissingCSS();const w=this._canvasContainer=y("div","mapboxgl-canvas-container",R);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 A=this._controlContainer=y("div","mapboxgl-control-container",R),F=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(V=>{F[V]=y("div",`mapboxgl-ctrl-${V}`,A)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(R,w){const A=o.o.devicePixelRatio||1;this._canvas.width=A*Math.ceil(R),this._canvas.height=A*Math.ceil(w),this._canvas.style.width=`${R}px`,this._canvas.style.height=`${w}px`}_addMarker(R){this._markers.push(R)}_removeMarker(R){const w=this._markers.indexOf(R);w!==-1&&this._markers.splice(w,1)}_addPopup(R){this._popups.push(R)}_removePopup(R){const w=this._popups.indexOf(R);w!==-1&&this._popups.splice(w,1)}_setupPainter(){const R=Object.assign({},x.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),w=this._canvas.getContext("webgl2",R);w?(Ue(w,!0),this.painter=new vl(w,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",A=>{if(A.dataType==="source"){const F=this.transform.elevation?this.transform.elevation._source():null;F&&A.sourceCacheId===F.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),o.k.testSupport(w)):this.fire(new o.B(new Error("Failed to initialize WebGL")))}_contextLost(R){R.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new o.C("webglcontextlost",{originalEvent:R}))}_contextRestored(R){this._setupPainter(),this.painter.resize(Math.ceil(this._containerWidth),Math.ceil(this._containerHeight)),this._updateTerrain(),this.style&&(this.style.clearLayers(),this.style.imageManager.destroyAtlasTextures(),this.style.imageManager.imageAtlasCache.destroyTextures(),this.style.reloadModels(),this.style.clearSources()),this._update(),this.fire(new o.C("webglcontextrestored",{originalEvent:R}))}_onMapScroll(R){if(R.target===this._container)return this._container.scrollTop=0,this._container.scrollLeft=0,!1}idle(){return!this.isMoving()&&this.loaded()}loaded(){return!this._styleDirty&&!this._sourcesDirty&&!!this.style&&this.style.loaded()}frameReady(){return this.loaded()&&!this._placementDirty}_update(R){return this.style?(this._styleDirty=this._styleDirty||R,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(R){return this._update(),this._renderTaskQueue.add(R)}_cancelRenderFrame(R){this._renderTaskQueue.remove(R)}_requestDomTask(R){!this.loaded()||this.loaded()&&!this.isMoving()?R():this._domRenderTaskQueue.add(R)}_render(R){let w;this.fire(new o.C("renderstart")),++this._frameId;const A=this.painter.context.extTimerQuery,F=o.o.now(),V=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(w=V.createQuery(),V.beginQuery(A.TIME_ELAPSED_EXT,w)),this.painter.context.setDirty(),this.painter.setBaseState(),(this.isMoving()||this.isRotating()||this.isZooming())&&(this._interactionRange[0]=Math.min(this._interactionRange[0],performance.now()),this._interactionRange[1]=Math.max(this._interactionRange[1],performance.now())),this._renderTaskQueue.run(R),this._domRenderTaskQueue.run(R),this._removed)return;this._updateProjectionTransition();const Z=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const pe=this.transform.zoom,ke=this.transform.pitch,Me=o.o.now(),Ke=new o.ae(pe,{now:Me,fadeDuration:Z,pitch:ke,transition:this.style.transition,worldview:this._worldview});this.style.update(Ke)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let X=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),X=this._updateAverageElevation(F),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):X=this._updateAverageElevation(F),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,Z,this._crossSourceCollisions,this.painter.replacementSource)),this.style&&this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:Z,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming}),this.fire(new o.C("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,u.mark(d.load),this.fire(new o.C("load"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&(this.style.snow||this.style.rain)&&(this._styleDirty=!0),this.style&&this.style.imageManager.hasPatternsInFlight()&&(this._styleDirty=!0),this.style&&!this.style.modelManager.isLoaded()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),w){const pe=o.o.now()-F;V.endQuery(A.TIME_ELAPSED_EXT),setTimeout(()=>{const ke=V.getQueryParameter(w,V.QUERY_RESULT)/1e6;V.deleteQuery(w),this.fire(new o.C("gpu-timing-frame",{cpuTime:pe,gpuTime:ke}))},50)}if(this.listens("gpu-timing-layer")){const pe=this.painter.collectGpuTimers();setTimeout(()=>{const ke=this.painter.queryGpuTimers(pe);this.fire(new o.C("gpu-timing-layer",{layerTimes:ke}))},50)}if(this.listens("gpu-timing-deferred-render")){const pe=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const ke=this.painter.queryGpuTimeDeferredRender(pe);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:ke}))},50)}const ae=this._sourcesDirty||this._styleDirty||this._placementDirty||X;if(ae||this._repaint)this.triggerRepaint();else{const pe=this.idle();if(pe&&(X=this._updateAverageElevation(F,!0)),X)this.triggerRepaint();else if(this._triggerFrame(!1),pe&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const ke=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:ke})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||ae||(this._fullyLoaded=!0,u.mark(d.fullLoad),this._performanceMetricsCollection&&_e(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:!!this.painter.style.getTerrain(),fogEnabled:!!this.painter.style.getFog(),projection:this.getProjection().name,zoom:this.transform.zoom,renderer:this.painter.context.renderer,vendor:this.painter.context.vendor}),this._authenticate())}_forceMarkerAndPopupUpdate(R){for(const w of this._markers)R&&!this.getRenderWorldCopies()&&(w._lngLat=w._lngLat.wrap()),w._update();for(const w of this._popups)!R||this.getRenderWorldCopies()||w._trackPointer||(w._lngLat=w._lngLat.wrap()),w._update()}_updateAverageElevation(R,w=!1){const A=V=>(this.transform.averageElevation=V,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&A(0);const F=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(F||(w||R-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(R)){const V=this.transform.averageElevation;let Z=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(Z)?Z=0:this._averageElevationLastSampledAt=R;const X=Math.abs(V-Z);if(X>1){if(this._isInitialLoad||F)return this._averageElevation.jumpTo(Z),A(Z);this._averageElevation.easeTo(Z,R,300)}else if(X>1e-4)return this._averageElevation.jumpTo(Z),A(Z)}return!!this._averageElevation.isEasing(R)&&A(this._averageElevation.getValue(R))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const R=this.painter.context.gl;Ue(R,!1),this._logoControl instanceof dV&&this._logoControl._updateLogo(),R&&R.clear(R.DEPTH_BUFFER_BIT|R.COLOR_BUFFER_BIT|R.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new o.B(new Error("A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/")))}_authenticate(){Ae(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,R=>{R&&(R.message!==W&&R.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),fe(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&Ee(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&De(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){Ne(this._requestManager._customAccessToken)}_updateTerrain(){const R=this._isDragging();this.painter.updateTerrain(this.style,R)}_calculateSpeedIndex(){const R=this.painter.canvasCopy(),w=this.painter.getCanvasCopiesAndTimestamps();w.timeStamps.push(performance.now());const A=this.painter.context.gl,F=A.createFramebuffer();function V(Z){A.framebufferTexture2D(A.FRAMEBUFFER,A.COLOR_ATTACHMENT0,A.TEXTURE_2D,Z,0);const X=new Uint8Array(A.drawingBufferWidth*A.drawingBufferHeight*4);return A.readPixels(0,0,A.drawingBufferWidth,A.drawingBufferHeight,A.RGBA,A.UNSIGNED_BYTE,X),X}return A.bindFramebuffer(A.FRAMEBUFFER,F),this._canvasPixelComparison(V(R),w.canvasCopies.map(V),w.timeStamps)}_canvasPixelComparison(R,w,A){let F=A[1]-A[0];const V=R.length/4;for(let Z=0;Z{const A=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,A&&this._render(w)}))}_preloadTiles(R){const w=this.style?this.style.getSourceCaches():[];return o.t(w,(A,F)=>A._preloadTiles(R,F),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(R){this._trackResize&&this.resize({originalEvent:R})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(R){this._showTileBoundaries!==R&&(this._showTileBoundaries=R,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(R){this._showParseStatus!==R&&(this._showParseStatus=R,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(R){this._showTerrainWireframe!==R&&(this._showTerrainWireframe=R,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(R){this._showLayers2DWireframe!==R&&(this._showLayers2DWireframe=R,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(R){this._showLayers3DWireframe!==R&&(this._showLayers3DWireframe=R,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(R){this._speedIndexTiming!==R&&(this._speedIndexTiming=R,this._update())}get showPadding(){return!!this._showPadding}set showPadding(R){this._showPadding!==R&&(this._showPadding=R,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(R){this._showCollisionBoxes!==R&&(this._showCollisionBoxes=R,this.style&&R?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(R){this._showOverdrawInspector!==R&&(this._showOverdrawInspector=R,this._update())}get repaint(){return!!this._repaint}set repaint(R){this._repaint!==R&&(this._repaint=R,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(R){this._vertices=R,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(R){this._showTileAABBs!==R&&(this._showTileAABBs=R,R&&this._update())}_setCacheLimits(R,w){o.e_(R,w)}get version(){return c}},NavigationControl:class{constructor(R={}){this.options=Object.assign({},$Te,R),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 A=this._map;A&&(this.options.visualizePitch?A.resetNorthPitch({},{originalEvent:w}):A.resetNorth({},{originalEvent:w}))}),this._compassIcon=y("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const R=this._map;if(!R)return;const w=R.getZoom(),A=w===R.getMaxZoom(),F=w===R.getMinZoom();this._zoomInButton.disabled=A,this._zoomOutButton.disabled=F,this._zoomInButton.setAttribute("aria-disabled",A.toString()),this._zoomOutButton.setAttribute("aria-disabled",F.toString())}_rotateCompassArrow(){const R=this._map;if(!R)return;const w=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(R.transform.pitch*(Math.PI/180)),.5)}) rotateX(${R.transform.pitch}deg) rotateZ(${R.transform.angle*(180/Math.PI)}deg)`:`rotate(${R.transform.angle*(180/Math.PI)}deg)`;R._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=w)})}onAdd(R){return this._map=R,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),R.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&R.on("pitch",this._rotateCompassArrow),R.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new V6(R,this._compass,this.options.visualizePitch)),this._container}onRemove(){const R=this._map;R&&(this._container.remove(),this.options.showZoom&&R.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&R.off("pitch",this._rotateCompassArrow),R.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(R,w){const A=y("button",R,this._container);return A.type="button",A.addEventListener("click",w),A}_setButtonTitle(R,w){if(!this._map)return;const A=this._map._getUIString(`NavigationControl.${w}`);R.setAttribute("aria-label",A),R.firstElementChild&&R.firstElementChild.setAttribute("title",A)}},GeolocateControl:class extends o.E{constructor(R={}){super();const w=navigator.geolocation;this.options=Object.assign({geolocation:w},G6,R),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=hi(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(R){return this._map=R,this._container=y("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._clearRequestTimeout(),this._geolocationWatchID!==void 0&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("zoom",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1}_checkGeolocationSupport(R){const w=(A=!!this.options.geolocation)=>{this._supportsGeolocation=A,R(A)};this._supportsGeolocation!==void 0?R(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(A=>w(A.state!=="denied")).catch(()=>w()):w()}_isOutOfMapMaxBounds(R){const w=this._map.getMaxBounds(),A=R.coords;return!!w&&(A.longitudew.getEast()||A.latitudew.getNorth())}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting")}}_onSuccess(R){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(R))return this._setErrorState(),this.fire(new o.C("outofmaxbounds",R)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=R,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this.options.followUserLocation?(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active")):(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"));break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background")}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(R),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(R),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("geolocate",Object.assign({coords:R.coords,timestamp:R.timestamp},R.toJSON?{toJSON:R.toJSON.bind(R)}:{}))),this._finish()}}_updateCamera(R){const w=new o.aU(R.coords.longitude,R.coords.latitude),A=R.coords.accuracy,F=this._map.getBearing(),V=Object.assign({bearing:F},this.options.fitBoundsOptions);this._map.fitBounds(w.toBounds(A),V,{geolocateSource:!0})}_updateMarker(R){if(R){const w=new o.aU(R.coords.longitude,R.coords.latitude);this._accuracyCircleMarker.setLngLat(w).addTo(this._map),this._userLocationDotMarker.setLngLat(w).addTo(this._map),this._accuracy=R.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const R=this._map.transform,w=o.bU(1,R._center.lat)*R.worldSize,A=Math.ceil(2*this._accuracy*w);this._circleElement.style.width=`${A}px`,this._circleElement.style.height=`${A}px`}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}_updateMarkerRotation(){this._userLocationDotMarker&&typeof this._heading=="number"?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName("mapboxgl-user-location-show-heading")):(this._userLocationDotMarker.removeClassName("mapboxgl-user-location-show-heading"),this._userLocationDotMarker.setRotation(0))}_onError(R){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(R.code===1){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;const w=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",w),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",w),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(R.code===3&&this._noTimeout)return;this._setErrorState()}this._watchState!=="OFF"&&this.options.showUserLocation&&this._userLocationDotMarker.addClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("error",{code:R.code,message:R.message,PERMISSION_DENIED:R.PERMISSION_DENIED,POSITION_UNAVAILABLE:R.POSITION_UNAVAILABLE,TIMEOUT:R.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const R=this.options.positionOptions.timeout;R&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},R))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(R){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",w=>w.preventDefault()),this._geolocateButton=y("button","mapboxgl-ctrl-geolocate",this._container),y("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",R===!1){o.w("Geolocation support is not available so the GeolocateControl will be disabled.");const 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 O1({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=y("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new O1({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.showButton||(this._container.style.display="none"),this.options.trackUserLocation&&this._map.on("movestart",w=>{w.geolocateSource||this._watchState!=="ACTIVE_LOCK"||w.originalEvent&&w.originalEvent.type==="resize"||(this._watchState="BACKGROUND",this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this.fire(new o.C("trackuserlocationend")))})}}_onDeviceOrientation(R){this._userLocationDotMarker&&(R.webkitCompassHeading?this._heading=R.webkitCompassHeading:R.absolute===!0&&(this._heading=-1*R.alpha),this._updateMarkerRotationThrottled())}trigger(){if(!this._setup)return o.w("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new o.C("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new o.C("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.C("trackuserlocationstart"))}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error")}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let R;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(R={maximumAge:6e5,timeout:0},this._noTimeout=!0):(R=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,R),this._startRequestTimeout(),this.options.showUserHeading&&this._addDeviceOrientationListener()}}else this.options.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._startRequestTimeout(),this._timeoutId=window.setTimeout(this._finish,1e4);return!0}setFollowUserLocation(R){return this.options.followUserLocation=R??G6.followUserLocation,this.options.trackUserLocation&&this._watchState!=="OFF"&&(this.options.followUserLocation?this._watchState!=="BACKGROUND"&&this._watchState!=="BACKGROUND_ERROR"||(this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.C("trackuserlocationstart"))):this._watchState!=="ACTIVE_LOCK"&&this._watchState!=="ACTIVE_ERROR"||(this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),this.fire(new o.C("trackuserlocationend")))),this}_addDeviceOrientationListener(){const R=()=>{const w="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(w,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(w=>{w==="granted"&&R()}).catch(console.error):R()}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:cV,ScaleControl:class{constructor(R={}){this.options=Object.assign({},Eh,R),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const R=this.options.maxWidth||100,w=this._map,A=w._containerHeight/2,F=w._containerWidth/2-R/2,V=w.unproject([F,A]),Z=w.unproject([F+R,A]),X=V.distanceTo(Z);if(this.options.unit==="imperial"){const ae=3.2808*X;ae>5280?this._setScale(R,ae/5280,"mile"):this._setScale(R,ae,"foot")}else this.options.unit==="nautical"?this._setScale(R,X/1852,"nautical-mile"):X>=1e3?this._setScale(R,X/1e3,"kilometer"):this._setScale(R,X,"meter")}_setScale(R,w,A){this._map._requestDomTask(()=>{const F=function(Z){const X=Math.pow(10,`${Math.floor(Z)}`.length-1);let ae=Z/X;return ae=ae>=10?10:ae>=5?5:ae>=3?3:ae>=2?2:ae>=1?1:function(pe){const ke=Math.pow(10,Math.ceil(-Math.log(pe)/Math.LN10));return Math.round(pe*ke)/ke}(ae),X*ae}(w),V=F/w;this._container.innerHTML=A!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:A}).format(F):`${F} ${F1[A]}`,this._container.style.width=R*V+"px"})}onAdd(R){return this._map=R,this._language=R.getLanguage(),this._container=y("div","mapboxgl-ctrl mapboxgl-ctrl-scale",R.getContainer()),this._container.dir="auto",this._map.on("move",this._update),this._update(),this._container}onRemove(){this._container.remove(),this._map.off("move",this._update),this._map=void 0}_setLanguage(R){this._language=R,this._update()}setUnit(R){this.options.unit=R,this._update()}},FullscreenControl:class{constructor(R={}){this._fullscreen=!1,R&&R.container&&(R.container instanceof HTMLElement?this._container=R.container:o.w("Full screen control 'container' must be a DOM element.")),o.aZ(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(R){return this._map=R,this._container||(this._container=this._map.getContainer()),this._controlContainer=y("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",o.w("This device does not support fullscreen mode.")),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,document.removeEventListener(this._fullscreenchange,this._changeIcon)}_checkFullscreenSupport(){return!(!document.fullscreenEnabled&&!document.webkitFullscreenEnabled)}_setupUI(){const R=this._fullscreenButton=y("button","mapboxgl-ctrl-fullscreen",this._controlContainer);y("span","mapboxgl-ctrl-icon",R).setAttribute("aria-hidden","true"),R.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const R=this._getTitle();this._fullscreenButton.setAttribute("aria-label",R),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",R)}_getTitle(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")}_isFullscreen(){return this._fullscreen}_changeIcon(){(document.fullscreenElement||document.webkitFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle())}_onClickFullscreen(){this._isFullscreen()?document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen&&document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen()}},IndoorControl:class{constructor(){o.aZ(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(R){return this._map=R,this._container=y("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const R=this._map.style.indoorManager;R.off("selector-update",this._onIndoorUpdate),R.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(R.getControlState())}}_createButton(R,w){const A=y("button",R,this._container);return A.type="button",A.addEventListener("click",w),A}_setButtonTitle(R,w){R.setAttribute("aria-label",w),R.textContent=w}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.style&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(R){if(!R||!R.floors||R.floors.length===0)return this._model=R,void(this._container.style.display="none");const w=this._model;this._model=R,this._container.style.display="inline-block";const A=!w||w.floors.length!==R.floors.length||w.floors.some((F,V)=>F.id!==R.floors[V].id);if(A&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),R.selectedFloorId){if(R.selectedFloorId!==this._lastSelectedFloorId||A){const F=R.floors.findIndex(V=>V.id===R.selectedFloorId);if(F!==-1){const V=R.floors.length;let Z,X;V<=5?(Z=0,X=V-1):this._visibleFloorStart===0?(Z=0,X=3):this._visibleFloorStart>=V-3?(Z=V-3-1,X=V-1):(Z=this._visibleFloorStart,X=this._visibleFloorStart+3-1),FX&&(this._visibleFloorStart=F-2)}}this._lastSelectedFloorId=R.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const R=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);y("span","mapboxgl-ctrl-icon",R).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||R.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(R);const w=this._model.floors,A=w.length;if(A<=5)return void w.forEach(X=>this._createFloorButton(X));const F=this._visibleFloorStart===0,V=this._visibleFloorStart>=A-3;if(F)this._createFloorButton(w[0]);else{const X=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);y("span","mapboxgl-ctrl-icon",X).setAttribute("aria-hidden","true"),this._container.appendChild(X)}let Z=[];if(Z=F?w.slice(1,4):V?w.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):w.slice(this._visibleFloorStart,this._visibleFloorStart+3),Z.forEach(X=>this._createFloorButton(X)),V)this._createFloorButton(w[A-1]);else{const X=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);y("span","mapboxgl-ctrl-icon",X).setAttribute("aria-hidden","true"),this._container.appendChild(X)}}_createFloorButton(R){const w=this._createButton("mapboxgl-ctrl-level-button",()=>{const Z=R.id;this._model&&this._model.selectedFloorId===Z&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(Z))}),A=(R.name||"").trim(),F=R.zIndex.toString(),V=A?Array.from(A).slice(0,3).join(""):F;this._setButtonTitle(w,V),this._model&&this._model.activeFloorsVisible&&R.id===this._model.selectedFloorId&&w.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(w)}_toggleIndoor(){this._map&&this._map.style&&this._map.style.indoorManager&&this._model&&this._model.activeFloorsVisible&&this._map.style.indoorManager.setActiveFloorsVisibility(!1)}_scrollUp(){if(this._visibleFloorStart>0){this._visibleFloorStart--,this._visibleFloorStart===1&&(this._visibleFloorStart=0);const R=this._model&&this._model.floors||[];if(R.length>3){const w=R.length-3;this._visibleFloorStart===w-1&&(this._visibleFloorStart=w-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const R=this._model.floors.length-3;this._visibleFloorStartR&&(this._visibleFloorStart=R),this._render())}}},Popup:class extends o.E{constructor(R){super(),this.options=Object.assign(Object.create(W6),R),this._altitude=this.options.altitude,o.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(R&&R.className?R.className.trim().split(/\s+/):[])}addTo(R){return this._map&&this.remove(),this._map=R,this.options.closeOnClick&&R.on("preclick",this._onClose),this.options.closeOnMove&&R.on("move",this._onClose),R.on("remove",this.remove),this._update(),R._addPopup(this),this._focusFirstElement(),this._trackPointer?(R.on("mousemove",this._onMouseEvent),R.on("mouseup",this._onMouseEvent),R._canvasContainer.classList.add("mapboxgl-track-pointer")):R.on("move",this._update),this.fire(new o.C("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const R=this._map;return R&&(R.off("move",this._update),R.off("move",this._onClose),R.off("preclick",this._onClose),R.off("click",this._onClose),R.off("remove",this.remove),R.off("mousemove",this._onMouseEvent),R.off("mouseup",this._onMouseEvent),R.off("drag",this._onMouseEvent),R._canvasContainer&&R._canvasContainer.classList.remove("mapboxgl-track-pointer"),R._removePopup(this),this._map=void 0),this.fire(new o.C("close")),this}getLngLat(){return this._lngLat}setLngLat(R){this._lngLat=o.aU.convert(R),this._pos=null,this._trackPointer=!1,this._update();const w=this._map;return w&&(w.on("move",this._update),w.off("mousemove",this._onMouseEvent),w._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(R){return this._altitude=R,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const R=this._map;return R&&(R.off("move",this._update),R.on("mousemove",this._onMouseEvent),R.on("drag",this._onMouseEvent),R._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(R){return this.setDOMContent(document.createTextNode(R))}setHTML(R){const w=document.createDocumentFragment(),A=document.createElement("body");let F;for(A.innerHTML=R;F=A.firstChild,F;)w.appendChild(F);return this.setDOMContent(w)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(R){return this.options.maxWidth=R,this._update(),this}setDOMContent(R){let w=this._content;if(w)for(;w.hasChildNodes();)w.firstChild&&w.removeChild(w.firstChild);else w=this._content=y("div","mapboxgl-popup-content",this._container||void 0);if(w.appendChild(R),this.options.closeButton){const A=this._closeButton=y("button","mapboxgl-popup-close-button",w);A.type="button",A.setAttribute("aria-label","Close popup"),A.innerHTML='',A.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(R){return this._classList.add(R),this._updateClassList(),this}removeClassName(R){return this._classList.delete(R),this._updateClassList(),this}setOffset(R){return this.options.offset=R,this._update(),this}toggleClassName(R){let w;return this._classList.delete(R)?w=!1:(this._classList.add(R),w=!0),this._updateClassList(),w}_onMouseEvent(R){this._update(R.point)}_getAnchor(R){if(this.options.anchor)return this.options.anchor;const w=this._map,A=this._container,F=this._pos;if(!w||!A||!F)return"bottom";const V=A.offsetWidth,Z=A.offsetHeight,X=F.xw.transform.width-V/2;if(F.y+Rw.transform.height-Z){if(X)return"bottom-left";if(ae)return"bottom-right"}return X?"left":ae?"right":"bottom"}_updateClassList(){const R=this._container;if(!R)return;const w=[...this._classList];w.push("mapboxgl-popup"),this._anchor&&w.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&w.push("mapboxgl-popup-track-pointer"),R.className=w.join(" ")}_update(R){const w=this._map,A=this._content;if(!w||!this._lngLat&&!this._trackPointer||!A)return;let F=this._container;if(F||(F=this._container=y("div","mapboxgl-popup",w.getContainer()),this._tip=y("div","mapboxgl-popup-tip",F),F.appendChild(A)),this.options.maxWidth&&F.style.maxWidth!==this.options.maxWidth&&(F.style.maxWidth=this.options.maxWidth),w.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=uV(this._lngLat,this._pos,w.transform)),!this._trackPointer||R){const V=this._pos=this._trackPointer&&R instanceof o.P?R:w.project(this._lngLat,this._altitude),Z=tF(this.options.offset),X=this._anchor=this._getAnchor(Z.y),ae=tF(this.options.offset,X),pe=V.add(ae).round();w._requestDomTask(()=>{this._container&&X&&(this._container.style.transform=`${H6[X]} translate(${pe.x}px,${pe.y}px)`)})}if(!this._marker&&w._showingGlobe()){const V=o.e$(w.transform,this._lngLat)?0:1;this._setOpacity(V)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const R=this._container.querySelector(UTe);R&&R.focus()}_onClose(){this.remove()}_setOpacity(R){this._container&&(this._container.style.opacity=`${R}`),this._content&&(this._content.style.pointerEvents=R?"auto":"none")}},Marker:O1,Style:yu,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:b0,Evented:o.E,config:o.g,prewarm:function(){zt().acquire(rt)},clearPrewarmedResources:function(){const R=Dt;R&&(R.isPreloaded()&&R.numActive()===1?(R.release(rt),Dt=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"))},get accessToken(){return o.g.ACCESS_TOKEN},set accessToken(R){o.g.ACCESS_TOKEN=R},get baseApiUrl(){return o.g.API_URL},set baseApiUrl(R){o.g.API_URL=R},get workerCount(){return Fe.workerCount},set workerCount(R){Fe.workerCount=R},get maxParallelImageRequests(){return o.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(R){o.g.MAX_PARALLEL_IMAGE_REQUESTS=R},clearStorage(R){o.f7(R)},get workerUrl(){return Ye.workerUrl},set workerUrl(R){Ye.workerUrl=R},get workerClass(){return Ye.workerClass},set workerClass(R){Ye.workerClass=R},get workerParams(){return Ye.workerParams},set workerParams(R){Ye.workerParams=R},get dracoUrl(){return o.f6()},set dracoUrl(R){o.g.DRACO_URL=o.o.resolveURL(R)},get meshoptUrl(){return o.f5()},set meshoptUrl(R){const w=o.o.resolveURL(R);o.g.MESHOPT_URL=w,o.g.MESHOPT_SIMD_URL=w},get buildingGenUrl(){return o.f4()},set buildingGenUrl(R){o.g.BUILDING_GEN_URL=o.o.resolveURL(R)},setNow:o.o.setNow,restoreNow:o.o.restoreNow}});var l=a;return l})})(e5t);var xcs=e5t.exports;const $c=sd(xcs),ent={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},tnt={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 gcs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function ycs({listings:s,isLoading:t}){const n=Hn(),r=j.useRef(null),a=j.useRef(null),i=j.useRef([]),[l,o]=j.useState(""),[c,d]=j.useState(!0);return j.useEffect(()=>{(async()=>{d(!0);try{const{data:m}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();m!=null&&m.value&&o(m.value)}catch(m){console.error("Error fetching mapbox token:",m)}d(!1)})()},[]),j.useEffect(()=>{if(!r.current||!l||a.current)return;$c.accessToken=l;const h=s.filter(x=>x.latitude!=null&&x.longitude!=null);let m=[-98.5795,39.8283],p=4;if(h.length>0){const x=h.reduce((g,b)=>g+b.longitude,0)/h.length,y=h.reduce((g,b)=>g+b.latitude,0)/h.length;m=[x,y],p=h.length===1?12:10}return a.current=new $c.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:p,center:m}),a.current.addControl(new $c.NavigationControl,"top-right"),()=>{var x;(x=a.current)==null||x.remove(),a.current=null}},[l]),j.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(m=>m.remove()),i.current=[];const h=s.filter(m=>m.latitude!=null&&m.longitude!=null);if(h.forEach(m=>{var C,T,M;const p=ent[m.status]||"#10B981",x=((C=m.photos)==null?void 0:C.find(P=>P.is_primary))||((T=m.photos)==null?void 0:T[0]),g=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${m.slug||m.id}`:`/public/listing/${m.slug||m.id}`,b=document.createElement("div");b.className="cursor-pointer",b.innerHTML=`
`;const v=new $c.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${x!=null&&x.photo_url?``:""}
${gcs(m.price)}
${m.property_address||""}
${m.city}, ${m.state}
${tnt[m.status]||m.status} ${m.bedrooms?`${m.bedrooms} bed`:""} ${m.bathrooms?`${m.bathrooms} bath`:""}
${(M=m.agent)!=null&&M.name?`
Listed by ${m.agent.name}
`:""}
Click to view details →
`),k=new $c.Marker(b).setLngLat([m.longitude,m.latitude]).setPopup(v).addTo(a.current);i.current.push(k)}),h.length>1){const m=new $c.LngLatBounds;h.forEach(p=>m.extend([p.longitude,p.latitude])),a.current.fitBounds(m,{padding:60,maxZoom:13})}else h.length===1&&a.current.flyTo({center:[h[0].longitude,h[0].latitude],zoom:12})},[s,l]),j.useEffect(()=>(window.__navigateToPublicListing__=h=>{n(h)},()=>{delete window.__navigateToPublicListing__}),[n]),c||t?e.jsx(gn,{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(ent).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:tnt[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const wMe={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},vcs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},OF="#0d0d0d",snt="#1a1a1a",Qc="#c9a84c",MC="#f0d78c";function s5t(){const[s,t]=j.useState(""),[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(-1),u=j.useRef(null),[h,m]=j.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:p}=ccs(),x=j.useMemo(()=>{if(!p)return[];const $=s.trim().toLowerCase(),q=[...p.cities.map(G=>({label:G.label,value:G.city,type:"city",count:G.count})),...p.neighborhoods.map(G=>({label:G.label,value:G.neighborhood,type:"neighborhood",count:G.count})),...p.zips.map(G=>({label:`ZIP ${G.label}`,value:G.zip,type:"zip",count:G.count}))];return($?q.filter(G=>G.label.toLowerCase().includes($)||G.value.toLowerCase().includes($)):q).slice(0,8)},[p,s]);j.useEffect(()=>{const $=q=>{u.current&&!u.current.contains(q.target)&&o(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[]);const{data:y,isLoading:g}=lcs({city:s||void 0,status:h.status||void 0,propertyType:h.propertyType||void 0,minPrice:h.minPrice?Number(h.minPrice):void 0,maxPrice:h.maxPrice?Number(h.maxPrice):void 0}),b=$=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format($),v=()=>{m({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},k=s||h.status||h.propertyType||h.minPrice||h.maxPrice,C=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),T=$=>C?`/${$.slug||$.id}`:`/public/listing/${$.slug||$.id}`,{featured:M,restListings:P,luxeCount:L,cities:I,activeCount:O}=j.useMemo(()=>{const $=y||[],q=$.filter(je=>je.status==="active"),W=q.length>0?q:$,G=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[K,ee,J]=G.split("-").map(Number),le=Math.floor(Date.UTC(K,ee-1,J)/864e5),ue=W.length>0?W[le%W.length]:void 0,oe=$.filter(je=>!ue||je.id!==ue.id),ie=Array.from(new Set($.map(je=>je.city).filter(Boolean))).slice(0,8),de=$.filter(je=>(je.price||0)>=1e6).length,we=q.length;return{featured:ue,restListings:oe,luxeCount:de,cities:ie,activeCount:we}},[y]);return e.jsxs(e.Fragment,{children:[e.jsxs(ql,{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:OF,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: ${Qc}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Qc}, 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(Yn,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:CNe,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(Yn,{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 ${Qc}`,color:Qc},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 ${Qc}`,color:Qc},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(dr,{className:"w-5 h-5"}):e.jsx(YT,{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(Yn,{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 ${Qc}`,color:Qc},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:fcs,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:Qc}}),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:MC},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 ${Qc}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:Qc}}),e.jsx(ye,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:$=>{t($.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:$=>{if(!(!l||x.length===0))if($.key==="ArrowDown")$.preventDefault(),d(q=>Math.min(q+1,x.length-1));else if($.key==="ArrowUp")$.preventDefault(),d(q=>Math.max(q-1,0));else if($.key==="Enter"&&c>=0){$.preventDefault();const q=x[c];t(q.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(sE,{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:Qc,color:OF},onClick:()=>o(!1),children:[e.jsx(Fr,{className:"h-5 w-5"}),e.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),l&&x.length>0&&e.jsxs("div",{className:"mt-2 rounded-2xl overflow-hidden shadow-2xl animate-fade-in",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.35)",backdropFilter:"blur(12px)"},children:[e.jsx("div",{className:"px-5 pt-3 pb-2 text-[10px] tracking-[0.2em] uppercase",style:{color:Qc},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:x.map(($,q)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(q),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===q?"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(oi,{className:"h-4 w-4 shrink-0",style:{color:Qc}}),$.type==="neighborhood"&&e.jsx(Ni,{className:"h-4 w-4 shrink-0",style:{color:Qc}}),$.type==="zip"&&e.jsx(ia,{className:"h-4 w-4 shrink-0",style:{color:Qc}}),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}-${q}`))})]}),l&&s.trim()&&x.length===0&&e.jsx("div",{className:"mt-2 rounded-2xl px-5 py-4 text-sm text-white/70",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.25)"},children:"No matches yet — try a nearby city or ZIP."}),n&&e.jsxs("div",{className:"mt-4 p-6 rounded-2xl grid sm:grid-cols-2 md:grid-cols-4 gap-4 animate-fade-in",style:{background:"rgba(26,26,26,0.9)",border:"1px solid rgba(201,168,76,0.25)"},children:[e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),e.jsxs(vs,{value:h.status||"all",onValueChange:$=>m({...h,status:$==="all"?"":$}),children:[e.jsx(gs,{className:"lu-input-dark",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"Any status"}),Object.entries(wMe).map(([$,q])=>e.jsx(Je,{value:$,children:q},$))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(vs,{value:h.propertyType||"all",onValueChange:$=>m({...h,propertyType:$==="all"?"":$}),children:[e.jsx(gs,{className:"lu-input-dark",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"Any type"}),Object.entries(vcs).map(([$,q])=>e.jsx(Je,{value:$,children:q},$))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),e.jsx(ye,{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(ye,{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:v,className:"text-white/70 hover:text-white gap-1",children:[e.jsx(dr,{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:O.toString()},{label:"Luxury $1M+",value:L.toString()}].map($=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:MC},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(Po,{className:"h-4 w-4 animate-bounce"})]})]})]}),I.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:snt,borderTop:"1px solid rgba(201,168,76,0.15)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:e.jsx("div",{className:"lu-marquee whitespace-nowrap",children:[...I,...I,...I].map(($,q)=>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:Qc}})]},q))})}),M&&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(yn,{className:"h-4 w-4",style:{color:Qc}}),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:MC},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(Yn,{to:T(M),className:"group block",children:e.jsxs("div",{className:"grid lg:grid-cols-5 gap-6 lg:gap-10 items-stretch",children:[e.jsxs("div",{className:"lg:col-span-3 relative overflow-hidden rounded-2xl aspect-[4/3] bg-black",children:[(()=>{var q,W;const $=((q=M.photos)==null?void 0:q.find(G=>G.is_primary))||((W=M.photos)==null?void 0:W[0]);return $?e.jsx("img",{src:$.photo_url,alt:M.property_address||M.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(ia,{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:Qc,color:OF},children:wMe[M.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(oi,{className:"h-3.5 w-3.5",style:{color:Qc}}),M.city,M.state?`, ${M.state}`:""]}),M.property_address&&e.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:M.property_address}),e.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:MC},children:b(M.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[M.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(U_,{className:"h-4 w-4",style:{color:Qc}}),M.bedrooms," bd"]}),M.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(t0,{className:"h-4 w-4",style:{color:Qc}}),M.bathrooms," ba"]}),M.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(H_,{className:"h-4 w-4",style:{color:Qc}}),M.square_footage.toLocaleString()," sf"]})]}),M.description&&e.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:M.description}),e.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:Qc},children:["View Residence ",e.jsx(Xa,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:snt},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:Qc}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:Qc}})]}),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:MC},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."})]}),g?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map(($,q)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(gn,{className:"aspect-[4/5] bg-white/5"}),e.jsx(gn,{className:"h-6 w-32 bg-white/5"}),e.jsx(gn,{className:"h-4 w-full bg-white/5"})]},q))}):P.length>0?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:P.map($=>{var W,G,K,ee,J;const q=((W=$.photos)==null?void 0:W.find(le=>le.is_primary))||((G=$.photos)==null?void 0:G[0]);return e.jsxs(Yn,{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:[q?e.jsx("img",{src:q.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(ia,{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:Qc,border:`1px solid ${Qc}`},children:wMe[$.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(oi,{className:"h-3 w-3",style:{color:Qc}}),$.city,$.state?`, ${$.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:MC},children:b($.price)}),$.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:$.property_address}),((K=$.agent)==null?void 0:K.name)&&e.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[e.jsx(Ni,{className:"h-3 w-3"}),$.agent.name,(((ee=$.agent.brokerage)==null?void 0:ee.name)||$.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((J=$.agent.brokerage)==null?void 0:J.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 ${Qc}`},children:e.jsx(ia,{className:"h-8 w-8",style:{color:Qc}})}),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:v,style:{background:Qc,color:OF},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:Qc}}),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:MC},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(ycs,{listings:y,isLoading:g})})]})}),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%, ${OF} 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:Qc}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:Qc}})]}),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:MC},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:Qc,color:OF},children:["Explore LevelUp",e.jsx(Xa,{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:CNe,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(cls,{}),e.jsx(dls,{})]})}const bcs=j.lazy(()=>Mi(()=>import("./PublicHomeValue-CNwoNg98.js"),[]));function _cs(){const s=$d(),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(s5t,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(j.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(bcs,{})}):r.startsWith("public/")?null:e.jsx(Jkt,{slugOverride:r})}function u3e({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 n5t=s=>mt({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:n}=await U.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(n)throw n;const{data:r}=await U.from("profiles").select("name, email, phone, brokerage_id").eq("id",t.user_id).single();let a=null;if(r!=null&&r.brokerage_id){const{data:o}=await U.from("brokerages").select("name").eq("id",r.brokerage_id).single();a=(o==null?void 0:o.name)||null}let i=null;try{const{data:o}=await U.from("profiles").select("avatar_url").eq("id",t.user_id).single();if(o!=null&&o.avatar_url)i=o.avatar_url;else{const{data:c}=await U.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=U.storage.from("avatars").getPublicUrl(`${t.user_id}/${c[0].name}`);i=`${d.publicUrl}?t=${Date.now()}`}}}catch{}const l={...r||{name:null,email:null,phone:null,brokerage_id:null},email:t.display_email||(r==null?void 0:r.email)||null};return{...t,social_links:t.social_links||[],profile:l,brokerage_name:t.brokerage_display_name||a,avatar_url:i}},enabled:!!s}),wcs=()=>mt({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await U.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),jcs=s=>mt({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),r5t=()=>{const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("agent_cards").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),re.success("Agent card created")},onError:t=>re.error(t.message)})},a5t=()=>{const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("agent_cards").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),re.success("Agent card updated")},onError:t=>re.error(t.message)})},Uc=async(s,t,n,r)=>{const a=new URLSearchParams(window.location.search);await U.from("agent_card_interactions").insert({card_id:s,interaction_type:t,interaction_detail:n||null,referrer:document.referrer||null,user_agent:navigator.userAgent||null,utm_source:a.get("utm_source")||null,utm_medium:a.get("utm_medium")||null,utm_campaign:a.get("utm_campaign")||null,metadata:{}})},Ncs=async(s,t)=>{const{error:n}=await U.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},i5t=s=>mt({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",s).order("created_at",{ascending:!1}).limit(500);if(n)throw n;const{data:r,error:a}=await U.from("agent_card_leads").select("*").eq("card_id",s).order("created_at",{ascending:!1});if(a)throw a;const i=(t==null?void 0:t.filter(c=>c.interaction_type==="card_view").length)||0,l=(t==null?void 0:t.filter(c=>c.interaction_type==="button_click").length)||0,o=(t==null?void 0:t.filter(c=>c.interaction_type==="contact_saved").length)||0;return{views:i,clicks:l,saves:o,leads:r||[],interactions:t||[]}},enabled:!!s});function h3e({open:s,onOpenChange:t,cardId:n,type:r,agentName:a}){const[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(""),[y,g]=j.useState(!1),b=async v=>{if(v.preventDefault(),!i.trim()){re.error("Please enter your name");return}g(!0);try{await Ncs(n,{lead_type:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:p.trim()||void 0,intent:h||void 0}),Uc(n,"lead_submitted",r),U.functions.invoke("card-lead-notify",{body:{cardId:n,leadType:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:p.trim()||void 0,intent:h||void 0}}).catch(k=>console.error("Card lead notify failed:",k)),re.success(r==="booking"?"Request sent! They'll be in touch soon.":r==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),u(""),m(""),x("")}catch{re.error("Something went wrong. Please try again.")}finally{g(!1)}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs($s,{children:[e.jsx(zs,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(kr,{children:r==="booking"?`Let ${a} know you'd like to connect.`:r==="connect"?`Share your info and ${a} will reach out.`:`Know someone who could use ${a}'s help?`})]}),e.jsxs("form",{onSubmit:b,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-name",children:"Name *"}),e.jsx(ye,{id:"lead-name",value:i,onChange:v=>l(v.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(ye,{id:"lead-phone",type:"tel",value:d,onChange:v=>u(v.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-email",children:"Email"}),e.jsx(ye,{id:"lead-email",type:"email",value:o,onChange:v=>c(v.target.value),placeholder:"you@example.com"})]}),r==="booking"&&e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"buy",children:"Buy a home"}),e.jsx(Je,{value:"sell",children:"Sell my home"}),e.jsx(Je,{value:"both",children:"Buy & Sell"}),e.jsx(Je,{value:"other",children:"Something else"})]})]})]}),r!=="connect"&&e.jsxs("div",{children:[e.jsx(se,{htmlFor:"lead-message",children:r==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(ye,{id:"lead-message",value:p,onChange:v=>x(v.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(B,{type:"submit",className:"w-full rounded-2xl",disabled:y,children:y?"Sending...":"Submit"})]})]})})}const kcs=s=>mt({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("card_blocks").select("*").eq("card_id",s).eq("is_visible",!0).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),Scs=s=>mt({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),Ccs=()=>{const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("card_blocks").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["card-blocks",n.card_id]}),s.invalidateQueries({queryKey:["card-blocks-all",n.card_id]}),re.success("Block added")},onError:t=>re.error(t.message)})},Acs=()=>{const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("card_blocks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),re.success("Block updated")},onError:t=>re.error(t.message)})},Tcs=()=>{const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("card_blocks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),re.success("Block removed")},onError:t=>re.error(t.message)})};function Ecs(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 Mcs(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 Lcs={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 Pcs({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=Mcs(n.video_url),i=r||!!a,l=r?Ecs(n.video_url):a||n.video_url;return e.jsx("div",{className:Lcs[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 Ics={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 Rcs({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=j.useState(0);if(r.length===0)return null;const l=Ics[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(yN,{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(Cc,{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 Dcs={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 Ocs({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=Dcs[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const Fcs={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 zcs({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=Fcs[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:()=>Uc(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 YDe={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 Bcs({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 $cs={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 Ucs({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=$cs[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=YDe[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Uc(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(Bcs,{path:c.icon,color:c.color})},o)})})]})}function m3e({cardId:s,variant:t}){const{data:n}=kcs(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(Pcs,{block:l,variant:t},l.id);case"testimonials":return e.jsx(Rcs,{block:l,variant:t},l.id);case"specialties":return e.jsx(Ocs,{block:l,variant:t},l.id);case"custom_links":return e.jsx(zcs,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(Ucs,{block:i,cardId:s,variant:t})]})}async function qcs(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 Vcs(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 p3e(s){const{first:t,last:n}=Vcs(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 qcs(s.avatarUrl);if(o){const d={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[o.mimeType]||"JPEG";r.push(`PHOTO;ENCODING=b;TYPE=${d}:${o.base64}`)}}r.push("END:VCARD");const a=new Blob([r.join(`\r `)],{type:"text/vcard"}),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=`${s.name.replace(/\s+/g,"_")}.vcf`,l.click(),URL.revokeObjectURL(i),re.success("Contact saved!")}function Hcs({card:s}){var b;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((b=s.profile)==null?void 0:b.name)||"Agent",l=i.split(" ").map(v=>v[0]).join("").toUpperCase().slice(0,2),o=(v,k)=>{Uc(s.id,"button_click",v),k()},c=()=>o("call",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),d=()=>o("text",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),u=()=>o("email",()=>{var v;(v=s.profile)!=null&&v.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Uc(s.id,"button_click","book"))},m=()=>{var v,k;Uc(s.id,"contact_saved"),p3e({name:i,phone:(v=s.profile)==null?void 0:v.phone,email:(k=s.profile)==null?void 0:k.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Uc(s.id,"share_event");const v=`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:v})}catch{}else await navigator.clipboard.writeText(v),re.success("Link copied!")},x=()=>{a("referral"),n(!0),Uc(s.id,"button_click","refer")},y=()=>{a("connect"),n(!0),Uc(s.id,"button_click","connect")},g={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(Ra,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Fi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Da,{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(pa,{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(ro,{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(on,{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(ra,{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(u3e,{card:s,variant:"standard"}),e.jsx(m3e,{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(ii,{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:()=>{Uc(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:x,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Bn,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(B,{variant:"ghost",onClick:y,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Sl,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs(B,{variant:"ghost",onClick:p,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(zd,{className:"h-4 w-4 mr-3 text-primary"}),"Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((v,k)=>e.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Uc(s.id,"button_click",`social_${v.platform}`),className:"h-10 w-10 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-lg transition-colors",children:g[v.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(h3e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function Gcs({card:s}){var b;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((b=s.profile)==null?void 0:b.name)||"Agent",l=i.split(" ").map(v=>v[0]).join("").toUpperCase().slice(0,2),o=(v,k)=>{Uc(s.id,"button_click",v),k()},c=()=>o("call",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),d=()=>o("text",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),u=()=>o("email",()=>{var v;(v=s.profile)!=null&&v.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Uc(s.id,"button_click","book"))},m=()=>{var v,k;Uc(s.id,"contact_saved"),p3e({name:i,phone:(v=s.profile)==null?void 0:v.phone,email:(k=s.profile)==null?void 0:k.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Uc(s.id,"share_event");const v=`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:v})}catch{}else await navigator.clipboard.writeText(v),re.success("Link copied!")},x=()=>{a("referral"),n(!0),Uc(s.id,"button_click","refer")},y=()=>{a("connect"),n(!0),Uc(s.id,"button_click","connect")},g={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(Ra,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(Fi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Da,{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:pa,label:"Call",handler:c},{icon:ro,label:"Text",handler:d},{icon:on,label:"Email",handler:u}].map(({icon:v,label:k,handler:C})=>e.jsxs("button",{onClick:C,className:"flex flex-col items-center gap-1.5 py-4 bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/20 rounded-xl transition-colors",children:[e.jsx(v,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children: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(ra,{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(u3e,{card:s,variant:"luxury"}),e.jsx(m3e,{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(ii,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Uc(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:x,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Bn,{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(Sl,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(zd,{className:"h-4 w-4 text-[#c9a84c]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((v,k)=>e.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Uc(s.id,"button_click",`social_${v.platform}`),className:"h-10 w-10 rounded-full bg-[#1e2636] border border-[#c9a84c]/20 hover:border-[#c9a84c]/50 flex items-center justify-center text-lg transition-colors",children:g[v.platform.toLowerCase()]||"🔗"},k))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(h3e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function Wcs({card:s}){var k,C,T,M;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((k=s.profile)==null?void 0:k.name)||"Agent",l=i.split(" ").map(P=>P[0]).join("").toUpperCase().slice(0,2),o={accent:((C=s.bold_theme_colors)==null?void 0:C.accent)||"#ff5722",dark:((T=s.bold_theme_colors)==null?void 0:T.dark)||"#1a1a2e",button:((M=s.bold_theme_colors)==null?void 0:M.button)||"#ff5722"},c=(P,L)=>{const I=parseInt(P.replace("#",""),16),O=Math.max(0,(I>>16)-L),$=Math.max(0,(I>>8&255)-L),q=Math.max(0,(I&255)-L);return`#${(O<<16|$<<8|q).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(P,L)=>{Uc(s.id,"button_click",P),L()},u=()=>d("call",()=>{var P;(P=s.profile)!=null&&P.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),h=()=>d("text",()=>{var P;(P=s.profile)!=null&&P.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),m=()=>d("email",()=>{var P;(P=s.profile)!=null&&P.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),p=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Uc(s.id,"button_click","book"))},x=()=>{var P,L;Uc(s.id,"contact_saved"),p3e({name:i,phone:(P=s.profile)==null?void 0:P.phone,email:(L=s.profile)==null?void 0:L.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},y=async()=>{Uc(s.id,"share_event");const P=`https://cards.relevelup.com/${s.slug}`,L="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:L,url:P})}catch{}else await navigator.clipboard.writeText(P),re.success("Link copied!")},g=()=>{a("referral"),n(!0),Uc(s.id,"button_click","refer")},b=()=>{a("connect"),n(!0),Uc(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen",style:{backgroundColor:o.accent},children:[e.jsxs("div",{className:"px-5 pt-10 pb-14 text-center relative",style:{backgroundColor:o.dark},children:[s.show_photo&&e.jsxs(Ra,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(Fi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Da,{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:pa,label:"Call",handler:u},{icon:ro,label:"Text",handler:h},{icon:on,label:"Email",handler:m}].map(({icon:P,label:L,handler:I})=>e.jsxs("button",{onClick:I,className:"flex flex-col items-center gap-1.5 py-4 text-white rounded-2xl transition-opacity font-bold hover:opacity-85",style:{backgroundColor:o.dark},children:[e.jsx(P,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:L})]},L))}),e.jsxs("button",{onClick:p,className:"w-full h-14 text-base font-black rounded-2xl mb-6 text-white transition-opacity hover:opacity-90 flex items-center justify-center gap-2 uppercase tracking-wide",style:{backgroundColor:o.button},children:[e.jsx(ra,{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(u3e,{card:s,variant:"bold"}),e.jsx(m3e,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:x,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(ii,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Uc(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: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(Bn,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:b,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Sl,{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(zd,{className:"h-4 w-4",style:{color:o.accent}})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-6",children:s.social_links.slice(0,3).map((P,L)=>e.jsx("a",{href:P.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Uc(s.id,"button_click",`social_${P.platform}`),className:"h-10 w-10 rounded-full flex items-center justify-center text-lg transition-opacity hover:opacity-85",style:{backgroundColor:o.dark},children:v[P.platform.toLowerCase()]||"🔗"},L))})]}),e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),e.jsx(h3e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function Kcs({card:s}){var b;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((b=s.profile)==null?void 0:b.name)||"Agent",l=i.split(" ").map(v=>v[0]).join("").toUpperCase().slice(0,2),o=(v,k)=>{Uc(s.id,"button_click",v),k()},c=()=>o("call",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),d=()=>o("text",()=>{var v;(v=s.profile)!=null&&v.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),u=()=>o("email",()=>{var v;(v=s.profile)!=null&&v.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Uc(s.id,"button_click","book"))},m=()=>{var v,k;Uc(s.id,"contact_saved"),p3e({name:i,phone:(v=s.profile)==null?void 0:v.phone,email:(k=s.profile)==null?void 0:k.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Uc(s.id,"share_event");const v=`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:v})}catch{}else await navigator.clipboard.writeText(v),re.success("Link copied!")},x=()=>{a("referral"),n(!0),Uc(s.id,"button_click","refer")},y=()=>{a("connect"),n(!0),Uc(s.id,"button_click","connect")},g={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(Ra,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(Fi,{src:s.avatar_url||void 0,alt:i}),e.jsx(Da,{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:pa,label:"Call",handler:c},{icon:ro,label:"Text",handler:d},{icon:on,label:"Email",handler:u}].map(({icon:v,label:k,handler:C})=>e.jsxs("button",{onClick:C,className:"flex flex-col items-center gap-1.5 py-4 bg-white hover:bg-[#e8e3db] border border-[#d4cfc5] rounded-lg transition-colors shadow-sm",children:[e.jsx(v,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children: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(ra,{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(u3e,{card:s,variant:"classic"}),e.jsx(m3e,{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(ii,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Uc(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:x,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Bn,{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(Sl,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(zd,{className:"h-4 w-4 text-[#5a7a6f]"})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-8",children:s.social_links.slice(0,3).map((v,k)=>e.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Uc(s.id,"button_click",`social_${v.platform}`),className:"h-10 w-10 rounded-full bg-white border border-[#d4cfc5] hover:bg-[#e8e3db] flex items-center justify-center text-lg transition-colors shadow-sm",children:g[v.platform.toLowerCase()]||"🔗"},k))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(h3e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function rqe({card:s}){switch(s.theme){case"luxury":return e.jsx(Gcs,{card:s});case"bold":return e.jsx(Wcs,{card:s});case"classic":return e.jsx(Kcs,{card:s});case"standard":default:return e.jsx(Hcs,{card:s})}}function Ycs(){const s=$d();j.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Agent Cards"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific agent's card URL to view their digital business card."})]})}):e.jsx(Zcs,{slug:t})}function Zcs({slug:s}){return e.jsx(Xcs,{slug:s})}function Xcs({slug:s}){var i;const{data:t,isLoading:n,error:r}=n5t(s);if(j.useEffect(()=>{t!=null&&t.id&&Uc(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(gn,{className:"h-28 w-28 rounded-full"}),e.jsx(gn,{className:"h-6 w-48"}),e.jsx(gn,{className:"h-4 w-36"})]}),e.jsx(gn,{className:"h-12 w-full"}),e.jsx(gn,{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(ql,{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(rqe,{card:t})]})}function o5t({presentationId:s,ctaLabel:t,agentName:n,prefillName:r,prefillEmail:a,prefillPhone:i}){const[l,o]=j.useState(r||""),[c,d]=j.useState(a||""),[u,h]=j.useState(i||""),[m,p]=j.useState(""),[x,y]=j.useState(""),[g,b]=j.useState(!1),[v,k]=j.useState(!1),C=async T=>{if(T.preventDefault(),!l.trim()){re.error("Please enter your name");return}b(!0);try{const{error:M}=await U.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:m||null,message:x.trim()||null});if(M)throw M;try{await U.rpc("log_presentation_view",{p_presentation_id:s,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}U.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:u.trim()||void 0,intent:m||void 0,message:x.trim()||void 0}}).catch(P=>console.error("Presentation lead notify failed:",P)),k(!0)}catch{re.error("Something went wrong. Please try again.")}finally{b(!1)}};return v?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-4",children:e.jsx(da,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),e.jsx("p",{className:"text-gray-500",children:n?`${n} will be in touch soon.`:"We'll be in touch soon."})]}):e.jsxs("form",{onSubmit:C,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(ye,{id:"pres-lead-name",value:l,onChange:T=>o(T.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(ye,{id:"pres-lead-phone",type:"tel",value:u,onChange:T=>h(T.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(ye,{id:"pres-lead-email",type:"email",value:c,onChange:T=>d(T.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(vs,{value:m,onValueChange:p,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"buy",children:"Buy a home"}),e.jsx(Je,{value:"sell",children:"Sell my home"}),e.jsx(Je,{value:"both",children:"Buy & Sell"}),e.jsx(Je,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(ye,{id:"pres-lead-message",value:x,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:g,children:g?"Sending...":t})]})}function Qcs(){const s=$d();j.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Smart Presentations"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific presentation URL to view it."})]})}):e.jsx(Jcs,{shareToken:t})}function Jcs({shareToken:s}){var x;const[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(0),[o,c]=j.useState(!1);j.useEffect(()=>{d()},[s]);const d=async()=>{const{data:y,error:g}=await U.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(g||!y){c(!0),a(!1);return}const{data:b}=await U.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",y.owner_user_id).single();let v;if(b!=null&&b.brokerage_id){const{data:C}=await U.from("brokerages").select("name").eq("id",b.brokerage_id).single();v=(C==null?void 0:C.name)||void 0}let k=null;if(y.contact_id){const{data:C}=await U.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",y.contact_id).single();k=C}n({...y,owner_name:b==null?void 0:b.name,owner_email:b==null?void 0:b.email,owner_phone:b==null?void 0:b.phone,owner_avatar:b==null?void 0:b.avatar_url,owner_title:(b==null?void 0:b.title)||void 0,brokerage_name:v,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 U.rpc("log_presentation_view",{p_presentation_id:y.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await U.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}},h=y=>{const g=y.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(g)return`https://www.youtube.com/embed/${g[1]}?rel=0`;if(y.includes("iframe.mediadelivery.net/play/")){const k=y.replace("/play/","/embed/"),C=k.includes("?")?"&":"?";return`${k}${C}responsive=true`}if(y.includes("iframe.mediadelivery.net")){const k=y.includes("?")?"&":"?";return`${y}${k}responsive=true`}const b=y.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(b)return`https://www.loom.com/embed/${b[1]}`;const v=y.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return v?`https://iframe.mediadelivery.net/embed/${v[1]}/${v[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(gn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(gn,{className:"h-64 w-full"}),e.jsx(gn,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const m=t.sections.filter(y=>y.is_visible!==!1),p=m[i];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[p!=null&&p.video_url?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:h(p.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):p!=null&&p.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:p.image_url,alt:p.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:p==null?void 0:p.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:p==null?void 0:p.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:p==null?void 0:p.description})]}),(p==null?void 0:p.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:m.map((y,g)=>e.jsx("button",{onClick:()=>l(g),className:Et("w-full text-left p-4 rounded-xl border transition-all",i===g?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(g+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children: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})]})]})},g))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(x=t.cta_url)!=null&&x.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(o5t,{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 Hj=()=>{const s=ei();return mt({queryKey:["user-team",s],queryFn:async()=>{const{data:t,error:n}=await U.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 U.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 eds(){const{user:s}=Ns(),t=ei(),{data:n}=Hj();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 U.from("open_houses").select("*").eq("agent_id",t).order("event_date",{ascending:!1});if(a)throw a;let i=r||[];if((n==null?void 0:n.role)==="team_leader"&&n.teamId){const{data:l,error:o}=await U.rpc("get_team_open_houses",{_user_id:t});if(!o&&l){const c=[...new Set(l.map(h=>h.agent_id))],d={};if(c.length>0){const{data:h}=await U.from("profiles").select("id, name").in("id",c);h==null||h.forEach(m=>{m.name&&(d[m.id]=m.name)})}const u=l.map(h=>({...h,agent_name:d[h.agent_id]||void 0}));i=[...i,...u]}}return i.sort((l,o)=>o.event_date.localeCompare(l.event_date)),i},enabled:!!s&&!!t})}function fBn(s){const{user:t}=Ns();return mt({queryKey:["open-house",s],queryFn:async()=>{const{data:n,error:r}=await U.from("open_houses").select("*").eq("id",s).single();if(r)throw r;return n},enabled:!!t&&!!s})}function l5t(s){const{user:t}=Ns(),n=as();return j.useEffect(()=>{if(!s)return;const r=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=U.channel(r).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${s}`},()=>{n.invalidateQueries({queryKey:["open-house-visitors",s]}),n.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{U.removeChannel(a)}},[s,n]),mt({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:r,error:a}=await U.from("open_house_visitors").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(a)throw a;return r},enabled:!!t&&!!s})}function tds(){const s=as(),t=ei();return vt({mutationFn:async n=>{const{data:r,error:a}=await U.from("open_houses").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),ba({title:"Open house created!"})},onError:n=>{ba({title:"Error",description:n.message,variant:"destructive"})}})}function c5t(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{error:r}=await U.from("open_houses").update(n).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-houses"]}),s.invalidateQueries({queryKey:["open-house",n.id]})}})}function sds(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("open_houses").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),ba({title:"Open house deleted"})}})}function nds(s){return mt({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:n}=await U.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",s).eq("is_active",!0).single();if(n)throw n;let r=null;if(t.agent_id){const{data:a}=await U.from("agent_cards").select("slug").eq("user_id",t.agent_id).eq("is_published",!0).maybeSingle();a&&(r=a.slug)}return{...t,agent_card_slug:r}},enabled:!!s})}function rds(s){const{user:t}=Ns();return mt({queryKey:["survey-questions",s],queryFn:async()=>{const{data:n,error:r}=await U.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;return n},enabled:!!t&&!!s})}function ads(s){return mt({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:n}=await U.from("open_house_survey_questions").select("*").eq("open_house_id",s).eq("is_active",!0).order("sort_order");if(n)throw n;return t},enabled:!!s})}function ids(){return vt({mutationFn:async s=>{const{error:t}=await U.from("open_house_survey_responses").insert(s);if(t)throw t}})}function ods(s){const{user:t}=Ns();return mt({queryKey:["survey-responses",s],queryFn:async()=>{const{data:n,error:r}=await U.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;const a=(n||[]).map(o=>o.id);if(a.length===0)return{questions:[],responses:[]};const{data:i,error:l}=await U.from("open_house_survey_responses").select("*").in("question_id",a).order("created_at",{ascending:!1});if(l)throw l;return{questions:n,responses:i||[]}},enabled:!!t&&!!s})}function lds(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("open_house_survey_questions").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function cds(){const s=as();return vt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await U.from("open_house_survey_questions").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function dds(){const s=as();return vt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await U.from("open_house_survey_questions").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function uds(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.rpc("seed_default_survey_questions",{_open_house_id:t});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n]})}})}function hds(){return vt({mutationFn:async s=>{const{data:t,error:n}=await U.from("open_house_visitors").insert(s).select("id").single();if(n)throw n;return t}})}function mds(){return vt({mutationFn:async({visitor_id:s,...t})=>{const{error:n}=await U.from("open_house_visitors").update(t).eq("id",s);if(n)throw n}})}function pds(){return vt({mutationFn:async s=>{await U.rpc("increment_open_house_scan",{_slug:s})}})}async function d5t(s){const{data:t,error:n}=await U.from("open_house_rooms").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(c=>c.id),{data:i,error:l}=await U.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var u;const d=c;(o[u=d.room_id]||(o[u]=[])).push(d)}),r.map(c=>({...c,media:o[c.id]||[]}))}function fds(s){const{user:t}=Ns();return mt({queryKey:["open-house-rooms",s],queryFn:()=>d5t(s),enabled:!!t&&!!s})}function xds(s){return mt({queryKey:["public-open-house-rooms",s],queryFn:()=>d5t(s),enabled:!!s})}function gds(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("open_house_rooms").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function yds(){const s=as();return vt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await U.from("open_house_rooms").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function vds(){const s=as();return vt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await U.from("open_house_rooms").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function bds(){const s=as();return vt({mutationFn:async({open_house_id:t,...n})=>{const{data:r,error:a}=await U.from("open_house_room_media").insert(n).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function _ds(){const s=as();return vt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await U.from("open_house_room_media").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function wds(s){const{user:t}=Ns();return mt({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:n,error:r}=await U.from("open_house_leads").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n||[]},enabled:!!t&&!!s})}function jds(){const s=as();return vt({mutationFn:async({id:t,status:n,open_house_id:r})=>{const{error:a}=await U.from("open_house_leads").update({status:n}).eq("id",t);if(a)throw a;return{open_house_id:r}},onSuccess:t=>{s.invalidateQueries({queryKey:["open-house-leads",t.open_house_id]})}})}var f3e="Switch",[Nds,xBn]=Zm(f3e),[kds,Sds]=Nds(f3e),u5t=j.forwardRef((s,t)=>{const{__scopeSwitch:n,name:r,checked:a,defaultChecked:i,required:l,disabled:o,value:c="on",onCheckedChange:d,form:u,...h}=s,[m,p]=j.useState(null),x=ko(t,k=>p(k)),y=j.useRef(!1),g=m?u||!!m.closest("form"):!0,[b,v]=Mx({prop:a,defaultProp:i??!1,onChange:d,caller:f3e});return e.jsxs(kds,{scope:n,checked:b,disabled:o,children:[e.jsx(Ua.button,{type:"button",role:"switch","aria-checked":b,"aria-required":l,"data-state":f5t(b),"data-disabled":o?"":void 0,disabled:o,value:c,...h,ref:x,onClick:ua(s.onClick,k=>{v(C=>!C),g&&(y.current=k.isPropagationStopped(),y.current||k.stopPropagation())})}),g&&e.jsx(p5t,{control:m,bubbles:!y.current,name:r,value:c,checked:b,required:l,disabled:o,form:u,style:{transform:"translateX(-100%)"}})]})});u5t.displayName=f3e;var h5t="SwitchThumb",m5t=j.forwardRef((s,t)=>{const{__scopeSwitch:n,...r}=s,a=Sds(h5t,n);return e.jsx(Ua.span,{"data-state":f5t(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});m5t.displayName=h5t;var Cds="SwitchBubbleInput",p5t=j.forwardRef(({__scopeSwitch:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=j.useRef(null),o=ko(l,i),c=xJ(n),d=iJ(t);return j.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&p){const x=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(x)}},[c,n,r]),e.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});p5t.displayName=Cds;function f5t(s){return s?"checked":"unchecked"}var x5t=u5t,Ads=m5t;const Mn=j.forwardRef(({className:s,...t},n)=>e.jsx(x5t,{className:Et("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(Ads,{className:Et("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")})}));Mn.displayName=x5t.displayName;function Vi(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 Hu(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function jd(s,t){const n=Vi(s);return isNaN(t)?Hu(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function Ax(s,t){const n=Vi(s);if(isNaN(t))return Hu(s,NaN);if(!t)return n;const r=n.getDate(),a=Hu(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 g5t(s,t){const n=+Vi(s);return Hu(s,n+t)}const aqe=6048e5,Tds=864e5,x3e=6e4,g3e=36e5,Eds=1e3,_se=43200,nnt=1440;function rnt(s,t){return g5t(s,t*g3e)}let Mds={};function t6(){return Mds}function xg(s,t){var o,c,d,u;const n=t6(),r=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,a=Vi(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function xm(s){const t=Vi(s);return t.setHours(0,0,0,0),t}function EE(s){const t=Vi(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 Ky(s,t){const n=xm(s),r=xm(t),a=+n-EE(n),i=+r-EE(r);return Math.round((a-i)/Tds)}function Lds(s){const t=y5t(s),n=Hu(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),B3(n)}function ant(s,t){return g5t(s,t*x3e)}function i3(s,t){const n=t*7;return jd(s,n)}function Pds(s,t){return Ax(s,t*12)}function Ids(s){let t;return s.forEach(function(n){const r=Vi(n);(t===void 0||t{const r=Vi(n);(!t||t>r||isNaN(+r))&&(t=r)}),t||new Date(NaN)}function mje(s,t){const n=Vi(s),r=Vi(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function y3e(s){return Hu(s,Date.now())}function pd(s,t){const n=xm(s),r=xm(t);return+n==+r}function iqe(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function ZDe(s){if(!iqe(s)&&typeof s!="number")return!1;const t=Vi(s);return!isNaN(Number(t))}function y$(s,t){const n=Vi(s),r=Vi(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function Dds(s,t,n){const r=xg(s,n),a=xg(t,n),i=+r-EE(r),l=+a-EE(a);return Math.round((i-l)/aqe)}function Fj(s,t){const n=Vi(s),r=Vi(t),a=int(n,r),i=Math.abs(Ky(n,r));n.setDate(n.getDate()-a*i);const l=+(int(n,r)===-a),o=a*(i-l);return o===0?0:o}function int(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 Ods(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function Fds(s,t){return+Vi(s)-+Vi(t)}function zds(s){const t=Vi(s);return t.setHours(23,59,59,999),t}function Uv(s){const t=Vi(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function Bds(s){const t=Vi(s);return+zds(t)==+Uv(t)}function $ds(s,t){const n=Vi(s),r=Vi(t),a=mje(n,r),i=Math.abs(y$(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=mje(n,r)===-a;Bds(Vi(s))&&i===1&&mje(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function Uds(s,t,n){const r=Fds(s,t)/1e3;return Ods(n==null?void 0:n.roundingMethod)(r)}function XDe(s,t){const n=Vi(s.start),r=Vi(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(Vi(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function Vu(s){const t=Vi(s);return t.setDate(1),t.setHours(0,0,0,0),t}function v5t(s){const t=Vi(s),n=Hu(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function v$(s,t){var o,c,d,u;const n=t6(),r=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,a=Vi(s),i=a.getDay(),l=(i{let r;const a=qds[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 jMe(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const Hds={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Gds={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Wds={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Kds={date:jMe({formats:Hds,defaultWidth:"full"}),time:jMe({formats:Gds,defaultWidth:"full"}),dateTime:jMe({formats:Wds,defaultWidth:"full"})},Yds={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Zds=(s,t,n,r)=>Yds[s];function pH(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 Xds={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Qds={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Jds={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"]},eus={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"]},tus={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"}},sus={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"}},nus=(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"},rus={ordinalNumber:nus,era:pH({values:Xds,defaultWidth:"wide"}),quarter:pH({values:Qds,defaultWidth:"wide",argumentCallback:s=>s-1}),month:pH({values:Jds,defaultWidth:"wide"}),day:pH({values:eus,defaultWidth:"wide"}),dayPeriod:pH({values:tus,defaultWidth:"wide",formattingValues:sus,defaultFormattingWidth:"wide"})};function fH(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)?ius(o,h=>h.test(l)):aus(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 aus(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function ius(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 lus=/^(\d+)(th|st|nd|rd)?/i,cus=/\d+/i,dus={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},uus={any:[/^b/i,/^(a|c)/i]},hus={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},mus={any:[/1/i,/2/i,/3/i,/4/i]},pus={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},fus={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]},xus={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},gus={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]},yus={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},vus={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}},bus={ordinalNumber:ous({matchPattern:lus,parsePattern:cus,valueCallback:s=>parseInt(s,10)}),era:fH({matchPatterns:dus,defaultMatchWidth:"wide",parsePatterns:uus,defaultParseWidth:"any"}),quarter:fH({matchPatterns:hus,defaultMatchWidth:"wide",parsePatterns:mus,defaultParseWidth:"any",valueCallback:s=>s+1}),month:fH({matchPatterns:pus,defaultMatchWidth:"wide",parsePatterns:fus,defaultParseWidth:"any"}),day:fH({matchPatterns:xus,defaultMatchWidth:"wide",parsePatterns:gus,defaultParseWidth:"any"}),dayPeriod:fH({matchPatterns:yus,defaultMatchWidth:"any",parsePatterns:vus,defaultParseWidth:"any"})},v3e={code:"en-US",formatDistance:Vds,formatLong:Kds,formatRelative:Zds,localize:rus,match:bus,options:{weekStartsOn:0,firstWeekContainsDate:1}};function _us(s){const t=Vi(s);return Ky(t,v5t(t))+1}function oqe(s){const t=Vi(s),n=+B3(t)-+Lds(t);return Math.round(n/aqe)+1}function lqe(s,t){var u,h,m,p;const n=Vi(s),r=n.getFullYear(),a=t6(),i=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??a.firstWeekContainsDate??((p=(m=a.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??1,l=Hu(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=xg(l,t),c=Hu(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=xg(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function wus(s,t){var o,c,d,u;const n=t6(),r=(t==null?void 0:t.firstWeekContainsDate)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.firstWeekContainsDate)??n.firstWeekContainsDate??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.firstWeekContainsDate)??1,a=lqe(s,t),i=Hu(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),xg(i,t)}function cqe(s,t){const n=Vi(s),r=+xg(n,t)-+wus(n,t);return Math.round(r/aqe)+1}function $u(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const LC={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return $u(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):$u(n+1,2)},d(s,t){return $u(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 $u(s.getHours()%12||12,t.length)},H(s,t){return $u(s.getHours(),t.length)},m(s,t){return $u(s.getMinutes(),t.length)},s(s,t){return $u(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return $u(a,t.length)}},FF={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},ont={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 LC.y(s,t)},Y:function(s,t,n,r){const a=lqe(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return $u(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):$u(i,t.length)},R:function(s,t){const n=y5t(s);return $u(n,t.length)},u:function(s,t){const n=s.getFullYear();return $u(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 $u(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 $u(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 LC.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 $u(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=cqe(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):$u(a,t.length)},I:function(s,t,n){const r=oqe(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):$u(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):LC.d(s,t)},D:function(s,t,n){const r=_us(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):$u(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 $u(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 $u(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 $u(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=FF.noon:r===0?a=FF.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=FF.evening:r>=12?a=FF.afternoon:r>=4?a=FF.morning:a=FF.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 LC.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):LC.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):$u(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):$u(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):LC.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):LC.s(s,t)},S:function(s,t){return LC.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return cnt(r);case"XXXX":case"XX":return EI(r);case"XXXXX":case"XXX":default:return EI(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return cnt(r);case"xxxx":case"xx":return EI(r);case"xxxxx":case"xxx":default:return EI(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+lnt(r,":");case"OOOO":default:return"GMT"+EI(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+lnt(r,":");case"zzzz":default:return"GMT"+EI(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return $u(r,t.length)},T:function(s,t,n){const r=s.getTime();return $u(r,t.length)}};function lnt(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+$u(i,2)}function cnt(s,t){return s%60===0?(s>0?"-":"+")+$u(Math.abs(s)/60,2):EI(s,t)}function EI(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=$u(Math.trunc(r/60),2),i=$u(r%60,2);return n+a+t+i}const dnt=(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"})}},_5t=(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"})}},jus=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return dnt(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}}",dnt(r,t)).replace("{{time}}",_5t(a,t))},QDe={p:_5t,P:jus},Nus=/^D+$/,kus=/^Y+$/,Sus=["D","DD","YY","YYYY"];function w5t(s){return Nus.test(s)}function j5t(s){return kus.test(s)}function JDe(s,t,n){const r=Cus(s,t,n);if(console.warn(r),Sus.includes(s))throw new RangeError(r)}function Cus(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 Aus=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Tus=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Eus=/^'([^]*?)'?$/,Mus=/''/g,Lus=/[a-zA-Z]/;function Bs(s,t,n){var u,h,m,p,x,y,g,b;const r=t6(),a=(n==null?void 0:n.locale)??r.locale??v3e,i=(n==null?void 0:n.firstWeekContainsDate)??((h=(u=n==null?void 0:n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??r.firstWeekContainsDate??((p=(m=r.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??1,l=(n==null?void 0:n.weekStartsOn)??((y=(x=n==null?void 0:n.locale)==null?void 0:x.options)==null?void 0:y.weekStartsOn)??r.weekStartsOn??((b=(g=r.locale)==null?void 0:g.options)==null?void 0:b.weekStartsOn)??0,o=Vi(s);if(!ZDe(o))throw new RangeError("Invalid time value");let c=t.match(Tus).map(v=>{const k=v[0];if(k==="p"||k==="P"){const C=QDe[k];return C(v,a.formatLong)}return v}).join("").match(Aus).map(v=>{if(v==="''")return{isToken:!1,value:"'"};const k=v[0];if(k==="'")return{isToken:!1,value:Pus(v)};if(ont[k])return{isToken:!0,value:v};if(k.match(Lus))throw new RangeError("Format string contains an unescaped latin alphabet character `"+k+"`");return{isToken:!1,value:v}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(v=>{if(!v.isToken)return v.value;const k=v.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&j5t(k)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&w5t(k))&&JDe(k,t,String(s));const C=ont[k[0]];return C(o,k,a.localize,d)}).join("")}function Pus(s){const t=s.match(Eus);return t?t[1].replace(Mus,"'"):s}function Ius(s,t,n){const r=t6(),a=(n==null?void 0:n.locale)??r.locale??v3e,i=2520,l=mje(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=Vi(t),d=Vi(s)):(c=Vi(s),d=Vi(t));const u=Uds(d,c),h=(EE(d)-EE(c))/1e3,m=Math.round((u-h)/60);let p;if(m<2)return n!=null&&n.includeSeconds?u<5?a.formatDistance("lessThanXSeconds",5,o):u<10?a.formatDistance("lessThanXSeconds",10,o):u<20?a.formatDistance("lessThanXSeconds",20,o):u<40?a.formatDistance("halfAMinute",0,o):u<60?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",1,o):m===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",m,o);if(m<45)return a.formatDistance("xMinutes",m,o);if(m<90)return a.formatDistance("aboutXHours",1,o);if(mr.getTime()}function W_(s,t){const n=Vi(s),r=Vi(t);return+n<+r}function $us(s){return+Vi(s)>Date.now()}function Uus(s,t){const n=t instanceof Date?Hu(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 qus=10;class N5t{constructor(){Ar(this,"subPriority",0)}validate(t,n){return!0}}class Vus extends N5t{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 Hus extends N5t{constructor(){super(...arguments);Ar(this,"priority",qus);Ar(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:Hu(n,Uus(n,Date))}}class mu{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new Vus(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class Gus extends mu{constructor(){super(...arguments);Ar(this,"priority",140);Ar(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 Jf={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}/},f5={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 ex(s,t){return s&&{value:t(s.value),rest:s.rest}}function Lp(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function x5(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*g3e+i*x3e+l*Eds),rest:t.slice(n[0].length)}}function k5t(s){return Lp(Jf.anyDigitsSigned,s)}function kf(s,t){switch(s){case 1:return Lp(Jf.singleDigit,t);case 2:return Lp(Jf.twoDigits,t);case 3:return Lp(Jf.threeDigits,t);case 4:return Lp(Jf.fourDigits,t);default:return Lp(new RegExp("^\\d{1,"+s+"}"),t)}}function ANe(s,t){switch(s){case 1:return Lp(Jf.singleDigitSigned,t);case 2:return Lp(Jf.twoDigitsSigned,t);case 3:return Lp(Jf.threeDigitsSigned,t);case 4:return Lp(Jf.fourDigitsSigned,t);default:return Lp(new RegExp("^-?\\d{1,"+s+"}"),t)}}function dqe(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 S5t(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 C5t(s){return s%400===0||s%4===0&&s%100!==0}class Wus extends mu{constructor(){super(...arguments);Ar(this,"priority",130);Ar(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 ex(kf(4,n),i);case"yo":return ex(a.ordinalNumber(n,{unit:"year"}),i);default:return ex(kf(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=S5t(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 Kus extends mu{constructor(){super(...arguments);Ar(this,"priority",130);Ar(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 ex(kf(4,n),i);case"Yo":return ex(a.ordinalNumber(n,{unit:"year"}),i);default:return ex(kf(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=lqe(n,i);if(a.isTwoDigitYear){const c=S5t(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),xg(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),xg(n,i)}}class Yus extends mu{constructor(){super(...arguments);Ar(this,"priority",130);Ar(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return ANe(r==="R"?4:r.length,n)}set(n,r,a){const i=Hu(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),B3(i)}}class Zus extends mu{constructor(){super(...arguments);Ar(this,"priority",130);Ar(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return ANe(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class Xus extends mu{constructor(){super(...arguments);Ar(this,"priority",120);Ar(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 kf(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 Qus extends mu{constructor(){super(...arguments);Ar(this,"priority",120);Ar(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 kf(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 Jus extends mu{constructor(){super(...arguments);Ar(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);Ar(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return ex(Lp(Jf.month,n),i);case"MM":return ex(kf(2,n),i);case"Mo":return ex(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 ehs extends mu{constructor(){super(...arguments);Ar(this,"priority",110);Ar(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 ex(Lp(Jf.month,n),i);case"LL":return ex(kf(2,n),i);case"Lo":return ex(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 ths(s,t,n){const r=Vi(s),a=cqe(r,n)-t;return r.setDate(r.getDate()-a*7),r}class shs extends mu{constructor(){super(...arguments);Ar(this,"priority",100);Ar(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return Lp(Jf.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return kf(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return xg(ths(n,a,i),i)}}function nhs(s,t){const n=Vi(s),r=oqe(n)-t;return n.setDate(n.getDate()-r*7),n}class rhs extends mu{constructor(){super(...arguments);Ar(this,"priority",100);Ar(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 Lp(Jf.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return kf(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return B3(nhs(n,a))}}const ahs=[31,28,31,30,31,30,31,31,30,31,30,31],ihs=[31,29,31,30,31,30,31,31,30,31,30,31];class ohs extends mu{constructor(){super(...arguments);Ar(this,"priority",90);Ar(this,"subPriority",1);Ar(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return Lp(Jf.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return kf(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=C5t(a),l=n.getMonth();return i?r>=1&&r<=ihs[l]:r>=1&&r<=ahs[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class lhs extends mu{constructor(){super(...arguments);Ar(this,"priority",90);Ar(this,"subpriority",1);Ar(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 Lp(Jf.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return kf(r.length,n)}}validate(n,r){const a=n.getFullYear();return C5t(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 uqe(s,t,n){var h,m,p,x;const r=t6(),a=(n==null?void 0:n.weekStartsOn)??((m=(h=n==null?void 0:n.locale)==null?void 0:h.options)==null?void 0:m.weekStartsOn)??r.weekStartsOn??((x=(p=r.locale)==null?void 0:p.options)==null?void 0:x.weekStartsOn)??0,i=Vi(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 jd(i,u)}class chs extends mu{constructor(){super(...arguments);Ar(this,"priority",90);Ar(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=uqe(n,a,i),n.setHours(0,0,0,0),n}}class dhs extends mu{constructor(){super(...arguments);Ar(this,"priority",90);Ar(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 ex(kf(r.length,n),l);case"eo":return ex(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=uqe(n,a,i),n.setHours(0,0,0,0),n}}class uhs extends mu{constructor(){super(...arguments);Ar(this,"priority",90);Ar(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 ex(kf(r.length,n),l);case"co":return ex(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=uqe(n,a,i),n.setHours(0,0,0,0),n}}function hhs(s,t){const n=Vi(s),r=Ous(n),a=t-r;return jd(n,a)}class mhs extends mu{constructor(){super(...arguments);Ar(this,"priority",90);Ar(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 kf(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return ex(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 ex(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return ex(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return ex(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=hhs(n,a),n.setHours(0,0,0,0),n}}class phs extends mu{constructor(){super(...arguments);Ar(this,"priority",80);Ar(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(dqe(a),0,0,0),n}}class fhs extends mu{constructor(){super(...arguments);Ar(this,"priority",80);Ar(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(dqe(a),0,0,0),n}}class xhs extends mu{constructor(){super(...arguments);Ar(this,"priority",80);Ar(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(dqe(a),0,0,0),n}}class ghs extends mu{constructor(){super(...arguments);Ar(this,"priority",70);Ar(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return Lp(Jf.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return kf(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 yhs extends mu{constructor(){super(...arguments);Ar(this,"priority",70);Ar(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return Lp(Jf.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return kf(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class vhs extends mu{constructor(){super(...arguments);Ar(this,"priority",70);Ar(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return Lp(Jf.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return kf(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 bhs extends mu{constructor(){super(...arguments);Ar(this,"priority",70);Ar(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return Lp(Jf.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return kf(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 _hs extends mu{constructor(){super(...arguments);Ar(this,"priority",60);Ar(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return Lp(Jf.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return kf(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class whs extends mu{constructor(){super(...arguments);Ar(this,"priority",50);Ar(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return Lp(Jf.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return kf(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class jhs extends mu{constructor(){super(...arguments);Ar(this,"priority",30);Ar(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return ex(kf(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class Nhs extends mu{constructor(){super(...arguments);Ar(this,"priority",10);Ar(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return x5(f5.basicOptionalMinutes,n);case"XX":return x5(f5.basic,n);case"XXXX":return x5(f5.basicOptionalSeconds,n);case"XXXXX":return x5(f5.extendedOptionalSeconds,n);case"XXX":default:return x5(f5.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Hu(n,n.getTime()-EE(n)-a)}}class khs extends mu{constructor(){super(...arguments);Ar(this,"priority",10);Ar(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return x5(f5.basicOptionalMinutes,n);case"xx":return x5(f5.basic,n);case"xxxx":return x5(f5.basicOptionalSeconds,n);case"xxxxx":return x5(f5.extendedOptionalSeconds,n);case"xxx":default:return x5(f5.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Hu(n,n.getTime()-EE(n)-a)}}class Shs extends mu{constructor(){super(...arguments);Ar(this,"priority",40);Ar(this,"incompatibleTokens","*")}parse(n){return k5t(n)}set(n,r,a){return[Hu(n,a*1e3),{timestampIsSet:!0}]}}class Chs extends mu{constructor(){super(...arguments);Ar(this,"priority",20);Ar(this,"incompatibleTokens","*")}parse(n){return k5t(n)}set(n,r,a){return[Hu(n,a),{timestampIsSet:!0}]}}const Ahs={G:new Gus,y:new Wus,Y:new Kus,R:new Yus,u:new Zus,Q:new Xus,q:new Qus,M:new Jus,L:new ehs,w:new shs,I:new rhs,d:new ohs,D:new lhs,E:new chs,e:new dhs,c:new uhs,i:new mhs,a:new phs,b:new fhs,B:new xhs,h:new ghs,H:new yhs,K:new vhs,k:new bhs,m:new _hs,s:new whs,S:new jhs,X:new Nhs,x:new khs,t:new Shs,T:new Chs},Ths=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Ehs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Mhs=/^'([^]*?)'?$/,Lhs=/''/g,Phs=/\S/,Ihs=/[a-zA-Z]/;function hqe(s,t,n,r){var y,g,b,v;const a=Dus(),i=a.locale??v3e,l=a.firstWeekContainsDate??((g=(y=a.locale)==null?void 0:y.options)==null?void 0:g.firstWeekContainsDate)??1,o=a.weekStartsOn??((v=(b=a.locale)==null?void 0:b.options)==null?void 0:v.weekStartsOn)??0;if(t==="")return s===""?Vi(n):Hu(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new Hus],u=t.match(Ehs).map(k=>{const C=k[0];if(C in QDe){const T=QDe[C];return T(k,i.formatLong)}return k}).join("").match(Ths),h=[];for(let k of u){j5t(k)&&JDe(k,t,s),w5t(k)&&JDe(k,t,s);const C=k[0],T=Ahs[C];if(T){const{incompatibleTokens:M}=T;if(Array.isArray(M)){const L=h.find(I=>M.includes(I.token)||I.token===C);if(L)throw new RangeError(`The format string mustn't contain \`${L.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:C,fullToken:k});const P=T.run(s,k,i.match,c);if(!P)return Hu(n,NaN);d.push(P.setter),s=P.rest}else{if(C.match(Ihs))throw new RangeError("Format string contains an unescaped latin alphabet character `"+C+"`");if(k==="''"?k="'":C==="'"&&(k=Rhs(k)),s.indexOf(k)===0)s=s.slice(k.length);else return Hu(n,NaN)}}if(s.length>0&&Phs.test(s))return Hu(n,NaN);const m=d.map(k=>k.priority).sort((k,C)=>C-k).filter((k,C,T)=>T.indexOf(k)===C).map(k=>d.filter(C=>C.priority===k).sort((C,T)=>T.subPriority-C.subPriority)).map(k=>k[0]);let p=Vi(n);if(isNaN(p.getTime()))return Hu(n,NaN);const x={};for(const k of m){if(!k.validate(p,c))return Hu(n,NaN);const C=k.set(p,x,c);Array.isArray(C)?(p=C[0],Object.assign(x,C[1])):p=C}return Hu(n,p)}function Rhs(s){return s.match(Mhs)[1].replace(Lhs,"'")}function F5(s){return+Vi(s)i-l);return n>=r&&n<=a}function kK(s,t){return jd(s,-t)}function Ep(s,t){const r=qhs(s);let a;if(r.date){const c=Vhs(r.date,2);a=Hhs(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=Ghs(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=Whs(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 wse={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},Bhs=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,$hs=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,Uhs=/^([+-])(\d{2})(?::?(\d{2}))?$/;function qhs(s){const t={},n=s.split(wse.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],wse.timeZoneDelimiter.test(t.date)&&(t.date=s.split(wse.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=wse.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function Vhs(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 Hhs(s,t){if(t===null)return new Date(NaN);const n=s.match(Bhs);if(!n)return new Date(NaN);const r=!!n[4],a=xH(n[1]),i=xH(n[2])-1,l=xH(n[3]),o=xH(n[4]),c=xH(n[5])-1;if(r)return Qhs(t,o,c)?Khs(t,o,c):new Date(NaN);{const d=new Date(0);return!Zhs(t,i,l)||!Xhs(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function xH(s){return s?parseInt(s):1}function Ghs(s){const t=s.match($hs);if(!t)return NaN;const n=NMe(t[1]),r=NMe(t[2]),a=NMe(t[3]);return Jhs(n,r,a)?n*g3e+r*x3e+a*1e3:NaN}function NMe(s){return s&&parseFloat(s.replace(",","."))||0}function Whs(s){if(s==="Z")return 0;const t=s.match(Uhs);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return ems(r,a)?n*(r*g3e+a*x3e):NaN}function Khs(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 Yhs=[31,null,31,30,31,30,31,31,30,31,30,31];function A5t(s){return s%400===0||s%4===0&&s%100!==0}function Zhs(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(Yhs[t]||(A5t(s)?29:28))}function Xhs(s,t){return t>=1&&t<=(A5t(s)?366:365)}function Qhs(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function Jhs(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function ems(s,t){return t>=0&&t<=59}function kMe(s,t){const n=Vi(s),r=n.getFullYear(),a=n.getDate(),i=Hu(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=Rus(i);return n.setMonth(t,Math.min(a,l)),n}function T5t(s,t){const n=Vi(s);return n.setHours(t),n}function E5t(s,t){const n=Vi(s);return n.setMinutes(t),n}function hnt(s,t){const n=Vi(s);return isNaN(+n)?Hu(s,NaN):(n.setFullYear(t),n)}function e8(s,t){return Ax(s,-t)}var mnt;function na(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 wz extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class M5t extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(mnt=globalThis).__zod_globalConfig??(mnt.__zod_globalConfig={});const mqe=globalThis.__zod_globalConfig;function TD(s){return mqe}function L5t(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 eOe(s,t){return typeof t=="bigint"?t.toString():t}function pqe(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function fqe(s){return s==null}function xqe(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function tms(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 TNe(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const nms=pqe(()=>{var s;if(mqe.jitless||typeof navigator<"u"&&((s=navigator==null?void 0:navigator.userAgent)!=null&&s.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function QY(s){if(TNe(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(TNe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function I5t(s){return QY(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const rms=new Set(["string","number","symbol"]);function b$(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function n6(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 Ro(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 ams(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const ims={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 oms(s,t){const n=s._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=s6(s._zod.def,{get shape(){const l={};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(l[o]=n.shape[o])}return xO(this,"shape",l),l},checks:[]});return n6(s,i)}function lms(s,t){const n=s._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=s6(s._zod.def,{get shape(){const l={...s._zod.def.shape};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete l[o]}return xO(this,"shape",l),l},checks:[]});return n6(s,i)}function cms(s,t){if(!QY(t))throw new Error("Invalid input to extend: expected a plain object");const n=s._zod.def.checks;if(n&&n.length>0){const i=s._zod.def.shape;for(const l in t)if(Object.getOwnPropertyDescriptor(i,l)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const a=s6(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t};return xO(this,"shape",i),i}});return n6(s,a)}function dms(s,t){if(!QY(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=s6(s._zod.def,{get shape(){const r={...s._zod.def.shape,...t};return xO(this,"shape",r),r}});return n6(s,n)}function ums(s,t){var r;if((r=s._zod.def.checks)!=null&&r.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=s6(s._zod.def,{get shape(){const a={...s._zod.def.shape,...t._zod.def.shape};return xO(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return n6(s,n)}function hms(s,t,n){const a=t._zod.def.checks;if(a&&a.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const l=s6(t._zod.def,{get shape(){const o=t._zod.def.shape,c={...o};if(n)for(const d in n){if(!(d in o))throw new Error(`Unrecognized key: "${d}"`);n[d]&&(c[d]=s?new s({type:"optional",innerType:o[d]}):o[d])}else for(const d in o)c[d]=s?new s({type:"optional",innerType:o[d]}):o[d];return xO(this,"shape",c),c},checks:[]});return n6(t,l)}function mms(s,t,n){const r=s6(t._zod.def,{get shape(){const a=t._zod.def.shape,i={...a};if(n)for(const l in n){if(!(l in i))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(i[l]=new s({type:"nonoptional",innerType:a[l]}))}else for(const l in a)i[l]=new s({type:"nonoptional",innerType:a[l]});return xO(this,"shape",i),i}});return n6(t,r)}function i9(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 jse(s){return typeof s=="string"?s:s==null?void 0:s.message}function ED(s,t,n){var c,d,u,h,m,p;const r=s.message?s.message:jse((u=(d=(c=s.inst)==null?void 0:c._zod.def)==null?void 0:d.error)==null?void 0:u.call(d,s))??jse((h=t==null?void 0:t.error)==null?void 0:h.call(t,s))??jse((m=n.customError)==null?void 0:m.call(n,s))??jse((p=n.localeError)==null?void 0:p.call(n,s))??"Invalid input",{inst:a,continue:i,input:l,...o}=s;return o.path??(o.path=[]),o.message=r,t!=null&&t.reportInput&&(o.input=l),o}function gqe(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function JY(...s){const[t,n,r]=s;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const D5t=(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,eOe,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},O5t=na("$ZodError",D5t),F5t=na("$ZodError",D5t,{Parent:Error});function fms(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 xms(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 wz;if(l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>ED(c,i,TD())));throw P5t(o,a==null?void 0:a.callee),o}return l.value},vqe=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=>ED(c,i,TD())));throw P5t(o,a==null?void 0:a.callee),o}return l.value},b3e=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 wz;return i.issues.length?{success:!1,error:new(s??O5t)(i.issues.map(l=>ED(l,a,TD())))}:{success:!0,data:i.value}},gms=b3e(F5t),_3e=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=>ED(l,a,TD())))}:{success:!0,data:i.value}},yms=_3e(F5t),vms=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return yqe(s)(t,n,a)},bms=s=>(t,n,r)=>yqe(s)(t,n,r),_ms=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return vqe(s)(t,n,a)},wms=s=>async(t,n,r)=>vqe(s)(t,n,r),jms=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return b3e(s)(t,n,a)},Nms=s=>(t,n,r)=>b3e(s)(t,n,r),kms=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return _3e(s)(t,n,a)},Sms=s=>async(t,n,r)=>_3e(s)(t,n,r),Cms=/^[cC][0-9a-z]{6,}$/,Ams=/^[0-9a-z]+$/,Tms=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ems=/^[0-9a-vA-V]{20}$/,Mms=/^[A-Za-z0-9]{27}$/,Lms=/^[a-zA-Z0-9_-]{21}$/,Pms=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ims=/^([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})$/,xnt=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)$/,Rms=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Dms="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Oms(){return new RegExp(Dms,"u")}const Fms=/^(?:(?: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])$/,zms=/^(([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}|:))$/,Bms=/^((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])$/,$ms=/^(([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])$/,Ums=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,z5t=/^[A-Za-z0-9_-]*$/,qms=/^https?$/,Vms=/^\+[1-9]\d{6,14}$/,B5t="(?:(?:\\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])))",Hms=new RegExp(`^${B5t}$`);function $5t(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 Gms(s){return new RegExp(`^${$5t(s)}$`)}function Wms(s){const t=$5t({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(`^${B5t}T(?:${r})$`)}const Kms=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}$`)},Yms=/^-?\d+$/,Zms=/^-?\d+(?:\.\d+)?$/,Xms=/^(?:true|false)$/i,Qms=/^[^A-Z]*$/,Jms=/^[^a-z]*$/,Mb=na("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),U5t={number:"number",bigint:"bigint",object:"date"},q5t=na("$ZodCheckLessThan",(s,t)=>{Mb.init(s,t);const n=U5t[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{Mb.init(s,t);const n=U5t[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})}}),eps=na("$ZodCheckMultipleOf",(s,t)=>{Mb.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):tms(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})}}),tps=na("$ZodCheckNumberFormat",(s,t)=>{var l;Mb.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]=ims[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=Yms)}),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})}}),sps=na("$ZodCheckMaxLength",(s,t)=>{var n;Mb.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!fqe(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=gqe(a);r.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),nps=na("$ZodCheckMinLength",(s,t)=>{var n;Mb.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!fqe(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=gqe(a);r.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),rps=na("$ZodCheckLengthEquals",(s,t)=>{var n;Mb.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!fqe(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=gqe(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})}}),w3e=na("$ZodCheckStringFormat",(s,t)=>{var n,r;Mb.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=()=>{})}),aps=na("$ZodCheckRegex",(s,t)=>{w3e.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})}}),ips=na("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=Qms),w3e.init(s,t)}),ops=na("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=Jms),w3e.init(s,t)}),lps=na("$ZodCheckIncludes",(s,t)=>{Mb.init(s,t);const n=b$(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})}}),cps=na("$ZodCheckStartsWith",(s,t)=>{Mb.init(s,t);const n=new RegExp(`^${b$(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})}}),dps=na("$ZodCheckEndsWith",(s,t)=>{Mb.init(s,t);const n=new RegExp(`.*${b$(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})}}),ups=na("$ZodCheckOverwrite",(s,t)=>{Mb.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class hps{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 mps={major:4,minor:4,patch:3},Cf=na("$ZodType",(s,t)=>{var a;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=mps;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=i9(o),h;for(const m of c){if(m._zod.def.when){if(pms(o)||!m._zod.def.when(o))continue}else if(u)continue;const p=o.issues.length,x=m._zod.check(o);if(x instanceof Promise&&(d==null?void 0:d.async)===!1)throw new wz;if(h||x instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await x,o.issues.length!==p&&(u||(u=i9(o,p)))});else{if(o.issues.length===p)continue;u||(u=i9(o,p))}}return h?h.then(()=>o):o},l=(o,c,d)=>{if(i9(o))return o.aborted=!0,o;const u=i(c,r,d);if(u instanceof Promise){if(d.async===!1)throw new wz;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 wz;return d.then(u=>i(u,r,c))}return i(d,r,c)}}rh(s,"~standard",()=>({validate:i=>{var l;try{const o=gms(s,i);return o.success?{value:o.data}:{issues:(l=o.error)==null?void 0:l.issues}}catch{return yms(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}))}),bqe=na("$ZodString",(s,t)=>{var n;Cf.init(s,t),s._zod.pattern=[...((n=s==null?void 0:s._zod.bag)==null?void 0:n.patterns)??[]].pop()??Kms(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}}),Xm=na("$ZodStringFormat",(s,t)=>{w3e.init(s,t),bqe.init(s,t)}),pps=na("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=Ims),Xm.init(s,t)}),fps=na("$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=xnt(r))}else t.pattern??(t.pattern=xnt());Xm.init(s,t)}),xps=na("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=Rms),Xm.init(s,t)}),gps=na("$ZodURL",(s,t)=>{Xm.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)===qms.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})}}}),yps=na("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=Oms()),Xm.init(s,t)}),vps=na("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=Lms),Xm.init(s,t)}),bps=na("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=Cms),Xm.init(s,t)}),_ps=na("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=Ams),Xm.init(s,t)}),wps=na("$ZodULID",(s,t)=>{t.pattern??(t.pattern=Tms),Xm.init(s,t)}),jps=na("$ZodXID",(s,t)=>{t.pattern??(t.pattern=Ems),Xm.init(s,t)}),Nps=na("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=Mms),Xm.init(s,t)}),kps=na("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=Wms(t)),Xm.init(s,t)}),Sps=na("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=Hms),Xm.init(s,t)}),Cps=na("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=Gms(t)),Xm.init(s,t)}),Aps=na("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=Pms),Xm.init(s,t)}),Tps=na("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=Fms),Xm.init(s,t),s._zod.bag.format="ipv4"}),Eps=na("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=zms),Xm.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})}}}),Mps=na("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=Bms),Xm.init(s,t)}),Lps=na("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=$ms),Xm.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 H5t(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const Pps=na("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=Ums),Xm.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=n=>{H5t(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}});function Ips(s){if(!z5t.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return H5t(n)}const Rps=na("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=z5t),Xm.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=n=>{Ips(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),Dps=na("$ZodE164",(s,t)=>{t.pattern??(t.pattern=Vms),Xm.init(s,t)});function Ops(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 Fps=na("$ZodJWT",(s,t)=>{Xm.init(s,t),s._zod.check=n=>{Ops(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),G5t=na("$ZodNumber",(s,t)=>{Cf.init(s,t),s._zod.pattern=s._zod.bag.pattern??Zms,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}}),zps=na("$ZodNumberFormat",(s,t)=>{tps.init(s,t),G5t.init(s,t)}),Bps=na("$ZodBoolean",(s,t)=>{Cf.init(s,t),s._zod.pattern=Xms,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}}),$ps=na("$ZodUnknown",(s,t)=>{Cf.init(s,t),s._zod.parse=n=>n}),Ups=na("$ZodNever",(s,t)=>{Cf.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function gnt(s,t,n){s.issues.length&&t.issues.push(...R5t(n,s.issues)),t.value[n]=s.value}const qps=na("$ZodArray",(s,t)=>{Cf.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;lgnt(d,n,l))):gnt(c,n,l)}return i.length?Promise.all(i).then(()=>n):n}});function ENe(s,t,n,r,a,i){const l=n in r;if(s.issues.length){if(a&&i&&!l)return;t.issues.push(...R5t(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 W5t(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=ams(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function K5t(s,t,n,r,a,i){const l=[],o=a.keySet,c=a.catchall._zod,d=c.def.type,u=c.optin==="optional",h=c.optout==="optional";for(const m in t){if(m==="__proto__"||o.has(m))continue;if(d==="never"){l.push(m);continue}const p=c.run({value:t[m],issues:[]},r);p instanceof Promise?s.push(p.then(x=>ENe(x,n,m,t,u,h))):ENe(p,n,m,t,u,h)}return l.length&&n.issues.push({code:"unrecognized_keys",keys:l,input:t,inst:i}),s.length?Promise.all(s).then(()=>n):n}const Vps=na("$ZodObject",(s,t)=>{Cf.init(s,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!(n!=null&&n.get)){const o=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...o};return Object.defineProperty(t,"shape",{value:c}),c}})}const r=pqe(()=>W5t(t));rh(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=TNe,i=t.catchall;let l;s._zod.parse=(o,c)=>{l??(l=r.value);const d=o.value;if(!a(d))return o.issues.push({expected:"object",code:"invalid_type",input:d,inst:s}),o;o.value={};const u=[],h=l.shape;for(const m of l.keys){const p=h[m],x=p._zod.optin==="optional",y=p._zod.optout==="optional",g=p._zod.run({value:d[m],issues:[]},c);g instanceof Promise?u.push(g.then(b=>ENe(b,o,m,d,x,y))):ENe(g,o,m,d,x,y)}return i?K5t(u,d,o,c,r.value,s):u.length?Promise.all(u).then(()=>o):o}}),Hps=na("$ZodObjectJIT",(s,t)=>{Vps.init(s,t);const n=s._zod.parse,r=pqe(()=>W5t(t)),a=m=>{var k,C;const p=new hps(["shape","payload","ctx"]),x=r.value,y=T=>{const M=fnt(T);return`shape[${M}]._zod.run({ value: input[${M}], issues: [] }, ctx)`};p.write("const input = payload.value;");const g=Object.create(null);let b=0;for(const T of x.keys)g[T]=`key_${b++}`;p.write("const newResult = {};");for(const T of x.keys){const M=g[T],P=fnt(T),L=m[T],I=((k=L==null?void 0:L._zod)==null?void 0:k.optin)==="optional",O=((C=L==null?void 0:L._zod)==null?void 0:C.optout)==="optional";p.write(`const ${M} = ${y(T)};`),I&&O?p.write(` if (${M}.issues.length) { if (${P} in input) { payload.issues = payload.issues.concat(${M}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } } if (${M}.value === undefined) { if (${P} in input) { newResult[${P}] = undefined; } } else { newResult[${P}] = ${M}.value; } `):I?p.write(` if (${M}.issues.length) { payload.issues = payload.issues.concat(${M}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } if (${M}.value === undefined) { if (${P} in input) { newResult[${P}] = undefined; } } else { newResult[${P}] = ${M}.value; } `):p.write(` const ${M}_present = ${P} in input; if (${M}.issues.length) { payload.issues = payload.issues.concat(${M}.issues.map(iss => ({ ...iss, path: iss.path ? [${P}, ...iss.path] : [${P}] }))); } if (!${M}_present && !${M}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${P}] }); } if (${M}_present) { if (${M}.value === undefined) { newResult[${P}] = undefined; } else { newResult[${P}] = ${M}.value; } } `)}p.write("payload.value = newResult;"),p.write("return payload;");const v=p.compile();return(T,M)=>v(m,T,M)};let i;const l=TNe,o=!mqe.jitless,d=o&&nms.value,u=t.catchall;let h;s._zod.parse=(m,p)=>{h??(h=r.value);const x=m.value;return l(x)?o&&d&&(p==null?void 0:p.async)===!1&&p.jitless!==!0?(i||(i=a(t.shape)),m=i(m,p),u?K5t([],x,m,p,h,s):m):n(m,p):(m.issues.push({expected:"object",code:"invalid_type",input:x,inst:s}),m)}});function ynt(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=>!i9(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=>ED(l,r,TD())))}),t)}const Gps=na("$ZodUnion",(s,t)=>{Cf.init(s,t),rh(s._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),rh(s._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),rh(s._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),rh(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=>xqe(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=>ynt(o,r,s,a)):ynt(l,r,s,a)}}),Wps=na("$ZodIntersection",(s,t)=>{Cf.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])=>vnt(n,c,d)):vnt(n,i,l)}});function tOe(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(QY(s)&&QY(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=tOe(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}),i9(s))return s;const l=tOe(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 Kps=na("$ZodEnum",(s,t)=>{Cf.init(s,t);const n=L5t(t.entries),r=new Set(n);s._zod.values=r,s._zod.pattern=new RegExp(`^(${n.filter(a=>rms.has(typeof a)).map(a=>typeof a=="string"?b$(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}}),Yps=na("$ZodLiteral",(s,t)=>{if(Cf.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"?b$(r):r?b$(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}}),Zps=na("$ZodTransform",(s,t)=>{Cf.init(s,t),s._zod.optin="optional",s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new M5t(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 wz;return n.value=a,n.fallback=!0,n}});function bnt(s,t){return t===void 0&&(s.issues.length||s.fallback)?{issues:[],value:void 0}:s}const Y5t=na("$ZodOptional",(s,t)=>{Cf.init(s,t),s._zod.optin="optional",s._zod.optout="optional",rh(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),rh(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${xqe(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=>bnt(l,a)):bnt(i,a)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),Xps=na("$ZodExactOptional",(s,t)=>{Y5t.init(s,t),rh(s._zod,"values",()=>t.innerType._zod.values),rh(s._zod,"pattern",()=>t.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),Qps=na("$ZodNullable",(s,t)=>{Cf.init(s,t),rh(s._zod,"optin",()=>t.innerType._zod.optin),rh(s._zod,"optout",()=>t.innerType._zod.optout),rh(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${xqe(n.source)}|null)$`):void 0}),rh(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)}),Jps=na("$ZodDefault",(s,t)=>{Cf.init(s,t),s._zod.optin="optional",rh(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=>_nt(i,t)):_nt(a,t)}});function _nt(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const efs=na("$ZodPrefault",(s,t)=>{Cf.init(s,t),s._zod.optin="optional",rh(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))}),tfs=na("$ZodNonOptional",(s,t)=>{Cf.init(s,t),rh(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=>wnt(i,s)):wnt(a,s)}});function wnt(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 sfs=na("$ZodCatch",(s,t)=>{Cf.init(s,t),s._zod.optin="optional",rh(s._zod,"optout",()=>t.innerType._zod.optout),rh(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=>ED(l,r,TD()))},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=>ED(i,r,TD()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),nfs=na("$ZodPipe",(s,t)=>{Cf.init(s,t),rh(s._zod,"values",()=>t.in._zod.values),rh(s._zod,"optin",()=>t.in._zod.optin),rh(s._zod,"optout",()=>t.out._zod.optout),rh(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=>Nse(l,t.in,r)):Nse(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>Nse(i,t.out,r)):Nse(a,t.out,r)}});function Nse(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 rfs=na("$ZodReadonly",(s,t)=>{Cf.init(s,t),rh(s._zod,"propValues",()=>t.innerType._zod.propValues),rh(s._zod,"values",()=>t.innerType._zod.values),rh(s._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),rh(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(jnt):jnt(a)}});function jnt(s){return s.value=Object.freeze(s.value),s}const afs=na("$ZodCustom",(s,t)=>{Mb.init(s,t),Cf.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=>Nnt(i,n,r,s));Nnt(a,n,r,s)}});function Nnt(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(JY(a))}}var knt;class ifs{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 ofs(){return new ifs}(knt=globalThis).__zod_globalRegistry??(knt.__zod_globalRegistry=ofs());const MG=globalThis.__zod_globalRegistry;function lfs(s,t){return new s({type:"string",...Ro(t)})}function cfs(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...Ro(t)})}function Snt(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...Ro(t)})}function dfs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...Ro(t)})}function ufs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ro(t)})}function hfs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ro(t)})}function mfs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ro(t)})}function pfs(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...Ro(t)})}function ffs(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...Ro(t)})}function xfs(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ro(t)})}function gfs(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...Ro(t)})}function yfs(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ro(t)})}function vfs(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...Ro(t)})}function bfs(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...Ro(t)})}function _fs(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ro(t)})}function wfs(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ro(t)})}function jfs(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ro(t)})}function Nfs(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ro(t)})}function kfs(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ro(t)})}function Sfs(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...Ro(t)})}function Cfs(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...Ro(t)})}function Afs(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...Ro(t)})}function Tfs(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...Ro(t)})}function Efs(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ro(t)})}function Mfs(s,t){return new s({type:"string",format:"date",check:"string_format",...Ro(t)})}function Lfs(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...Ro(t)})}function Pfs(s,t){return new s({type:"string",format:"duration",check:"string_format",...Ro(t)})}function Ifs(s,t){return new s({type:"number",checks:[],...Ro(t)})}function Rfs(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...Ro(t)})}function Dfs(s,t){return new s({type:"boolean",...Ro(t)})}function Ofs(s){return new s({type:"unknown"})}function Ffs(s,t){return new s({type:"never",...Ro(t)})}function Cnt(s,t){return new q5t({check:"less_than",...Ro(t),value:s,inclusive:!1})}function SMe(s,t){return new q5t({check:"less_than",...Ro(t),value:s,inclusive:!0})}function Ant(s,t){return new V5t({check:"greater_than",...Ro(t),value:s,inclusive:!1})}function CMe(s,t){return new V5t({check:"greater_than",...Ro(t),value:s,inclusive:!0})}function Tnt(s,t){return new eps({check:"multiple_of",...Ro(t),value:s})}function Z5t(s,t){return new sps({check:"max_length",...Ro(t),maximum:s})}function MNe(s,t){return new nps({check:"min_length",...Ro(t),minimum:s})}function X5t(s,t){return new rps({check:"length_equals",...Ro(t),length:s})}function zfs(s,t){return new aps({check:"string_format",format:"regex",...Ro(t),pattern:s})}function Bfs(s){return new ips({check:"string_format",format:"lowercase",...Ro(s)})}function $fs(s){return new ops({check:"string_format",format:"uppercase",...Ro(s)})}function Ufs(s,t){return new lps({check:"string_format",format:"includes",...Ro(t),includes:s})}function qfs(s,t){return new cps({check:"string_format",format:"starts_with",...Ro(t),prefix:s})}function Vfs(s,t){return new dps({check:"string_format",format:"ends_with",...Ro(t),suffix:s})}function WU(s){return new ups({check:"overwrite",tx:s})}function Hfs(s){return WU(t=>t.normalize(s))}function Gfs(){return WU(s=>s.trim())}function Wfs(){return WU(s=>s.toLowerCase())}function Kfs(){return WU(s=>s.toUpperCase())}function Yfs(){return WU(s=>sms(s))}function Zfs(s,t,n){return new s({type:"array",element:t,...Ro(n)})}function Xfs(s,t,n){return new s({type:"custom",check:"custom",fn:t,...Ro(n)})}function Qfs(s,t){const n=Jfs(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(JY(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(JY(i))}},s(r.value,r)),t);return n}function Jfs(s,t){const n=new Mb({check:"custom",...Ro(t)});return n._zod.check=s,n}function Q5t(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)??MG,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 hy(s,t,n={path:[],schemaPath:[]}){var u,h;var r;const a=s._zod.def,i=t.seen.get(s);if(i)return i.count++,n.schemaPath.includes(s)&&(i.cycle=n.path),i.schema;const l={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(s,l);const o=(h=(u=s._zod).toJSONSchema)==null?void 0:h.call(u);if(o)l.schema=o;else{const m={...n,schemaPath:[...n.schemaPath,s],path:n.path};if(s._zod.processJSONSchema)s._zod.processJSONSchema(t,l.schema,m);else{const x=l.schema,y=t.processors[a.type];if(!y)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);y(s,t,x,m)}const p=s._zod.parent;p&&(l.ref||(l.ref=p),hy(p,t,m),t.seen.get(p).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&Object.assign(l.schema,c),t.io==="input"&&Mv(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 J5t(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 g=(y=s.external.registry.get(u[0]))==null?void 0:y.id,b=s.external.uri??(k=>k);if(g)return{ref:b(g)};const v=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=v,{defId:v,ref:`${b("__shared")}#/${h}/${v}`}}if(u[1]===n)return{ref:"#"};const p=`#/${h}/`,x=u[1].schema.id??`__schema${s.counter++}`;return{defId:x,ref:p+x}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:m,defId:p}=a(u);h.def={...h.schema},p&&(h.defId=p);const x=h.schema;for(const y in x)delete x[y];x.$ref=m};if(s.cycles==="throw")for(const u of s.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${(o=h.cycle)==null?void 0:o.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of s.seen.entries()){const h=u[1];if(t===u[0]){i(u);continue}if(s.external){const p=(c=s.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&p){i(u);continue}}if((d=s.metadataRegistry.get(u[0]))==null?void 0:d.id){i(u);continue}if(h.cycle){i(u);continue}if(h.count>1&&s.reused==="ref"){i(u);continue}}}function eSt(s,t){var o,c,d,u;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=h=>{const m=s.seen.get(h);if(m.ref===null)return;const p=m.def??m.schema,x={...p},y=m.ref;if(m.ref=null,y){r(y);const b=s.seen.get(y),v=b.schema;if(v.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(v)):Object.assign(p,v),Object.assign(p,x),h._zod.parent===y)for(const C in p)C==="$ref"||C==="allOf"||C in x||delete p[C];if(v.$ref&&b.def)for(const C in p)C==="$ref"||C==="allOf"||C in b.def&&JSON.stringify(p[C])===JSON.stringify(b.def[C])&&delete p[C]}const g=h._zod.parent;if(g&&g!==y){r(g);const b=s.seen.get(g);if(b!=null&&b.schema.$ref&&(p.$ref=b.schema.$ref,b.def))for(const v in p)v==="$ref"||v==="allOf"||v in b.def&&JSON.stringify(p[v])===JSON.stringify(b.def[v])&&delete p[v]}s.override({zodSchema:h,jsonSchema:p,path:m.path??[]})};for(const h of[...s.seen.entries()].reverse())r(h[0]);const a={};if(s.target==="draft-2020-12"?a.$schema="https://json-schema.org/draft/2020-12/schema":s.target==="draft-07"?a.$schema="http://json-schema.org/draft-07/schema#":s.target==="draft-04"?a.$schema="http://json-schema.org/draft-04/schema#":s.target,(o=s.external)!=null&&o.uri){const h=(c=s.external.registry.get(t))==null?void 0:c.id;if(!h)throw new Error("Schema is missing an `id` property");a.$id=s.external.uri(h)}Object.assign(a,n.def??n.schema);const i=(d=s.metadataRegistry.get(t))==null?void 0:d.id;i!==void 0&&a.id===i&&delete a.id;const l=((u=s.external)==null?void 0:u.defs)??{};for(const h of s.seen.entries()){const m=h[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,l[m.defId]=m.def)}s.external||Object.keys(l).length>0&&(s.target==="draft-2020-12"?a.$defs=l:a.definitions=l);try{const h=JSON.parse(JSON.stringify(a));return Object.defineProperty(h,"~standard",{value:{...t["~standard"],jsonSchema:{input:LNe(t,"input",s.processors),output:LNe(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function Mv(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 Mv(r.element,n);if(r.type==="set")return Mv(r.valueType,n);if(r.type==="lazy")return Mv(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 Mv(r.innerType,n);if(r.type==="intersection")return Mv(r.left,n)||Mv(r.right,n);if(r.type==="record"||r.type==="map")return Mv(r.keyType,n)||Mv(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:Mv(r.in,n)||Mv(r.out,n);if(r.type==="object"){for(const a in r.shape)if(Mv(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(Mv(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(Mv(a,n))return!0;return!!(r.rest&&Mv(r.rest,n))}return!1}const exs=(s,t={})=>n=>{const r=Q5t({...n,processors:t});return hy(s,r),J5t(r,s),eSt(r,s)},LNe=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=Q5t({...a??{},target:i,io:t,processors:n});return hy(s,l),J5t(l,s),eSt(l,s)},txs={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sxs=(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=txs[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}))])}},nxs=(s,t,n,r)=>{const a=n,{minimum:i,maximum:l,format:o,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:u}=s._zod.bag;typeof o=="string"&&o.includes("int")?a.type="integer":a.type="number";const h=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),m=typeof d=="number"&&d<=(l??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";h?p?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u:typeof i=="number"&&(a.minimum=i),m?p?(a.maximum=d,a.exclusiveMaximum=!0):a.exclusiveMaximum=d:typeof l=="number"&&(a.maximum=l),typeof c=="number"&&(a.multipleOf=c)},rxs=(s,t,n,r)=>{n.type="boolean"},axs=(s,t,n,r)=>{n.not={}},ixs=(s,t,n,r)=>{},oxs=(s,t,n,r)=>{const a=s._zod.def,i=L5t(a.entries);i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),n.enum=i},lxs=(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},cxs=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},dxs=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},uxs=(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=hy(i.element,t,{...r,path:[...r.path,"items"]})},hxs=(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]=hy(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=hy(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},mxs=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>hy(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},pxs=(s,t,n,r)=>{const a=s._zod.def,i=hy(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=hy(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},fxs=(s,t,n,r)=>{const a=s._zod.def,i=hy(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"}]},xxs=(s,t,n,r)=>{const a=s._zod.def;hy(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},gxs=(s,t,n,r)=>{const a=s._zod.def;hy(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},yxs=(s,t,n,r)=>{const a=s._zod.def;hy(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)))},vxs=(s,t,n,r)=>{const a=s._zod.def;hy(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},bxs=(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;hy(l,t,r);const o=t.seen.get(s);o.ref=l},_xs=(s,t,n,r)=>{const a=s._zod.def;hy(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},tSt=(s,t,n,r)=>{const a=s._zod.def;hy(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},wxs=na("ZodISODateTime",(s,t)=>{kps.init(s,t),qp.init(s,t)});function jxs(s){return Efs(wxs,s)}const Nxs=na("ZodISODate",(s,t)=>{Sps.init(s,t),qp.init(s,t)});function kxs(s){return Mfs(Nxs,s)}const Sxs=na("ZodISOTime",(s,t)=>{Cps.init(s,t),qp.init(s,t)});function Cxs(s){return Lfs(Sxs,s)}const Axs=na("ZodISODuration",(s,t)=>{Aps.init(s,t),qp.init(s,t)});function Txs(s){return Pfs(Axs,s)}const sSt=(s,t)=>{O5t.init(s,t),s.name="ZodError",Object.defineProperties(s,{format:{value:n=>xms(s,n)},flatten:{value:n=>fms(s,n)},addIssue:{value:n=>{s.issues.push(n),s.message=JSON.stringify(s.issues,eOe,2)}},addIssues:{value:n=>{s.issues.push(...n),s.message=JSON.stringify(s.issues,eOe,2)}},isEmpty:{get(){return s.issues.length===0}}})},Exs=na("ZodError",sSt),Gj=na("ZodError",sSt,{Parent:Error}),Mxs=yqe(Gj),Lxs=vqe(Gj),Pxs=b3e(Gj),Ixs=_3e(Gj),Rxs=vms(Gj),Dxs=bms(Gj),Oxs=_ms(Gj),Fxs=wms(Gj),zxs=jms(Gj),Bxs=Nms(Gj),$xs=kms(Gj),Uxs=Sms(Gj),Ent=new WeakMap;function gJ(s,t,n){const r=Object.getPrototypeOf(s);let a=Ent.get(r);if(a||(a=new Set,Ent.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 Af=na("ZodType",(s,t)=>(Cf.init(s,t),Object.assign(s["~standard"],{jsonSchema:{input:LNe(s,"input"),output:LNe(s,"output")}}),s.toJSONSchema=exs(s,{}),s.def=t,s.type=t.type,Object.defineProperty(s,"_def",{value:t}),s.parse=(n,r)=>Mxs(s,n,r,{callee:s.parse}),s.safeParse=(n,r)=>Pxs(s,n,r),s.parseAsync=async(n,r)=>Lxs(s,n,r,{callee:s.parseAsync}),s.safeParseAsync=async(n,r)=>Ixs(s,n,r),s.spa=s.safeParseAsync,s.encode=(n,r)=>Rxs(s,n,r),s.decode=(n,r)=>Dxs(s,n,r),s.encodeAsync=async(n,r)=>Oxs(s,n,r),s.decodeAsync=async(n,r)=>Fxs(s,n,r),s.safeEncode=(n,r)=>zxs(s,n,r),s.safeDecode=(n,r)=>Bxs(s,n,r),s.safeEncodeAsync=async(n,r)=>$xs(s,n,r),s.safeDecodeAsync=async(n,r)=>Uxs(s,n,r),gJ(s,"ZodType",{check(...n){const r=this.def;return this.clone(s6(r,{checks:[...r.checks??[],...n.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return n6(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Ogs(n,r))},superRefine(n,r){return this.check(Fgs(n,r))},overwrite(n){return this.check(WU(n))},optional(){return Int(this)},exactOptional(){return Ngs(this)},nullable(){return Rnt(this)},nullish(){return Int(Rnt(this))},nonoptional(n){return Egs(this,n)},array(){return pgs(this)},or(n){return ggs([this,n])},and(n){return vgs(this,n)},transform(n){return Dnt(this,wgs(n))},default(n){return Cgs(this,n)},prefault(n){return Tgs(this,n)},catch(n){return Lgs(this,n)},pipe(n){return Dnt(this,n)},readonly(){return Rgs(this)},describe(n){const r=this.clone();return MG.add(r,{description:n}),r},meta(...n){if(n.length===0)return MG.get(this);const r=this.clone();return MG.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=MG.get(s))==null?void 0:n.description},configurable:!0}),s)),nSt=na("_ZodString",(s,t)=>{bqe.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(r,a,i)=>sxs(s,r,a);const n=s._zod.bag;s.format=n.format??null,s.minLength=n.minimum??null,s.maxLength=n.maximum??null,gJ(s,"_ZodString",{regex(...r){return this.check(zfs(...r))},includes(...r){return this.check(Ufs(...r))},startsWith(...r){return this.check(qfs(...r))},endsWith(...r){return this.check(Vfs(...r))},min(...r){return this.check(MNe(...r))},max(...r){return this.check(Z5t(...r))},length(...r){return this.check(X5t(...r))},nonempty(...r){return this.check(MNe(1,...r))},lowercase(r){return this.check(Bfs(r))},uppercase(r){return this.check($fs(r))},trim(){return this.check(Gfs())},normalize(...r){return this.check(Hfs(...r))},toLowerCase(){return this.check(Wfs())},toUpperCase(){return this.check(Kfs())},slugify(){return this.check(Yfs())}})}),qxs=na("ZodString",(s,t)=>{bqe.init(s,t),nSt.init(s,t),s.email=n=>s.check(cfs(Vxs,n)),s.url=n=>s.check(pfs(Hxs,n)),s.jwt=n=>s.check(Tfs(igs,n)),s.emoji=n=>s.check(ffs(Gxs,n)),s.guid=n=>s.check(Snt(Mnt,n)),s.uuid=n=>s.check(dfs(kse,n)),s.uuidv4=n=>s.check(ufs(kse,n)),s.uuidv6=n=>s.check(hfs(kse,n)),s.uuidv7=n=>s.check(mfs(kse,n)),s.nanoid=n=>s.check(xfs(Wxs,n)),s.guid=n=>s.check(Snt(Mnt,n)),s.cuid=n=>s.check(gfs(Kxs,n)),s.cuid2=n=>s.check(yfs(Yxs,n)),s.ulid=n=>s.check(vfs(Zxs,n)),s.base64=n=>s.check(Sfs(ngs,n)),s.base64url=n=>s.check(Cfs(rgs,n)),s.xid=n=>s.check(bfs(Xxs,n)),s.ksuid=n=>s.check(_fs(Qxs,n)),s.ipv4=n=>s.check(wfs(Jxs,n)),s.ipv6=n=>s.check(jfs(egs,n)),s.cidrv4=n=>s.check(Nfs(tgs,n)),s.cidrv6=n=>s.check(kfs(sgs,n)),s.e164=n=>s.check(Afs(ags,n)),s.datetime=n=>s.check(jxs(n)),s.date=n=>s.check(kxs(n)),s.time=n=>s.check(Cxs(n)),s.duration=n=>s.check(Txs(n))});function Cl(s){return lfs(qxs,s)}const qp=na("ZodStringFormat",(s,t)=>{Xm.init(s,t),nSt.init(s,t)}),Vxs=na("ZodEmail",(s,t)=>{xps.init(s,t),qp.init(s,t)}),Mnt=na("ZodGUID",(s,t)=>{pps.init(s,t),qp.init(s,t)}),kse=na("ZodUUID",(s,t)=>{fps.init(s,t),qp.init(s,t)}),Hxs=na("ZodURL",(s,t)=>{gps.init(s,t),qp.init(s,t)}),Gxs=na("ZodEmoji",(s,t)=>{yps.init(s,t),qp.init(s,t)}),Wxs=na("ZodNanoID",(s,t)=>{vps.init(s,t),qp.init(s,t)}),Kxs=na("ZodCUID",(s,t)=>{bps.init(s,t),qp.init(s,t)}),Yxs=na("ZodCUID2",(s,t)=>{_ps.init(s,t),qp.init(s,t)}),Zxs=na("ZodULID",(s,t)=>{wps.init(s,t),qp.init(s,t)}),Xxs=na("ZodXID",(s,t)=>{jps.init(s,t),qp.init(s,t)}),Qxs=na("ZodKSUID",(s,t)=>{Nps.init(s,t),qp.init(s,t)}),Jxs=na("ZodIPv4",(s,t)=>{Tps.init(s,t),qp.init(s,t)}),egs=na("ZodIPv6",(s,t)=>{Eps.init(s,t),qp.init(s,t)}),tgs=na("ZodCIDRv4",(s,t)=>{Mps.init(s,t),qp.init(s,t)}),sgs=na("ZodCIDRv6",(s,t)=>{Lps.init(s,t),qp.init(s,t)}),ngs=na("ZodBase64",(s,t)=>{Pps.init(s,t),qp.init(s,t)}),rgs=na("ZodBase64URL",(s,t)=>{Rps.init(s,t),qp.init(s,t)}),ags=na("ZodE164",(s,t)=>{Dps.init(s,t),qp.init(s,t)}),igs=na("ZodJWT",(s,t)=>{Fps.init(s,t),qp.init(s,t)}),rSt=na("ZodNumber",(s,t)=>{G5t.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(r,a,i)=>nxs(s,r,a),gJ(s,"ZodNumber",{gt(r,a){return this.check(Ant(r,a))},gte(r,a){return this.check(CMe(r,a))},min(r,a){return this.check(CMe(r,a))},lt(r,a){return this.check(Cnt(r,a))},lte(r,a){return this.check(SMe(r,a))},max(r,a){return this.check(SMe(r,a))},int(r){return this.check(Lnt(r))},safe(r){return this.check(Lnt(r))},positive(r){return this.check(Ant(0,r))},nonnegative(r){return this.check(CMe(0,r))},negative(r){return this.check(Cnt(0,r))},nonpositive(r){return this.check(SMe(0,r))},multipleOf(r,a){return this.check(Tnt(r,a))},step(r,a){return this.check(Tnt(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 SK(s){return Ifs(rSt,s)}const ogs=na("ZodNumberFormat",(s,t)=>{zps.init(s,t),rSt.init(s,t)});function Lnt(s){return Rfs(ogs,s)}const lgs=na("ZodBoolean",(s,t)=>{Bps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>rxs(s,n,r)});function cgs(s){return Dfs(lgs,s)}const dgs=na("ZodUnknown",(s,t)=>{$ps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>ixs()});function Pnt(){return Ofs(dgs)}const ugs=na("ZodNever",(s,t)=>{Ups.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>axs(s,n,r)});function hgs(s){return Ffs(ugs,s)}const mgs=na("ZodArray",(s,t)=>{qps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>uxs(s,n,r,a),s.element=t.element,gJ(s,"ZodArray",{min(n,r){return this.check(MNe(n,r))},nonempty(n){return this.check(MNe(1,n))},max(n,r){return this.check(Z5t(n,r))},length(n,r){return this.check(X5t(n,r))},unwrap(){return this.element}})});function pgs(s,t){return Zfs(mgs,s,t)}const fgs=na("ZodObject",(s,t)=>{Hps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>hxs(s,n,r,a),rh(s,"shape",()=>t.shape),gJ(s,"ZodObject",{keyof(){return _qe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Pnt()})},loose(){return this.clone({...this._zod.def,catchall:Pnt()})},strict(){return this.clone({...this._zod.def,catchall:hgs()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return cms(this,n)},safeExtend(n){return dms(this,n)},merge(n){return ums(this,n)},pick(n){return oms(this,n)},omit(n){return lms(this,n)},partial(...n){return hms(aSt,this,n[0])},required(...n){return mms(iSt,this,n[0])}})});function iS(s,t){const n={type:"object",shape:s??{},...Ro(t)};return new fgs(n)}const xgs=na("ZodUnion",(s,t)=>{Gps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>mxs(s,n,r,a),s.options=t.options});function ggs(s,t){return new xgs({type:"union",options:s,...Ro(t)})}const ygs=na("ZodIntersection",(s,t)=>{Wps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>pxs(s,n,r,a)});function vgs(s,t){return new ygs({type:"intersection",left:s,right:t})}const sOe=na("ZodEnum",(s,t)=>{Kps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(r,a,i)=>oxs(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 sOe({...t,checks:[],...Ro(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 sOe({...t,checks:[],...Ro(a),entries:i})}});function _qe(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new sOe({type:"enum",entries:n,...Ro(t)})}const bgs=na("ZodLiteral",(s,t)=>{Yps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>lxs(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 Xg(s,t){return new bgs({type:"literal",values:Array.isArray(s)?s:[s],...Ro(t)})}const _gs=na("ZodTransform",(s,t)=>{Zps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>dxs(s,n),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new M5t(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(JY(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(JY(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 wgs(s){return new _gs({type:"transform",transform:s})}const aSt=na("ZodOptional",(s,t)=>{Y5t.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>tSt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Int(s){return new aSt({type:"optional",innerType:s})}const jgs=na("ZodExactOptional",(s,t)=>{Xps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>tSt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Ngs(s){return new jgs({type:"optional",innerType:s})}const kgs=na("ZodNullable",(s,t)=>{Qps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>fxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Rnt(s){return new kgs({type:"nullable",innerType:s})}const Sgs=na("ZodDefault",(s,t)=>{Jps.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>gxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function Cgs(s,t){return new Sgs({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():I5t(t)}})}const Ags=na("ZodPrefault",(s,t)=>{efs.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>yxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Tgs(s,t){return new Ags({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():I5t(t)}})}const iSt=na("ZodNonOptional",(s,t)=>{tfs.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>xxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Egs(s,t){return new iSt({type:"nonoptional",innerType:s,...Ro(t)})}const Mgs=na("ZodCatch",(s,t)=>{sfs.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>vxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function Lgs(s,t){return new Mgs({type:"catch",innerType:s,catchValue:typeof t=="function"?t:()=>t})}const Pgs=na("ZodPipe",(s,t)=>{nfs.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>bxs(s,n,r,a),s.in=t.in,s.out=t.out});function Dnt(s,t){return new Pgs({type:"pipe",in:s,out:t})}const Igs=na("ZodReadonly",(s,t)=>{rfs.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>_xs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Rgs(s){return new Igs({type:"readonly",innerType:s})}const Dgs=na("ZodCustom",(s,t)=>{afs.init(s,t),Af.init(s,t),s._zod.processJSONSchema=(n,r,a)=>cxs(s,n)});function Ogs(s,t={}){return Xfs(Dgs,s,t)}function Fgs(s,t){return Qfs(s,t)}const zgs=["Excellent","Good","Neutral","Bad","Very Bad"],Bgs=[5,4,3,2,1];function $gs({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=ids(),[i,l]=j.useState({}),o=s.filter(m=>m.question_type==="rating"),c=s.filter(m=>m.question_type!=="rating"),d=(m,p)=>{l(x=>({...x,[m]:{rating_value:p}}))},u=(m,p)=>{l(x=>({...x,[m]:{text_value:p}}))},h=async()=>{const m=Object.entries(i).filter(([,p])=>p.rating_value!=null||p.text_value&&p.text_value.trim()).map(([p,x])=>{var y;return{visitor_id:t,question_id:p,rating_value:x.rating_value??null,text_value:((y=x.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"}),zgs.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}),Bgs.map(p=>{var x;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(m.id,p),className:`w-6 h-6 rounded-full border-2 transition-all ${((x=i[m.id])==null?void 0:x.rating_value)===p?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},p)})]},m.id))]}),c.map(m=>{var p;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:m.question_text}),e.jsx(Ds,{value:((p=i[m.id])==null?void 0:p.text_value)||"",onChange:x=>u(m.id,x.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},m.id)}),e.jsx(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(Wt,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}var j3e="Checkbox",[Ugs,gBn]=Zm(j3e),[qgs,wqe]=Ugs(j3e);function Vgs(s){const{__scopeCheckbox:t,checked:n,children:r,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:u="on",internal_do_not_use_render:h}=s,[m,p]=Mx({prop:n,defaultProp:a??!1,onChange:c,caller:j3e}),[x,y]=j.useState(null),[g,b]=j.useState(null),v=j.useRef(!1),k=x?!!l||!!x.closest("form"):!0,C={checked:m,disabled:i,setChecked:p,control:x,setControl:y,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:v,required:d,defaultChecked:cE(a)?!1:a,isFormControl:k,bubbleInput:g,setBubbleInput:b};return e.jsx(qgs,{scope:t,...C,children:Hgs(h)?h(C):r})}var oSt="CheckboxTrigger",lSt=j.forwardRef(({__scopeCheckbox:s,onKeyDown:t,onClick:n,...r},a)=>{const{control:i,value:l,disabled:o,checked:c,required:d,setControl:u,setChecked:h,hasConsumerStoppedPropagationRef:m,isFormControl:p,bubbleInput:x}=wqe(oSt,s),y=ko(a,u),g=j.useRef(c);return j.useEffect(()=>{const b=i==null?void 0:i.form;if(b){const v=()=>h(g.current);return b.addEventListener("reset",v),()=>b.removeEventListener("reset",v)}},[i,h]),e.jsx(Ua.button,{type:"button",role:"checkbox","aria-checked":cE(c)?"mixed":c,"aria-required":d,"data-state":mSt(c),"data-disabled":o?"":void 0,disabled:o,value:l,...r,ref:y,onKeyDown:ua(t,b=>{b.key==="Enter"&&b.preventDefault()}),onClick:ua(n,b=>{h(v=>cE(v)?!0:!v),x&&p&&(m.current=b.isPropagationStopped(),m.current||b.stopPropagation())})})});lSt.displayName=oSt;var jqe=j.forwardRef((s,t)=>{const{__scopeCheckbox:n,name:r,checked:a,defaultChecked:i,required:l,disabled:o,value:c,onCheckedChange:d,form:u,...h}=s;return e.jsx(Vgs,{__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(lSt,{...h,ref:t,__scopeCheckbox:n}),m&&e.jsx(hSt,{__scopeCheckbox:n})]})})});jqe.displayName=j3e;var cSt="CheckboxIndicator",dSt=j.forwardRef((s,t)=>{const{__scopeCheckbox:n,forceMount:r,...a}=s,i=wqe(cSt,n);return e.jsx(ax,{present:r||cE(i.checked)||i.checked===!0,children:e.jsx(Ua.span,{"data-state":mSt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});dSt.displayName=cSt;var uSt="CheckboxBubbleInput",hSt=j.forwardRef(({__scopeCheckbox:s,...t},n)=>{const{control:r,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:l,required:o,disabled:c,name:d,value:u,form:h,bubbleInput:m,setBubbleInput:p}=wqe(uSt,s),x=ko(n,p),y=xJ(i),g=iJ(r);j.useEffect(()=>{const v=m;if(!v)return;const k=window.HTMLInputElement.prototype,T=Object.getOwnPropertyDescriptor(k,"checked").set,M=!a.current;if(y!==i&&T){const P=new Event("click",{bubbles:M});v.indeterminate=cE(i),T.call(v,cE(i)?!1:i),v.dispatchEvent(P)}},[m,y,i,a]);const b=j.useRef(cE(i)?!1:i);return e.jsx(Ua.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??b.current,required:o,disabled:c,name:d,value:u,form:h,...t,tabIndex:-1,ref:x,style:{...t.style,...g,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});hSt.displayName=uSt;function Hgs(s){return typeof s=="function"}function cE(s){return s==="indeterminate"}function mSt(s){return cE(s)?"indeterminate":s?"checked":"unchecked"}const wi=j.forwardRef(({className:s,...t},n)=>e.jsx(jqe,{ref:n,className:Et("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(dSt,{className:Et("flex items-center justify-center text-current"),children:e.jsx(da,{className:"h-4 w-4"})})}));wi.displayName=jqe.displayName;const v1=I4e,yJ=vUe,Ggs=R4e,pSt=j.forwardRef(({className:s,...t},n)=>e.jsx(IU,{className:Et("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}));pSt.displayName=IU.displayName;const Wgs=hO("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"}}),rv=j.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(Ggs,{children:[e.jsx(pSt,{}),e.jsxs(RU,{ref:a,className:Et(Wgs({side:s}),t),...r,children:[n,e.jsxs(rJ,{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(dr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));rv.displayName=RU.displayName;const Lb=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col space-y-2 text-center sm:text-left",s),...t});Lb.displayName="SheetHeader";const fSt=({className:s,...t})=>e.jsx("div",{className:Et("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});fSt.displayName="SheetFooter";const Pb=j.forwardRef(({className:s,...t},n)=>e.jsx(sJ,{ref:n,className:Et("text-lg font-semibold text-foreground",s),...t}));Pb.displayName=sJ.displayName;const vJ=j.forwardRef(({className:s,...t},n)=>e.jsx(nJ,{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));vJ.displayName=nJ.displayName;function nOe(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function Kgs({rooms:s}){var h;const[t,n]=j.useState(((h=s[0])==null?void 0:h.id)||""),[r,a]=j.useState(null),i=s.find(m=>m.id===t)||s[0],l=r!==null?i==null?void 0:i.media[r]:null,o=(i==null?void 0:i.media.length)??0,c=()=>a(null),d=()=>a(m=>m===null||o===0?m:(m-1+o)%o),u=()=>a(m=>m===null||o===0?m:(m+1)%o);return j.useEffect(()=>{if(r===null)return;const m=p=>{p.key==="Escape"?c():p.key==="ArrowLeft"?d():p.key==="ArrowRight"&&u()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[r,o]),s.length?e.jsxs("div",{className:"hidden md:block",children:[e.jsx("div",{className:"sticky top-0 z-20 -mx-5 px-5 py-3 bg-slate-950/80 backdrop-blur-md border-b border-white/10 overflow-x-auto",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(m=>e.jsxs("button",{onClick:()=>n(m.id),className:Et("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===m.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[m.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:m.media.length})]},m.id))})}),i&&e.jsxs("div",{className:"mt-6",children:[e.jsx("h3",{className:"text-2xl font-bold",children:i.name}),i.description&&e.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:i.description}),i.media.length===0?e.jsx("p",{className:"text-white/40 text-sm mt-6 italic",children:"No media yet for this room."}):e.jsx("div",{className:"mt-5 grid grid-cols-2 lg:grid-cols-3 gap-3",children:i.media.map((m,p)=>e.jsx("button",{onClick:()=>a(p),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:m.kind==="video"?e.jsxs(e.Fragment,{children:[nOe(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(Zr,{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(Cc,{className:"h-6 w-6"})}),l.kind==="video"?nOe(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 Ygs({rooms:s}){var o;const t=[];s.forEach(c=>{t.push({type:"cover",roomId:c.id,roomName:c.name,description:c.description,mediaCount:c.media.length}),c.media.forEach((d,u)=>{t.push({type:"media",roomId:c.id,roomName:c.name,url:d.url,kind:d.kind,index:u,total:c.media.length})})});const n=j.useRef(null),[r,a]=j.useState(0);j.useEffect(()=>{const c=n.current;if(!c)return;let d=0;const u=()=>{cancelAnimationFrame(d),d=requestAnimationFrame(()=>{const h=Math.round(c.scrollLeft/c.clientWidth);a(h)})};return c.addEventListener("scroll",u,{passive:!0}),()=>{c.removeEventListener("scroll",u),cancelAnimationFrame(d)}},[]);const i=c=>{const d=n.current;d&&d.scrollTo({left:c*d.clientWidth,behavior:"smooth"})};if(!t.length)return null;const l=(o=t[r])==null?void 0:o.roomId;return e.jsxs("div",{className:"md:hidden -mx-5",children:[e.jsx("div",{className:"px-5 py-3 overflow-x-auto sticky top-0 z-20 bg-slate-950/80 backdrop-blur-md border-b border-white/10",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(c=>{const d=t.findIndex(h=>h.roomId===c.id),u=l===c.id;return e.jsx("button",{onClick:()=>i(d),className:Et("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"?nOe(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(Cc,{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 AMe={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:ro},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:ra},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:$r},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:Od}},Zgs=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function Xgs(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 Qgs({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]=j.useState(null),[h,m]=j.useState(""),[p,x]=j.useState(r||""),[y,g]=j.useState(a||""),[b,v]=j.useState(!1),[k,C]=j.useState(null),[T,M]=j.useState(""),[P,L]=j.useState(""),[I,O]=j.useState(""),[$,q]=j.useState([]),[W,G]=j.useState(""),[K,ee]=j.useState(""),[J,le]=j.useState(""),[ue,oe]=j.useState(""),ie=Xgs(s.price),de=s.tour_mode==="rooms",{data:we=[]}=xds(de?s.id:void 0),je=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),xe=Ne=>{u(Ne),m(""),M(""),L(""),O(""),q([]),G(""),ee(""),le(""),oe("")},fe=()=>{u(null)},Se=Ne=>{q(Ge=>Ge.includes(Ne)?Ge.filter(_e=>_e!==Ne):[...Ge,Ne])},Ee=Ne=>Ne==="showing"?{preferred_date:T||null,preferred_time:P||null,alternate_date:I||null}:Ne==="disclosure"?{requested_documents:$}:Ne==="offer"?{offer_amount:W||null,financing:K||null,timeline:J||null,pre_approved:ue||null}:{},Le=d?d==="showing"?!!T:d==="question"?h.trim().length>0:!0:!1,De=async()=>{if(d){if(i){ba({title:"Preview mode",description:"Lead not sent — this is just a preview."}),C(d),setTimeout(()=>{u(null),C(null)},1500);return}v(!0);try{const Ne=Ee(d),{error:Ge}=await U.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:h.trim()||null,email:p.trim()||null,phone:y.trim()||null,visitor_name:n,...Ne}});if(Ge)throw Ge;U.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:h.trim()||null,visitor_name:n,visitor_email:p.trim()||null,visitor_phone:y.trim()||null,extras:Ne}}).catch(()=>{}),C(d),ba({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{fe(),C(null)},1400)}catch(Ne){ba({title:"Something went wrong",description:Ne.message,variant:"destructive"})}finally{v(!1)}}};return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[s.hero_video_url?e.jsx("video",{src:s.hero_video_url,poster:s.hero_video_thumbnail_url||s.photo_url||void 0,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):s.photo_url?e.jsx("img",{src:s.photo_url,alt:s.property_address,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[e.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[e.jsx("h1",{className:"text-2xl font-bold leading-tight",children:s.property_address}),s.city&&e.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[e.jsx(oi,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),ie&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:ie}),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(U_,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(t0,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(H_,{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(Ra,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(Fi,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(Da,{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(pa,{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(on,{className:"h-4 w-4"})})]})]}),de&&we.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(Kgs,{rooms:we}),e.jsx(Ygs,{rooms:we})]}),je.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:je.map(Ne=>{const Ge=AMe[Ne],_e=Ge.icon;return e.jsxs("button",{onClick:()=>xe(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(_e,{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(v1,{open:!!d,onOpenChange:Ne=>!Ne&&fe(),children:e.jsx(rv,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(Lb,{className:"text-left",children:[e.jsx(Pb,{children:AMe[d].title}),e.jsxs(vJ,{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(Rr,{className:"h-7 w-7 text-green-600"})}),e.jsx("p",{className:"font-medium",children:"Message sent!"})]}):e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Email"}),e.jsx(ye,{type:"email",value:p,onChange:Ne=>x(Ne.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Phone"}),e.jsx(ye,{type:"tel",value:y,onChange:Ne=>g(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(se,{className:"text-xs",children:"Preferred date *"}),e.jsx(ye,{type:"date",value:T,onChange:Ne=>M(Ne.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Preferred time"}),e.jsx(ye,{type:"time",value:P,onChange:Ne=>L(Ne.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(ye,{type:"date",value:I,onChange:Ne=>O(Ne.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:Zgs.map(Ne=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(wi,{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(se,{className:"text-xs",children:"Estimated offer"}),e.jsx(ye,{value:W,onChange:Ne=>G(Ne.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Financing"}),e.jsxs(vs,{value:K,onValueChange:ee,children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{placeholder:"Select..."})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"Cash",children:"Cash"}),e.jsx(Je,{value:"Conventional",children:"Conventional"}),e.jsx(Je,{value:"FHA",children:"FHA"}),e.jsx(Je,{value:"VA",children:"VA"}),e.jsx(Je,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Timeline"}),e.jsxs(vs,{value:J,onValueChange:le,children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{placeholder:"Select..."})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"ASAP",children:"ASAP"}),e.jsx(Je,{value:"30 days",children:"30 days"}),e.jsx(Je,{value:"60 days",children:"60 days"}),e.jsx(Je,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(vs,{value:ue,onValueChange:oe,children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{placeholder:"Select..."})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"Yes",children:"Yes"}),e.jsx(Je,{value:"No",children:"No"}),e.jsx(Je,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Ds,{value:h,onChange:Ne=>m(Ne.target.value),placeholder:AMe[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(B,{onClick:De,disabled:b||!Le,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:b?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const Jgs=iS({first_name:Cl().trim().min(1,"First name is required").max(50),last_name:Cl().trim().max(50).optional(),email:Cl().trim().email("Please enter a valid email").max(255).optional().or(Xg("")),phone:Cl().trim().max(20).optional().or(Xg(""))}),e0s=[{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 xSt({slug:s}={}){var Ue;const t=$i(),n=s||t.slug,[r]=dc(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=nds(n),d=hds(),u=mds(),h=pds(),m=j.useRef(!1),[p,x]=j.useState("welcome"),[y,g]=j.useState(null),[b,v]=j.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[k,C]=j.useState(""),[T,M]=j.useState(!1),[P,L]=j.useState(!1),[I,O]=j.useState(""),[$,q]=j.useState(""),[W,G]=j.useState(i),K=j.useCallback(()=>{g(null),v({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),C(""),M(!1),L(!1),O(""),q(""),G(i),x(a?"info":"welcome")},[a]),ee=j.useCallback((Ze,Qe)=>{l!=null&&l.id&&U.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:Ze,first_name:Qe.first_name??b.first_name,last_name:Qe.last_name??b.last_name,email:Qe.email??b.email,phone:Qe.phone??b.phone,visitor_intent:Qe.visitor_intent??k,message:Qe.message,wants_market_updates:Qe.wants_market_updates??T,has_agent:Qe.has_agent??P,working_with_agent_name:Qe.working_with_agent_name??I,visitor_address:Qe.visitor_address??b.visitor_address}}).catch(Ye=>console.error("Guest book lead notify failed:",Ye))},[l==null?void 0:l.id,b,k,T,P,I]);j.useEffect(()=>{if(!a||p!=="done")return;G(i);const Ze=setInterval(()=>{G(Qe=>Qe<=1?(clearInterval(Ze),K(),0):Qe-1)},1e3);return()=>clearInterval(Ze)},[a,p,K]),j.useEffect(()=>{if(!a)return;x(Qe=>Qe==="welcome"?"info":Qe);let Ze=null;return(async()=>{var Qe,Ye;try{Ze=await((Ye=(Qe=navigator.wakeLock)==null?void 0:Qe.request)==null?void 0:Ye.call(Qe,"screen"))}catch{}})(),()=>{var Qe;try{(Qe=Ze==null?void 0:Ze.release)==null||Qe.call(Ze)}catch{}}},[a]);const J=j.useCallback(()=>{var Qe;const Ze=document.documentElement;document.fullscreenElement||(Qe=Ze.requestFullscreen||Ze.webkitRequestFullscreen)==null||Qe.call(Ze).catch(()=>{})},[]),{data:le,isLoading:ue}=ads(l==null?void 0:l.id),oe=!!(l!=null&&l.enable_survey),ie=(l==null?void 0:l.ask_visitor_intent)!==!1,de=(l==null?void 0:l.ask_visitor_address)===!0;j.useEffect(()=>{if(!n||!(l!=null&&l.id)||m.current)return;const Ze=`oh_scan_${l.id}`;if(sessionStorage.getItem(Ze)){m.current=!0;return}m.current=!0,sessionStorage.setItem(Ze,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),j.useEffect(()=>{p==="pending_survey"&&(ue||x(oe&&((le==null?void 0:le.length)??0)>0?"survey":"done"))},[p,ue,oe,le]);const we=Ze=>{if(!Ze)return"";const[Qe,Ye]=Ze.split(":"),nt=parseInt(Qe),rt=nt>=12?"PM":"AM";return`${nt>12?nt-12:nt||12}:${Ye} ${rt}`},je=async()=>{q("");const Ze=Jgs.safeParse(b);if(!Ze.success){q(Ze.error.issues[0].message);return}if(!b.email&&!b.phone){q("Please provide either an email or phone number");return}const Qe=(l==null?void 0:l.kind)==="virtual";let Ye=null;if(!y&&(l!=null&&l.id))try{const nt=await d.mutateAsync({open_house_id:l.id,first_name:b.first_name.trim(),last_name:b.last_name.trim()||void 0,email:b.email.trim()||void 0,phone:b.phone.trim()||void 0,visitor_address:de&&b.visitor_address.trim()?b.visitor_address.trim():void 0,wants_market_updates:T,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():void 0,partial_signin:Qe?!1:ie});Ye=nt.id,g(nt.id)}catch{if(Qe){q("We could not start the virtual tour. Please try again.");return}}if(Qe){ie?x("intent"):(Ye&&ee(Ye,{}),x("done"));return}if(!ie){Ye&&ee(Ye,{}),oe?!ue&&le&&le.length>0?x("survey"):x("pending_survey"):x("done");return}x("intent")},xe=async Ze=>{C(Ze);try{let Qe=y;if(Qe?await u.mutateAsync({visitor_id:Qe,visitor_intent:Ze,wants_market_updates:T,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():null,partial_signin:!1}):(Qe=(await d.mutateAsync({open_house_id:l.id,first_name:b.first_name.trim(),last_name:b.last_name.trim()||void 0,email:b.email.trim()||void 0,phone:b.phone.trim()||void 0,visitor_address:de&&b.visitor_address.trim()?b.visitor_address.trim():void 0,visitor_intent:Ze,wants_market_updates:T,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():void 0,partial_signin:!1})).id,g(Qe)),Qe&&ee(Qe,{visitor_intent:Ze,wants_market_updates:T,has_agent:P,working_with_agent_name:P&&I.trim()?I.trim():null}),(l==null?void 0:l.kind)==="virtual"){x("done");return}oe?!ue&&le&&le.length>0?x("survey"):x("pending_survey"):x("done")}catch{q("Something went wrong. Please try again.")}};if(o)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})});if(c||!l)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(ia,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Open House Not Found"}),e.jsx("p",{className:"text-white/60",children:"This sign-in page doesn't exist or is no longer active."})]})});const fe=l.profiles,Se=((Ue=fe==null?void 0:fe.name)==null?void 0:Ue.split(" ").map(Ze=>Ze[0]).join("").slice(0,2))||"?",Ee=l.event_type==="community",Le=l.kind==="virtual",De=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Le&&(De||p==="done"))return!De&&!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(ql,{children:[e.jsxs("title",{children:["Virtual Tour | ",l.property_address]}),e.jsx("meta",{name:"description",content:`Take a virtual tour of ${l.property_address}`}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),De&&e.jsx("div",{className:"fixed top-3 left-1/2 -translate-x-1/2 z-[100] bg-amber-500 text-white text-xs font-semibold px-3 py-1.5 rounded-full shadow-lg pointer-events-none",children:"Agent Preview Mode — visitors won't see this"}),e.jsx(Qgs,{openHouse:l,visitorId:De?"preview":y,visitorName:De?"Preview Visitor":`${b.first_name} ${b.last_name}`.trim(),visitorEmail:De?"":b.email,visitorPhone:De?"":b.phone,previewMode:De})]});const Ne=`${Le?"Virtual Open House":Ee?"Community Event":"Open House"} — ${l.property_address}`,_e=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?Bs(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,fe!=null&&fe.name?`Hosted by ${fe.name}`:null].filter(Boolean).join(" · "),Oe=l.photo_url||"",Ae=Oe&&Oe.includes("/storage/v1/object/public/")?Oe.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Oe||"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(ql,{children:[e.jsx("title",{children:Ne}),e.jsx("meta",{name:"description",content:_e||`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:_e||`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:_e||`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(Ra,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(Fi,{src:(fe==null?void 0:fe.avatar_url)||"",alt:(fe==null?void 0:fe.name)||""}),e.jsx(Da,{className:"bg-white/10 text-white text-lg",children:Se})]}),e.jsx("p",{className:"text-white/60 text-sm",children:fe==null?void 0:fe.name}),(fe==null?void 0:fe.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:fe.title})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[l.photo_url&&e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[e.jsx("img",{src:l.photo_url,alt:l.property_address,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(oi,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Le&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ra,{className:"h-3 w-3"}),Bs(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(Vr,{className:"h-3 w-3"}),we(l.start_time),l.end_time?` – ${we(l.end_time)}`:""]})]})]})]})]}),!l.photo_url&&e.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:Ee?e.jsx(Ni,{className:"h-5 w-5 text-white"}):e.jsx(ia,{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(oi,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Le&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ra,{className:"h-3 w-3"}),Bs(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(Vr,{className:"h-3 w-3"}),we(l.start_time),l.end_time?` – ${we(l.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[p==="welcome"&&e.jsxs("div",{className:"text-center space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),e.jsx("p",{className:"text-slate-500 text-sm",children:l.agent_greeting||"Please sign in below."})]}),e.jsxs(B,{onClick:()=>x("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(Xa,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),p==="info"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>x("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Your Info"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(ye,{value:b.first_name,onChange:Ze=>v(Qe=>({...Qe,first_name:Ze.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(ye,{value:b.last_name,onChange:Ze=>v(Qe=>({...Qe,last_name:Ze.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(ye,{type:"email",value:b.email,onChange:Ze=>v(Qe=>({...Qe,email:Ze.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(ye,{type:"tel",value:b.phone,onChange:Ze=>v(Qe=>({...Qe,phone:Ze.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),de&&e.jsxs("div",{children:[e.jsx(se,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(ye,{value:b.visitor_address,onChange:Ze=>v(Qe=>({...Qe,visitor_address:Ze.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:Ze=>M(Ze.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),e.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-slate-400",children:P?"Yes":"No"}),e.jsx(Mn,{checked:P,onCheckedChange:L})]})]}),P&&e.jsx(ye,{value:I,onChange:Ze=>O(Ze.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:je,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(Xa,{className:"h-5 w-5 ml-2"})]})]}),p==="intent"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>x("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(_a,{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:e0s.map(Ze=>e.jsxs("button",{onClick:()=>xe(Ze.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:Ze.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Ze.label})]},Ze.value))}),$&&e.jsx("p",{className:"text-destructive text-sm text-center",children:$})]}),p==="pending_survey"&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[e.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),p==="survey"&&y&&le&&e.jsx($gs,{questions:le,visitorId:y,onComplete:()=>x("done"),onSkip:()=>x("done")}),p==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:e.jsx(Rr,{className:"h-8 w-8 text-green-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"You're all set!"}),e.jsxs("p",{className:"text-slate-500 text-sm mt-1",children:["Thanks for signing in, ",b.first_name,". ",Ee?"Enjoy the event!":"Enjoy the open house!"]})]}),(l==null?void 0:l.disclosure_pdf_url)&&e.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(l.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[e.jsx($r,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(fe==null?void 0:fe.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:fe.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx(B,{onClick:K,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),e.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",W,"s…"]})]})]})]})]}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),a&&e.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10",children:[e.jsx(cz,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:J,className:"inline-flex items-center gap-1 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10 hover:bg-white/20",title:"Enter full screen",children:e.jsx(WW,{className:"h-3 w-3"})})]})]})})]})}function yBn(s){const{user:t}=Ns();return mt({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:n,error:r}=await U.from("open_house_cohost_tokens").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n},enabled:!!t&&!!s})}function vBn(){const s=as(),{user:t}=Ns();return vt({mutationFn:async({openHouseId:n,label:r})=>{const{data:a,error:i}=await U.from("open_house_cohost_tokens").insert({open_house_id:n,label:r||null,created_by:t.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function bBn(){const s=as();return vt({mutationFn:async({id:t,openHouseId:n})=>{const{error:r}=await U.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function t0s(s){return mt({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:n}=await U.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",s).eq("is_active",!0).single();if(n)throw n;if(t.expires_at&&new Date(t.expires_at)t[n][r]??n,s)}var Nqe="ScrollArea",[gSt,_Bn]=Zm(Nqe),[n0s,Wj]=gSt(Nqe),ySt=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,x]=j.useState(null),[y,g]=j.useState(null),[b,v]=j.useState(0),[k,C]=j.useState(0),[T,M]=j.useState(!1),[P,L]=j.useState(!1),I=ko(t,$=>c($)),O=J3(a);return e.jsx(n0s,{scope:n,type:r,dir:O,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:u,content:h,onContentChange:m,scrollbarX:p,onScrollbarXChange:x,scrollbarXEnabled:T,onScrollbarXEnabledChange:M,scrollbarY:y,onScrollbarYChange:g,scrollbarYEnabled:P,onScrollbarYEnabledChange:L,onCornerWidthChange:v,onCornerHeightChange:C,children:e.jsx(Ua.div,{dir:O,...l,ref:I,style:{position:"relative","--radix-scroll-area-corner-width":b+"px","--radix-scroll-area-corner-height":k+"px",...s.style}})})});ySt.displayName=Nqe;var vSt="ScrollAreaViewport",bSt=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,children:r,nonce:a,...i}=s,l=Wj(vSt,n),o=j.useRef(null),c=ko(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(Ua.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})})]})});bSt.displayName=vSt;var oS="ScrollAreaScrollbar",kqe=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Wj(oS,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:l}=a,o=s.orientation==="horizontal";return j.useEffect(()=>(o?i(!0):l(!0),()=>{o?i(!1):l(!1)}),[o,i,l]),a.type==="hover"?e.jsx(r0s,{...r,ref:t,forceMount:n}):a.type==="scroll"?e.jsx(a0s,{...r,ref:t,forceMount:n}):a.type==="auto"?e.jsx(_St,{...r,ref:t,forceMount:n}):a.type==="always"?e.jsx(Sqe,{...r,ref:t}):null});kqe.displayName=oS;var r0s=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Wj(oS,s.__scopeScrollArea),[i,l]=j.useState(!1);return j.useEffect(()=>{const o=a.scrollArea;let c=0;if(o){const d=()=>{window.clearTimeout(c),l(!0)},u=()=>{c=window.setTimeout(()=>l(!1),a.scrollHideDelay)};return o.addEventListener("pointerenter",d),o.addEventListener("pointerleave",u),()=>{window.clearTimeout(c),o.removeEventListener("pointerenter",d),o.removeEventListener("pointerleave",u)}}},[a.scrollArea,a.scrollHideDelay]),e.jsx(ax,{present:n||i,children:e.jsx(_St,{"data-state":i?"visible":"hidden",...r,ref:t})})}),a0s=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Wj(oS,s.__scopeScrollArea),i=s.orientation==="horizontal",l=k3e(()=>c("SCROLL_END"),100),[o,c]=s0s("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return j.useEffect(()=>{if(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),j.useEffect(()=>{const d=a.viewport,u=i?"scrollLeft":"scrollTop";if(d){let h=d[u];const m=()=>{const p=d[u];h!==p&&(c("SCROLL"),l()),h=p};return d.addEventListener("scroll",m),()=>d.removeEventListener("scroll",m)}},[a.viewport,i,c,l]),e.jsx(ax,{present:n||o!=="hidden",children:e.jsx(Sqe,{"data-state":o==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:ua(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:ua(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),_St=j.forwardRef((s,t)=>{const n=Wj(oS,s.__scopeScrollArea),{forceMount:r,...a}=s,[i,l]=j.useState(!1),o=s.orientation==="horizontal",c=k3e(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=s,a=Wj(oS,s.__scopeScrollArea),i=j.useRef(null),l=j.useRef(0),[o,c]=j.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=SSt(o.viewport,o.content),u={...r,sizes:o,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:m=>i.current=m,onThumbPointerUp:()=>l.current=0,onThumbPointerDown:m=>l.current=m};function h(m,p){return u0s(m,l.current,o,p)}return n==="horizontal"?e.jsx(i0s,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollLeft,p=Ont(m,o,a.dir);i.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:m=>{a.viewport&&(a.viewport.scrollLeft=m)},onDragScroll:m=>{a.viewport&&(a.viewport.scrollLeft=h(m,a.dir))}}):n==="vertical"?e.jsx(o0s,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const m=a.viewport.scrollTop,p=Ont(m,o);i.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:m=>{a.viewport&&(a.viewport.scrollTop=m)},onDragScroll:m=>{a.viewport&&(a.viewport.scrollTop=h(m))}}):null}),i0s=j.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=Wj(oS,s.__scopeScrollArea),[l,o]=j.useState(),c=j.useRef(null),d=ko(t,c,i.onScrollbarXChange);return j.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(jSt,{"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":N3e(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),ASt(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:INe(l.paddingLeft),paddingEnd:INe(l.paddingRight)}})}})}),o0s=j.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=Wj(oS,s.__scopeScrollArea),[l,o]=j.useState(),c=j.useRef(null),d=ko(t,c,i.onScrollbarYChange);return j.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(jSt,{"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":N3e(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),ASt(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:INe(l.paddingTop),paddingEnd:INe(l.paddingBottom)}})}})}),[l0s,wSt]=gSt(oS),jSt=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:a,onThumbChange:i,onThumbPointerUp:l,onThumbPointerDown:o,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:u,onResize:h,...m}=s,p=Wj(oS,n),[x,y]=j.useState(null),g=ko(t,I=>y(I)),b=j.useRef(null),v=j.useRef(""),k=p.viewport,C=r.content-r.viewport,T=gf(u),M=gf(c),P=k3e(h,10);function L(I){if(b.current){const O=I.clientX-b.current.left,$=I.clientY-b.current.top;d({x:O,y:$})}}return j.useEffect(()=>{const I=O=>{const $=O.target;(x==null?void 0:x.contains($))&&T(O,C)};return document.addEventListener("wheel",I,{passive:!1}),()=>document.removeEventListener("wheel",I,{passive:!1})},[k,x,C,T]),j.useEffect(M,[r,M]),_$(x,P),_$(p.content,P),e.jsx(l0s,{scope:n,scrollbar:x,hasThumb:a,onThumbChange:gf(i),onThumbPointerUp:gf(l),onThumbPositionChange:M,onThumbPointerDown:gf(o),children:e.jsx(Ua.div,{...m,ref:g,style:{position:"absolute",...m.style},onPointerDown:ua(s.onPointerDown,I=>{I.button===0&&(I.target.setPointerCapture(I.pointerId),b.current=x.getBoundingClientRect(),v.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),L(I))}),onPointerMove:ua(s.onPointerMove,L),onPointerUp:ua(s.onPointerUp,I=>{const O=I.target;O.hasPointerCapture(I.pointerId)&&O.releasePointerCapture(I.pointerId),document.body.style.webkitUserSelect=v.current,p.viewport&&(p.viewport.style.scrollBehavior=""),b.current=null})})})}),PNe="ScrollAreaThumb",NSt=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=wSt(PNe,s.__scopeScrollArea);return e.jsx(ax,{present:n||a.hasThumb,children:e.jsx(c0s,{ref:t,...r})})}),c0s=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,style:r,...a}=s,i=Wj(PNe,n),l=wSt(PNe,n),{onThumbPositionChange:o}=l,c=ko(t,h=>l.onThumbChange(h)),d=j.useRef(void 0),u=k3e(()=>{d.current&&(d.current(),d.current=void 0)},100);return j.useEffect(()=>{const h=i.viewport;if(h){const m=()=>{if(u(),!d.current){const p=h0s(h,o);d.current=p,o()}};return o(),h.addEventListener("scroll",m),()=>h.removeEventListener("scroll",m)}},[i.viewport,u,o]),e.jsx(Ua.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:ua(s.onPointerDownCapture,h=>{const p=h.target.getBoundingClientRect(),x=h.clientX-p.left,y=h.clientY-p.top;l.onThumbPointerDown({x,y})}),onPointerUp:ua(s.onPointerUp,l.onThumbPointerUp)})});NSt.displayName=PNe;var Cqe="ScrollAreaCorner",kSt=j.forwardRef((s,t)=>{const n=Wj(Cqe,s.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?e.jsx(d0s,{...s,ref:t}):null});kSt.displayName=Cqe;var d0s=j.forwardRef((s,t)=>{const{__scopeScrollArea:n,...r}=s,a=Wj(Cqe,n),[i,l]=j.useState(0),[o,c]=j.useState(0),d=!!(i&&o);return _$(a.scrollbarX,()=>{var h;const u=((h=a.scrollbarX)==null?void 0:h.offsetHeight)||0;a.onCornerHeightChange(u),c(u)}),_$(a.scrollbarY,()=>{var h;const u=((h=a.scrollbarY)==null?void 0:h.offsetWidth)||0;a.onCornerWidthChange(u),l(u)}),d?e.jsx(Ua.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 INe(s){return s?parseInt(s,10):0}function SSt(s,t){const n=s/t;return isNaN(n)?0:n}function N3e(s){const t=SSt(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}function u0s(s,t,n,r="ltr"){const a=N3e(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 CSt([c,d],h)(s)}function Ont(s,t,n="ltr"){const r=N3e(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=XY(s,c);return CSt([0,l],[0,o])(d)}function CSt(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 ASt(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 k3e(s,t){const n=gf(s),r=j.useRef(0);return j.useEffect(()=>()=>window.clearTimeout(r.current),[]),j.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function _$(s,t){const n=gf(t);Nf(()=>{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 TSt=ySt,m0s=bSt,p0s=kSt;const lo=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(TSt,{ref:r,className:Et("relative overflow-hidden",s),...n,children:[e.jsx(m0s,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(KU,{}),e.jsx(p0s,{})]}));lo.displayName=TSt.displayName;const KU=j.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(kqe,{ref:r,orientation:t,className:Et("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(NSt,{className:"relative flex-1 rounded-full bg-border"})}));KU.displayName=kqe.displayName;const Aqe=j.createContext({});function Tqe(s){const t=j.useRef(null);return t.current===null&&(t.current=s()),t.current}const f0s=typeof window<"u",ESt=f0s?j.useLayoutEffect:j.useEffect,S3e=j.createContext(null);function Eqe(s,t){s.indexOf(t)===-1&&s.push(t)}function RNe(s,t){const n=s.indexOf(t);n>-1&&s.splice(n,1)}const Y5=(s,t,n)=>n>t?t:n{},w$=()=>{};const ME={},MSt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function LSt(s){return typeof s=="object"&&s!==null}const PSt=s=>/^0[^.\s]+$/u.test(s);function ISt(s){let t;return()=>(t===void 0&&(t=s()),t)}const Mj=s=>s,x0s=(s,t)=>n=>t(s(n)),bJ=(...s)=>s.reduce(x0s),eZ=(s,t,n)=>{const r=t-s;return r===0?1:(n-s)/r};class Mqe{constructor(){this.subscriptions=[]}add(t){return Eqe(this.subscriptions,t),()=>RNe(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,yj=s=>s/1e3;function RSt(s,t){return t?s*(1e3/t):0}const DSt=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,g0s=1e-7,y0s=12;function v0s(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=DSt(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>g0s&&++ov0s(i,0,1,s,n);return i=>i===0||i===1?i:DSt(a(i),t,r)}const OSt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,FSt=s=>t=>1-s(1-t),zSt=_J(.33,1.53,.69,.99),Lqe=FSt(zSt),BSt=OSt(Lqe),$St=s=>s>=1?1:(s*=2)<1?.5*Lqe(s):.5*(2-Math.pow(2,-10*(s-1))),Pqe=s=>1-Math.sin(Math.acos(s)),USt=FSt(Pqe),qSt=OSt(Pqe),b0s=_J(.42,0,1,1),_0s=_J(0,0,.58,1),VSt=_J(.42,0,.58,1),w0s=s=>Array.isArray(s)&&typeof s[0]!="number",HSt=s=>Array.isArray(s)&&typeof s[0]=="number",Fnt={linear:Mj,easeIn:b0s,easeInOut:VSt,easeOut:_0s,circIn:Pqe,circInOut:qSt,circOut:USt,backIn:Lqe,backInOut:BSt,backOut:zSt,anticipate:$St},j0s=s=>typeof s=="string",znt=s=>{if(HSt(s)){w$(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,r,a]=s;return _J(t,n,r,a)}else if(j0s(s))return w$(Fnt[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),Fnt[s];return s},Sse=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Bnt={value:null,addProjectionMetrics:null};function N0s(s,t){let n=new Set,r=new Set,a=!1,i=!1;const l=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1},c=0;function d(h){l.has(h)&&(u.schedule(h),s()),c++,h(o)}const u={schedule:(h,m=!1,p=!1)=>{const y=p&&a?n:r;return m&&l.add(h),y.add(h),h},cancel:h=>{r.delete(h),l.delete(h)},process:h=>{if(o=h,a){i=!0;return}a=!0;const m=n;n=r,r=m,n.forEach(d),t&&Bnt.value&&Bnt.value.frameloop[t].push(c),c=0,n.clear(),a=!1,i&&(i=!1,u.process(h))}};return u}const k0s=40;function GSt(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=Sse.reduce((k,C)=>(k[C]=N0s(i,t?C:void 0),k),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:m,render:p,postRender:x}=l,y=()=>{const k=ME.useManualTiming,C=k?a.timestamp:performance.now();n=!1,k||(a.delta=r?1e3/60:Math.max(Math.min(C-a.timestamp,k0s),1)),a.timestamp=C,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),h.process(a),m.process(a),p.process(a),x.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(y))},g=()=>{n=!0,r=!0,a.isProcessing||s(y)};return{schedule:Sse.reduce((k,C)=>{const T=l[C];return k[C]=(M,P=!1,L=!1)=>(n||g(),T.schedule(M,P,L)),k},{}),cancel:k=>{for(let C=0;C(pje===void 0&&Gv.set(V0.isProcessing||ME.useManualTiming?V0.timestamp:performance.now()),pje),set:s=>{pje=s,queueMicrotask(S0s)}},WSt=s=>t=>typeof t=="string"&&t.startsWith(s),KSt=WSt("--"),C0s=WSt("var(--"),Iqe=s=>C0s(s)?A0s.test(s.split("/*")[0].trim()):!1,A0s=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function $nt(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const YU={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},tZ={...YU,transform:s=>Y5(0,1,s)},Cse={...YU,default:1},CK=s=>Math.round(s*1e5)/1e5,Rqe=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function T0s(s){return s==null}const E0s=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Dqe=(s,t)=>n=>!!(typeof n=="string"&&E0s.test(n)&&n.startsWith(s)||t&&!T0s(n)&&Object.prototype.hasOwnProperty.call(n,t)),YSt=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(Rqe);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},M0s=s=>Y5(0,255,s),EMe={...YU,transform:s=>Math.round(M0s(s))},t8={test:Dqe("rgb","red"),parse:YSt("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+EMe.transform(s)+", "+EMe.transform(t)+", "+EMe.transform(n)+", "+CK(tZ.transform(r))+")"};function L0s(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 rOe={test:Dqe("#"),parse:L0s,transform:t8.transform},wJ=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),XC=wJ("deg"),z5=wJ("%"),eo=wJ("px"),P0s=wJ("vh"),I0s=wJ("vw"),Unt={...z5,parse:s=>z5.parse(s)/100,transform:s=>z5.transform(s*100)},o9={test:Dqe("hsl","hue"),parse:YSt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+z5.transform(CK(t))+", "+z5.transform(CK(n))+", "+CK(tZ.transform(r))+")"},gx={test:s=>t8.test(s)||rOe.test(s)||o9.test(s),parse:s=>t8.test(s)?t8.parse(s):o9.test(s)?o9.parse(s):rOe.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?t8.transform(s):o9.transform(s),getAnimatableNone:s=>{const t=gx.parse(s);return t.alpha=0,gx.transform(t)}},R0s=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function D0s(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(Rqe))==null?void 0:t.length)||0)+(((n=s.match(R0s))==null?void 0:n.length)||0)>0}const ZSt="number",XSt="color",O0s="var",F0s="var(",qnt="${}",z0s=/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 j$(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(z0s,c=>(gx.test(c)?(r.color.push(i),a.push(XSt),n.push(gx.parse(c))):c.startsWith(F0s)?(r.var.push(i),a.push(O0s),n.push(c)):(r.number.push(i),a.push(ZSt),n.push(parseFloat(c))),++i,qnt)).split(qnt);return{values:n,split:o,indexes:r,types:a}}function B0s(s){return j$(s).values}function QSt({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:gx.test(s)?gx.getAnimatableNone(s):s,q0s=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:U0s(s);function V0s(s){const t=j$(s);return QSt(t)(t.values.map((r,a)=>q0s(r,t.split[a])))}const _N={test:D0s,parse:B0s,createTransformer:$0s,getAnimatableNone:V0s};function MMe(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 H0s({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=MMe(c,o,s+1/3),i=MMe(c,o,s),l=MMe(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function DNe(s,t){return n=>n>0?t:s}const hm=(s,t,n)=>s+(t-s)*n,LMe=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},G0s=[rOe,t8,o9],W0s=s=>G0s.find(t=>t.test(s));function Vnt(s){const t=W0s(s);if(C3e(!!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===o9&&(n=H0s(n)),n}const Hnt=(s,t)=>{const n=Vnt(s),r=Vnt(t);if(!n||!r)return DNe(s,t);const a={...n};return i=>(a.red=LMe(n.red,r.red,i),a.green=LMe(n.green,r.green,i),a.blue=LMe(n.blue,r.blue,i),a.alpha=hm(n.alpha,r.alpha,i),t8.transform(a))},aOe=new Set(["none","hidden"]);function K0s(s,t){return aOe.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function Y0s(s,t){return n=>hm(s,t,n)}function Oqe(s){return typeof s=="number"?Y0s:typeof s=="string"?Iqe(s)?DNe:gx.test(s)?Hnt:Q0s:Array.isArray(s)?JSt:typeof s=="object"?gx.test(s)?Hnt:Z0s:DNe}function JSt(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>Oqe(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function X0s(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=_N.createTransformer(t),r=j$(s),a=j$(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?aOe.has(s)&&!a.values.length||aOe.has(t)&&!r.values.length?K0s(s,t):bJ(JSt(X0s(r,a),a.values),n):(C3e(!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"),DNe(s,t))};function e4t(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?hm(s,t,n):Oqe(s)(s,t)}const J0s=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>Nh.update(t,n),stop:()=>LE(t),now:()=>V0.isProcessing?V0.timestamp:Gv.now()}},t4t=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=ONe?1/0:t}function eys(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(Fqe(r),ONe);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:yj(a)}}const Sp={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 iOe(s,t){return s*Math.sqrt(1-t*t)}const tys=12;function sys(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,m=u-n,p=iOe(d,l),x=Math.exp(-h);return PMe-m/p*x},i=d=>{const h=d*l*s,m=h*n+n,p=Math.pow(l,2)*Math.pow(d,2)*s,x=Math.exp(-h),y=iOe(Math.pow(d,2),l);return(-a(d)+PMe>0?-1:1)*((m-p)*x)/y}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-PMe+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=sys(a,i,o);if(s=bb(s),isNaN(c))return{stiffness:Sp.stiffness,damping:Sp.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const rys=["duration","bounce"],ays=["stiffness","damping","mass"];function Gnt(s,t){return t.some(n=>s[n]!==void 0)}function iys(s){let t={velocity:Sp.velocity,stiffness:Sp.stiffness,damping:Sp.damping,mass:Sp.mass,isResolvedFromDuration:!1,...s};if(!Gnt(s,ays)&&Gnt(s,rys))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*Y5(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:Sp.mass,stiffness:a,damping:i}}else{const n=nys({...s,velocity:0});t={...t,...n,mass:Sp.mass},t.isResolvedFromDuration=!0}return t}function FNe(s=Sp.visualDuration,t=Sp.bounce){const n=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:r,restDelta:a}=n;const i=n.keyframes[0],l=n.keyframes[n.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:u,duration:h,velocity:m,isResolvedFromDuration:p}=iys({...n,velocity:-yj(n.velocity||0)}),x=m||0,y=d/(2*Math.sqrt(c*u)),g=l-i,b=yj(Math.sqrt(c/u)),v=Math.abs(g)<5;r||(r=v?Sp.restSpeed.granular:Sp.restSpeed.default),a||(a=v?Sp.restDelta.granular:Sp.restDelta.default);let k,C,T,M,P,L;if(y<1)T=iOe(b,y),M=(x+y*b*g)/T,k=O=>{const $=Math.exp(-y*b*O);return l-$*(M*Math.sin(T*O)+g*Math.cos(T*O))},P=y*b*M+g*T,L=y*b*g-M*T,C=O=>Math.exp(-y*b*O)*(P*Math.sin(T*O)+L*Math.cos(T*O));else if(y===1){k=$=>l-Math.exp(-b*$)*(g+(x+b*g)*$);const O=x+b*g;C=$=>Math.exp(-b*$)*(b*O*$-x)}else{const O=b*Math.sqrt(y*y-1);k=G=>{const K=Math.exp(-y*b*G),ee=Math.min(O*G,300);return l-K*((x+y*b*g)*Math.sinh(ee)+O*g*Math.cosh(ee))/O};const $=(x+y*b*g)/O,q=y*b*$-g*O,W=y*b*g-$*O;C=G=>{const K=Math.exp(-y*b*G),ee=Math.min(O*G,300);return K*(q*Math.sinh(ee)+W*Math.cosh(ee))}}const I={calculatedDuration:p&&h||null,velocity:O=>bb(C(O)),next:O=>{if(!p&&y<1){const q=Math.exp(-y*b*O),W=Math.sin(T*O),G=Math.cos(T*O),K=l-q*(M*W+g*G),ee=bb(q*(P*W+L*G));return o.done=Math.abs(ee)<=r&&Math.abs(l-K)<=a,o.value=o.done?l:K,o}const $=k(O);if(p)o.done=O>=h;else{const q=bb(C(O));o.done=Math.abs(q)<=r&&Math.abs(l-$)<=a}return o.value=o.done?l:$,o},toString:()=>{const O=Math.min(Fqe(I),ONe),$=t4t(q=>I.next(O*q).value,O,30);return O+"ms "+$},toTransition:()=>{}};return I}FNe.applyToOptions=s=>{const t=eys(s,100,FNe);return s.ease=t.ease,s.duration=bb(t.duration),s.type="keyframes",s};const oys=5;function s4t(s,t,n){const r=Math.max(t-oys,0);return RSt(n-s(r),t-r)}function oOe({keyframes:s,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:u}){const h=s[0],m={done:!1,value:h},p=L=>o!==void 0&&Lc,x=L=>o===void 0?c:c===void 0||Math.abs(o-L)-y*Math.exp(-L/r),k=L=>b+v(L),C=L=>{const I=v(L),O=k(L);m.done=Math.abs(I)<=d,m.value=m.done?b:O};let T,M;const P=L=>{p(m.value)&&(T=L,M=FNe({keyframes:[m.value,x(m.value)],velocity:s4t(k,L,m.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return P(0),{calculatedDuration:null,next:L=>{let I=!1;return!M&&T===void 0&&(I=!0,C(L),P(L)),T!==void 0&&L>=T?M.next(L-T):(!I&&C(L),m)}}}function lys(s,t,n){const r=[],a=n||ME.mix||e4t,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=lys(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(Y5(s[0],s[i-1],u)):d}function dys(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=eZ(0,t,r);s.push(hm(n,1,a))}}function uys(s){const t=[0];return dys(t,s.length-1),t}function hys(s,t){return s.map(n=>n*t)}function mys(s,t){return s.map(()=>t||VSt).splice(0,s.length-1)}function AK({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=w0s(r)?r.map(znt):znt(r),i={done:!1,value:t[0]},l=hys(n&&n.length===t.length?n:uys(t),s),o=cys(l,t,{ease:Array.isArray(a)?a:mys(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const pys=s=>s!==null;function A3e(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(pys),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const fys={decay:oOe,inertia:oOe,tween:AK,keyframes:AK,spring:FNe};function n4t(s){typeof s.type=="string"&&(s.type=fys[s.type])}class zqe{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 xys=s=>s/100;class zNe extends zqe{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!==Gv.now()&&this.tick(Gv.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;n4t(t);const{type:n=AK,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||AK;c!==AK&&typeof o[0]!="number"&&(this.mixKeyframes=bJ(xys,e4t(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=Fqe(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+a,this.totalDuration=this.resolvedDuration*(r+1)-a,this.generator=d}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:r,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:u,repeat:h,repeatType:m,repeatDelay:p,type:x,onUpdate:y,finalKeyframe:g}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-a/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const b=this.currentTime-d*(this.playbackSpeed>=0?1:-1),v=this.playbackSpeed>=0?b<0:b>a;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let k=this.currentTime,C=r;if(h){const L=Math.min(this.currentTime,a)/o;let I=Math.floor(L),O=L%1;!O&&L>=1&&(O=1),O===1&&I--,I=Math.min(I,h+1),!!(I%2)&&(m==="reverse"?(O=1-O,p&&(O-=p/o)):m==="mirror"&&(C=l)),k=Y5(0,1,O)*o}let T;v?(this.delayState.value=u[0],T=this.delayState):T=C.next(k),i&&!v&&(T.value=i(T.value));let{done:M}=T;!v&&c!==null&&(M=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const P=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&M);return P&&x!==oOe&&(T.value=A3e(u,this.options,g,this.speed)),y&&y(T.value),P&&this.finish(),T}then(t,n){return this.finished.then(t,n)}get duration(){return yj(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+yj(t)}get time(){return yj(this.currentTime)}set time(t){t=bb(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 s4t(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(Gv.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=yj(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=J0s,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(Gv.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 gys(s){for(let t=1;ts*180/Math.PI,lOe=s=>{const t=s8(Math.atan2(s[1],s[0]));return cOe(t)},yys={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:lOe,rotateZ:lOe,skewX:s=>s8(Math.atan(s[1])),skewY:s=>s8(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},cOe=s=>(s=s%360,s<0&&(s+=360),s),Wnt=lOe,Knt=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),Ynt=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),vys={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Knt,scaleY:Ynt,scale:s=>(Knt(s)+Ynt(s))/2,rotateX:s=>cOe(s8(Math.atan2(s[6],s[5]))),rotateY:s=>cOe(s8(Math.atan2(-s[2],s[0]))),rotateZ:Wnt,rotate:Wnt,skewX:s=>s8(Math.atan(s[4])),skewY:s=>s8(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function dOe(s){return s.includes("scale")?1:0}function uOe(s,t){if(!s||s==="none")return dOe(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=vys,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=yys,a=o}if(!a)return dOe(t);const i=r[t],l=a[1].split(",").map(_ys);return typeof i=="function"?i(l):l[i]}const bys=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return uOe(n,t)};function _ys(s){return parseFloat(s.trim())}const ZU=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],XU=new Set(ZU),Znt=s=>s===YU||s===eo,wys=new Set(["x","y","z"]),jys=ZU.filter(s=>!wys.has(s));function Nys(s){const t=[];return jys.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const bT={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})=>uOe(t,"x"),y:(s,{transform:t})=>uOe(t,"y")};bT.translateX=bT.x;bT.translateY=bT.y;const XR=new Set;let hOe=!1,mOe=!1,pOe=!1;function r4t(){if(mOe){const s=Array.from(XR).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=Nys(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)})}mOe=!1,hOe=!1,XR.forEach(s=>s.complete(pOe)),XR.clear()}function a4t(){XR.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(mOe=!0)})}function kys(){pOe=!0,a4t(),r4t(),pOe=!1}class Bqe{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?(XR.add(this),hOe||(hOe=!0,Nh.read(a4t),Nh.resolveKeyframes(r4t))):(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])}gys(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),XR.delete(this)}cancel(){this.state==="scheduled"&&(XR.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Sys=s=>s.startsWith("--");function i4t(s,t,n){Sys(t)?s.style.setProperty(t,n):s.style[t]=n}const Cys={};function o4t(s,t){const n=ISt(s);return()=>Cys[t]??n()}const Ays=o4t(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),l4t=o4t(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),LG=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,Xnt={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:LG([0,.65,.55,1]),circOut:LG([.55,0,1,.45]),backIn:LG([.31,.01,.66,-.59]),backOut:LG([.33,1.53,.69,.99])};function c4t(s,t){if(s)return typeof s=="function"?l4t()?t4t(s,t):"ease-out":HSt(s)?LG(s):Array.isArray(s)?s.map(n=>c4t(n,t)||Xnt.easeOut):Xnt[s]}function Tys(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=c4t(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 d4t(s){return typeof s=="function"&&"applyToOptions"in s}function Eys({type:s,...t}){return d4t(s)&&l4t()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class u4t extends zqe{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,w$(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=Eys(t);this.animation=Tys(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=A3e(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),i4t(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 yj(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+yj(t)}get time(){return yj(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=bb(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&&Ays()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),Mj):a(this)}}const h4t={anticipate:$St,backInOut:BSt,circInOut:qSt};function Mys(s){return s in h4t}function Lys(s){typeof s.ease=="string"&&Mys(s.ease)&&(s.ease=h4t[s.ease])}const IMe=10;class Pys extends u4t{constructor(t){Lys(t),n4t(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 zNe({...l,autoplay:!1}),c=Math.max(IMe,Gv.now()-this.startTime),d=Y5(0,IMe,c-IMe),u=o.sample(c).value,{name:h}=this.options;i&&h&&i4t(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const Qnt=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(_N.test(s)||s==="0")&&!s.startsWith("url("));function Iys(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function Bys(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 zys()&&n&&(m4t.has(n)||Fys.has(n)&&Oys(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const $ys=40;class Uys extends zqe{constructor({autoplay:t=!0,delay:n=0,type:r="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:u,...h}){var x;super(),this.stop=()=>{var y,g;this._animation&&(this._animation.stop(),(y=this.stopTimeline)==null||y.call(this)),(g=this.keyframeResolver)==null||g.cancel()},this.createdAt=Gv.now();const m={autoplay:t,delay:n,type:r,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:u,...h},p=(u==null?void 0:u.KeyframeResolver)||Bqe;this.keyframeResolver=new p(o,(y,g,b)=>this.onKeyframesResolved(y,g,m,!b),c,d,u),(x=this.keyframeResolver)==null||x.scheduleResolve()}onKeyframesResolved(t,n,r,a){var b,v;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=Gv.now();let h=!0;Rys(t,i,l,o)||(h=!1,(ME.instantAnimations||!c)&&(u==null||u(A3e(t,r,n))),t[0]=t[t.length-1],fOe(r),r.repeat=0);const p={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>$ys?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},x=h&&!d&&Bys(p),y=(v=(b=p.motionValue)==null?void 0:b.owner)==null?void 0:v.current;let g;if(x)try{g=new Pys({...p,element:y})}catch{g=new zNe(p)}else g=new zNe(p);g.finished.then(()=>{this.notifyFinished()}).catch(Mj),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}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(),kys()),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 p4t(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 qys=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Vys(s){const t=qys.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}const Hys=4;function f4t(s,t,n=1){w$(n<=Hys,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[r,a]=Vys(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return MSt(l)?parseFloat(l):l}return Iqe(a)?f4t(a,t,n+1):a}const Gys={type:"spring",stiffness:500,damping:25,restSpeed:10},Wys=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),Kys={type:"keyframes",duration:.8},Yys={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Zys=(s,{keyframes:t})=>t.length>2?Kys:XU.has(s)?s.startsWith("scale")?Wys(t[1]):Gys:Yys;function x4t(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function $qe(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?x4t(n,s):n}const Xys=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function Qys(s){for(const t in s)if(!Xys.has(t))return!0;return!1}const Uqe=(s,t,n,r={},a,i)=>l=>{const o=$qe(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-bb(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};Qys(o)||Object.assign(u,Zys(s,u)),u.duration&&(u.duration=bb(u.duration)),u.repeatDelay&&(u.repeatDelay=bb(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(fOe(u),u.delay===0&&(h=!0)),(ME.instantAnimations||ME.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(h=!0,fOe(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const m=A3e(u.keyframes,o);if(m!==void 0){Nh.update(()=>{u.onUpdate(m),u.onComplete()});return}}return o.isSync?new zNe(u):new Uys(u)};function Jnt(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function qqe(s,t,n,r){if(typeof t=="function"){const[a,i]=Jnt(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]=Jnt(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function QR(s,t,n){const r=s.getProps();return qqe(r,t,n!==void 0?n:r.custom,s)}const g4t=new Set(["width","height","top","left","right","bottom",...ZU]),ert=30,Jys=s=>!isNaN(parseFloat(s));class evs{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=Gv.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=Gv.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=Jys(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 Mqe);const r=this.events[t].add(n);return t==="change"?()=>{r(),Nh.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=Gv.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>ert)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,ert);return RSt(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 N$(s,t){return new evs(s,t)}const xOe=s=>Array.isArray(s);function tvs(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,N$(n))}function svs(s){return xOe(s)?s[s.length-1]||0:s}function nvs(s,t){const n=QR(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=svs(i[l]);tvs(s,l,o)}}const Q0=s=>!!(s&&s.getVelocity);function rvs(s){return!!(Q0(s)&&s.add)}function gOe(s,t){const n=s.getValue("willChange");if(rvs(n))return n.add(t);if(!n&&ME.WillChange){const r=new ME.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function Vqe(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const avs="framerAppearId",y4t="data-"+Vqe(avs);function v4t(s){return s.props[y4t]}function ivs({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function b4t(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?x4t(i,c):c;const d=i==null?void 0:i.reduceMotion;r&&(i=r);const u=[],h=a&&s.animationState&&s.animationState.getState()[a];for(const m in o){const p=s.getValue(m,s.latestValues[m]??null),x=o[m];if(x===void 0||h&&ivs(h,m))continue;const y={delay:n,...$qe(i||{},m)},g=p.get();if(g!==void 0&&!p.isAnimating()&&!Array.isArray(x)&&x===g&&!y.velocity){Nh.update(()=>p.set(x));continue}let b=!1;if(window.MotionHandoffAnimation){const C=v4t(s);if(C){const T=window.MotionHandoffAnimation(C,m,Nh);T!==null&&(y.startTime=T,b=!0)}}gOe(s,m);const v=d??s.shouldReduceMotion;p.start(Uqe(m,p,x,v&&g4t.has(m)?{type:!1}:y,s,b));const k=p.animation;k&&u.push(k)}if(l){const m=()=>Nh.update(()=>{l&&nvs(s,l)});u.length?Promise.all(u).then(m):m()}return u}function yOe(s,t,n={}){var c;const r=QR(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(b4t(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:m}=a;return ovs(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 ovs(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(yOe(c,t,{...l,delay:n+(typeof r=="function"?0:r)+p4t(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function lvs(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>yOe(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=yOe(s,t,n);else{const a=typeof t=="function"?QR(s,t,n.custom):t;r=Promise.all(b4t(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const cvs={test:s=>s==="auto",parse:s=>s},_4t=s=>t=>t.test(s),w4t=[YU,eo,z5,XC,I0s,P0s,cvs],trt=s=>w4t.find(_4t(s));function dvs(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||PSt(s):!0}const uvs=new Set(["brightness","contrast","saturate","opacity"]);function hvs(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(Rqe)||[];if(!r)return s;const a=n.replace(r,"");let i=uvs.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const mvs=/\b([a-z-]*)\(.*?\)/gu,vOe={..._N,getAnimatableNone:s=>{const t=s.match(mvs);return t?t.map(hvs).join(" "):s}},bOe={..._N,getAnimatableNone:s=>{const t=_N.parse(s);return _N.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},srt={...YU,transform:Math.round},pvs={rotate:XC,rotateX:XC,rotateY:XC,rotateZ:XC,scale:Cse,scaleX:Cse,scaleY:Cse,scaleZ:Cse,skew:XC,skewX:XC,skewY:XC,distance:eo,translateX:eo,translateY:eo,translateZ:eo,x:eo,y:eo,z:eo,perspective:eo,transformPerspective:eo,opacity:tZ,originX:Unt,originY:Unt,originZ:eo},Hqe={borderWidth:eo,borderTopWidth:eo,borderRightWidth:eo,borderBottomWidth:eo,borderLeftWidth:eo,borderRadius:eo,borderTopLeftRadius:eo,borderTopRightRadius:eo,borderBottomRightRadius:eo,borderBottomLeftRadius:eo,width:eo,maxWidth:eo,height:eo,maxHeight:eo,top:eo,right:eo,bottom:eo,left:eo,inset:eo,insetBlock:eo,insetBlockStart:eo,insetBlockEnd:eo,insetInline:eo,insetInlineStart:eo,insetInlineEnd:eo,padding:eo,paddingTop:eo,paddingRight:eo,paddingBottom:eo,paddingLeft:eo,paddingBlock:eo,paddingBlockStart:eo,paddingBlockEnd:eo,paddingInline:eo,paddingInlineStart:eo,paddingInlineEnd:eo,margin:eo,marginTop:eo,marginRight:eo,marginBottom:eo,marginLeft:eo,marginBlock:eo,marginBlockStart:eo,marginBlockEnd:eo,marginInline:eo,marginInlineStart:eo,marginInlineEnd:eo,fontSize:eo,backgroundPositionX:eo,backgroundPositionY:eo,...pvs,zIndex:srt,fillOpacity:tZ,strokeOpacity:tZ,numOctaves:srt},fvs={...Hqe,color:gx,backgroundColor:gx,outlineColor:gx,fill:gx,stroke:gx,borderColor:gx,borderTopColor:gx,borderRightColor:gx,borderBottomColor:gx,borderLeftColor:gx,filter:vOe,WebkitFilter:vOe,mask:bOe,WebkitMask:bOe},j4t=s=>fvs[s],xvs=new Set([vOe,bOe]);function N4t(s,t){let n=j4t(s);return xvs.has(n)||(n=_N),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const gvs=new Set(["auto","none","0"]);function yvs(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function Gqe(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 k4t=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function fje(s){return LSt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:Wqe,cancel:wBn}=GSt(queueMicrotask,!1),A2={x:!1,y:!1};function S4t(){return A2.x||A2.y}function bvs(s){return s==="x"||s==="y"?A2[s]?null:(A2[s]=!0,()=>{A2[s]=!1}):A2.x||A2.y?null:(A2.x=A2.y=!0,()=>{A2.x=A2.y=!1})}function C4t(s,t){const n=Gqe(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function _vs(s){return!(s.pointerType==="touch"||S4t())}function wvs(s,t,n={}){const[r,a,i]=C4t(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",x)},h=g=>{d&&(d(g),d=void 0),u()},m=g=>{o=!1,window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),c&&(c=!1,h(g))},p=()=>{o=!0,window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",m,a)},x=g=>{if(g.pointerType!=="touch"){if(o){c=!0;return}h(g)}},y=g=>{if(!_vs(g))return;c=!1;const b=t(l,g);typeof b=="function"&&(d=b,l.addEventListener("pointerleave",x,a))};l.addEventListener("pointerenter",y,a),l.addEventListener("pointerdown",p,a)}),i}const A4t=(s,t)=>t?s===t?!0:A4t(s,t.parentElement):!1,Kqe=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,jvs=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Nvs(s){return jvs.has(s.tagName)||s.isContentEditable===!0}const kvs=new Set(["INPUT","SELECT","TEXTAREA"]);function Svs(s){return kvs.has(s.tagName)||s.isContentEditable===!0}const xje=new WeakSet;function nrt(s){return t=>{t.key==="Enter"&&s(t)}}function RMe(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const Cvs=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=nrt(()=>{if(xje.has(n))return;RMe(n,"down");const a=nrt(()=>{RMe(n,"up")}),i=()=>RMe(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 rrt(s){return Kqe(s)&&!S4t()}const art=new WeakSet;function Avs(s,t,n={}){const[r,a,i]=C4t(s,n),l=o=>{const c=o.currentTarget;if(!rrt(o)||art.has(o))return;xje.add(c),n.stopPropagation&&art.add(o);const d=t(c,o),u=(p,x)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",m),xje.has(c)&&xje.delete(c),rrt(p)&&typeof d=="function"&&d(p,{success:x})},h=p=>{u(p,c===window||c===document||n.useGlobalTarget||A4t(c,p.target))},m=p=>{u(p,!1)};window.addEventListener("pointerup",h,a),window.addEventListener("pointercancel",m,a)};return r.forEach(o=>{(n.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),fje(o)&&(o.addEventListener("focus",d=>Cvs(d,a)),!Nvs(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function Yqe(s){return LSt(s)&&"ownerSVGElement"in s}const gje=new WeakMap;let QC;const T4t=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:Yqe(r)&&"getBBox"in r?r.getBBox()[t]:r[n],Tvs=T4t("inline","width","offsetWidth"),Evs=T4t("block","height","offsetHeight");function Mvs({target:s,borderBoxSize:t}){var n;(n=gje.get(s))==null||n.forEach(r=>{r(s,{get width(){return Tvs(s,t)},get height(){return Evs(s,t)}})})}function Lvs(s){s.forEach(Mvs)}function Pvs(){typeof ResizeObserver>"u"||(QC=new ResizeObserver(Lvs))}function Ivs(s,t){QC||Pvs();const n=Gqe(s);return n.forEach(r=>{let a=gje.get(r);a||(a=new Set,gje.set(r,a)),a.add(t),QC==null||QC.observe(r)}),()=>{n.forEach(r=>{const a=gje.get(r);a==null||a.delete(t),a!=null&&a.size||QC==null||QC.unobserve(r)})}}const yje=new Set;let l9;function Rvs(){l9=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};yje.forEach(t=>t(s))},window.addEventListener("resize",l9)}function Dvs(s){return yje.add(s),l9||Rvs(),()=>{yje.delete(s),!yje.size&&typeof l9=="function"&&(window.removeEventListener("resize",l9),l9=void 0)}}function irt(s,t){return typeof s=="function"?Dvs(s):Ivs(s,t)}function Ovs(s){return Yqe(s)&&s.tagName==="svg"}const Fvs=[...w4t,gx,_N],zvs=s=>Fvs.find(_4t(s)),ort=()=>({translate:0,scale:1,origin:0,originPoint:0}),c9=()=>({x:ort(),y:ort()}),lrt=()=>({min:0,max:0}),Xx=()=>({x:lrt(),y:lrt()}),Bvs=new WeakMap;function T3e(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function sZ(s){return typeof s=="string"||Array.isArray(s)}const Zqe=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Xqe=["initial",...Zqe];function E3e(s){return T3e(s.animate)||Xqe.some(t=>sZ(s[t]))}function E4t(s){return!!(E3e(s)||s.variants)}function $vs(s,t,n){for(const r in t){const a=t[r],i=n[r];if(Q0(a))s.addValue(r,a);else if(Q0(i))s.addValue(r,N$(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,N$(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const _Oe={current:null},M4t={current:!1},Uvs=typeof window<"u";function qvs(){if(M4t.current=!0,!!Uvs)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>_Oe.current=s.matches;s.addEventListener("change",t),t()}else _Oe.current=!1}const crt=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let BNe={};function L4t(s){BNe=s}function Vvs(){return BNe}class Hvs{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=Bqe,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const p=Gv.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(M4t.current||qvs(),this.shouldReduceMotion=_Oe.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(),LE(this.notifyUpdate),LE(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&&m4t.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new u4t({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:bb(u)}),m=l(h);this.valueSubscriptions.set(t,()=>{m(),h.cancel()});return}const r=XU.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&Nh.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 BNe){const n=BNe[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):Xx()}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=N$(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"&&(MSt(r)||PSt(r))?r=parseFloat(r):!zvs(r)&&_N.test(n)&&(r=N4t(t,n)),this.setBaseTarget(t,Q0(r)?r.get():r)),Q0(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=qqe(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&&!Q0(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 Mqe),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){Wqe.render(this.render)}}class P4t extends Hvs{constructor(){super(...arguments),this.KeyframeResolver=vvs}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;Q0(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class r6{constructor(t){this.isMounted=!1,this.node=t}update(){}}function I4t({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function Gvs({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function Wvs(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 DMe(s){return s===void 0||s===1}function wOe({scale:s,scaleX:t,scaleY:n}){return!DMe(s)||!DMe(t)||!DMe(n)}function MI(s){return wOe(s)||R4t(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function R4t(s){return drt(s.x)||drt(s.y)}function drt(s){return s&&s!=="0%"}function $Ne(s,t,n){const r=s-n,a=t*r;return n+a}function urt(s,t,n,r,a){return a!==void 0&&(s=$Ne(s,a,r)),$Ne(s,n,r)+t}function jOe(s,t=0,n=1,r,a){s.min=urt(s.min,t,n,r,a),s.max=urt(s.max,t,n,r,a)}function D4t(s,{x:t,y:n}){jOe(s.x,t.translate,t.scale,t.originPoint),jOe(s.y,n.translate,n.scale,n.originPoint)}const hrt=.999999999999,mrt=1.0000000000001;function Kvs(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;chrt&&(t.x=1),t.yhrt&&(t.y=1)}function u5(s,t){s.min+=t,s.max+=t}function prt(s,t,n,r,a=.5){const i=hm(s.min,s.max,a);jOe(s,t,n,i,r)}function frt(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function vje(s,t,n){const r=n??s;prt(s.x,frt(t.x,r.x),t.scaleX,t.scale,t.originX),prt(s.y,frt(t.y,r.y),t.scaleY,t.scale,t.originY)}function O4t(s,t){return I4t(Wvs(s.getBoundingClientRect(),t))}function Yvs(s,t,n){const r=O4t(s,n),{scroll:a}=t;return a&&(u5(r.x,a.offset.x),u5(r.y,a.offset.y)),r}const Zvs={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Xvs=ZU.length;function Qvs(s,t,n){let r="",a=!0;for(let i=0;i{if(!t.target)return s;if(typeof s=="string")if(eo.test(s))s=parseFloat(s);else return s;const n=xrt(s,t.target.x),r=xrt(s,t.target.y);return`${n}% ${r}%`}},Jvs={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=_N.parse(s);if(a.length>5)return r;const i=_N.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=hm(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},NOe={borderRadius:{...gH,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:gH,borderTopRightRadius:gH,borderBottomLeftRadius:gH,borderBottomRightRadius:gH,boxShadow:Jvs};function z4t(s,{layout:t,layoutId:n}){return XU.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!NOe[s]||s==="opacity")}function Jqe(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)(Q0(r[o])||a&&Q0(a[o])||z4t(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function e1s(s){return window.getComputedStyle(s)}class t1s extends P4t{constructor(){super(...arguments),this.type="html",this.renderInstance=F4t}readValueFromInstance(t,n){var r;if(XU.has(n))return(r=this.projection)!=null&&r.isProjecting?dOe(n):bys(t,n);{const a=e1s(t),i=(KSt(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return O4t(t,n)}build(t,n,r){Qqe(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return Jqe(t,n,r)}}const s1s={offset:"stroke-dashoffset",array:"stroke-dasharray"},n1s={offset:"strokeDashoffset",array:"strokeDasharray"};function r1s(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?s1s:n1s;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const a1s=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function B4t(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(Qqe(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:h,style:m}=s;h.transform&&(m.transform=h.transform,delete h.transform),(m.transform||h.transformOrigin)&&(m.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),m.transform&&(m.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete h.transformBox);for(const p of a1s)h[p]!==void 0&&(m[p]=h[p],delete h[p]);t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),a!==void 0&&r1s(h,a,i,l,!1)}const $4t=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"]),U4t=s=>typeof s=="string"&&s.toLowerCase()==="svg";function i1s(s,t,n,r){F4t(s,t,void 0,r);for(const a in t.attrs)s.setAttribute($4t.has(a)?a:Vqe(a),t.attrs[a])}function q4t(s,t,n){const r=Jqe(s,t,n);for(const a in s)if(Q0(s[a])||Q0(t[a])){const i=ZU.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class o1s extends P4t{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Xx}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(XU.has(n)){const r=j4t(n);return r&&r.default||0}return n=$4t.has(n)?n:Vqe(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return q4t(t,n,r)}build(t,n,r){B4t(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){i1s(t,n,r,a)}mount(t){this.isSVGTag=U4t(t.tagName),super.mount(t)}}const l1s=Xqe.length;function V4t(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?V4t(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})=>lvs(s,n,r)))}function h1s(s){let t=u1s(s),n=grt(),r=!0,a=!1;const i=d=>(u,h)=>{var p;const m=QR(s,h,d==="exit"?(p=s.presenceContext)==null?void 0:p.custom:void 0);if(m){const{transition:x,transitionEnd:y,...g}=m;u={...u,...g,...y}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=V4t(s.parent)||{},m=[],p=new Set;let x={},y=1/0;for(let b=0;by&&T,O=!1;const $=Array.isArray(C)?C:[C];let q=$.reduce(i(v),{});M===!1&&(q={});const{prevResolvedValues:W={}}=k,G={...W,...q},K=le=>{I=!0,p.has(le)&&(O=!0,p.delete(le)),k.needsAnimating[le]=!0;const ue=s.getValue(le);ue&&(ue.liveStyle=!1)};for(const le in G){const ue=q[le],oe=W[le];if(x.hasOwnProperty(le))continue;let ie=!1;xOe(ue)&&xOe(oe)?ie=!H4t(ue,oe):ie=ue!==oe,ie?ue!=null?K(le):p.add(le):ue!==void 0&&p.has(le)?K(le):k.protectedKeys[le]=!0}k.prevProp=C,k.prevResolvedValues=q,k.isActive&&(x={...x,...q}),(r||a)&&s.blockInitialAnimation&&(I=!1);const ee=P&&L;I&&(!ee||O)&&m.push(...$.map(le=>{const ue={type:v};if(typeof le=="string"&&(r||a)&&!ee&&s.manuallyAnimateOnMount&&s.parent){const{parent:oe}=s,ie=QR(oe,le);if(oe.enteringChildren&&ie){const{delayChildren:de}=ie.transition||{};ue.delay=p4t(oe.enteringChildren,s,de)}}return{animation:le,options:ue}}))}if(p.size){const b={};if(typeof u.initial!="boolean"){const v=QR(s,Array.isArray(u.initial)?u.initial[0]:u.initial);v&&v.transition&&(b.transition=v.transition)}p.forEach(v=>{const k=s.getBaseTarget(v),C=s.getValue(v);C&&(C.liveStyle=!0),b[v]=k??null}),m.push({animation:b})}let g=!!m.length;return r&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(g=!1),r=!1,a=!1,g?t(m):Promise.resolve()}function c(d,u){var m;if(n[d].isActive===u)return Promise.resolve();(m=s.variantChildren)==null||m.forEach(p=>{var x;return(x=p.animationState)==null?void 0:x.setActive(d,u)}),n[d].isActive=u;const h=o(d);for(const p in n)n[p].protectedKeys={};return h}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>n,reset:()=>{n=grt(),a=!0}}}function m1s(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!H4t(t,s):!1}function lM(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function grt(){return{animate:lM(!0),whileInView:lM(),whileHover:lM(),whileTap:lM(),whileDrag:lM(),whileFocus:lM(),exit:lM()}}function kOe(s,t){s.min=t.min,s.max=t.max}function w2(s,t){kOe(s.x,t.x),kOe(s.y,t.y)}function yrt(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const G4t=1e-4,p1s=1-G4t,f1s=1+G4t,W4t=.01,x1s=0-W4t,g1s=0+W4t;function Wv(s){return s.max-s.min}function y1s(s,t,n){return Math.abs(s-t)<=n}function vrt(s,t,n,r=.5){s.origin=r,s.originPoint=hm(t.min,t.max,s.origin),s.scale=Wv(n)/Wv(t),s.translate=hm(n.min,n.max,s.origin)-s.originPoint,(s.scale>=p1s&&s.scale<=f1s||isNaN(s.scale))&&(s.scale=1),(s.translate>=x1s&&s.translate<=g1s||isNaN(s.translate))&&(s.translate=0)}function TK(s,t,n,r){vrt(s.x,t.x,n.x,r?r.originX:void 0),vrt(s.y,t.y,n.y,r?r.originY:void 0)}function brt(s,t,n,r=0){const a=r?hm(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+Wv(t)}function v1s(s,t,n,r){brt(s.x,t.x,n.x,r==null?void 0:r.x),brt(s.y,t.y,n.y,r==null?void 0:r.y)}function _rt(s,t,n,r=0){const a=r?hm(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+Wv(t)}function UNe(s,t,n,r){_rt(s.x,t.x,n.x,r==null?void 0:r.x),_rt(s.y,t.y,n.y,r==null?void 0:r.y)}function wrt(s,t,n,r,a){return s-=t,s=$Ne(s,1/n,r),a!==void 0&&(s=$Ne(s,1/a,r)),s}function b1s(s,t=0,n=1,r=.5,a,i=s,l=s){if(z5.test(t)&&(t=parseFloat(t),t=hm(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=hm(i.min,i.max,r);s===i&&(o-=t),s.min=wrt(s.min,t,n,o,a),s.max=wrt(s.max,t,n,o,a)}function jrt(s,t,[n,r,a],i,l){b1s(s,t[n],t[r],t[a],t.scale,i,l)}const _1s=["x","scaleX","originX"],w1s=["y","scaleY","originY"];function Nrt(s,t,n,r){jrt(s.x,t,_1s,n?n.x:void 0,r?r.x:void 0),jrt(s.y,t,w1s,n?n.y:void 0,r?r.y:void 0)}function krt(s){return s.translate===0&&s.scale===1}function K4t(s){return krt(s.x)&&krt(s.y)}function Srt(s,t){return s.min===t.min&&s.max===t.max}function j1s(s,t){return Srt(s.x,t.x)&&Srt(s.y,t.y)}function Crt(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function Y4t(s,t){return Crt(s.x,t.x)&&Crt(s.y,t.y)}function Art(s){return Wv(s.x)/Wv(s.y)}function Trt(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function Rk(s){return[s("x"),s("y")]}function N1s(s,t,n){let r="";const a=s.x.translate/t.x,i=s.y.translate/t.y,l=(n==null?void 0:n.z)||0;if((a||i||l)&&(r=`translate3d(${a}px, ${i}px, ${l}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:d,rotate:u,rotateX:h,rotateY:m,skewX:p,skewY:x}=n;d&&(r=`perspective(${d}px) ${r}`),u&&(r+=`rotate(${u}deg) `),h&&(r+=`rotateX(${h}deg) `),m&&(r+=`rotateY(${m}deg) `),p&&(r+=`skewX(${p}deg) `),x&&(r+=`skewY(${x}deg) `)}const o=s.x.scale*t.x,c=s.y.scale*t.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const Z4t=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],k1s=Z4t.length,Ert=s=>typeof s=="string"?parseFloat(s):s,Mrt=s=>typeof s=="number"||eo.test(s);function S1s(s,t,n,r,a,i){a?(s.opacity=hm(0,n.opacity??1,C1s(r)),s.opacityExit=hm(t.opacity??1,0,A1s(r))):i&&(s.opacity=hm(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(eZ(s,t,r))}function T1s(s,t,n){const r=Q0(s)?s:N$(s);return r.start(Uqe("",r,t,n)),r.animation}function nZ(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n)}const E1s=(s,t)=>s.depth-t.depth;class M1s{constructor(){this.children=[],this.isDirty=!1}add(t){Eqe(this.children,t),this.isDirty=!0}remove(t){RNe(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(E1s),this.isDirty=!1,this.children.forEach(t)}}function L1s(s,t){const n=Gv.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(LE(r),s(i-t))};return Nh.setup(r,!0),()=>LE(r)}function bje(s){return Q0(s)?s.get():s}class P1s{constructor(){this.members=[]}add(t){Eqe(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&&(RNe(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(RNe(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 _je={hasAnimatedSinceResize:!0,hasEverUpdated:!1},OMe=["","X","Y","Z"],I1s=1e3;let R1s=0;function FMe(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function Q4t(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=v4t(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",Nh,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&Q4t(r)}function J4t({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=R1s++,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(F1s),this.nodes.forEach(V1s),this.nodes.forEach(H1s),this.nodes.forEach(z1s)},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;Nh.read(()=>{h=window.innerWidth}),s(l,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,u&&u(),u=L1s(m,250),_je.hasAnimatedSinceResize&&(_je.hasAnimatedSinceResize=!1,this.nodes.forEach(Rrt)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const x=this.options.transition||d.getDefaultTransition()||Z1s,{onLayoutAnimationStart:y,onLayoutAnimationComplete:g}=d.getProps(),b=!this.targetLayout||!Y4t(this.targetLayout,p),v=!h&&m;if(this.options.layoutRoot||this.resumeFrom||v||h&&(b||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...$qe(x,"layout"),onPlay:y,onComplete:g};(d.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(u,v)}else h||Rrt(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),LE(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(G1s),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&&Q4t(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&&!Wv(this.snapshot.measuredBox.x)&&!Wv(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=C/1e3;Drt(h.x,l.x,T),Drt(h.y,l.y,T),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(UNe(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),K1s(this.relativeTarget,this.relativeTargetOrigin,m,T),k&&j1s(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=Xx()),w2(k,this.relativeTarget)),y&&(this.animationValues=u,S1s(u,d,this.latestValues,T,v,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&&(LE(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Nh.update(()=>{_je.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=N$(0)),this.motionValue.jump(0,!1),this.currentAnimation=T1s(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(I1s),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&&e3t(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Xx();const h=Wv(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const m=Wv(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+m}w2(o,c),vje(o,u),TK(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new P1s),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&&FMe("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(Prt),this.root.sharedNodes.clear()}}}function D1s(s){s.updateLayout()}function O1s(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")Rk(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=Wv(m);m.min=r[h].min,m.max=m.min+p});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";kOe(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else e3t(i,t.layoutBox,r)&&Rk(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=Wv(r[h]);m.max=m.min+p,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[h].max=s.relativeTarget[h].min+p)});const o=c9();TK(o,r,t.layoutBox);const c=c9();l?TK(c,s.applyTransform(a,!0),t.measuredBox):TK(c,r,t.layoutBox);const d=!K4t(o);let u=!1;if(!s.resumeFrom){const h=s.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:m,layout:p}=h;if(m&&p){const x=s.options.layoutAnchor||void 0,y=Xx();UNe(y,t.layoutBox,m.layoutBox,x);const g=Xx();UNe(g,r,p.layoutBox,x),Y4t(y,g)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=g,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 F1s(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 z1s(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function B1s(s){s.clearSnapshot()}function Prt(s){s.clearMeasurements()}function $1s(s){s.isLayoutDirty=!0,s.updateLayout()}function Irt(s){s.isLayoutDirty=!1}function U1s(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function q1s(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function Rrt(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function V1s(s){s.resolveTargetDelta()}function H1s(s){s.calcProjection()}function G1s(s){s.resetSkewAndRotation()}function W1s(s){s.removeLeadSnapshot()}function Drt(s,t,n){s.translate=hm(t.translate,0,n),s.scale=hm(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function Ort(s,t,n,r){s.min=hm(t.min,n.min,r),s.max=hm(t.max,n.max,r)}function K1s(s,t,n,r){Ort(s.x,t.x,n.x,r),Ort(s.y,t.y,n.y,r)}function Y1s(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const Z1s={duration:.45,ease:[.4,0,.1,1]},Frt=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),zrt=Frt("applewebkit/")&&!Frt("chrome/")?Math.round:Mj;function Brt(s){s.min=zrt(s.min),s.max=zrt(s.max)}function X1s(s){Brt(s.x),Brt(s.y)}function e3t(s,t,n){return s==="position"||s==="preserve-aspect"&&!y1s(Art(t),Art(n),.2)}function Q1s(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const J1s=J4t({attachResizeListener:(s,t)=>nZ(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}),zMe={current:void 0},t3t=J4t({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!zMe.current){const s=new J1s({});s.mount(window),s.setOptions({layoutScroll:!0}),zMe.current=s}return zMe.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),eVe=j.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function $rt(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function ebs(...s){return t=>{let n=!1;const r=s.map(a=>{const i=$rt(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:p,height:x,top:y,left:g,right:b,bottom:v}=c.current;if(t||i===!1||!o.current||!p||!x)return;const k=n==="left"?`left: ${g}`:`right: ${b}`,C=r==="bottom"?`bottom: ${v}`:`top: ${y}`;o.current.dataset.motionPopId=l;const T=document.createElement("style");d&&(T.nonce=d);const M=a??document.head;return M.appendChild(T),T.sheet&&T.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${p}px !important; height: ${x}px !important; ${k}px !important; ${C}px !important; } `),()=>{var P;(P=o.current)==null||P.removeAttribute("data-motion-pop-id"),M.contains(T)&&M.removeChild(T)}},[t]),e.jsx(sbs,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:j.cloneElement(s,{ref:h})})}const rbs=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=Tqe(abs),h=j.useId();let m=!0,p=j.useMemo(()=>(m=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:x=>{u.set(x,!0);for(const y of u.values())if(!y)return;r&&r()},register:x=>(u.set(x,!1),()=>u.delete(x))}),[n,u,r]);return i&&m&&(p={...p}),j.useMemo(()=>{u.forEach((x,y)=>u.set(y,!1))},[n]),j.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(nbs,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(S3e.Provider,{value:p,children:s})};function abs(){return new Map}function s3t(s=!0){const t=j.useContext(S3e);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:a}=t,i=j.useId();j.useEffect(()=>{if(s)return a(i)},[s]);const l=j.useCallback(()=>s&&r&&r(i),[i,r,s]);return!n&&r?[!1,l]:[!0]}const Ase=s=>s.key||"";function Urt(s){const t=[];return j.Children.forEach(s,n=>{j.isValidElement(n)&&t.push(n)}),t}const QU=({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]=s3t(l),m=j.useMemo(()=>Urt(s),[s]),p=l&&!u?[]:m.map(Ase),x=j.useRef(!0),y=j.useRef(m),g=Tqe(()=>new Map),b=j.useRef(new Set),[v,k]=j.useState(m),[C,T]=j.useState(m);ESt(()=>{x.current=!1,y.current=m;for(let L=0;L{const I=Ase(L),O=l&&!u?!1:m===C||p.includes(I),$=()=>{if(b.current.has(I))return;if(g.has(I))b.current.add(I),g.set(I,!0);else return;let q=!0;g.forEach(W=>{W||(q=!1)}),q&&(P==null||P(),T(y.current),l&&(h==null||h()),r&&r())};return e.jsx(rbs,{isPresent:O,initial:!x.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:O?void 0:$,anchorX:o,anchorY:c,children:L},I)})})},n3t=j.createContext({strict:!1}),qrt={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 Vrt=!1;function ibs(){if(Vrt)return;const s={};for(const t in qrt)s[t]={isEnabled:n=>qrt[t].some(r=>!!n[r])};L4t(s),Vrt=!0}function r3t(){return ibs(),Vvs()}function obs(s){const t=r3t();for(const n in s)t[n]={...t[n],...s[n]};L4t(t)}const lbs=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 qNe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||lbs.has(s)}let a3t=s=>!qNe(s);function cbs(s){typeof s=="function"&&(a3t=t=>t.startsWith("on")?!qNe(t):s(t))}try{cbs(require("@emotion/is-prop-valid").default)}catch{}function dbs(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||Q0(s[a])||(a3t(a)||n===!0&&qNe(a)||!t&&!qNe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const M3e=j.createContext({});function ubs(s,t){if(E3e(s)){const{initial:n,animate:r}=s;return{initial:n===!1||sZ(n)?n:void 0,animate:sZ(r)?r:void 0}}return s.inherit!==!1?t:{}}function hbs(s){const{initial:t,animate:n}=ubs(s,j.useContext(M3e));return j.useMemo(()=>({initial:t,animate:n}),[Hrt(t),Hrt(n)])}function Hrt(s){return Array.isArray(s)?s.join(" "):s}const tVe=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function i3t(s,t,n){for(const r in t)!Q0(t[r])&&!z4t(r,n)&&(s[r]=t[r])}function mbs({transformTemplate:s},t){return j.useMemo(()=>{const n=tVe();return Qqe(n,t,s),Object.assign({},n.vars,n.style)},[t])}function pbs(s,t){const n=s.style||{},r={};return i3t(r,n,s),Object.assign(r,mbs(s,t)),r}function fbs(s,t){const n={},r=pbs(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 o3t=()=>({...tVe(),attrs:{}});function xbs(s,t,n,r){const a=j.useMemo(()=>{const i=o3t();return B4t(i,t,U4t(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};i3t(i,s.style,s),a.style={...i,...a.style}}return a}const gbs=["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 sVe(s){return typeof s!="string"||s.includes("-")?!1:!!(gbs.indexOf(s)>-1||/[A-Z]/u.test(s))}function ybs(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??sVe(s)?xbs:fbs)(t,r,a,s),d=dbs(t,typeof s=="string",i),u=s!==j.Fragment?{...d,...c,ref:n}:{},{children:h}=t,m=j.useMemo(()=>Q0(h)?h.get():h,[h]);return j.createElement(s,{...u,children:m})}function vbs({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:bbs(n,r,a,s),renderState:t()}}function bbs(s,t,n,r){const a={},i=r(s,{});for(const m in i)a[m]=bje(i[m]);let{initial:l,animate:o}=s;const c=E3e(s),d=E4t(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"&&!T3e(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p(t,n)=>{const r=j.useContext(M3e),a=j.useContext(S3e),i=()=>vbs(s,t,r,a);return n?i():Tqe(i)},_bs=l3t({scrapeMotionValuesFromProps:Jqe,createRenderState:tVe}),wbs=l3t({scrapeMotionValuesFromProps:q4t,createRenderState:o3t}),jbs=Symbol.for("motionComponentSymbol");function Nbs(s,t,n){const r=j.useRef(n);j.useInsertionEffect(()=>{r.current=n});const a=j.useRef(null);return j.useCallback(i=>{var o;i&&((o=s.onMount)==null||o.call(s,i));const l=r.current;if(typeof l=="function")if(i){const c=l(i);typeof c=="function"&&(a.current=c)}else a.current?(a.current(),a.current=null):l(i);else l&&(l.current=i);t&&(i?t.mount(i):t.unmount())},[t])}const c3t=j.createContext({});function A7(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function kbs(s,t,n,r,a,i){var k,C;const{visualElement:l}=j.useContext(M3e),o=j.useContext(n3t),c=j.useContext(S3e),d=j.useContext(eVe),u=d.reducedMotion,h=d.skipAnimations,m=j.useRef(null),p=j.useRef(!1);r=r||o.renderer,!m.current&&r&&(m.current=r(s,{visualState:t,parent:l,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:i}),p.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const x=m.current,y=j.useContext(c3t);x&&!x.projection&&a&&(x.type==="html"||x.type==="svg")&&Sbs(m.current,n,a,y);const g=j.useRef(!1);j.useInsertionEffect(()=>{x&&g.current&&x.update(n,c)});const b=n[y4t],v=j.useRef(!!b&&typeof window<"u"&&!((k=window.MotionHandoffIsComplete)!=null&&k.call(window,b))&&((C=window.MotionHasOptimisedAnimation)==null?void 0:C.call(window,b)));return ESt(()=>{p.current=!0,x&&(g.current=!0,window.MotionIsMounted=!0,x.updateFeatures(),x.scheduleRenderMicrotask(),v.current&&x.animationState&&x.animationState.animateChanges())}),j.useEffect(()=>{x&&(!v.current&&x.animationState&&x.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{var T;(T=window.MotionHandoffMarkAsComplete)==null||T.call(window,b)}),v.current=!1),x.enteringChildren=void 0)}),x}function Sbs(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:d3t(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&A7(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function d3t(s){if(s)return s.options.allowProjection!==!1?s.projection:d3t(s.parent)}function BMe(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&obs(r);const i=n?n==="svg":sVe(s),l=i?wbs:_bs;function o(d,u){let h;const m={...j.useContext(eVe),...d,layoutId:Cbs(d)},{isStatic:p}=m,x=hbs(d),y=l(d,p);if(!p&&typeof window<"u"){Abs();const g=Tbs(m);h=g.MeasureLayout,x.visualElement=kbs(s,y,m,a,g.ProjectionNode,i)}return e.jsxs(M3e.Provider,{value:x,children:[h&&x.visualElement?e.jsx(h,{visualElement:x.visualElement,...m}):null,ybs(s,d,Nbs(y,x.visualElement,u),y,p,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=j.forwardRef(o);return c[jbs]=s,c}function Cbs({layoutId:s}){const t=j.useContext(Aqe).id;return t&&s!==void 0?t+"-"+s:s}function Abs(s,t){j.useContext(n3t).strict}function Tbs(s){const t=r3t(),{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 Ebs(s,t){if(typeof Proxy>"u")return BMe;const n=new Map,r=(i,l)=>BMe(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,BMe(l,void 0,s,t)),n.get(l))})}const Mbs=(s,t)=>t.isSVG??sVe(s)?new o1s(t):new t1s(t,{allowProjection:s!==j.Fragment});class Lbs extends r6{constructor(t){super(t),t.animationState||(t.animationState=h1s(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();T3e(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 Pbs=0;class Ibs extends r6{constructor(){super(...arguments),this.id=Pbs++,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=QR(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 Rbs={animation:{Feature:Lbs},exit:{Feature:Ibs}};function jJ(s){return{point:{x:s.pageX,y:s.pageY}}}const Dbs=s=>t=>Kqe(t)&&s(t,jJ(t));function EK(s,t,n,r){return nZ(s,t,Dbs(n),r)}const u3t=({current:s})=>s?s.ownerDocument.defaultView:null,Grt=(s,t)=>Math.abs(s-t);function Obs(s,t){const n=Grt(s.x,t.x),r=Grt(s.y,t.y);return Math.sqrt(n**2+r**2)}const Wrt=new Set(["auto","scroll"]);class h3t{constructor(t,n,{transformPagePoint:r,contextWindow:a=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=p=>{this.handleScroll(p.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Tse(this.lastRawMoveEventInfo,this.transformPagePoint));const p=$Me(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,y=Obs(p.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!y)return;const{point:g}=p,{timestamp:b}=V0;this.history.push({...g,timestamp:b});const{onStart:v,onMove:k}=this.handlers;x||(v&&v(this.lastMoveEvent,p),this.startEvent=this.lastMoveEvent),k&&k(this.lastMoveEvent,p)},this.handlePointerMove=(p,x)=>{this.lastMoveEvent=p,this.lastRawMoveEventInfo=x,this.lastMoveEventInfo=Tse(x,this.transformPagePoint),Nh.update(this.updatePoint,!0)},this.handlePointerUp=(p,x)=>{this.end();const{onEnd:y,onSessionEnd:g,resumeAnimation:b}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const v=$Me(p.type==="pointercancel"?this.lastMoveEventInfo:Tse(x,this.transformPagePoint),this.history);this.startEvent&&y&&y(p,v),g&&g(p,v)},!Kqe(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=jJ(t),d=Tse(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=V0;this.history=[{...u,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,$Me(d,this.history)),this.removeListeners=bJ(EK(this.contextWindow,"pointermove",this.handlePointerMove),EK(this.contextWindow,"pointerup",this.handlePointerUp),EK(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(Wrt.has(r.overflowX)||Wrt.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),Nh.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),LE(this.updatePoint)}}function Tse(s,t){return t?{point:t(s.point)}:s}function Krt(s,t){return{x:s.x-t.x,y:s.y-t.y}}function $Me({point:s},t){return{point:s,delta:Krt(s,m3t(t)),offset:Krt(s,Fbs(t)),velocity:zbs(t,.1)}}function Fbs(s){return s[0]}function m3t(s){return s[s.length-1]}function zbs(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=m3t(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>bb(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>bb(t)*2&&(r=s[1]);const i=yj(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 Bbs(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?hm(n,s,r.max):Math.min(s,n)),s}function Yrt(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 $bs(s,{top:t,left:n,bottom:r,right:a}){return{x:Yrt(s.x,n,a),y:Yrt(s.y,t,r)}}function Zrt(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=eZ(t.min,t.max-r,s.min):r>a&&(n=eZ(s.min,s.max-a,t.min)),Y5(0,1,n)}function Vbs(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 SOe=.35;function Hbs(s=SOe){return s===!1?s=0:s===!0&&(s=SOe),{x:Xrt(s,"left","right"),y:Xrt(s,"top","bottom")}}function Xrt(s,t,n){return{min:Qrt(s,t),max:Qrt(s,n)}}function Qrt(s,t){return typeof s=="number"?s:s[t]||0}const Gbs=new WeakMap;class Wbs{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=Xx(),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(jJ(h).point),this.stopAnimation()},l=(h,m)=>{const{drag:p,dragPropagation:x,onDragStart:y}=this.getProps();if(p&&!x&&(this.openDragLock&&this.openDragLock(),this.openDragLock=bvs(p),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Rk(b=>{let v=this.getAxisMotionValue(b).get()||0;if(z5.test(v)){const{projection:k}=this.visualElement;if(k&&k.layout){const C=k.layout.layoutBox[b];C&&(v=Wv(C)*(parseFloat(v)/100))}}this.originPoint[b]=v}),y&&Nh.update(()=>y(h,m),!1,!0),gOe(this.visualElement,"transform");const{animationState:g}=this.visualElement;g&&g.setActive("whileDrag",!0)},o=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:x,onDirectionLock:y,onDrag:g}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:b}=m;if(x&&this.currentDirection===null){this.currentDirection=Ybs(b),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",m.point,b),this.updateAxis("y",m.point,b),this.visualElement.render(),g&&Nh.update(()=>g(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 h3t(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:u3t(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&&Nh.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||!Ese(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=Bbs(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&&A7(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=$bs(r.layoutBox,t):this.constraints=!1,this.elastic=Hbs(n),a!==this.constraints&&!A7(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&Rk(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=Vbs(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!A7(t))return!1;const r=t.current;w$(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=Yvs(r,a.root,this.visualElement.getTransformPagePoint());let l=Ubs(a.layout.layoutBox,i);if(n){const o=n(Gvs(l));this.hasMutatedConstraints=!!o,o&&(l=I4t(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=Rk(u=>{if(!Ese(u,n,this.currentDirection))return;let h=c&&c[u]||{};(l===!0||l===u)&&(h={min:0,max:0});const m=a?200:1e6,p=a?40:1e7,x={type:"inertia",velocity:r?t[u]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(u,x)});return Promise.all(d).then(o)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return gOe(this.visualElement,t),r.start(Uqe(t,r,0,n,this.visualElement,!1))}stopAnimation(){Rk(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){Rk(n=>{const{drag:r}=this.getProps();if(!Ese(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]-hm(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!A7(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};Rk(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=qbs({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(),Rk(l=>{if(!Ese(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(hm(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;Gbs.set(this.visualElement,this);const t=this.visualElement.current,n=EK(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),m=d.target,p=m!==t&&Svs(m);u&&h&&!p&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();A7(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=Kbs(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),Nh.read(a);const o=nZ(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(Rk(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=SOe,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function Jrt(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function Kbs(s,t,n){const r=irt(s,Jrt(n)),a=irt(t,Jrt(n));return()=>{r(),a()}}function Ese(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function Ybs(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class Zbs extends r6{constructor(t){super(t),this.removeGroupControls=Mj,this.removeListeners=Mj,this.controls=new Wbs(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Mj}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 UMe=s=>(t,n)=>{s&&Nh.update(()=>s(t,n),!1,!0)};class Xbs extends r6{constructor(){super(...arguments),this.removePointerDownListener=Mj}onPointerDown(t){this.session=new h3t(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:u3t(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:UMe(t),onStart:UMe(n),onMove:UMe(r),onEnd:(i,l)=>{delete this.session,a&&Nh.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=EK(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 qMe=!1;class Qbs extends j.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r,layoutId:a}=this.props,{projection:i}=t;i&&(n.group&&n.group.add(i),r&&r.register&&a&&r.register(i),qMe&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),_je.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}),qMe=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||Nh.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(),Wqe.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;qMe=!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 p3t(s){const[t,n]=s3t(),r=j.useContext(Aqe);return e.jsx(Qbs,{...s,layoutGroup:r,switchLayoutGroup:j.useContext(c3t),isPresent:t,safeToRemove:n})}const Jbs={pan:{Feature:Xbs},drag:{Feature:Zbs,ProjectionNode:t3t,MeasureLayout:p3t}};function eat(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&&Nh.postRender(()=>i(t,jJ(t)))}class e_s extends r6{mount(){const{current:t}=this.node;t&&(this.unmount=wvs(t,(n,r)=>(eat(this.node,r,"Start"),a=>eat(this.node,a,"End"))))}unmount(){}}class t_s extends r6{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=bJ(nZ(this.node.current,"focus",()=>this.onFocus()),nZ(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function tat(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&&Nh.postRender(()=>i(t,jJ(t)))}class s_s extends r6{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=Avs(t,(a,i)=>(tat(this.node,i,"Start"),(l,{success:o})=>tat(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const COe=new WeakMap,VMe=new WeakMap,n_s=s=>{const t=COe.get(s.target);t&&t(s)},r_s=s=>{s.forEach(n_s)};function a_s({root:s,...t}){const n=s||document;VMe.has(n)||VMe.set(n,{});const r=VMe.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(r_s,{root:s,...t})),r[a]}function i_s(s,t,n){const r=a_s(t);return COe.set(s,n),r.observe(s),()=>{COe.delete(s),r.unobserve(s)}}const o_s={some:0,all:1};class l_s extends r6{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:o_s[a]},o=d=>{const{isIntersecting:u}=d;if(this.isInView===u||(this.isInView=u,i&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:h,onViewportLeave:m}=this.node.getProps(),p=u?h:m;p&&p(d)};this.stopObserver=i_s(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(c_s(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function c_s({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const d_s={inView:{Feature:l_s},tap:{Feature:s_s},focus:{Feature:t_s},hover:{Feature:e_s}},u_s={layout:{ProjectionNode:t3t,MeasureLayout:p3t}},h_s={...Rbs,...d_s,...Jbs,...u_s},br=Ebs(h_s,Mbs),m_s={some:0,all:1};function p_s(s,t,{root:n,margin:r,amount:a="some"}={}){const i=Gqe(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:m_s[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function f_s(s,{root:t,margin:n,amount:r,once:a=!1,initial:i=!1}={}){const[l,o]=j.useState(i);return j.useEffect(()=>{if(!s.current||a&&l)return;const c=()=>(o(!0),a?void 0:()=>o(!1)),d={root:t&&t.current||void 0,margin:n,amount:r};return p_s(s.current,c,d)},[t,s,n,a,r]),l}function x_s(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 sat(s){return s.visitor_intent==="buying"&&!s.has_agent}function g_s({token:s}={}){var x;const t=$i(),n=s||t.token,{data:r,isLoading:a,isError:i}=t0s(n),l=as(),o=(x=r==null?void 0:r.open_houses)==null?void 0:x.id,{data:c}=mt({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:y,error:g}=await U.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(g)throw g;return y},enabled:!!o});if(j.useEffect(()=>{if(!o)return;const y=U.channel(`cohost-visitors-${o}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${o}`},()=>{l.invalidateQueries({queryKey:["cohost-visitors",o]})}).subscribe();return()=>{U.removeChannel(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(sat).length)||0,p=y=>{if(!y)return"";const[g,b]=y.split(":"),v=parseInt(g);return`${v>12?v-12:v||12}:${b} ${v>=12?"PM":"AM"}`};return e.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[e.jsxs("div",{className:"border-b border-white/10 px-4 sm:px-6 py-3 flex items-center justify-between bg-black/30 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),e.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:d.property_address})]}),e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:u})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[e.jsx(Fd,{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(ia,{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:Bs(new Date(d.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),d.start_time&&e.jsxs("span",{children:[p(d.start_time),d.end_time?` – ${p(d.end_time)}`:""]})]}),e.jsx(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(QU,{children:c.map((y,g)=>{var k;const b=x_s(y.visitor_intent),v=sat(y);return e.jsxs(br.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:g*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${v?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[e.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center text-lg font-bold shrink-0 ${v?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(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||""]}),v&&e.jsx(qe,{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(qe,{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(qe,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${b.color}`,children:[b.emoji," ",b.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:Bs(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(iy,{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 y_s(){const t=$d().pathname.slice(1);if(j.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),t.startsWith("live/")){const n=t.slice(5);if(n)return e.jsx(g_s,{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(xSt,{slug:t})}function v_s({dealData:s,agentProfile:t,welcomeMessage:n,isWon:r,branding:a}){var d;const i=s!=null&&s.property_address?`${s.property_address}, ${s.city||""}, ${s.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,l=(a==null?void 0:a.logo_url)||null,o=(a==null?void 0:a.cover_photo_url)||null,c=(a==null?void 0:a.tagline)||"Your Real Estate Concierge";return e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsxs("div",{className:"relative px-4 pt-10 pb-20",children:[o&&e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${o})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter-mobile)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:o?"var(--portal-hero-scrim-mobile)":"radial-gradient(ellipse 100% 70% at 50% 0%, hsl(var(--portal-gold) / 0.12), transparent 60%), linear-gradient(180deg, hsl(0 0% 7%), hsl(0 0% 4%))"}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, hsl(var(--portal-gold)) 1px, transparent 1px)",backgroundSize:"32px 32px"}}),e.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[l&&e.jsx(br.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},transition:{duration:.5},className:"mb-6 flex justify-center",children:e.jsx("div",{className:"rounded-xl px-4 py-2.5",style:{background:"hsl(0 0% 100% / 0.06)",backdropFilter:"blur(8px)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:l,alt:"Brand",className:"h-9 max-w-[160px] object-contain"})})}),t&&e.jsxs(br.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.5,delay:.05},className:"mb-6",children:[t.avatar_url?e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:t.avatar_url,alt:t.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 rounded-full flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"var(--portal-hero-accent)"},children:((d=t.name)==null?void 0:d.charAt(0))||"?"}),e.jsx("p",{className:"portal-serif text-lg",style:{color:"var(--portal-hero-ink)"},children:t.name}),e.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"var(--portal-hero-ink-dim)"},children:c})]}),e.jsxs(br.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6,delay:.1},children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.2em] uppercase mb-4",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.25)",color:"var(--portal-hero-accent)"},children:[e.jsx(ia,{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(oi,{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(pa,{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(on,{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(Yd,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function f3t({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=Fj(a,new Date);if(F5(a)&&!Jg(a))return null;const o=Jg(a),c=o?"0":String(Math.max(0,l)),d=Math.max(4,Math.min(100,(60-Math.min(60,l))/60*100));return e.jsxs("div",{className:"portal-tile p-8 text-center",children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:o?"The Moment Has Arrived":"Countdown to Closing"}),o?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"portal-serif text-5xl mb-2",style:{color:"hsl(var(--portal-gold))"},children:"Closing Day"}),e.jsxs("p",{className:"text-sm mt-3",style:{color:"hsl(var(--portal-ink-muted))"},children:["Congratulations",n?`, ${n.split(" ")[0]}`:"","."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-baseline justify-center gap-3",children:[e.jsx(br.span,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6},className:"portal-serif tabular-nums leading-none",style:{fontSize:"5.5rem",color:"hsl(var(--portal-gold))",textShadow:"0 0 40px hsl(var(--portal-gold) / 0.4)"},children:c}),e.jsx("span",{className:"portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink-muted))"},children:l===1?"day":"days"})]}),e.jsx("div",{className:"portal-hairline w-16 mx-auto my-4"}),e.jsx("p",{className:"text-xs tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-muted))"},children:"Until you hold the keys"}),e.jsx("div",{className:"mt-6 mx-auto max-w-[260px]",children:e.jsx("div",{className:"h-[2px] rounded-full overflow-hidden",style:{background:"hsl(var(--portal-gold) / 0.15)"},children:e.jsx(br.div,{initial:{width:0},animate:{width:`${d}%`},transition:{duration:1.2,ease:"easeOut"},className:"h-full rounded-full",style:{background:"var(--portal-gradient-gold)",boxShadow:"0 0 12px hsl(var(--portal-gold) / 0.6)"}})})})]})]})}function x3t({journeyStages:s,currentIndex:t}){return s.length===0?null:e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"The Journey"}),e.jsx("h2",{className:"portal-serif text-2xl mb-6",style:{color:"hsl(var(--portal-ink))"},children:"Your path to the keys"}),e.jsx("div",{className:"relative",children:s.map((n,r)=>{const a=rt;return e.jsxs(br.div,{initial:{opacity:0,x:-6},animate:{opacity:1,x:0},transition:{duration:.35,delay:r*.05},className:"flex items-start gap-4 relative",children:[r{var l,o;if(i.includes("youtube.com/watch")){const c=new URL(i).searchParams.get("v");return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("youtu.be/")){const c=(l=i.split("youtu.be/")[1])==null?void 0:l.split("?")[0];return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("loom.com/share/")){const c=(o=i.split("loom.com/share/")[1])==null?void 0:o.split("?")[0];return c?`https://www.loom.com/embed/${c}`:null}return i};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Right Now"}),e.jsx("h4",{className:"portal-serif text-3xl mb-2 portal-gold-underline",style:{color:"hsl(var(--portal-ink))"},children:s.label}),e.jsx("p",{className:"text-sm leading-relaxed mt-4",style:{color:"hsl(var(--portal-ink-muted))"},children:s.description}),t&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Note From Your Agent"}),e.jsxs("p",{className:"text-sm leading-relaxed portal-serif italic",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:["“",t,"”"]})]}),n&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"linear-gradient(135deg, hsl(var(--portal-gold) / 0.08), hsl(var(--portal-gold) / 0.02))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"What’s Next"}),e.jsx("p",{className:"text-sm leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:n})]}),r&&e.jsx("div",{className:"mt-5 rounded-xl overflow-hidden aspect-video relative group",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("iframe",{src:a(r)||r,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Next step video"})})]})}function Ic(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 b_s=[{key:"contract_date",label:"Contract Accepted",icon:x3},{key:"earnest_money_due_date",label:"Earnest Money",icon:Od},{key:"inspection_date",label:"Inspection",icon:Fr},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:$r},{key:"appraisal_date",label:"Appraisal",icon:ia},{key:"loan_approval_date",label:"Loan Approval",icon:VW},{key:"title_docs_due_date",label:"Title & Disclosures",icon:$r},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:b3},{key:"target_close_date",label:"Target Close",icon:ra}];function __s(s,t){const n=Bs(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 w_s(s,t){const n=Bs(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 y3t({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=b_s.map(p=>p.key==="target_close_date"&&c?{...p,label:"Closed",date:c,done:!0}:{...p,date:o[p.key],done:d.includes(p.key)}).filter(p=>!!p.date);if(u.length===0)return null;const h=(p,x,y)=>{const g=Ic(x);if(y==="google")window.open(__s(p,g),"_blank");else{const b=w_s(p,g),v=document.createElement("a");v.href=b,v.download=`${p.replace(/\s+/g,"-").toLowerCase()}.ics`,v.click()}},m=u.filter(p=>p.done).length;return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-5 flex-wrap",children:[e.jsx("h2",{className:"portal-serif text-2xl",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),e.jsxs("span",{className:"text-[11px] tracking-[0.18em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[m," of ",u.length," complete"]})]}),e.jsxs("div",{className:"space-y-4 relative",children:[e.jsx("div",{className:"absolute left-[10px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.18)"}}),u.map(({label:p,date:x,done:y,icon:g})=>{const b=Ic(x),v=F5(b)&&!Jg(b),k=Jg(b),C=!v&&!k,T=y?"Completed":k?"Today":v?"In progress":"Upcoming";return e.jsxs("div",{className:"flex items-start gap-3 relative",children:[e.jsx("div",{className:"w-[21px] h-[21px] rounded-full mt-0.5 flex-shrink-0 relative z-10 flex items-center justify-center",style:{background: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(da,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):e.jsx(g,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:p}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:y?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:Bs(b,"MMM d, yyyy")}),e.jsx("span",{className:"inline-block mt-1 text-[9px] tracking-[0.2em] uppercase px-2 py-0.5 rounded-full",style:{color:y||k?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${y||k?.5:.18})`},children:T})]}),C&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("button",{onClick:()=>h(p,x,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:M=>{M.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:M=>{M.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:e.jsx(Wy,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>h(p,x,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},p)})]})]})}function v3t({documents:s}){const t=r=>r<1024?`${r} B`:r<1048576?`${(r/1024).toFixed(0)} KB`:`${(r/1048576).toFixed(1)} MB`,n=async r=>{const{data:a}=await U.storage.from("deal-files").createSignedUrl(r.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsxs("button",{onClick:()=>n(r),className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},onMouseEnter:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.35)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.08)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx($r,{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(ii,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function b3t({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(_x,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(Nx,{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:Bs(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 be=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));be.displayName="Card";const Ft=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("flex flex-col space-y-1.5 p-6",s),...t}));Ft.displayName="CardHeader";const Ut=j.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:Et("text-2xl font-semibold leading-none tracking-tight",s),...t}));Ut.displayName="CardTitle";const fr=j.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Et("text-sm text-muted-foreground",s),...t}));fr.displayName="CardDescription";const Re=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("p-6 pt-0",s),...t}));Re.displayName="CardContent";const MK=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("flex items-center p-6 pt-0",s),...t}));MK.displayName="CardFooter";const JU=[{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"}],j_s=[{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 N_s(s){return mt({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function k_s(){const s=ei(),{brokerageId:t}=Ns();return mt({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let n=U.from("vendors").select("*");t?n=n.or(`and(owner_type.eq.agent,owner_user_id.eq.${s}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${t})`):n=n.eq("owner_type","agent").eq("owner_user_id",s);const[{data:r,error:a},{data:i,error:l}]=await Promise.all([n.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),U.from("agent_vendor_selections").select("*").eq("agent_user_id",s)]);if(a)throw a;if(l)throw l;return{vendors:r||[],selections:i||[]}},enabled:!!s})}function S_s(){const s=as();return vt({mutationFn:async t=>{if(t.id){const{id:n,created_at:r,...a}=t,{data:i,error:l}=await U.from("vendors").update(a).eq("id",n).select().single();if(l)throw l;return i}else{const{data:n,error:r}=await U.from("vendors").insert(t).select().single();if(r)throw r;return n}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function _3t(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function C_s(){const s=ei(),t=as();return vt({mutationFn:async({vendorId:n,isVisible:r})=>{if(!s)throw new Error("No user");const{data:a}=await U.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",n).maybeSingle();if(a){const{error:i}=await U.from("agent_vendor_selections").update({is_visible:r}).eq("id",a.id);if(i)throw i}else{const{error:i}=await U.from("agent_vendor_selections").insert({agent_user_id:s,vendor_id:n,is_visible:r});if(i)throw i}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function w3t(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 U.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),r=n==null?void 0:n.brokerage_id,a=U.from("vendors").select("*").eq("is_active",!0),i=r?a.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${r})`):a.eq("owner_type","agent").eq("owner_user_id",t),[{data:l,error:o},{data:c},{data:d}]=await Promise.all([i.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),U.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",t),U.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]);if(o)throw o;const u=new Map;(c||[]).forEach(p=>u.set(p.vendor_id,{display_order:p.display_order,is_visible:p.is_visible}));const h=new Map;return(d||[]).forEach(p=>h.set(p.vendor_id,p.is_visible)),(l||[]).filter(p=>{if(h.get(p.id)===!1)return!1;const x=u.get(p.id);return!(x&&x.is_visible===!1&&!p.is_required)}).map(p=>{var x;return{...p,display_order:((x=u.get(p.id))==null?void 0:x.display_order)??p.sort_order??0}}).sort((p,x)=>(p.display_order||0)-(x.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function nat(s){try{await U.from("vendor_clicks").insert({vendor_id:s.vendorId,portal_id:s.portalId||null,agent_user_id:s.agentUserId||null,action_taken:s.actionTaken||null,user_agent:typeof navigator<"u"?navigator.userAgent.slice(0,500):null})}catch(t){console.warn("vendor click track failed",t)}}function j3t(s,t){return mt({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:n}=await U.from("vendors").select("id").eq(s==="agent"?"owner_user_id":"owner_brokerage_id",t).eq("owner_type",s),r=(n||[]).map(l=>l.id);if(r.length===0)return{};const{data:a}=await U.from("vendor_clicks").select("vendor_id").in("vendor_id",r),i={};return(a||[]).forEach(l=>{i[l.vendor_id]=(i[l.vendor_id]||0)+1}),i},enabled:!!t})}function N3t({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=w3t({id:s,owner_user_id:t});if(l||i.length===0)return null;const o=i.filter(v=>!v.stage_filter||v.stage_filter.length===0||!n?!0:v.stage_filter.includes(n));if(o.length===0)return null;const c=r||"#406E71",d=(v,k)=>{switch(k){case"book":return v.booking_url;case"website":return v.website;case"call":return v.phone?`tel:${v.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return v.email?`mailto:${v.email}`:null}},u=v=>{const k=d(v,v.action_type);nat({vendorId:v.id,portalId:s,agentUserId:t,actionTaken:v.action_type}),k&&window.open(k,v.action_type==="call"||v.action_type==="email"||v.action_type==="quote"?"_self":"_blank")},h=v=>{const k=d(v,v.action_type);return[{action:"website",label:"Website",icon:e.jsx(Ql,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(on,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(pa,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(ra,{className:"w-3.5 h-3.5"})}].filter(T=>T.action!==v.action_type).map(T=>{const M=d(v,T.action);return!M||M===k?null:e.jsxs("button",{onClick:()=>{nat({vendorId:v.id,portalId:s,agentUserId:t,actionTaken:T.action}),window.open(M,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=v=>{switch(v.action_type){case"book":return"Book Now";case"quote":return"Request Quote";case"call":return"Call";case"email":return"Email";case"website":return"Visit Site"}},p=v=>{switch(v.action_type){case"book":return e.jsx(ra,{className:"w-3.5 h-3.5"});case"call":return e.jsx(pa,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(on,{className:"w-3.5 h-3.5"});case"website":return e.jsx(Ql,{className:"w-3.5 h-3.5"})}},x=v=>{var k;return((k=JU.find(C=>C.value===v))==null?void 0:k.label)||v},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(yn,{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"})]})]}),g=o.some(v=>v.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:o.filter(v=>v.disclosure_text).map(v=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[v.company||v.name,":"]})," ",v.disclosure_text]},v.id))});if(a==="grid")return e.jsxs(be,{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(v=>e.jsxs("div",{className:"group flex flex-col p-4 rounded-xl border border-slate-200/70 bg-white hover:shadow-md hover:-translate-y-0.5 transition-all",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-slate-50 border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:v.logo_url?e.jsx("img",{src:v.logo_url,alt:v.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-base font-semibold text-slate-500",children:(v.company||v.name).charAt(0)})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-semibold text-sm text-slate-800 truncate",children:v.company||v.name}),v.company&&v.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:v.name}),e.jsx("span",{className:"inline-block mt-1 text-[10px] font-medium px-1.5 py-0.5 rounded",style:{backgroundColor:`${c}12`,color:c},children:x(v.category)})]})]}),v.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:v.description}),e.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>u(v),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[p(v),e.jsx("span",{className:"ml-1.5 text-xs",children:m(v)})]}),h(v).length>0&&e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:h(v)})]})]},v.id))}),g]});const b=o.reduce((v,k)=>((v[k.category]=v[k.category]||[]).push(k),v),{});return e.jsxs(be,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[y,e.jsx("div",{className:"space-y-4",children:Object.entries(b).map(([v,k])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:x(v)}),e.jsx("div",{className:"space-y-2",children:k.map(C=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-white border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:C.logo_url?e.jsx("img",{src:C.logo_url,alt:C.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-slate-500",children:C.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:C.company||C.name}),C.company&&C.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:C.name}),C.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:C.description})]}),e.jsxs(B,{size:"sm",onClick:()=>u(C),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[p(C),e.jsx("span",{className:"ml-1.5 text-xs",children:m(C)})]})]},C.id))})]},v))}),g]})}function A_s(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 T_s(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 k3t({portalId:s,portalSlug:t,ownerUserId:n,rewardText:r,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,u]=j.useState(!1),h=j.useRef(!1),m=A_s(t);j.useEffect(()=>{h.current||(h.current=!0,U.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,n]);const p=async M=>{await U.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:M,user_agent:navigator.userAgent.slice(0,500)})},x=()=>`${l?`Hey, it's ${l}!`:"Hey!"} I just had an amazing experience working with ${i||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${m}`,y=async()=>{await navigator.clipboard.writeText(m),u(!0),p("copy_link"),setTimeout(()=>u(!1),2e3)},g=()=>{p("share_sms");const M=encodeURIComponent(x());window.location.href=`sms:?&body=${M}`},b=()=>{p("share_email");const M=encodeURIComponent("A referral you'll thank me for"),P=encodeURIComponent(x());window.location.href=`mailto:?subject=${M}&body=${P}`},v=()=>{p("open_form"),window.open(m,"_blank")},k=a||"Know someone buying or selling?",C=c?T_s(c):null,T=C==null?void 0:C.match(/\.(mp4|webm|mov)(\?|$)/i);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-gradient-to-br from-emerald-50 via-teal-50 to-cyan-50 rounded-2xl p-6 border border-emerald-100 text-center",children:[e.jsx("div",{className:"text-5xl mb-2",children:"🎉"}),e.jsxs("h3",{className:"text-xl font-bold text-emerald-900 mb-1 font-serif",children:["Welcome Home",l?`, ${l.split(" ")[0]}`:"","!"]}),e.jsx("p",{className:"text-sm text-emerald-700/80",children:"Your transaction is complete. We're so proud to have been part of your journey."})]}),C&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"px-4 pt-4 pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yn,{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:C,controls:!0,className:"w-full h-full",playsInline:!0}):e.jsx("iframe",{src:C,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white shadow-xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.07]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"20px 20px"}}),e.jsxs("div",{className:"relative p-6",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium mb-3",children:[e.jsx(zo,{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:v,className:"w-full bg-white text-[#2a4c64] font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 shadow-md hover:bg-white/95 active:scale-[0.99] transition-all",children:["Refer a Friend",e.jsx(Xa,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:g,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(Yd,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:b,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(on,{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(da,{className:"w-3.5 h-3.5"}):e.jsx(ja,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>p("review_click"),className:"block bg-white border border-slate-200 hover:border-amber-300 hover:bg-amber-50/30 rounded-2xl p-4 transition-colors",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-2xl",children:"⭐"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),e.jsx(Xa,{className:"w-4 h-4 text-slate-400"})]})})]})}function E_s(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function M_s(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 L_s={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. 🎉"}},S3t=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function L3e(s){return S3t.map(t=>{if(t==="Active")return{key:"Active",label:E_s(s),description:M_s(s)};const n=L_s[t];return{key:t,label:n.label,description:n.description}})}function VNe(s){if(!s)return 0;const t=S3t.indexOf(s);return t>=0?t:0}function P_s({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var K,ee,J;const d=(l==null?void 0:l.cover_photo_url)||null,u=(l==null?void 0:l.logo_url)||null,h=(l==null?void 0:l.tagline)||"Your Real Estate Concierge",m=n==null?void 0:n.deal_pipeline,p=m==null?void 0:m.deal_pipeline_stages,x=p==null?void 0:p.is_won_stage,y=m==null?void 0:m.deal_type,g=n==null?void 0:n.stage_mapping;let b=L3e(y);g&&g.length>0&&(b=g.map((le,ue)=>{var oe,ie;return{key:`custom-${ue}`,label:le.label||((oe=b[ue])==null?void 0:oe.label)||`Stage ${ue+1}`,description:le.description||((ie=b[ue])==null?void 0:ie.description)||"",video_url:le.video_url||void 0}}));const v=g&&g.length>0?Math.min(VNe(p==null?void 0:p.name),b.length-1):VNe(p==null?void 0:p.name),k=b[v],C=k==null?void 0:k.video_url,T=x&&n.show_post_close_tips!==!1&&n.referral_enabled!==!1,M=m!=null&&m.property_address?`${m.property_address}, ${m.city||""}, ${m.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,P=!!t,L=(K=s==null?void 0:s.deal_pipeline)==null?void 0:K.deal_type,I=(ee=t==null?void 0:t.deal_pipeline)==null?void 0:ee.deal_type,O=le=>le==="listing"?"Your Sale":le==="buy-side"?"Your Purchase":"Transaction",$=b.length>1?Math.round((v+1)/b.length*100):0,{data:q=[]}=w3t({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),W=q.some(le=>!le.stage_filter||le.stage_filter.length===0||!(p!=null&&p.name)?!0:le.stage_filter.includes(p.name)),G=()=>{var le;(le=document.getElementById("trusted-vendors"))==null||le.scrollIntoView({behavior:"smooth",block:"start"})};return e.jsxs("div",{className:"min-h-screen relative",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[600px] opacity-70",style:{background:"radial-gradient(ellipse 70% 100% at 50% 0%, hsl(var(--portal-gold) / 0.08), transparent 60%)"}}),e.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-8",children:[e.jsxs(br.div,{initial:{opacity:0,y:-6},animate:{opacity:1,y:0},transition:{duration:.4},className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[u?e.jsx("div",{className:"rounded-lg px-3 py-1.5",style:{background:"hsl(0 0% 100% / 0.04)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:u,alt:"Brand",className:"h-8 max-w-[140px] object-contain"})}):e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center portal-serif text-xl",style:{background:"var(--portal-gradient-gold)",color:"hsl(var(--portal-bg))"},children:"✦"}),e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow",children:"Private Client Portal"}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.1rem",color:"hsl(var(--portal-ink))"},children:n!=null&&n.client_name?`Welcome, ${n.client_name.split(" ")[0]}`:"Your transaction"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(_f,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(br.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.6,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl mb-8",style:{minHeight:380,border:"1px solid hsl(var(--portal-gold) / 0.25)",boxShadow:"var(--portal-shadow-luxe)"},children:[d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${d})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-scrim)"}})]}):e.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-fallback)"}}),e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.6), transparent)"}}),e.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-12",children:[e.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.22em] uppercase mb-6 self-start",style:{background:"hsl(0 0% 0% / 0.28)",backdropFilter:"blur(6px)",border:"1px solid var(--portal-hero-accent)",color:"var(--portal-hero-accent)"},children:[e.jsx(ia,{className:"w-3 h-3"}),y==="listing"?"Sale":y==="buy-side"?"Purchase":"Transaction",x&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif leading-[0.95] mb-4",style:{fontSize:"4.5rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:(m==null?void 0:m.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-32 mb-5"}),M&&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(oi,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{className:"text-base",children:M})]}),(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(I_s,{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 ",v+1," of ",b.length]})]})]}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.4), transparent)"}})]}),P&&e.jsx("div",{className:"inline-flex gap-1 rounded-xl p-1 mb-8",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(le=>{const ue=le==="primary"?L:I,oe=r===le;return e.jsx("button",{onClick:()=>a(le),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:oe?"hsl(var(--portal-surface-3))":"transparent",color:oe?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:oe?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:O(ue)},le)})}),e.jsxs(br.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.06}}},className:"grid grid-cols-12 gap-5",children:[e.jsx("aside",{className:"col-span-3 space-y-5",children:e.jsxs("div",{className:"sticky top-6 space-y-5",children:[e.jsxs(PC,{children:[e.jsxs("div",{className:"text-center pt-2 pb-1",children:[i!=null&&i.avatar_url?e.jsx("div",{className:"w-24 h-24 mx-auto relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.4)",color:"hsl(var(--portal-gold))"},children:((J=i==null?void 0:i.name)==null?void 0:J.charAt(0))||"?"}),e.jsx("h3",{className:"mt-4 portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink))"},children:i==null?void 0:i.name}),e.jsx("div",{className:"portal-hairline w-12 mx-auto my-2"}),e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:h})]}),e.jsxs("div",{className:"mt-5 space-y-2",children:[(i==null?void 0:i.phone)&&e.jsx(HMe,{href:`tel:${i.phone}`,icon:pa,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(HMe,{href:`sms:${i.phone}`,icon:Yd,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(HMe,{href:`mailto:${i.email}`,icon:on,label:"Email",sub:i.email})]})]}),e.jsxs(PC,{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(GMe,{icon:ra,label:"Target close",value:rat(m.target_close_date)}),(m==null?void 0:m.contract_date)&&e.jsx(GMe,{icon:Vr,label:"Under contract",value:rat(m.contract_date)}),e.jsx(GMe,{icon:Po,label:"Progress",value:`${$}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[T&&e.jsx(k3t,{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(f3t,{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(PC,{children:e.jsx(g3t,{currentStage:k,nextStepText:n.next_step_text,nextStepVideoUrl:C||n.next_step_video_url})}),e.jsx(PC,{children:e.jsx(x3t,{journeyStages:b,currentIndex:v})}),o&&o.length>0&&e.jsx(PC,{children:e.jsx(b3t,{updates:o})})]}),e.jsxs("aside",{className:"col-span-3 space-y-5",children:[e.jsx(PC,{children:e.jsx(y3t,{deal:m,portal:n})}),c&&c.length>0&&e.jsx(PC,{children:e.jsx(v3t,{documents:c})}),W&&e.jsx(PC,{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:le=>{le.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:le=>{le.currentTarget.style.background="hsl(var(--portal-gold) / 0.06)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},children:e.jsx(lK,{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(Po,{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(N3t,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:p==null?void 0:p.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function PC({children:s}){return e.jsx(br.div,{variants:{hidden:{opacity:0,y:10},show:{opacity:1,y:0,transition:{duration:.45,ease:"easeOut"}}},className:"portal-tile p-6",children:s})}function HMe({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 GMe({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 I_s({pct:s}){const a=2*Math.PI*78,i=a-s/100*a;return e.jsxs("div",{className:"relative",style:{width:170,height:170},children:[e.jsxs("svg",{width:170,height:170,className:"-rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"portal-progress-gold",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"var(--portal-hero-accent)"}),e.jsx("stop",{offset:"100%",stopColor:"var(--portal-hero-ink)"})]})}),e.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(0 0% 100% / 0.22)",strokeWidth:2,fill:"none"}),e.jsx(br.circle,{cx:170/2,cy:170/2,r:78,stroke:"url(#portal-progress-gold)",strokeWidth:3,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:a},animate:{strokeDashoffset:i},transition:{duration:1.4,ease:"easeOut"},strokeDasharray:a,style:{filter:"drop-shadow(0 0 6px hsl(0 0% 0% / 0.45))"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"portal-serif tabular-nums leading-none",style:{fontSize:"3rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:s}),e.jsx("span",{className:"text-[10px] tracking-[0.25em] uppercase mt-1",style:{color:"var(--portal-hero-ink-dim)",textShadow:"var(--portal-hero-text-shadow)"},children:"percent"})]})]})}function rat(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 R_s({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var g,b;const[l,o]=j.useState({first_name:((g=s.client_name)==null?void 0:g.split(" ")[0])||"",last_name:((b=s.client_name)==null?void 0:b.split(" ").slice(1).join(" "))||"",email:s.client_email||"",phone:s.client_phone||"",preferred_contact_method:"email",client_role:"buyer",notes:"",spouse_first_name:"",spouse_last_name:"",spouse_email:"",spouse_phone:""}),[c,d]=j.useState({}),[u,h]=j.useState(!1),m=vt({mutationFn:async()=>{const{error:v}=await U.from("portal_onboarding_submissions").insert({portal_id:s.id,first_name:l.first_name,last_name:l.last_name||null,email:l.email||null,phone:l.phone||null,preferred_contact_method:l.preferred_contact_method,client_role:l.client_role,notes:l.notes||null,device_fingerprint:a,custom_answers:Object.keys(c).length>0?c:null,spouse_first_name:u&&l.spouse_first_name||null,spouse_last_name:u&&l.spouse_last_name||null,spouse_email:u&&l.spouse_email||null,spouse_phone:u&&l.spouse_phone||null});if(v)throw v},onSuccess:i,onError:v=>{console.error("[PortalOnboarding] Submit failed:",v),re.error("Something went wrong. Please try again.")}}),p=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null,x="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",y="mt-1 w-full rounded-xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400";return e.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[(n==null?void 0:n.avatar_url)&&e.jsx("img",{src:n.avatar_url,alt:n.name,className:"w-16 h-16 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),p&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(oi,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:p.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:v=>{v.preventDefault(),m.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),e.jsx(ye,{required:!0,value:l.first_name,onChange:v=>o(k=>({...k,first_name:v.target.value})),className:x,placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(ye,{value:l.last_name,onChange:v=>o(k=>({...k,last_name:v.target.value})),className:x,placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(ye,{type:"email",value:l.email,onChange:v=>o(k=>({...k,email:v.target.value})),className:x,placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(ye,{type:"tel",value:l.phone,onChange:v=>o(k=>({...k,phone:v.target.value})),className:x,placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Preferred Contact Method"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(v=>e.jsx("button",{type:"button",onClick:()=>o(k=>({...k,preferred_contact_method:v.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.preferred_contact_method===v.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:v.label},v.value))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Your Role"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(v=>e.jsx("button",{type:"button",onClick:()=>o(k=>({...k,client_role:v})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.client_role===v?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:v.charAt(0).toUpperCase()+v.slice(1)},v))})]}),r.map(v=>e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs font-medium text-slate-700",children:[v.question_text," ",v.is_required&&"*"]}),v.field_type==="text"&&e.jsx(ye,{required:v.is_required,value:c[v.id]||"",onChange:k=>d(C=>({...C,[v.id]:k.target.value})),className:x}),v.field_type==="textarea"&&e.jsx("textarea",{required:v.is_required,value:c[v.id]||"",onChange:k=>d(C=>({...C,[v.id]:k.target.value})),className:`${y} min-h-[80px]`}),v.field_type==="dropdown"&&e.jsxs("select",{required:v.is_required,value:c[v.id]||"",onChange:k=>d(C=>({...C,[v.id]:k.target.value})),className:`${y} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(v.options||[]).map(k=>e.jsx("option",{value:k,children:k},k))]}),v.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(C=>({...C,[v.id]:k})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[v.id]===k?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:k},k))})]},v.id)),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:v=>o(k=>({...k,notes:v.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(se,{className:"text-xs font-medium text-slate-700",children:"First Name"}),e.jsx(ye,{value:l.spouse_first_name,onChange:v=>o(k=>({...k,spouse_first_name:v.target.value})),className:x})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(ye,{value:l.spouse_last_name,onChange:v=>o(k=>({...k,spouse_last_name:v.target.value})),className:x})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(ye,{type:"email",value:l.spouse_email,onChange:v=>o(k=>({...k,spouse_email:v.target.value})),className:x})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(ye,{type:"tel",value:l.spouse_phone,onChange:v=>o(k=>({...k,spouse_phone:v.target.value})),className:x})]})]})]}),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 D_s(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 C3t(){const s=ei();return mt({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function O_s(s){return mt({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message, portal_theme").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function F_s(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("agent_portal_branding").upsert({user_id:s,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-portal-branding",s]}),t.invalidateQueries({queryKey:["agent-portal-branding-public",s]})}})}async function A3t(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await U.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=U.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function z_s(s,t){return mt({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:n,error:r}=await U.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("slug",s).eq("is_enabled",!0).maybeSingle();if(r)throw r;return n},enabled:t})}function B_s(s){return mt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("id",s).eq("is_enabled",!0).maybeSingle();if(n)throw n;return t},enabled:!!s})}function T3t({slug:s}){var le,ue,oe,ie,de,we;const[t,n]=j.useState(!1),[r,a]=j.useState("primary"),[i]=j.useState(()=>{const je=`portal_fp_${s}`;let xe=localStorage.getItem(je);return xe||(xe=localStorage.getItem("portal_fp"),xe?localStorage.setItem(je,xe):(xe=crypto.randomUUID(),localStorage.setItem(je,xe),localStorage.setItem("portal_fp",xe))),xe});j.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=z_s(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=B_s(d),h=(le=l==null?void 0:l.deal_pipeline)==null?void 0:le.owner_user_id;mt({queryKey:["portal-stages",h],queryFn:async()=>{const{data:je,error:xe}=await U.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(xe)throw xe;return je},enabled:!!h});const{data:m}=mt({queryKey:["portal-agent",h],queryFn:async()=>{const{data:je,error:xe}=await U.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(xe)throw xe;return je},enabled:!!h}),{data:p}=O_s(h),x=r==="linked"&&u?u:l,y=x==null?void 0:x.id,g=D_s(p,x==null?void 0:x.branding_override),b=g.portal_theme==="azure"?"azure":"noir";j.useEffect(()=>{const je=`portal-theme-${b}`;return document.body.classList.add(je),()=>document.body.classList.remove(je)},[b]);const{data:v}=mt({queryKey:["portal-updates-public",y],queryFn:async()=>{const{data:je,error:xe}=await U.from("portal_updates").select("*").eq("portal_id",y).order("created_at",{ascending:!1});if(xe)throw xe;return je},enabled:!!y}),k=(ue=x==null?void 0:x.deal_pipeline)==null?void 0:ue.id,{data:C}=mt({queryKey:["portal-documents",k],queryFn:async()=>{const{data:je,error:xe}=await U.from("deal_files").select("*").eq("deal_id",k).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(xe)throw xe;return je},enabled:!!k}),T=l==null?void 0:l.id,M=T?`portal_onboarded_${T}_${i}`:null,P=M?localStorage.getItem(M)==="1":!1,{data:L,isLoading:I}=mt({queryKey:["portal-onboarding-check",T,i],queryFn:async()=>{const{data:je,error:xe}=await U.from("portal_onboarding_submissions").select("id").eq("portal_id",T).eq("device_fingerprint",i).maybeSingle();if(xe)throw xe;return je&&M&&localStorage.setItem(M,"1"),je},enabled:!!T&&!!(l!=null&&l.require_onboarding)&&!P,staleTime:5*60*1e3}),O=!!(l!=null&&l.require_onboarding)&&!P&&!L&&!t,{data:$}=mt({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:je,error:xe}=await U.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(xe)throw xe;return je},enabled:!!h&&O}),q=P||!!L||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!P&&I)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:e.jsx(Wt,{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(_f,{className:"w-6 h-6",style:{color:"hsl(var(--portal-gold))"}})}),e.jsx("h1",{className:"portal-serif text-4xl mb-3",style:{color:"hsl(var(--portal-ink))"},children:"Portal Not Available"}),e.jsx("div",{className:"portal-hairline mx-auto w-24 mb-4"}),e.jsx("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:"This portal is no longer active or doesn't exist."})]})});if(!q){const je=l==null?void 0:l.deal_pipeline;return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:e.jsx(R_s,{portal:l,dealData:je,agentProfile:m,customQuestions:$||[],deviceFingerprint:i,onComplete:()=>{M&&localStorage.setItem(M,"1"),n(!0)}})})}const W=(oe=l==null?void 0:l.deal_pipeline)==null?void 0:oe.deal_type,G=(ie=u==null?void 0:u.deal_pipeline)==null?void 0:ie.deal_type,K=!!u,ee=je=>je==="listing"?"Your Sale":je==="buy-side"?"Your Purchase":"Transaction",J=je=>je==="listing"?e.jsx(ia,{className:"w-3.5 h-3.5"}):e.jsx(gb,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(P_s,{portal:l,linkedPortal:u,activePortal:x,activeTab:r,onTabChange:a,agentProfile:m,branding:g,updates:v,documents:C})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(v_s,{dealData:x==null?void 0:x.deal_pipeline,agentProfile:m,welcomeMessage:(x==null?void 0:x.welcome_message)||g.welcome_message,isWon:(we=(de=x==null?void 0:x.deal_pipeline)==null?void 0:de.deal_pipeline_stages)==null?void 0:we.is_won_stage,branding:g}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[K&&e.jsx("div",{className:"flex gap-1 rounded-xl p-1",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(je=>{const xe=r===je,fe=je==="primary"?W:G;return e.jsxs("button",{onClick:()=>a(je),className:"flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all portal-serif",style:{background:xe?"hsl(var(--portal-surface-3))":"transparent",color:xe?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:xe?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[J(fe),e.jsx("span",{style:{fontSize:"1rem"},children:ee(fe)})]},je)})}),e.jsx($_s,{portal:x,updates:v,documents:C,agentProfile:m}),e.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[e.jsx("div",{className:"portal-hairline w-16 mx-auto"}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(_f,{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 $_s({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=L3e(c);d&&d.length>0&&(u=d.map((y,g)=>{var b,v;return{key:`custom-${g}`,label:y.label||((b=u[g])==null?void 0:b.label)||`Stage ${g+1}`,description:y.description||((v=u[g])==null?void 0:v.description)||"",video_url:y.video_url||void 0}}));const h=d&&d.length>0?Math.min(VNe(l==null?void 0:l.name),u.length-1):VNe(l==null?void 0:l.name),m=u[h],p=m==null?void 0:m.video_url,x=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[x&&e.jsx(k3t,{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(f3t,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(x3t,{journeyStages:u,currentIndex:h}),m&&e.jsx(g3t,{currentStage:m,nextStepText:s.next_step_text,nextStepVideoUrl:p||s.next_step_video_url}),e.jsx(y3t,{deal:i,portal:s}),n&&n.length>0&&e.jsx(v3t,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(N3t,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(b3t,{updates:t})]})}function E3t({slug:s}){const t=$i(),n=s||t.slug,[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(""),[y,g]=j.useState(""),[b,v]=j.useState("buying"),[k,C]=j.useState("");j.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:T,isLoading:M,error:P}=mt({queryKey:["portal-referral-target",n],queryFn:async()=>{if(!n)return null;const{data:O,error:$}=await U.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",n).eq("is_enabled",!0).maybeSingle();if($)throw $;return O},enabled:!!n}),{data:L}=mt({queryKey:["portal-referral-agent",T==null?void 0:T.owner_user_id],queryFn:async()=>{const{data:O}=await U.from("profiles").select("id, name, avatar_url").eq("id",T.owner_user_id).single();return O},enabled:!!(T!=null&&T.owner_user_id)}),I=async O=>{if(O.preventDefault(),!T||!h.trim()){re.error("Please enter your friend's name");return}if(!p.trim()&&!y.trim()){re.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:$}=await U.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:p.trim()||null,friend_phone:y.trim()||null,friend_interest:b,friend_message:k.trim()||null});if($)throw $;l(!0)}catch($){re.error($.message||"Could not submit referral")}finally{a(!1)}};return M?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(gn,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):P||!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(da,{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 ",(L==null?void 0:L.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(_a,{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:[L!=null&&L.avatar_url?e.jsx("img",{src:L.avatar_url,alt:L.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(zo,{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(zo,{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 ",(L==null?void 0:L.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:I,className:"bg-white rounded-2xl shadow-lg border border-slate-100 p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Tell us about your friend"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ye,{id:"friend_name",value:h,onChange:O=>m(O.target.value),placeholder:"Jane Smith",required:!0,className:"mt-1"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(ye,{id:"friend_email",type:"email",value:p,onChange:O=>x(O.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(ye,{id:"friend_phone",type:"tel",value:y,onChange:O=>g(O.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm",children:"They're interested in..."}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[{v:"buying",l:"Buying"},{v:"selling",l:"Selling"},{v:"both",l:"Both"},{v:"unsure",l:"Not sure"}].map(O=>e.jsx("button",{type:"button",onClick:()=>v(O.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${b===O.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:O.l},O.v))})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:k,onChange:O=>C(O.target.value),placeholder:"They're moving from Boston in the spring...",rows:3,className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(ye,{id:"referrer_name",value:o,onChange:O=>c(O.target.value),placeholder:T.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(ye,{id:"referrer_email",type:"email",value:d,onChange:O=>u(O.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(Wt,{className:"w-4 h-4 animate-spin"}):e.jsx(zo,{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 U_s(){const t=$d().pathname.slice(1).replace(/\/$/,"");if(j.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>{document.body.classList.remove("client-portal-page")}),[]),!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Client Portal"}),e.jsx("p",{className:"text-slate-500",children:"Visit your personalized portal link to view your transaction details."})]})});const n=t.match(/^([^/]+)\/refer$/);return n?e.jsx(E3t,{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(T3t,{slug:t})}function q_s(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 HNe({photos:s,alt:t="",className:n="w-full h-full",imgClassName:r="w-full h-full object-cover",iconClassName:a="w-8 h-8"}){const i=j.useMemo(()=>q_s(Array.isArray(s)?s:[]),[s]),[l,o]=j.useState(0);return j.useEffect(()=>{o(0)},[i.join("|")]),!i.length||l>=i.length?e.jsx("div",{className:`${n} bg-muted flex items-center justify-center text-muted-foreground`,children:e.jsx(ia,{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 M3t({comp:s,open:t,onClose:n}){var d;const[r,a]=j.useState(0);if(!s)return null;const i=Array.isArray(s.photos)?s.photos.filter(Boolean):[],l=s.soldPrice||s.price,o=s.sqft&&l?Math.round(l/s.sqft):null,c=u=>{if(!u)return null;const[h,m,p]=u.split(/[-/T]/);return h?`${m}/${p}/${h}`:null};return e.jsx(Fs,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs($s,{className:"px-6 pt-6 pb-2",children:[e.jsx(zs,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(oi,{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(HNe,{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(HNe,{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(ia,{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(Od,{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(qe,{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(WMe,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(WMe,{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(WMe,{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(Mse,{icon:e.jsx(U_,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(Mse,{icon:e.jsx(t0,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(Mse,{icon:e.jsx(j3,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(Mse,{icon:e.jsx(ra,{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(Ev,{label:"MLS #",value:s.mlsNumber}),e.jsx(Ev,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(Ev,{label:"Lot Size",value:s.lotSize}),e.jsx(Ev,{label:"Garage",value:s.garageSpaces}),e.jsx(Ev,{label:"Stories",value:s.stories}),e.jsx(Ev,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(Ev,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(Ev,{label:"Heating",value:s.heating}),e.jsx(Ev,{label:"Cooling",value:s.cooling}),e.jsx(Ev,{label:"Parking",value:s.parking}),e.jsx(Ev,{label:"Elementary",value:s.elementarySchool}),e.jsx(Ev,{label:"Middle",value:s.middleSchool}),e.jsx(Ev,{label:"High",value:s.highSchool}),e.jsx(Ev,{label:"Listed By",value:s.listAgentFullName}),e.jsx(Ev,{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 Mse({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 Ev({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 WMe({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 Lse({to:s,durationMs:t=1400,prefix:n="",suffix:r="",className:a,delayMs:i=0}){const[l,o]=j.useState(0),c=j.useRef(null);return j.useEffect(()=>{if(!Number.isFinite(s))return;let d=0;const u=0,h=p=>1-Math.pow(1-p,3),m=setTimeout(()=>{const p=x=>{d||(d=x);const y=x-d,g=Math.min(1,y/t);o(Math.round(u+(s-u)*h(g))),g<1&&(c.current=requestAnimationFrame(p))};c.current=requestAnimationFrame(p)},i);return()=>{clearTimeout(m),c.current&&cancelAnimationFrame(c.current)}},[s,t,i]),e.jsxs("span",{className:a,children:[n,l.toLocaleString(),r]})}function V_s({low:s,likely:t,high:n,defaultMortgage:r=0,defaultCommissionPct:a=6,defaultClosingPct:i=1}){const[l,o]=j.useState(t),[c,d]=j.useState(r),[u,h]=j.useState(a),[m,p]=j.useState(i),{commission:x,closing:y,net:g}=j.useMemo(()=>{const k=Math.round(l*u/100),C=Math.round(l*m/100);return{commission:k,closing:C,net:Math.max(0,l-k-C-(c||0))}},[l,u,m,c]),b=k=>`$${k.toLocaleString()}`,v=n>s?(l-s)/(n-s)*100:50;return e.jsxs(be,{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(kl,{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(Re,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-end justify-between mb-3",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"List price"}),e.jsx("span",{className:"text-3xl font-bold tabular-nums",children:b(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx(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:b(s)}),e.jsxs("span",{children:["Suggested ",b(t)]}),e.jsx("span",{children:b(n)})]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-emerald-500 via-primary to-amber-500 transition-all",style:{width:`${Math.min(100,Math.max(0,v))}%`}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(ye,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:k=>d(Number(k.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Commission %"}),e.jsx(ye,{type:"number",step:"0.25",value:u,onChange:k=>h(Number(k.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Closing costs %"}),e.jsx(ye,{type:"number",step:"0.25",value:m,onChange:k=>p(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:b(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",b(x)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",m,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",b(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:["−",b(c)]})]})]}),e.jsxs("div",{className:"bg-gradient-to-r from-emerald-500/10 to-primary/10 px-5 py-4 border-t flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mz,{className:"w-5 h-5 text-emerald-600"}),e.jsx("span",{className:"font-semibold",children:"Your estimated walk-away"})]}),e.jsx("span",{className:"text-2xl font-bold tabular-nums text-emerald-700",children:b(g)})]})]}),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 L3t({tokenOverride:s}={}){var De,Be,Ne,Ge,_e,Oe,Ae,Xe,Ue,Ze,Qe,Ye;const t=$i(),n=s??t.token,[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState([]),[d,u]=j.useState(!0),[h,m]=j.useState(""),[p,x]=j.useState(""),[y,g]=j.useState(""),[b,v]=j.useState(!1),[k,C]=j.useState(!1),[T,M]=j.useState(null),[P,L]=j.useState(null),[I,O]=j.useState(!1),{toast:$}=pi();j.useEffect(()=>{n&&(async()=>{const{data:nt}=await U.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!nt){u(!1);return}a(nt);const[{data:rt},{data:Fe}]=await Promise.all([U.from("cma_comps").select("*").eq("cma_id",nt.id).order("position"),U.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",nt.agent_id).maybeSingle()]);c((rt||[]).filter(Dt=>Dt.selected)),l(Fe);const dt=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",dt),await U.from("cma_views").insert({cma_id:nt.id,visitor_token:dt,user_agent:navigator.userAgent}),u(!1)})()},[n]);const q=async nt=>{if(!r)return;const rt=localStorage.getItem("cma_visitor_token")||"";await U.from("cma_views").insert({cma_id:r.id,visitor_token:rt,reactions:{[nt]:!0}}),U.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:nt,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&&(!p.trim()||!y.trim())){$({title:"Please add your name and email",variant:"destructive"});return}v(!0);const nt=localStorage.getItem("cma_visitor_token")||"",{data:rt,error:Fe}=await U.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:nt,viewerName:p.trim()||void 0,viewerEmail:y.trim()||void 0}});if(v(!1),Fe||!(rt!=null&&rt.success)){$({title:"Could not send",description:(Fe==null?void 0:Fe.message)||(rt==null?void 0:rt.error),variant:"destructive"});return}m(""),C(!0),$({title:"Message sent to your agent"})},K=j.useMemo(()=>{const nt=o.map(rt=>{const Fe=rt.snapshot,dt=(Fe==null?void 0:Fe.soldPrice)||(Fe==null?void 0:Fe.price);return dt&&(Fe!=null&&Fe.sqft)?dt/Fe.sqft:null}).filter(rt=>!!rt).sort((rt,Fe)=>rt-Fe);return nt.length?Math.round(nt[Math.floor(nt.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(Wt,{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(ia,{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 ee=r.subject||{},J=(De=r.settings)==null?void 0:De.personalVideo,le=(Be=ee.photos)==null?void 0:Be[0],ue=r.contact_first_name?r.contact_first_name:null,oe=((i==null?void 0:i.name)||"A").split(" ").map(nt=>nt[0]).slice(0,2).join("").toUpperCase(),ie=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,de=i!=null&&i.email?`mailto:${i.email}`:null,we=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,je=r.price_low??null,xe=r.price_likely??null,fe=r.price_high??null,Se=je&&xe&&fe,Ee=xe&&ee.sqft?Math.round(xe/ee.sqft):null,Le=Ee&&K?Math.round((Ee-K)/K*100):null;return e.jsxs("div",{className:"min-h-screen bg-background pb-28 md:pb-0",children:[i&&e.jsx("div",{className:"border-b bg-card sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-6 py-3 flex items-center gap-3",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-10 h-10 rounded-full object-cover ring-2 ring-primary/20"}):e.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center font-semibold text-primary text-sm",children:oe}),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(Ni,{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:[ie&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ie,children:[e.jsx(pa,{className:"w-4 h-4 mr-1"}),"Call"]})}),de&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:de,children:[e.jsx(on,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[le?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:le,alt:ee.address,className:"w-full h-full object-cover scale-110 animate-[kenburns_18s_ease-out_infinite_alternate]",style:{animation:"kenburns 22s ease-in-out infinite alternate"}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),e.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),e.jsx("div",{className:"relative container mx-auto max-w-6xl px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-24",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[e.jsxs("div",{className:`${J!=null&&J.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs(qe,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(yn,{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:ee.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(oi,{className:"w-4 h-4"}),ee.city,", ",ee.state," ",ee.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(Lse,{to:xe,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(Lse,{to:je,prefix:"$",delayMs:500})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Likely"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(Lse,{to:xe,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(Lse,{to:fe,prefix:"$",delayMs:800})})]})]})]})]}),(J==null?void 0:J.url)&&e.jsx("div",{className:"md:col-span-2 animate-scale-in",children:e.jsxs("button",{onClick:()=>O(!0),className:"group relative w-full aspect-[4/5] md:aspect-[4/5] rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/20 bg-black",children:[J.thumb?e.jsx("img",{src:J.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:J.url,className:"w-full h-full object-cover",muted:!0,playsInline:!0,preload:"metadata"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-black/10 group-hover:from-black/40 transition-colors"}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white",children:[e.jsx("div",{className:"w-16 h-16 md:w-20 md:h-20 rounded-full bg-white/95 text-primary flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform",children:e.jsx(fd,{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"]})]})]})})]})})]}),I&&(J==null?void 0:J.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>O(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick:nt=>nt.stopPropagation(),children:[e.jsx("video",{src:J.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:()=>O(!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:ee.bedrooms??"—"},{label:"Baths",value:ee.bathrooms??"—"},{label:"Sq Ft",value:((Ge=ee.sqft)==null?void 0:Ge.toLocaleString())??"—"},{label:"Year Built",value:ee.yearBuilt??"—"}].map((nt,rt)=>e.jsx(be,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${rt*80}ms`},children:e.jsxs(Re,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:nt.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:nt.label})]})},rt))}),((Oe=(_e=r.settings)==null?void 0:_e.priceOverride)==null?void 0:Oe.enabled)&&((Xe=(Ae=r.settings)==null?void 0:Ae.priceOverride)==null?void 0:Xe.note)&&e.jsx(be,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(Re,{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(V_s,{low:je,likely:xe,high:fe}),K&&Ee&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(be,{className:"md:col-span-2",children:e.jsxs(Re,{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 ",ee.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",K,"/sqft"]}),". Applied to your home's ",(Ue=ee.sqft)==null?void 0:Ue.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(K*(ee.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(be,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(Re,{className:"p-6 md:p-8 h-full flex flex-col justify-center",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground mb-1",children:"Your home"}),e.jsxs("div",{className:"text-3xl font-bold tabular-nums",children:["$",Ee,e.jsx("span",{className:"text-base font-normal text-muted-foreground",children:"/sqft"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Neighborhood avg: ",e.jsxs("span",{className:"font-medium text-foreground",children:["$",K,"/sqft"]})]}),Le!==null&&Le!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Le>0?"text-emerald-600":"text-rose-600"}`,children:[Le>0?"▲":"▼"," ",Math.abs(Le),"% ",Le>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(qe,{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((nt,rt)=>{var Dt;const Fe=nt.snapshot,dt=Fe.soldPrice||Fe.price;return e.jsxs(be,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${P===rt?"ring-2 ring-primary":""}`,style:{animationDelay:`${rt*60}ms`},onClick:()=>M(rt),onMouseEnter:()=>L(rt),onMouseLeave:()=>L(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(HNe,{photos:Fe.photos,className:"w-full h-44"}),e.jsxs(qe,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",rt+1]}),e.jsx(qe,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:Fe.status})]}),e.jsxs(Re,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:Fe.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Fe.city,", ",Fe.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[Fe.bedrooms??"?","bd · ",Fe.bathrooms??"?","ba · ",((Dt=Fe.sqft)==null?void 0:Dt.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:["$",dt==null?void 0:dt.toLocaleString()]}),Fe.sqft&&dt?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(dt/Fe.sqft),"/sqft"]}):null]})]})]},rt)})})]}),e.jsx(M3t,{comp:T!==null?(Ze=o[T])==null?void 0:Ze.snapshot:null,open:T!==null,onClose:()=>M(null)}),e.jsx(be,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(Re,{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. ",((Qe=i==null?void 0:i.name)==null?void 0:Qe.split(" ")[0])||"Your agent"," hears you instantly."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:mo,label:"I love this price"},{kind:"fair",icon:mg,label:"Seems fair"},{kind:"lower",icon:vN,label:"I'd price lower"},{kind:"higher",icon:kl,label:"I'd price higher"},{kind:"ready_to_list",icon:fN,label:"Ready to list"},{kind:"want_walkthrough",icon:ma,label:"Want a walkthrough"},{kind:"need_time",icon:ra,label:"Need more time"},{kind:"have_questions",icon:c5,label:"I have questions"}].map(({kind:nt,icon:rt,label:Fe})=>e.jsxs(B,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>q(nt),children:[e.jsx(rt,{className:"w-4 h-4 mr-2"}),Fe]},nt))}),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(Yd,{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! ",((Ye=i==null?void 0:i.name)==null?void 0:Ye.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):e.jsxs(e.Fragment,{children:[W&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[e.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:p,onChange:nt=>x(nt.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:y,onChange:nt=>g(nt.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:nt=>m(nt.target.value)}),e.jsx(B,{onClick:G,disabled:!h.trim()||b,className:"mt-2",children:b?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(be,{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:oe}),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:[ie&&e.jsx(B,{asChild:!0,children:e.jsxs("a",{href:ie,children:[e.jsx(pa,{className:"w-4 h-4 mr-2"}),i.phone]})}),de&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:de,children:[e.jsx(on,{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(Ql,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(ie||we||de)&&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:[ie&&e.jsx(B,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ie,children:[e.jsx(pa,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),we&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:we,children:[e.jsx(Yd,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),de&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:de,children:[e.jsx(on,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function H_s(){const t=$d().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(L3t,{tokenOverride:t})}const AOe="levelup_affiliate_ref",G_s=30,W_s=()=>{const[s]=dc();j.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(AOe,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},K_s=()=>{try{const s=localStorage.getItem(AOe);if(!s)return null;const t=JSON.parse(s),n=G_s*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(AOe),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},GNe="/assets/levelup-logo-header-_ZX7DvlA.png",Y_s="/assets/scale-your-team-ku4MPatU.png";function Z_s({open:s,onOpenChange:t}){return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx($s,{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(Ni,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(zs,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(kr,{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 Rg={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}},X_s=[{icon:vh,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:Ac,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ra,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Yd,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:$r,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:zo,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],Q_s=[{icon:Bn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:yn,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:pa,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Wm,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:oi,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:ol,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:mo,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:jf,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],J_s=[{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."}],ews=()=>{const{user:s,loading:t}=Ns(),n=Hn(),[r]=dc();j.useEffect(()=>{const P=window.location.host==="listings.relevelup.com",L=window.location.pathname==="/";if(P&&L){n("/public/listings",{replace:!0});return}},[n]);const[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState(""),[x,y]=j.useState(""),[g,b]=j.useState(!1),[v,k]=j.useState(!1),C=(P,L=!1)=>{o({tier:P,skipTrial:L}),d(!0)};W_s(),j.useEffect(()=>{const P=window.location.host==="listings.relevelup.com",L=location.pathname.startsWith("/public/");!t&&s&&!P&&!L&&n("/dashboard")},[s,t,n,location.pathname]),j.useEffect(()=>{r.get("canceled")==="true"&&re.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const T=async(P,L=!1)=>{if(!u){re.error("Please enter your email address");return}if(!m.trim()){re.error("Please enter your full name");return}b(!0),i(P+(L?"_direct":""));const I=K_s();try{const{data:O,error:$}=await U.functions.invoke("create-checkout",{body:{tier:P,email:u,name:m.trim(),couponCode:x.trim()||void 0,skipTrial:L,referralCode:I}});if($)throw $;if(O!=null&&O.url)window.open(O.url,"_blank","noopener,noreferrer"),re.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(O){console.error("Checkout error:",O),re.error(O.message||"Failed to start checkout. Please try again.")}finally{b(!1),i(null),d(!1),o(null)}},M=()=>{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:GNe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var P;return(P=document.getElementById("features"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx(B,{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 P;return(P=document.getElementById("free-trial"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",e.jsx(Xa,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(B,{size:"lg",variant:"outline",onClick:()=>{var P;return(P=document.getElementById("features"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white 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 P;return(P=document.getElementById("brokerage"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(Ni,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs(B,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(Eo,{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:X_s.map((P,L)=>e.jsxs(be,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Ft,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(P.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Ut,{className:"text-xl font-sans",children:P.title})]}),e.jsx(Re,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:P.description})})]},L))})]})}),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(yn,{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:Q_s.map((P,L)=>e.jsxs(be,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(P.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Ut,{className:"text-lg font-semibold text-white",children:P.title})]}),e.jsx(Re,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:P.description})})]},L))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(B,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"bg-white text-[#4a6b6d] hover:bg-white/90 shadow-xl transition-all hover:scale-105",children:["Get Agent OS with Your Membership",e.jsx(Xa,{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(Ni,{className:"w-4 h-4"}),"For Brokerages"]}),e.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Give every agent on your team access to world-class training and resources. Track performance, streamline onboarding, and watch your brokerage thrive."}),e.jsx("ul",{className:"space-y-4",children:["Dedicated brokerage manager dashboard","Invite and manage agents with one click","Exclusive brokerage-only resources","Team analytics and performance tracking","Simplified agent onboarding","Share resources across your team"].map((P,L)=>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(da,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:P})]},L))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs(B,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(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(ra,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:Y_s,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:J_s.map((P,L)=>e.jsx(be,{className:"bg-muted/30 border-0",children:e.jsxs(Re,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(I=>e.jsx(Wa,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},I))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',P.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:P.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:P.role})]})]})},L))})]})}),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:()=>C("individual_agent"),children:["Start Free Trial",e.jsx(Xa,{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(be,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Ft,{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(Eo,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(Ut,{className:"text-xl font-sans",children:Rg.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:Rg.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Rg.individual_agent.period})]}),e.jsx(fr,{className:"text-base mt-2",children:Rg.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(Vr,{className:"w-4 h-4"}),Rg.individual_agent.trial]})]}),e.jsx(Re,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Rg.individual_agent.features.map((P,L)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(da,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:P})]},L))})}),e.jsxs(MK,{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:()=>C("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:()=>C("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(be,{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(Ft,{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(Ni,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-xl font-sans",children:Rg.brokerage_under_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Rg.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:Rg.brokerage_under_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Rg.brokerage_under_25.period})]}),e.jsx(fr,{className:"text-base mt-2",children:Rg.brokerage_under_25.description})]}),e.jsx(Re,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Rg.brokerage_under_25.features.map((P,L)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(da,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:P})]},L))})}),e.jsx(MK,{className:"pt-4",children:e.jsx(B,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>C("brokerage_under_25"),children:"Get Started"})})]}),e.jsxs(be,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Ft,{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(Ni,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-xl font-sans",children:Rg.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Rg.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:Rg.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Rg.brokerage_over_25.period})]}),e.jsx(fr,{className:"text-base mt-2",children:Rg.brokerage_over_25.description})]}),e.jsx(Re,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Rg.brokerage_over_25.features.map((P,L)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(da,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:P})]},L))})}),e.jsx(MK,{className:"pt-4",children:e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>C("brokerage_over_25"),children:"Get Started"})})]})]})]})}),e.jsx("section",{id:"neutrality",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium mb-4",children:[e.jsx(_f,{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(be,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Re,{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(Ni,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(be,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Re,{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(du,{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(be,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Re,{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(bN,{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(be,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Re,{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($r,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not use LevelUp events, trainings, webinars, CRM data, or member lists for recruiting purposes."})]})})]})]})})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),e.jsx("p",{className:"text-lg text-white/80 max-w-2xl mx-auto",children:"Join thousands of agents who are closing more deals, saving time, and growing their business with LevelUp."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs(B,{size:"lg",onClick:()=>{var P;return(P=document.getElementById("pricing"))==null?void 0:P.scrollIntoView({behavior:"smooth"})},className:"px-10 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105",children:["Start Your Free Trial",e.jsx(Xa,{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:GNe,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(Z_s,{open:v,onOpenChange:k}),e.jsx(Fs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(kr,{children:(l==null?void 0:l.tier)==="individual_agent"&&!(l!=null&&l.skipTrial)?"Start your 7-day free trial":(l==null?void 0:l.tier)==="individual_agent"?"Subscribe to Individual Agent":(l==null?void 0:l.tier)==="brokerage_under_25"?"Subscribe to Brokerage (Under 25 Agents)":"Subscribe to Brokerage (Over 25 Agents)"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ye,{id:"dialog-name",type:"text",placeholder:"John Smith",value:m,onChange:P=>p(P.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ye,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:P=>h(P.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(se,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(ye,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:x,onChange:P=>y(P.target.value),className:"mt-1"})]})]}),e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:M,disabled:g,children:g?"Loading...":"Continue to Checkout"})]})})]})},aat=()=>e.jsxs(e.Fragment,{children:[e.jsxs(ql,{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"})]})]})]})]})})]}),iat=()=>e.jsxs(e.Fragment,{children:[e.jsxs(ql,{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"})]})]})]})]})})]}),tws=()=>e.jsxs(e.Fragment,{children:[e.jsxs(ql,{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"})]})]})]})]})})]}),oat="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.",sws=iS({name:Cl().trim().min(1,"Name is required").max(200),phone:Cl().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:Cl().trim().email("Enter a valid email").max(320).optional().or(Xg(""))});function nws(){const[s,t]=j.useState(""),[n,r]=j.useState(""),[a,i]=j.useState(""),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState(!1),x=Hn(),y=async g=>{var k;if(g.preventDefault(),!l){re.error("Please check the consent box to opt in.");return}const b=sws.safeParse({name:s,phone:n,email:a});if(!b.success){re.error(((k=b.error.issues[0])==null?void 0:k.message)??"Please check your inputs.");return}d(!0);const{error:v}=await U.from("sms_opt_in_consents").insert({name:b.data.name,phone:b.data.phone,email:b.data.email||null,consent_text:oat,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),v){re.error("Something went wrong. Please try again.");return}h(!0)};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-background via-background to-muted/30 py-10 px-4",children:[e.jsxs(ql,{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(ro,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp — SMS Opt-In"}),e.jsx("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:"Sign up to receive SMS account notifications and real-time lead alerts from LevelUp. These messages help subscribed real estate agents review and respond to new consumer inquiries submitted through their websites."})]}),e.jsx("div",{className:"mb-6 rounded-lg border border-primary/30 bg-primary/5 p-4 text-center",children:e.jsx("p",{className:"text-sm font-medium",children:"SMS notifications are optional. You may use LevelUp without providing a mobile number or consenting to text messages."})}),m?e.jsxs(be,{className:"p-8 text-center",children:[e.jsx(Rr,{className:"w-14 h-14 text-primary mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"No text messages — you're all set"}),e.jsx("p",{className:"text-muted-foreground",children:"You declined SMS notifications. No mobile number or consent was recorded, and you can continue using LevelUp normally."}),e.jsx(B,{className:"mt-6",onClick:()=>x("/auth"),children:"Continue to LevelUp"})]}):u?e.jsxs(be,{className:"p-8 text-center",children:[e.jsx(Rr,{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(be,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:y,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Full Name (only if you opt in to SMS)"}),e.jsx(ye,{id:"name",value:s,onChange:g=>t(g.target.value),maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Mobile Number (only if you opt in to SMS)"}),e.jsx(ye,{id:"phone",type:"tel",value:n,onChange:g=>r(g.target.value),maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email (optional)"}),e.jsx(ye,{id:"email",type:"email",value:a,onChange:g=>i(g.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(wi,{id:"consent",checked:l,onCheckedChange:g=>o(g===!0),className:"mt-0.5"}),e.jsx(se,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:oat})]})}),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(Yn,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(Yn,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"}),"."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Message types:"})," account notifications, real-time lead alerts, service updates, customer support."," ",e.jsx("strong",{children:"Frequency:"})," varies."," ",e.jsx("strong",{children:"Msg & data rates may apply."})," ","Reply ",e.jsx("strong",{children:"STOP"})," to opt out, ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsx("p",{children:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties."})]}),e.jsx(B,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsx(B,{type:"button",variant:"outline",size:"lg",className:"w-full",disabled:c,onClick:()=>p(!0),children:"Skip SMS / Continue without text alerts"}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Skipping records no consent and does not limit your access to LevelUp."}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-muted-foreground pt-2",children:[e.jsx(a0,{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 P3t="/assets/levelup-logo-horizontal-DEFNc0ms.png",rws=iS({email:Cl().email("Invalid email address"),password:Cl().min(6,"Password must be at least 6 characters")}),aws="https://dashboard.relevelup.com",Pse="/oauth-connect",wje="levelupOAuthRouteHistory";function lat(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function iws(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(wje)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(wje,JSON.stringify([{route:s,at:t}])),!1}}function ows(){sessionStorage.removeItem(wje)}const lws=()=>{const{signIn:s,user:t,loading:n}=Ns(),r=(t==null?void 0:t.id)??null,a=Hn(),[i]=dc(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=j.useState(!1),[u,h]=j.useState({}),[m,p]=j.useState(""),[x,y]=j.useState(!1),[g,b]=j.useState(!1),[v,k]=j.useState(null),C=j.useRef(!1);j.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const P=new URL("/auth",aws);P.searchParams.set("next",`${Pse}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(P.toString());return}if(l){const P=`${Pse}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",P);return}o&&lat(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),j.useEffect(()=>{if(n||!r||C.current)return;const P=l?`${Pse}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!lat(P)){sessionStorage.removeItem("redirectAfterLogin"),C.current=!0,a("/dashboard",{replace:!0});return}const L=P.startsWith(Pse)||P.startsWith("/oauth/consent")||P.startsWith("/.lovable/oauth/consent");if(L&&iws("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}C.current=!0,L||(ows(),sessionStorage.removeItem("redirectAfterLogin")),a(P,{replace:!0})},[l,n,a,r]);const T=async P=>{P.preventDefault(),h({}),d(!0);const L=new FormData(P.currentTarget),I=L.get("email"),O=L.get("password");try{rws.parse({email:I,password:O}),await s(I,O)}catch($){if($ instanceof Exs){const q={};$.issues.forEach(W=>{W.path[0]&&(q[W.path[0]]=W.message)}),h(q)}}finally{d(!1)}},M=async()=>{if(!m){re.error("Please enter your email address");return}y(!0);try{const{error:P}=await U.functions.invoke("send-password-reset",{body:{email:m,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(P)throw P;re.success("Password reset email sent! Check your inbox."),b(!1),p("")}catch(P){re.error(P instanceof Error?P.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(Yn,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(_a,{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:P3t,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(be,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Ft,{className:"space-y-1 text-center pb-4",children:[e.jsx(Ut,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(fr,{className:"text-gray-600",children:v||"Sign in to access your dashboard"})]}),e.jsx(Re,{children:e.jsxs("form",{onSubmit:T,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(ye,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.email&&e.jsx("p",{className:"text-sm text-red-600",children:u.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(ye,{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(Fs,{open:g,onOpenChange:b,children:[e.jsx(Io,{asChild:!0,children:e.jsx(B,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(Os,{className:"bg-white",children:[e.jsxs($s,{children:[e.jsx(zs,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(kr,{className:"text-gray-600",children:"Enter your email address and we'll send you a link to reset your password."})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(ye,{id:"reset-email",type:"email",placeholder:"your@email.com",value:m,onChange:P=>p(P.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(B,{onClick:M,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:x,children:x?"Sending...":"Send Reset Link"})]})]})]})]})})]}),e.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",e.jsx(Yn,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},cat=()=>U.auth.oauth,cws="https://dashboard.relevelup.com",dws="/oauth-connect",jje="levelupOAuthRouteHistory",uws="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",hws="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function mws(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function pws(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(jje)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(jje,JSON.stringify([{route:s,at:t}])),!1}}function fws(){sessionStorage.removeItem(jje)}async function dat(s,t,n){const r=await fetch(`${uws}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:hws,"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 KMe(){var y;const{user:s,session:t,loading:n}=Ns(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=dc(),l=i.get("authorization_id")??"",[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState(!1);j.useEffect(()=>{let g=!0;return(async()=>{if(!l){u("Missing authorization_id");return}const b=`${dws}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${cws}${b}`;return}if(n)return;if(!r){if(pws("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}mws(b)&&sessionStorage.setItem("redirectAfterLogin",b),window.location.replace(`/auth?next=${encodeURIComponent(b)}`);return}if(!a)return;fws(),sessionStorage.removeItem("redirectAfterLogin");const v=cat(),{data:k,error:C}=v?await v.getAuthorizationDetails(l):await dat(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!g)return;if(C){u(C.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)})(),()=>{g=!1}},[a,l,n,r]);async function p(g){if(!(t!=null&&t.access_token)){u("Your sign-in session is not ready yet. Please refresh and try again.");return}m(!0);const b=cat(),{data:v,error:k}=b?g?await b.approveAuthorization(l,{skipBrowserRedirect:!0}):await b.denyAuthorization(l,{skipBrowserRedirect:!0}):await dat(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:g?"approve":"deny"})});if(k){m(!1),u(k.message);return}const C=(v==null?void 0:v.redirect_url)??(v==null?void 0:v.redirect_to);if(!C){m(!1),u("No redirect returned by the authorization server.");return}window.location.href=C}if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(be,{className:"w-full max-w-md",children:e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Authorization error"}),e.jsx(fr,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-primary"})});const x=((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(be,{className:"w-full max-w-md",children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{children:["Connect ",x," to LevelUp"]}),e.jsxs(fr,{children:[x," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(Re,{className:"flex gap-3 justify-end",children:[e.jsx(B,{variant:"outline",disabled:h,onClick:()=>p(!1),children:"Deny"}),e.jsx(B,{disabled:h,onClick:()=>p(!0),children:h?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const I3t=s=>{const[t,n]=j.useState(null),[r,a]=j.useState(!0);return j.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await U.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=U.storage.from("avatars").getPublicUrl(`${s}/${o[0].name}`);n(`${c.publicUrl}?t=${Date.now()}`)}else n(null)}catch(o){console.error("Error fetching avatar:",o),n(null)}finally{a(!1)}})()},[s]),{avatarUrl:t,loading:r,refreshAvatar:async()=>{if(s)try{const{data:l}=await U.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=U.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);n(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},R3t=async s=>{const t=new Map;return await Promise.all(s.map(async n=>{try{const{data:r}=await U.storage.from("avatars").list(`${n}`);if(r&&r.length>0){const{data:a}=U.storage.from("avatars").getPublicUrl(`${n}/${r[0].name}`);t.set(n,a.publicUrl)}}catch{}})),t},xws=s=>{const[t,n]=j.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return j.useEffect(()=>{if(!s){n(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await U.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",s).single();if(i){console.error("Error fetching trial status:",i),n(h=>({...h,loading:!1}));return}const l=(a==null?void 0:a.subscription_status)==="trialing",o=!!(a!=null&&a.is_trial),c=!!(a!=null&&a.trial_expires_at)&&new Date(a.trial_expires_at).getTime()>Date.now()&&(a==null?void 0:a.subscription_status)!=="active",d=l&&(a==null?void 0:a.subscription_end_date)||(a==null?void 0:a.trial_expires_at)||(a==null?void 0:a.subscription_end_date)||null;if((l||o||c)&&!!d&&d){const h=new Date().getTime(),m=new Date(d).getTime(),p=Math.ceil((m-h)/(1e3*60*60*24)),x=p<=0;n({isTrial:!0,isExpired:x,expiresAt:d,daysLeft:x?0:p,loading:!1})}else n({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),n(i=>({...i,loading:!1}))}})()},[s]),t},D3t=()=>{const{data:s,isLoading:t}=mt({queryKey:["feature-flags"],queryFn:async()=>{const{data:r,error:a}=await U.from("feature_flags").select("*");if(a)throw a;return r}}),n=r=>{if(!s)return!1;const a=s.find(i=>i.key===r);return(a==null?void 0:a.enabled)??!1};return{flags:s,isLoading:t,isFeatureEnabled:n,isAgentOSEnabled:n("agent_os_enabled"),isInnerCircleEnabled:n("innercircle_enabled"),isMarketplaceEnabled:n("marketplace")}},uat="community_last_seen_post_at";function gws(){const{user:s}=Ns(),t=$d(),[n,r]=j.useState(0),[a,i]=j.useState(null);j.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${uat}_${s.id}`);i(o)},[s]),j.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const p=sessionStorage.getItem(o);if(p){const x=JSON.parse(p);if(x.ts&&Date.now()-x.ts{if(!s)return;const o=U.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async c=>{const d=c.new;if(d.user_id===s.id)return;const u=t.pathname==="/community";u||r(y=>y+1);const{data:h}=await U.from("profiles").select("name").eq("id",d.user_id).single(),m=(h==null?void 0:h.name)||"Someone",p=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),x=p.length>50?p.substring(0,50)+"...":p;u||re("New Community Post",{description:`${m}: ${x}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{U.removeChannel(o)}},[s,t.pathname]);const l=j.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${uat}_${s.id}`,o),i(o),r(0)},[s]);return j.useEffect(()=>{t.pathname==="/community"&&n>0&&l()},[t.pathname,n,l]),{unreadCount:n,markAsRead:l}}function yws(){const{isAdmin:s}=Ns(),{data:t=0}=mt({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:n,error:r}=await U.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(r)throw r;return n||0},enabled:s,staleTime:6e4});return{openCount:s?t:0}}const d9="weekly_reels";function nVe(){const{user:s,loading:t,isAdmin:n}=Ns(),{data:r,isLoading:a}=mt({queryKey:["feature-entitlement",d9,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:i,error:l}=await U.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",d9).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 P3e="Collapsible",[vws,O3t]=Zm(P3e),[bws,rVe]=vws(P3e),F3t=j.forwardRef((s,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=Mx({prop:r,defaultProp:a??!1,onChange:l,caller:P3e});return e.jsx(bws,{scope:n,disabled:i,contentId:Cx(),open:c,onOpenToggle:j.useCallback(()=>d(u=>!u),[d]),children:e.jsx(Ua.div,{"data-state":lVe(c),"data-disabled":i?"":void 0,...o,ref:t})})});F3t.displayName=P3e;var z3t="CollapsibleTrigger",aVe=j.forwardRef((s,t)=>{const{__scopeCollapsible:n,...r}=s,a=rVe(z3t,n);return e.jsx(Ua.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":lVe(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:t,onClick:ua(s.onClick,a.onOpenToggle)})});aVe.displayName=z3t;var iVe="CollapsibleContent",oVe=j.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=rVe(iVe,s.__scopeCollapsible);return e.jsx(ax,{present:n||a.open,children:({present:i})=>e.jsx(_ws,{...r,ref:t,present:i})})});oVe.displayName=iVe;var _ws=j.forwardRef((s,t)=>{const{__scopeCollapsible:n,present:r,children:a,...i}=s,l=rVe(iVe,n),[o,c]=j.useState(r),d=j.useRef(null),u=ko(t,d),h=j.useRef(0),m=h.current,p=j.useRef(0),x=p.current,y=l.open||o,g=j.useRef(y),b=j.useRef(void 0);return j.useEffect(()=>{const v=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(v)},[]),Nf(()=>{const v=d.current;if(v){b.current=b.current||{transitionDuration:v.style.transitionDuration,animationName:v.style.animationName},v.style.transitionDuration="0s",v.style.animationName="none";const k=v.getBoundingClientRect();h.current=k.height,p.current=k.width,g.current||(v.style.transitionDuration=b.current.transitionDuration,v.style.animationName=b.current.animationName),c(r)}},[l.open,r]),e.jsx(Ua.div,{"data-state":lVe(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":x?`${x}px`:void 0,...s.style},children:y&&a})});function lVe(s){return s?"open":"closed"}var B3t=F3t,wws=aVe,jws=oVe;const i0=B3t,o0=aVe,l0=oVe,Nws="/assets/levelup-logo-Eif24dqY.png",kws="/assets/levelup-logo-icon-C-7iromj.png",Sws="/assets/levelup-logo-mobile-B9skSjUG.png";var NJ=s=>s.type==="checkbox",n8=s=>s instanceof Date,$v=s=>s==null;const $3t=s=>typeof s=="object";var nx=s=>!$v(s)&&!Array.isArray(s)&&$3t(s)&&!n8(s),U3t=s=>nx(s)&&s.target?NJ(s.target)?s.target.checked:s.target.value:s,Cws=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,q3t=(s,t)=>s.has(Cws(t)),Aws=s=>{const t=s.constructor&&s.constructor.prototype;return nx(t)&&t.hasOwnProperty("isPrototypeOf")},cVe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Gx(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(!(cVe&&(s instanceof Blob||r))&&(n||nx(s)))if(t=n?[]:{},!n&&!Aws(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=Gx(s[a]));else return s;return t}var I3e=s=>/^\w*$/.test(s),Uf=s=>s===void 0,dVe=s=>Array.isArray(s)?s.filter(Boolean):[],uVe=s=>dVe(s.replace(/["|']|\]/g,"").split(/\.|\[/)),yi=(s,t,n)=>{if(!t||!nx(s))return n;const r=(I3e(t)?[t]:uVe(t)).reduce((a,i)=>$v(a)?a:a[i],s);return Uf(r)||r===s?Uf(s[t])?n:s[t]:r},E_=s=>typeof s=="boolean",Bu=(s,t,n)=>{let r=-1;const a=I3e(t)?[t]:uVe(t),i=a.length,l=i-1;for(;++rLt.useContext(hVe),Tws=s=>{const{children:t,...n}=s;return Lt.createElement(hVe.Provider,{value:n},t)};var V3t=(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]!==nN.all&&(t._proxyFormState[l]=!r||nN.all),n&&(n[l]=!0),s[l]}});return a};const mVe=typeof window<"u"?Lt.useLayoutEffect:Lt.useEffect;function Ews(s){const t=R3e(),{control:n=t.control,disabled:r,name:a,exact:i}=s||{},[l,o]=Lt.useState(n._formState),c=Lt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return mVe(()=>n._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!r&&o({...n._formState,...d})}}),[a,r,i]),Lt.useEffect(()=>{c.current.isValid&&n._setValid(!0)},[n]),Lt.useMemo(()=>V3t(l,n,c.current,!1),[l,n])}var b5=s=>typeof s=="string",H3t=(s,t,n,r,a)=>b5(s)?(r&&t.watch.add(s),yi(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),yi(n,i))):(r&&(t.watchAll=!0),n),TOe=s=>$v(s)||!$3t(s);function e3(s,t,n=new WeakSet){if(TOe(s)||TOe(t))return s===t;if(n8(s)&&n8(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(n8(l)&&n8(o)||nx(l)&&nx(o)||Array.isArray(l)&&Array.isArray(o)?!e3(l,o,n):l!==o)return!1}}return!0}function Mws(s){const t=R3e(),{control:n=t.control,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=Lt.useRef(a),d=Lt.useRef(o),u=Lt.useRef(void 0);d.current=o;const h=Lt.useMemo(()=>n._getWatch(r,c.current),[n,r]),[m,p]=Lt.useState(d.current?d.current(h):h);return mVe(()=>n._subscribe({name:r,formState:{values:!0},exact:l,callback:x=>{if(!i){const y=H3t(r,n._names,x.values||n._formValues,!1,c.current);if(d.current){const g=d.current(y);e3(g,u.current)||(p(g),u.current=g)}else p(y)}}}),[n,i,r,l]),Lt.useEffect(()=>n._removeUnmounted()),m}function Lws(s){const t=R3e(),{name:n,disabled:r,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=q3t(a._names.array,n),c=Lt.useMemo(()=>yi(a._formValues,n,yi(a._defaultValues,n,l)),[a,n,l]),d=Mws({control:a,name:n,defaultValue:c,exact:!0}),u=Ews({control:a,name:n,exact:!0}),h=Lt.useRef(s),m=Lt.useRef(a.register(n,{...s.rules,value:d,...E_(s.disabled)?{disabled:s.disabled}:{}}));h.current=s;const p=Lt.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!yi(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!yi(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!yi(u.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!yi(u.validatingFields,n)},error:{enumerable:!0,get:()=>yi(u.errors,n)}}),[u,n]),x=Lt.useCallback(v=>m.current.onChange({target:{value:U3t(v),name:n},type:WNe.CHANGE}),[n]),y=Lt.useCallback(()=>m.current.onBlur({target:{value:yi(a._formValues,n),name:n},type:WNe.BLUR}),[n,a._formValues]),g=Lt.useCallback(v=>{const k=yi(a._fields,n);k&&v&&(k._f.ref={focus:()=>v.focus&&v.focus(),select:()=>v.select&&v.select(),setCustomValidity:C=>v.setCustomValidity(C),reportValidity:()=>v.reportValidity()})},[a._fields,n]),b=Lt.useMemo(()=>({name:n,value:d,...E_(r)||u.disabled?{disabled:u.disabled||r}:{},onChange:x,onBlur:y,ref:g}),[n,r,u.disabled,x,y,g,d]);return Lt.useEffect(()=>{const v=a._options.shouldUnregister||i;a.register(n,{...h.current.rules,...E_(h.current.disabled)?{disabled:h.current.disabled}:{}});const k=(C,T)=>{const M=yi(a._fields,C);M&&M._f&&(M._f.mount=T)};if(k(n,!0),v){const C=Gx(yi(a._options.defaultValues,n));Bu(a._defaultValues,n,C),Uf(yi(a._formValues,n))&&Bu(a._formValues,n,C)}return!o&&a.register(n),()=>{(o?v&&!a._state.action:v)?a.unregister(n):k(n,!1)}},[n,a,o,i]),Lt.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),Lt.useMemo(()=>({field:b,formState:u,fieldState:p}),[b,u,p])}const Pws=s=>s.render(Lws(s));var G3t=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{},LK=s=>Array.isArray(s)?s:[s],hat=()=>{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=[]}}},Q1=s=>nx(s)&&!Object.keys(s).length,pVe=s=>s.type==="file",rN=s=>typeof s=="function",KNe=s=>{if(!cVe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},W3t=s=>s.type==="select-multiple",fVe=s=>s.type==="radio",Iws=s=>fVe(s)||NJ(s),YMe=s=>KNe(s)&&s.isConnected;function Rws(s,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in s)if(rN(s[t]))return!0;return!1};function YNe(s,t={}){const n=Array.isArray(s);if(nx(s)||n)for(const r in s)Array.isArray(s[r])||nx(s[r])&&!K3t(s[r])?(t[r]=Array.isArray(s[r])?[]:{},YNe(s[r],t[r])):$v(s[r])||(t[r]=!0);return t}function Y3t(s,t,n){const r=Array.isArray(s);if(nx(s)||r)for(const a in s)Array.isArray(s[a])||nx(s[a])&&!K3t(s[a])?Uf(t)||TOe(n[a])?n[a]=Array.isArray(s[a])?YNe(s[a],[]):{...YNe(s[a])}:Y3t(s[a],$v(t)?{}:t[a],n[a]):n[a]=!e3(s[a],t[a]);return n}var yH=(s,t)=>Y3t(s,t,YNe(t));const mat={value:!1,isValid:!1},pat={value:!0,isValid:!0};var Z3t=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&&!Uf(s[0].attributes.value)?Uf(s[0].value)||s[0].value===""?pat:{value:s[0].value,isValid:!0}:pat:mat}return mat},X3t=(s,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Uf(s)?s:t?s===""?NaN:s&&+s:n&&b5(s)?new Date(s):r?r(s):s;const fat={isValid:!1,value:null};var Q3t=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,fat):fat;function xat(s){const t=s.ref;return pVe(t)?t.files:fVe(t)?Q3t(s.refs).value:W3t(t)?[...t.selectedOptions].map(({value:n})=>n):NJ(t)?Z3t(s.refs).value:X3t(Uf(t.value)?s.ref.value:t.value,s)}var Ows=(s,t,n,r)=>{const a={};for(const i of s){const l=yi(t,i);l&&Bu(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},ZNe=s=>s instanceof RegExp,vH=s=>Uf(s)?s:ZNe(s)?s.source:nx(s)?ZNe(s.value)?s.value.source:s.value:s,gat=s=>({isOnSubmit:!s||s===nN.onSubmit,isOnBlur:s===nN.onBlur,isOnChange:s===nN.onChange,isOnAll:s===nN.all,isOnTouch:s===nN.onTouched});const yat="AsyncFunction";var Fws=s=>!!s&&!!s.validate&&!!(rN(s.validate)&&s.validate.constructor.name===yat||nx(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===yat)),zws=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),vat=(s,t,n)=>!n&&(t.watchAll||t.watch.has(s)||[...t.watch].some(r=>s.startsWith(r)&&/^\.\w+/.test(s.slice(r.length))));const PK=(s,t,n,r)=>{for(const a of n||Object.keys(s)){const i=yi(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(PK(o,t))break}else if(nx(o)&&PK(o,t))break}}};function bat(s,t,n){const r=yi(s,n);if(r||I3e(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=yi(t,i),o=yi(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 Bws=(s,t,n,r)=>{n(s);const{name:a,...i}=s;return Q1(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||nN.all))},$ws=(s,t,n)=>!s||!t||s===t||LK(s).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r))),Uws=(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,qws=(s,t)=>!dVe(yi(s,t)).length&&px(s,t),Vws=(s,t,n)=>{const r=LK(yi(s,n));return Bu(r,"root",t[n]),Bu(s,n,r),s},Nje=s=>b5(s);function _at(s,t,n="validate"){if(Nje(s)||Array.isArray(s)&&s.every(Nje)||E_(s)&&!s)return{type:n,message:Nje(s)?s:"",ref:t}}var zF=s=>nx(s)&&!ZNe(s)?s:{value:s,message:""},wat=async(s,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:m,pattern:p,validate:x,name:y,valueAsNumber:g,mount:b}=s._f,v=yi(n,y);if(!b||t.has(y))return{};const k=o?o[0]:l,C=q=>{a&&k.reportValidity&&(k.setCustomValidity(E_(q)?"":q||""),k.reportValidity())},T={},M=fVe(l),P=NJ(l),L=M||P,I=(g||pVe(l))&&Uf(l.value)&&Uf(v)||KNe(l)&&l.value===""||v===""||Array.isArray(v)&&!v.length,O=G3t.bind(null,y,r,T),$=(q,W,G,K=WS.maxLength,ee=WS.minLength)=>{const J=q?W:G;T[y]={type:q?K:ee,message:J,ref:l,...O(q?K:ee,J)}};if(i?!Array.isArray(v)||!v.length:c&&(!L&&(I||$v(v))||E_(v)&&!v||P&&!Z3t(o).isValid||M&&!Q3t(o).isValid)){const{value:q,message:W}=Nje(c)?{value:!!c,message:c}:zF(c);if(q&&(T[y]={type:WS.required,message:W,ref:k,...O(WS.required,W)},!r))return C(W),T}if(!I&&(!$v(h)||!$v(m))){let q,W;const G=zF(m),K=zF(h);if(!$v(v)&&!isNaN(v)){const ee=l.valueAsNumber||v&&+v;$v(G.value)||(q=ee>G.value),$v(K.value)||(W=eenew Date(new Date().toDateString()+" "+oe),le=l.type=="time",ue=l.type=="week";b5(G.value)&&v&&(q=le?J(v)>J(G.value):ue?v>G.value:ee>new Date(G.value)),b5(K.value)&&v&&(W=le?J(v)+q.value,K=!$v(W.value)&&v.length<+W.value;if((G||K)&&($(G,q.message,W.message),!r))return C(T[y].message),T}if(p&&!I&&b5(v)){const{value:q,message:W}=zF(p);if(ZNe(q)&&!v.match(q)&&(T[y]={type:WS.pattern,message:W,ref:l,...O(WS.pattern,W)},!r))return C(W),T}if(x){if(rN(x)){const q=await x(v,n),W=_at(q,k);if(W&&(T[y]={...W,...O(WS.validate,W.message)},!r))return C(W.message),T}else if(nx(x)){let q={};for(const W in x){if(!Q1(q)&&!r)break;const G=_at(await x[W](v,n),k,W);G&&(q={...G,...O(W,G.message)},C(G.message),r&&(T[y]=q))}if(!Q1(q)&&(T[y]={ref:k,...q},!r))return T}}return C(!0),T};const Hws={mode:nN.onSubmit,reValidateMode:nN.onChange,shouldFocusError:!0};function Gws(s={}){let t={...Hws,...s},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:rN(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=nx(t.defaultValues)||nx(t.values)?Gx(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:Gx(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:hat(),state:hat()},p=t.criteriaMode===nN.all,x=Qe=>Ye=>{clearTimeout(d),d=setTimeout(Qe,Ye)},y=async Qe=>{if(!t.disabled&&(u.isValid||h.isValid||Qe)){const Ye=t.resolver?Q1((await P()).errors):await I(r,!0);Ye!==n.isValid&&m.state.next({isValid:Ye})}},g=(Qe,Ye)=>{!t.disabled&&(u.isValidating||u.validatingFields||h.isValidating||h.validatingFields)&&((Qe||Array.from(o.mount)).forEach(nt=>{nt&&(Ye?Bu(n.validatingFields,nt,Ye):px(n.validatingFields,nt))}),m.state.next({validatingFields:n.validatingFields,isValidating:!Q1(n.validatingFields)}))},b=(Qe,Ye=[],nt,rt,Fe=!0,dt=!0)=>{if(rt&&nt&&!t.disabled){if(l.action=!0,dt&&Array.isArray(yi(r,Qe))){const Dt=nt(yi(r,Qe),rt.argA,rt.argB);Fe&&Bu(r,Qe,Dt)}if(dt&&Array.isArray(yi(n.errors,Qe))){const Dt=nt(yi(n.errors,Qe),rt.argA,rt.argB);Fe&&Bu(n.errors,Qe,Dt),qws(n.errors,Qe)}if((u.touchedFields||h.touchedFields)&&dt&&Array.isArray(yi(n.touchedFields,Qe))){const Dt=nt(yi(n.touchedFields,Qe),rt.argA,rt.argB);Fe&&Bu(n.touchedFields,Qe,Dt)}(u.dirtyFields||h.dirtyFields)&&(n.dirtyFields=yH(a,i)),m.state.next({name:Qe,isDirty:$(Qe,Ye),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Bu(i,Qe,Ye)},v=(Qe,Ye)=>{Bu(n.errors,Qe,Ye),m.state.next({errors:n.errors})},k=Qe=>{n.errors=Qe,m.state.next({errors:n.errors,isValid:!1})},C=(Qe,Ye,nt,rt)=>{const Fe=yi(r,Qe);if(Fe){const dt=yi(i,Qe,Uf(nt)?yi(a,Qe):nt);Uf(dt)||rt&&rt.defaultChecked||Ye?Bu(i,Qe,Ye?dt:xat(Fe._f)):G(Qe,dt),l.mount&&y()}},T=(Qe,Ye,nt,rt,Fe)=>{let dt=!1,Dt=!1;const pt={name:Qe};if(!t.disabled){if(!nt||rt){(u.isDirty||h.isDirty)&&(Dt=n.isDirty,n.isDirty=pt.isDirty=$(),dt=Dt!==pt.isDirty);const zt=e3(yi(a,Qe),Ye);Dt=!!yi(n.dirtyFields,Qe),zt?px(n.dirtyFields,Qe):Bu(n.dirtyFields,Qe,!0),pt.dirtyFields=n.dirtyFields,dt=dt||(u.dirtyFields||h.dirtyFields)&&Dt!==!zt}if(nt){const zt=yi(n.touchedFields,Qe);zt||(Bu(n.touchedFields,Qe,nt),pt.touchedFields=n.touchedFields,dt=dt||(u.touchedFields||h.touchedFields)&&zt!==nt)}dt&&Fe&&m.state.next(pt)}return dt?pt:{}},M=(Qe,Ye,nt,rt)=>{const Fe=yi(n.errors,Qe),dt=(u.isValid||h.isValid)&&E_(Ye)&&n.isValid!==Ye;if(t.delayError&&nt?(c=x(()=>v(Qe,nt)),c(t.delayError)):(clearTimeout(d),c=null,nt?Bu(n.errors,Qe,nt):px(n.errors,Qe)),(nt?!e3(Fe,nt):Fe)||!Q1(rt)||dt){const Dt={...rt,...dt&&E_(Ye)?{isValid:Ye}:{},errors:n.errors,name:Qe};n={...n,...Dt},m.state.next(Dt)}},P=async Qe=>{g(Qe,!0);const Ye=await t.resolver(i,t.context,Ows(Qe||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return g(Qe),Ye},L=async Qe=>{const{errors:Ye}=await P(Qe);if(Qe)for(const nt of Qe){const rt=yi(Ye,nt);rt?Bu(n.errors,nt,rt):px(n.errors,nt)}else n.errors=Ye;return Ye},I=async(Qe,Ye,nt={valid:!0})=>{for(const rt in Qe){const Fe=Qe[rt];if(Fe){const{_f:dt,...Dt}=Fe;if(dt){const pt=o.array.has(dt.name),zt=Fe._f&&Fws(Fe._f);zt&&u.validatingFields&&g([rt],!0);const Gt=await wat(Fe,o.disabled,i,p,t.shouldUseNativeValidation&&!Ye,pt);if(zt&&u.validatingFields&&g([rt]),Gt[dt.name]&&(nt.valid=!1,Ye))break;!Ye&&(yi(Gt,dt.name)?pt?Vws(n.errors,Gt,dt.name):Bu(n.errors,dt.name,Gt[dt.name]):px(n.errors,dt.name))}!Q1(Dt)&&await I(Dt,Ye,nt)}}return nt.valid},O=()=>{for(const Qe of o.unMount){const Ye=yi(r,Qe);Ye&&(Ye._f.refs?Ye._f.refs.every(nt=>!YMe(nt)):!YMe(Ye._f.ref))&&Se(Qe)}o.unMount=new Set},$=(Qe,Ye)=>!t.disabled&&(Qe&&Ye&&Bu(i,Qe,Ye),!e3(oe(),a)),q=(Qe,Ye,nt)=>H3t(Qe,o,{...l.mount?i:Uf(Ye)?a:b5(Qe)?{[Qe]:Ye}:Ye},nt,Ye),W=Qe=>dVe(yi(l.mount?i:a,Qe,t.shouldUnregister?yi(a,Qe,[]):[])),G=(Qe,Ye,nt={})=>{const rt=yi(r,Qe);let Fe=Ye;if(rt){const dt=rt._f;dt&&(!dt.disabled&&Bu(i,Qe,X3t(Ye,dt)),Fe=KNe(dt.ref)&&$v(Ye)?"":Ye,W3t(dt.ref)?[...dt.ref.options].forEach(Dt=>Dt.selected=Fe.includes(Dt.value)):dt.refs?NJ(dt.ref)?dt.refs.forEach(Dt=>{(!Dt.defaultChecked||!Dt.disabled)&&(Array.isArray(Fe)?Dt.checked=!!Fe.find(pt=>pt===Dt.value):Dt.checked=Fe===Dt.value||!!Fe)}):dt.refs.forEach(Dt=>Dt.checked=Dt.value===Fe):pVe(dt.ref)?dt.ref.value="":(dt.ref.value=Fe,dt.ref.type||m.state.next({name:Qe,values:Gx(i)})))}(nt.shouldDirty||nt.shouldTouch)&&T(Qe,Fe,nt.shouldTouch,nt.shouldDirty,!0),nt.shouldValidate&&ue(Qe)},K=(Qe,Ye,nt)=>{for(const rt in Ye){if(!Ye.hasOwnProperty(rt))return;const Fe=Ye[rt],dt=Qe+"."+rt,Dt=yi(r,dt);(o.array.has(Qe)||nx(Fe)||Dt&&!Dt._f)&&!n8(Fe)?K(dt,Fe,nt):G(dt,Fe,nt)}},ee=(Qe,Ye,nt={})=>{const rt=yi(r,Qe),Fe=o.array.has(Qe),dt=Gx(Ye);Bu(i,Qe,dt),Fe?(m.array.next({name:Qe,values:Gx(i)}),(u.isDirty||u.dirtyFields||h.isDirty||h.dirtyFields)&&nt.shouldDirty&&m.state.next({name:Qe,dirtyFields:yH(a,i),isDirty:$(Qe,dt)})):rt&&!rt._f&&!$v(dt)?K(Qe,dt,nt):G(Qe,dt,nt),vat(Qe,o)&&m.state.next({...n,name:Qe}),m.state.next({name:l.mount?Qe:void 0,values:Gx(i)})},J=async Qe=>{l.mount=!0;const Ye=Qe.target;let nt=Ye.name,rt=!0;const Fe=yi(r,nt),dt=zt=>{rt=Number.isNaN(zt)||n8(zt)&&isNaN(zt.getTime())||e3(zt,yi(i,nt,zt))},Dt=gat(t.mode),pt=gat(t.reValidateMode);if(Fe){let zt,Gt;const qs=Ye.type?xat(Fe._f):U3t(Qe),As=Qe.type===WNe.BLUR||Qe.type===WNe.FOCUS_OUT,Bt=!zws(Fe._f)&&!t.resolver&&!yi(n.errors,nt)&&!Fe._f.deps||Uws(As,yi(n.touchedFields,nt),n.isSubmitted,pt,Dt),At=vat(nt,o,As);Bu(i,nt,qs),As?(Fe._f.onBlur&&Fe._f.onBlur(Qe),c&&c(0)):Fe._f.onChange&&Fe._f.onChange(Qe);const Is=T(nt,qs,As),jt=!Q1(Is)||At;if(!As&&m.state.next({name:nt,type:Qe.type,values:Gx(i)}),Bt)return(u.isValid||h.isValid)&&(t.mode==="onBlur"?As&&y():As||y()),jt&&m.state.next({name:nt,...At?{}:Is});if(!As&&At&&m.state.next({...n}),t.resolver){const{errors:Qs}=await P([nt]);if(dt(qs),rt){const cn=bat(n.errors,r,nt),qt=bat(Qs,r,cn.name||nt);zt=qt.error,nt=qt.name,Gt=Q1(Qs)}}else g([nt],!0),zt=(await wat(Fe,o.disabled,i,p,t.shouldUseNativeValidation))[nt],g([nt]),dt(qs),rt&&(zt?Gt=!1:(u.isValid||h.isValid)&&(Gt=await I(r,!0)));rt&&(Fe._f.deps&&ue(Fe._f.deps),M(nt,Gt,zt,Is))}},le=(Qe,Ye)=>{if(yi(n.errors,Ye)&&Qe.focus)return Qe.focus(),1},ue=async(Qe,Ye={})=>{let nt,rt;const Fe=LK(Qe);if(t.resolver){const dt=await L(Uf(Qe)?Qe:Fe);nt=Q1(dt),rt=Qe?!Fe.some(Dt=>yi(dt,Dt)):nt}else Qe?(rt=(await Promise.all(Fe.map(async dt=>{const Dt=yi(r,dt);return await I(Dt&&Dt._f?{[dt]:Dt}:Dt)}))).every(Boolean),!(!rt&&!n.isValid)&&y()):rt=nt=await I(r);return m.state.next({...!b5(Qe)||(u.isValid||h.isValid)&&nt!==n.isValid?{}:{name:Qe},...t.resolver||!Qe?{isValid:nt}:{},errors:n.errors}),Ye.shouldFocus&&!rt&&PK(r,le,Qe?Fe:o.mount),rt},oe=Qe=>{const Ye={...l.mount?i:a};return Uf(Qe)?Ye:b5(Qe)?yi(Ye,Qe):Qe.map(nt=>yi(Ye,nt))},ie=(Qe,Ye)=>({invalid:!!yi((Ye||n).errors,Qe),isDirty:!!yi((Ye||n).dirtyFields,Qe),error:yi((Ye||n).errors,Qe),isValidating:!!yi(n.validatingFields,Qe),isTouched:!!yi((Ye||n).touchedFields,Qe)}),de=Qe=>{Qe&&LK(Qe).forEach(Ye=>px(n.errors,Ye)),m.state.next({errors:Qe?n.errors:{}})},we=(Qe,Ye,nt)=>{const rt=(yi(r,Qe,{_f:{}})._f||{}).ref,Fe=yi(n.errors,Qe)||{},{ref:dt,message:Dt,type:pt,...zt}=Fe;Bu(n.errors,Qe,{...zt,...Ye,ref:rt}),m.state.next({name:Qe,errors:n.errors,isValid:!1}),nt&&nt.shouldFocus&&rt&&rt.focus&&rt.focus()},je=(Qe,Ye)=>rN(Qe)?m.state.subscribe({next:nt=>"values"in nt&&Qe(q(void 0,Ye),nt)}):q(Qe,Ye,!0),xe=Qe=>m.state.subscribe({next:Ye=>{$ws(Qe.name,Ye.name,Qe.exact)&&Bws(Ye,Qe.formState||u,Xe,Qe.reRenderRoot)&&Qe.callback({values:{...i},...n,...Ye,defaultValues:a})}}).unsubscribe,fe=Qe=>(l.mount=!0,h={...h,...Qe.formState},xe({...Qe,formState:h})),Se=(Qe,Ye={})=>{for(const nt of Qe?LK(Qe):o.mount)o.mount.delete(nt),o.array.delete(nt),Ye.keepValue||(px(r,nt),px(i,nt)),!Ye.keepError&&px(n.errors,nt),!Ye.keepDirty&&px(n.dirtyFields,nt),!Ye.keepTouched&&px(n.touchedFields,nt),!Ye.keepIsValidating&&px(n.validatingFields,nt),!t.shouldUnregister&&!Ye.keepDefaultValue&&px(a,nt);m.state.next({values:Gx(i)}),m.state.next({...n,...Ye.keepDirty?{isDirty:$()}:{}}),!Ye.keepIsValid&&y()},Ee=({disabled:Qe,name:Ye})=>{(E_(Qe)&&l.mount||Qe||o.disabled.has(Ye))&&(Qe?o.disabled.add(Ye):o.disabled.delete(Ye))},Le=(Qe,Ye={})=>{let nt=yi(r,Qe);const rt=E_(Ye.disabled)||E_(t.disabled);return Bu(r,Qe,{...nt||{},_f:{...nt&&nt._f?nt._f:{ref:{name:Qe}},name:Qe,mount:!0,...Ye}}),o.mount.add(Qe),nt?Ee({disabled:E_(Ye.disabled)?Ye.disabled:t.disabled,name:Qe}):C(Qe,!0,Ye.value),{...rt?{disabled:Ye.disabled||t.disabled}:{},...t.progressive?{required:!!Ye.required,min:vH(Ye.min),max:vH(Ye.max),minLength:vH(Ye.minLength),maxLength:vH(Ye.maxLength),pattern:vH(Ye.pattern)}:{},name:Qe,onChange:J,onBlur:J,ref:Fe=>{if(Fe){Le(Qe,Ye),nt=yi(r,Qe);const dt=Uf(Fe.value)&&Fe.querySelectorAll&&Fe.querySelectorAll("input,select,textarea")[0]||Fe,Dt=Iws(dt),pt=nt._f.refs||[];if(Dt?pt.find(zt=>zt===dt):dt===nt._f.ref)return;Bu(r,Qe,{_f:{...nt._f,...Dt?{refs:[...pt.filter(YMe),dt,...Array.isArray(yi(a,Qe))?[{}]:[]],ref:{type:dt.type,name:Qe}}:{ref:dt}}}),C(Qe,!1,void 0,dt)}else nt=yi(r,Qe,{}),nt._f&&(nt._f.mount=!1),(t.shouldUnregister||Ye.shouldUnregister)&&!(q3t(o.array,Qe)&&l.action)&&o.unMount.add(Qe)}}},De=()=>t.shouldFocusError&&PK(r,le,o.mount),Be=Qe=>{E_(Qe)&&(m.state.next({disabled:Qe}),PK(r,(Ye,nt)=>{const rt=yi(r,nt);rt&&(Ye.disabled=rt._f.disabled||Qe,Array.isArray(rt._f.refs)&&rt._f.refs.forEach(Fe=>{Fe.disabled=rt._f.disabled||Qe}))},0,!1))},Ne=(Qe,Ye)=>async nt=>{let rt;nt&&(nt.preventDefault&&nt.preventDefault(),nt.persist&&nt.persist());let Fe=Gx(i);if(m.state.next({isSubmitting:!0}),t.resolver){const{errors:dt,values:Dt}=await P();n.errors=dt,Fe=Gx(Dt)}else await I(r);if(o.disabled.size)for(const dt of o.disabled)px(Fe,dt);if(px(n.errors,"root"),Q1(n.errors)){m.state.next({errors:{}});try{await Qe(Fe,nt)}catch(dt){rt=dt}}else Ye&&await Ye({...n.errors},nt),De(),setTimeout(De);if(m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Q1(n.errors)&&!rt,submitCount:n.submitCount+1,errors:n.errors}),rt)throw rt},Ge=(Qe,Ye={})=>{yi(r,Qe)&&(Uf(Ye.defaultValue)?ee(Qe,Gx(yi(a,Qe))):(ee(Qe,Ye.defaultValue),Bu(a,Qe,Gx(Ye.defaultValue))),Ye.keepTouched||px(n.touchedFields,Qe),Ye.keepDirty||(px(n.dirtyFields,Qe),n.isDirty=Ye.defaultValue?$(Qe,Gx(yi(a,Qe))):$()),Ye.keepError||(px(n.errors,Qe),u.isValid&&y()),m.state.next({...n}))},_e=(Qe,Ye={})=>{const nt=Qe?Gx(Qe):a,rt=Gx(nt),Fe=Q1(Qe),dt=Fe?a:rt;if(Ye.keepDefaultValues||(a=nt),!Ye.keepValues){if(Ye.keepDirtyValues){const Dt=new Set([...o.mount,...Object.keys(yH(a,i))]);for(const pt of Array.from(Dt))yi(n.dirtyFields,pt)?Bu(dt,pt,yi(i,pt)):ee(pt,yi(dt,pt))}else{if(cVe&&Uf(Qe))for(const Dt of o.mount){const pt=yi(r,Dt);if(pt&&pt._f){const zt=Array.isArray(pt._f.refs)?pt._f.refs[0]:pt._f.ref;if(KNe(zt)){const Gt=zt.closest("form");if(Gt){Gt.reset();break}}}}if(Ye.keepFieldsRef)for(const Dt of o.mount)ee(Dt,yi(dt,Dt));else r={}}i=t.shouldUnregister?Ye.keepDefaultValues?Gx(a):{}:Gx(dt),m.array.next({values:{...dt}}),m.state.next({values:{...dt}})}o={mount:Ye.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!u.isValid||!!Ye.keepIsValid||!!Ye.keepDirtyValues,l.watch=!!t.shouldUnregister,m.state.next({submitCount:Ye.keepSubmitCount?n.submitCount:0,isDirty:Fe?!1:Ye.keepDirty?n.isDirty:!!(Ye.keepDefaultValues&&!e3(Qe,a)),isSubmitted:Ye.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:Fe?{}:Ye.keepDirtyValues?Ye.keepDefaultValues&&i?yH(a,i):n.dirtyFields:Ye.keepDefaultValues&&Qe?yH(a,Qe):Ye.keepDirty?n.dirtyFields:{},touchedFields:Ye.keepTouched?n.touchedFields:{},errors:Ye.keepErrors?n.errors:{},isSubmitSuccessful:Ye.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},Oe=(Qe,Ye)=>_e(rN(Qe)?Qe(i):Qe,Ye),Ae=(Qe,Ye={})=>{const nt=yi(r,Qe),rt=nt&&nt._f;if(rt){const Fe=rt.refs?rt.refs[0]:rt.ref;Fe.focus&&(Fe.focus(),Ye.shouldSelect&&rN(Fe.select)&&Fe.select())}},Xe=Qe=>{n={...n,...Qe}},Ze={control:{register:Le,unregister:Se,getFieldState:ie,handleSubmit:Ne,setError:we,_subscribe:xe,_runSchema:P,_focusError:De,_getWatch:q,_getDirty:$,_setValid:y,_setFieldArray:b,_setDisabledField:Ee,_setErrors:k,_getFieldArray:W,_reset:_e,_resetDefaultValues:()=>rN(t.defaultValues)&&t.defaultValues().then(Qe=>{Oe(Qe,t.resetOptions),m.state.next({isLoading:!1})}),_removeUnmounted:O,_disableForm:Be,_subjects:m,_proxyFormState:u,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(Qe){l=Qe},get _defaultValues(){return a},get _names(){return o},set _names(Qe){o=Qe},get _formState(){return n},get _options(){return t},set _options(Qe){t={...t,...Qe}}},subscribe:fe,trigger:ue,register:Le,handleSubmit:Ne,watch:je,setValue:ee,getValues:oe,reset:Oe,resetField:Ge,clearErrors:de,unregister:Se,setError:we,setFocus:Ae,getFieldState:ie};return{...Ze,formControl:Ze}}function D3e(s={}){const t=Lt.useRef(void 0),n=Lt.useRef(void 0),[r,a]=Lt.useState({isDirty:!1,isValidating:!1,isLoading:rN(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:rN(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:r},s.defaultValues&&!rN(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=Gws(s);t.current={...o,formState:r}}const i=t.current.control;return i._options=s,mVe(()=>{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]),Lt.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),Lt.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),Lt.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),Lt.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),Lt.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),Lt.useEffect(()=>{s.values&&!e3(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]),Lt.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=V3t(r,i),t.current}const jat=(s,t,n)=>{if(s&&"reportValidity"in s){const r=yi(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},J3t=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?jat(r.ref,n,s):r.refs&&r.refs.forEach(a=>jat(a,n,s))}},Wws=(s,t)=>{t.shouldUseNativeValidation&&J3t(s,t);const n={};for(const r in s){const a=yi(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(Kws(t.names||Object.keys(s),r)){const l=Object.assign({},yi(n,r));Bu(l,"root",i),Bu(n,r,l)}else Bu(n,r,i)}return n},Kws=(s,t)=>s.some(n=>n.startsWith(t+"."));var Yws=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]=G3t(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},O3e=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&&J3t({},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:Wws(Yws(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};const F3e=Tws,eCt=j.createContext({}),Np=({...s})=>e.jsx(eCt.Provider,{value:{name:s.name},children:e.jsx(Pws,{...s})}),z3e=()=>{const s=j.useContext(eCt),t=j.useContext(tCt),{getFieldState:n,formState:r}=R3e(),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}},tCt=j.createContext({}),Bm=j.forwardRef(({className:s,...t},n)=>{const r=j.useId();return e.jsx(tCt.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Et("space-y-2",s),...t})})});Bm.displayName="FormItem";const $m=j.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=z3e();return e.jsx(se,{ref:n,className:Et(r&&"text-destructive",s),htmlFor:a,...t})});$m.displayName="FormLabel";const Um=j.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=z3e();return e.jsx(dUe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});Um.displayName="FormControl";const kje=j.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=z3e();return e.jsx("p",{ref:n,id:r,className:Et("text-sm text-muted-foreground",s),...t})});kje.displayName="FormDescription";const Kv=j.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=z3e(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:r,id:i,className:Et("text-sm font-medium text-destructive",s),...n,children:l}):null});Kv.displayName="FormMessage";const Zws=iS({category:_qe(["general","technology","crm","marketing"]),subject:Cl().min(5,"Subject must be at least 5 characters").max(200),description:Cl().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),Xws={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function EOe({trigger:s}){const[t,n]=j.useState(!1),[r,a]=j.useState(!1),{user:i}=Ns(),l=D3e({resolver:O3e(Zws),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){re.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await U.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await U.functions.invoke("support-ticket-notify",{body:{category:Xws[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}re.success("Support ticket submitted successfully!"),l.reset(),n(!1)}catch(d){console.error("Error submitting ticket:",d),re.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(Fs,{open:t,onOpenChange:n,children:[e.jsx(Io,{asChild:!0,children:s||e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(Y9,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(Os,{className:"sm:max-w-[500px]",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Need Help?"}),e.jsx(kr,{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(pa,{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(F3e,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(Np,{control:l.control,name:"category",render:({field:c})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Category"}),e.jsxs(vs,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(Um,{children:e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a category"})})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"general",children:"General Support"}),e.jsx(Je,{value:"technology",children:"Technology Support"}),e.jsx(Je,{value:"crm",children:"CRM Support"}),e.jsx(Je,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(Kv,{})]})}),e.jsx(Np,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Subject"}),e.jsx(Um,{children:e.jsx(ye,{placeholder:"Brief description of your issue",...c})}),e.jsx(Kv,{})]})}),e.jsx(Np,{control:l.control,name:"description",render:({field:c})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Description"}),e.jsx(Um,{children:e.jsx(Ds,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(Kv,{})]})}),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 Qws=()=>{const{user:s}=Ns(),t=Hn(),[n,r]=j.useState([]),[a,i]=j.useState(0),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=j.useRef(null);j.useEffect(()=>{u.current=c},[c]),j.useEffect(()=>{if(!s)return;const y=`notification_last_read_${s.id}`,g=localStorage.getItem(y);g&&!u.current&&(u.current=g,d(g));const b=`nb_cache_${s.id}`,v=60*1e3,k=async()=>{try{const L=sessionStorage.getItem(b);if(L){const I=JSON.parse(L);if(I.ts&&Date.now()-I.ts{r(M);const P=u.current?new Date(u.current):null,L=M.filter(I=>P?new Date(I.created_at)>P:!0);i(L.length)};k();const T=U.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},M=>{const P=M.new;r(I=>{const O=[P,...I].slice(0,20);try{sessionStorage.setItem(b,JSON.stringify({ts:Date.now(),data:O}))}catch{}return O});const L=u.current?new Date(u.current):null;(!L||new Date(P.created_at)>L)&&i(I=>I+1),Notification.permission==="granted"&&new Notification(P.title,{body:P.body,icon:"/favicon.ico"})}).subscribe();return()=>{U.removeChannel(T)}},[s]);const h=y=>{const g=y.toLowerCase();return g.includes("community")||g.includes("post")?ro:g.includes("academy")||g.includes("video")?Zr:g.includes("template")?Ac:g.includes("event")?ra:g.includes("newsletter")?V_:g.includes("brokerage")?kx:g.includes("swag")||g.includes("social")?zo:g.includes("toolbox")||g.includes("tool")?O5:g.includes("brief")?yn:ro},m=y=>{o(!1),y.url&&y.url!=="/"&&t(y.url)},p=()=>{if(!s)return;const y=new Date().toISOString(),g=`notification_last_read_${s.id}`;localStorage.setItem(g,y),d(y),i(0)},x=y=>{o(y),y&&a>0&&p()};return e.jsxs(kd,{open:l,onOpenChange:x,children:[e.jsx(Sd,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(Nx,{className:"h-5 w-5"}),a>0&&e.jsx(qe,{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(xd,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),n.length>0&&e.jsx(B,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:p,children:"Mark all read"})]}),e.jsx(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 g=h(y.title);return e.jsxs(wa,{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(g,{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:oc(new Date(y.created_at),{addSuffix:!0})})]})]},y.id)})})]})]})};var Nat=1,Jws=.9,ejs=.8,tjs=.17,ZMe=.1,XMe=.999,sjs=.9999,njs=.99,rjs=/[\\\/_+.#"@\[\(\{&]/,ajs=/[\\\/_+.#"@\[\(\{&]/g,ijs=/[\s-]/,sCt=/[\s-]/g;function MOe(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?Nat:njs;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=r.charAt(i),d=n.indexOf(c,a),u=0,h,m,p,x;d>=0;)h=MOe(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=Nat:rjs.test(s.charAt(d-1))?(h*=ejs,p=s.slice(a,d-1).match(ajs),p&&a>0&&(h*=Math.pow(XMe,p.length))):ijs.test(s.charAt(d-1))?(h*=Jws,x=s.slice(a,d-1).match(sCt),x&&a>0&&(h*=Math.pow(XMe,x.length))):(h*=tjs,a>0&&(h*=Math.pow(XMe,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=sjs)),(hh&&(h=m*ZMe)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function kat(s){return s.toLowerCase().replace(sCt," ")}function ojs(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,MOe(s,t,kat(s),kat(t),0,0,{})}var bH='[cmdk-group=""]',QMe='[cmdk-group-items=""]',ljs='[cmdk-group-heading=""]',nCt='[cmdk-item=""]',Sat=`${nCt}:not([aria-disabled="true"])`,LOe="cmdk-item-select",T7="data-value",cjs=(s,t,n)=>ojs(s,t,n),rCt=j.createContext(void 0),kJ=()=>j.useContext(rCt),aCt=j.createContext(void 0),xVe=()=>j.useContext(aCt),iCt=j.createContext(void 0),oCt=j.forwardRef((s,t)=>{let n=E7(()=>{var de,we;return{search:"",value:(we=(de=s.value)!=null?de:s.defaultValue)!=null?we:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=E7(()=>new Set),a=E7(()=>new Map),i=E7(()=>new Map),l=E7(()=>new Set),o=lCt(s),{label:c,children:d,value:u,onValueChange:h,filter:m,shouldFilter:p,loop:x,disablePointerSelection:y=!1,vimBindings:g=!0,...b}=s,v=Cx(),k=Cx(),C=Cx(),T=j.useRef(null),M=bjs();MD(()=>{if(u!==void 0){let de=u.trim();n.current.value=de,P.emit()}},[u]),MD(()=>{M(6,W)},[]);let P=j.useMemo(()=>({subscribe:de=>(l.current.add(de),()=>l.current.delete(de)),snapshot:()=>n.current,setState:(de,we,je)=>{var xe,fe,Se,Ee;if(!Object.is(n.current[de],we)){if(n.current[de]=we,de==="search")q(),O(),M(1,$);else if(de==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Le=document.getElementById(C);Le?Le.focus():(xe=document.getElementById(v))==null||xe.focus()}if(M(7,()=>{var Le;n.current.selectedItemId=(Le=G())==null?void 0:Le.id,P.emit()}),je||M(5,W),((fe=o.current)==null?void 0:fe.value)!==void 0){let Le=we??"";(Ee=(Se=o.current).onValueChange)==null||Ee.call(Se,Le);return}}P.emit()}},emit:()=>{l.current.forEach(de=>de())}}),[]),L=j.useMemo(()=>({value:(de,we,je)=>{var xe;we!==((xe=i.current.get(de))==null?void 0:xe.value)&&(i.current.set(de,{value:we,keywords:je}),n.current.filtered.items.set(de,I(we,je)),M(2,()=>{O(),P.emit()}))},item:(de,we)=>(r.current.add(de),we&&(a.current.has(we)?a.current.get(we).add(de):a.current.set(we,new Set([de]))),M(3,()=>{q(),O(),n.current.value||$(),P.emit()}),()=>{i.current.delete(de),r.current.delete(de),n.current.filtered.items.delete(de);let je=G();M(4,()=>{q(),(je==null?void 0:je.getAttribute("id"))===de&&$(),P.emit()})}),group:de=>(a.current.has(de)||a.current.set(de,new Set),()=>{i.current.delete(de),a.current.delete(de)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:v,inputId:C,labelId:k,listInnerRef:T}),[]);function I(de,we){var je,xe;let fe=(xe=(je=o.current)==null?void 0:je.filter)!=null?xe:cjs;return de?fe(de,n.current.search,we):0}function O(){if(!n.current.search||o.current.shouldFilter===!1)return;let de=n.current.filtered.items,we=[];n.current.filtered.groups.forEach(xe=>{let fe=a.current.get(xe),Se=0;fe.forEach(Ee=>{let Le=de.get(Ee);Se=Math.max(Le,Se)}),we.push([xe,Se])});let je=T.current;K().sort((xe,fe)=>{var Se,Ee;let Le=xe.getAttribute("id"),De=fe.getAttribute("id");return((Se=de.get(De))!=null?Se:0)-((Ee=de.get(Le))!=null?Ee:0)}).forEach(xe=>{let fe=xe.closest(QMe);fe?fe.appendChild(xe.parentElement===fe?xe:xe.closest(`${QMe} > *`)):je.appendChild(xe.parentElement===je?xe:xe.closest(`${QMe} > *`))}),we.sort((xe,fe)=>fe[1]-xe[1]).forEach(xe=>{var fe;let Se=(fe=T.current)==null?void 0:fe.querySelector(`${bH}[${T7}="${encodeURIComponent(xe[0])}"]`);Se==null||Se.parentElement.appendChild(Se)})}function $(){let de=K().find(je=>je.getAttribute("aria-disabled")!=="true"),we=de==null?void 0:de.getAttribute(T7);P.setState("value",we||void 0)}function q(){var de,we,je,xe;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let fe=0;for(let Se of r.current){let Ee=(we=(de=i.current.get(Se))==null?void 0:de.value)!=null?we:"",Le=(xe=(je=i.current.get(Se))==null?void 0:je.keywords)!=null?xe:[],De=I(Ee,Le);n.current.filtered.items.set(Se,De),De>0&&fe++}for(let[Se,Ee]of a.current)for(let Le of Ee)if(n.current.filtered.items.get(Le)>0){n.current.filtered.groups.add(Se);break}n.current.filtered.count=fe}function W(){var de,we,je;let xe=G();xe&&(((de=xe.parentElement)==null?void 0:de.firstChild)===xe&&((je=(we=xe.closest(bH))==null?void 0:we.querySelector(ljs))==null||je.scrollIntoView({block:"nearest"})),xe.scrollIntoView({block:"nearest"}))}function G(){var de;return(de=T.current)==null?void 0:de.querySelector(`${nCt}[aria-selected="true"]`)}function K(){var de;return Array.from(((de=T.current)==null?void 0:de.querySelectorAll(Sat))||[])}function ee(de){let we=K()[de];we&&P.setState("value",we.getAttribute(T7))}function J(de){var we;let je=G(),xe=K(),fe=xe.findIndex(Ee=>Ee===je),Se=xe[fe+de];(we=o.current)!=null&&we.loop&&(Se=fe+de<0?xe[xe.length-1]:fe+de===xe.length?xe[0]:xe[fe+de]),Se&&P.setState("value",Se.getAttribute(T7))}function le(de){let we=G(),je=we==null?void 0:we.closest(bH),xe;for(;je&&!xe;)je=de>0?yjs(je,bH):vjs(je,bH),xe=je==null?void 0:je.querySelector(Sat);xe?P.setState("value",xe.getAttribute(T7)):J(de)}let ue=()=>ee(K().length-1),oe=de=>{de.preventDefault(),de.metaKey?ue():de.altKey?le(1):J(1)},ie=de=>{de.preventDefault(),de.metaKey?ee(0):de.altKey?le(-1):J(-1)};return j.createElement(Ua.div,{ref:t,tabIndex:-1,...b,"cmdk-root":"",onKeyDown:de=>{var we;(we=b.onKeyDown)==null||we.call(b,de);let je=de.nativeEvent.isComposing||de.keyCode===229;if(!(de.defaultPrevented||je))switch(de.key){case"n":case"j":{g&&de.ctrlKey&&oe(de);break}case"ArrowDown":{oe(de);break}case"p":case"k":{g&&de.ctrlKey&&ie(de);break}case"ArrowUp":{ie(de);break}case"Home":{de.preventDefault(),ee(0);break}case"End":{de.preventDefault(),ue();break}case"Enter":{de.preventDefault();let xe=G();if(xe){let fe=new Event(LOe);xe.dispatchEvent(fe)}}}}},j.createElement("label",{"cmdk-label":"",htmlFor:L.inputId,id:L.labelId,style:wjs},c),B3e(s,de=>j.createElement(aCt.Provider,{value:P},j.createElement(rCt.Provider,{value:L},de))))}),djs=j.forwardRef((s,t)=>{var n,r;let a=Cx(),i=j.useRef(null),l=j.useContext(iCt),o=kJ(),c=lCt(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;MD(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=cCt(a,i,[s.value,s.children,i],s.keywords),h=xVe(),m=PE(M=>M.value&&M.value===u.current),p=PE(M=>d||o.filter()===!1?!0:M.search?M.filtered.items.get(a)>0:!0);j.useEffect(()=>{let M=i.current;if(!(!M||s.disabled))return M.addEventListener(LOe,x),()=>M.removeEventListener(LOe,x)},[p,s.onSelect,s.disabled]);function x(){var M,P;y(),(P=(M=c.current).onSelect)==null||P.call(M,u.current)}function y(){h.setState("value",u.current,!0)}if(!p)return null;let{disabled:g,value:b,onSelect:v,forceMount:k,keywords:C,...T}=s;return j.createElement(Ua.div,{ref:O3(i,t),...T,id:a,"cmdk-item":"",role:"option","aria-disabled":!!g,"aria-selected":!!m,"data-disabled":!!g,"data-selected":!!m,onPointerMove:g||o.getDisablePointerSelection()?void 0:y,onClick:g?void 0:x},s.children)}),ujs=j.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=Cx(),o=j.useRef(null),c=j.useRef(null),d=Cx(),u=kJ(),h=PE(p=>a||u.filter()===!1?!0:p.search?p.filtered.groups.has(l):!0);MD(()=>u.group(l),[]),cCt(l,o,[s.value,s.heading,c]);let m=j.useMemo(()=>({id:l,forceMount:a}),[a]);return j.createElement(Ua.div,{ref:O3(o,t),...i,"cmdk-group":"",role:"presentation",hidden:h?void 0:!0},n&&j.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),B3e(s,p=>j.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},j.createElement(iCt.Provider,{value:m},p))))}),hjs=j.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=j.useRef(null),i=PE(l=>!l.search);return!n&&!i?null:j.createElement(Ua.div,{ref:O3(a,t),...r,"cmdk-separator":"",role:"separator"})}),mjs=j.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=xVe(),l=PE(d=>d.search),o=PE(d=>d.selectedItemId),c=kJ();return j.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),j.createElement(Ua.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)}})}),pjs=j.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=j.useRef(null),l=j.useRef(null),o=PE(d=>d.selectedItemId),c=kJ();return j.useEffect(()=>{if(l.current&&i.current){let d=l.current,u=i.current,h,m=new ResizeObserver(()=>{h=requestAnimationFrame(()=>{let p=d.offsetHeight;u.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return m.observe(d),()=>{cancelAnimationFrame(h),m.unobserve(d)}}},[]),j.createElement(Ua.div,{ref:O3(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},B3e(s,d=>j.createElement("div",{ref:O3(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),fjs=j.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return j.createElement(I4e,{open:n,onOpenChange:r},j.createElement(R4e,{container:l},j.createElement(IU,{"cmdk-overlay":"",className:a}),j.createElement(RU,{"aria-label":s.label,"cmdk-dialog":"",className:i},j.createElement(oCt,{ref:t,...o}))))}),xjs=j.forwardRef((s,t)=>PE(n=>n.filtered.count===0)?j.createElement(Ua.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),gjs=j.forwardRef((s,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=s;return j.createElement(Ua.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},B3e(s,l=>j.createElement("div",{"aria-hidden":!0},l)))}),Ib=Object.assign(oCt,{List:pjs,Item:djs,Input:mjs,Group:ujs,Separator:hjs,Dialog:fjs,Empty:xjs,Loading:gjs});function yjs(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function vjs(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function lCt(s){let t=j.useRef(s);return MD(()=>{t.current=s}),t}var MD=typeof window>"u"?j.useEffect:j.useLayoutEffect;function E7(s){let t=j.useRef();return t.current===void 0&&(t.current=s()),t}function PE(s){let t=xVe(),n=()=>s(t.snapshot());return j.useSyncExternalStore(t.subscribe,n,n)}function cCt(s,t,n,r=[]){let a=j.useRef(),i=kJ();return MD(()=>{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(T7,o),a.current=o}),a}var bjs=()=>{let[s,t]=j.useState(),n=E7(()=>new Map);return MD(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function _js(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function B3e({asChild:s,children:t},n){return s&&j.isValidElement(t)?j.cloneElement(_js(t),{ref:t.ref},n(t.props.children)):n(t)}var wjs={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Sb=j.forwardRef(({className:s,...t},n)=>e.jsx(Ib,{ref:n,className:Et("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));Sb.displayName=Ib.displayName;const jjs=({children:s,...t})=>e.jsx(Fs,{...t,children:e.jsx(Os,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(Sb,{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})})}),Cb=j.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Fr,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(Ib.Input,{ref:n,className:Et("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})]}));Cb.displayName=Ib.Input.displayName;const Ab=j.forwardRef(({className:s,...t},n)=>e.jsx(Ib.List,{ref:n,className:Et("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));Ab.displayName=Ib.List.displayName;const Tb=j.forwardRef((s,t)=>e.jsx(Ib.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));Tb.displayName=Ib.Empty.displayName;const Eb=j.forwardRef(({className:s,...t},n)=>e.jsx(Ib.Group,{ref:n,className:Et("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}));Eb.displayName=Ib.Group.displayName;const Njs=j.forwardRef(({className:s,...t},n)=>e.jsx(Ib.Separator,{ref:n,className:Et("-mx-1 h-px bg-border",s),...t}));Njs.displayName=Ib.Separator.displayName;const Yy=j.forwardRef(({className:s,...t},n)=>e.jsx(Ib.Item,{ref:n,className:Et("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}));Yy.displayName=Ib.Item.displayName;const kjs={event:{label:"Events",icon:Vc,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:Ac,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:Uh,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:O5,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:yn,color:"bg-fuchsia-500/10 text-fuchsia-600"}},Cat=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(""),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=Hn();j.useEffect(()=>{const m=p=>{p.key==="k"&&(p.metaKey||p.ctrlKey)&&(p.preventDefault(),t(x=>!x))};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[]);const d=j.useCallback(async m=>{if(!m.trim()){i([]);return}o(!0);const p=`%${m}%`;try{const[x,y,g,b,v]=await Promise.all([U.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${p},description.ilike.${p}`).limit(5),U.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${p},description.ilike.${p}`).limit(5),U.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${p},description.ilike.${p}`).limit(5),U.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${p},description.ilike.${p}`).limit(5),U.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${p},description.ilike.${p}`).limit(5)]),k=[];x.data&&x.data.forEach(C=>{k.push({id:C.id,title:C.title,description:C.description,type:"event",date:C.event_date,path:`/event/${C.id}`})}),y.data&&y.data.forEach(C=>{k.push({id:C.id,title:C.name,description:C.description,type:"template",date:C.publish_date,path:`/templates/${C.id}`})}),g.data&&g.data.forEach(C=>{k.push({id:C.id,title:C.title,description:C.description,type:"academy",date:C.publish_date,path:`/academy/${C.id}`})}),b.data&&b.data.forEach(C=>{k.push({id:C.id,title:C.name,description:C.description,type:"toolbox",date:C.publish_date,path:`/toolbox/${C.id}`})}),v.data&&v.data.forEach(C=>{k.push({id:C.id,title:C.title,description:C.description,type:"social-swag",date:C.publish_date,path:`/social-swag/${C.id}`})}),i(k)}catch(x){console.error("Search error:",x)}finally{o(!1)}},[]);j.useEffect(()=>{const m=setTimeout(()=>{d(n)},300);return()=>clearTimeout(m)},[n,d]);const u=m=>{t(!1),r(""),c(m)},h=a.reduce((m,p)=>(m[p.type]||(m[p.type]=[]),m[p.type].push(p),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(Fr,{className:"h-4 w-4 xl:mr-2"}),e.jsx("span",{className:"hidden xl:inline-flex text-muted-foreground text-sm",children:"Search..."}),e.jsxs("kbd",{className:"pointer-events-none absolute right-1.5 top-1.5 hidden h-6 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 xl:flex",children:[e.jsx("span",{className:"text-xs",children:"⌘"}),"K"]})]}),e.jsxs(jjs,{open:s,onOpenChange:t,children:[e.jsx(Cb,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(Ab,{children:[l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&e.jsxs(Tb,{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,p])=>{const x=kjs[m],y=x.icon;return e.jsx(Eb,{heading:x.label,children:p.map(g=>e.jsxs(Yy,{value:`${g.type}-${g.id}-${g.title}`,onSelect:()=>u(g.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${x.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:g.title}),g.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:g.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(qe,{variant:"secondary",className:"text-xs",children:x.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:oc(new Date(g.date),{addSuffix:!0})})]})]},`${g.type}-${g.id}`))},m)})]})]})]})},Sjs=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=j.useState(null),i=Hn();if(j.useEffect(()=>{const d=()=>{const h=new Date().getTime(),p=new Date(s).getTime()-h;if(p<=0){a({days:0,hours:0,minutes:0});return}const x=Math.floor(p/(1e3*60*60*24)),y=Math.floor(p%(1e3*60*60*24)/(1e3*60*60)),g=Math.floor(p%(1e3*60*60)/(1e3*60));a({days:x,hours:y,minutes:g})};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:Et("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(hd,{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(yn,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:Et("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(Vr,{className:Et("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:Et("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:Et("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),e.jsxs("span",{className:Et("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),e.jsxs("span",{className:Et("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),e.jsx("span",{className:Et("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:Et("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(yn,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},Cjs=()=>{const s=Hn();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(be,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(Ft,{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(hd,{className:"h-8 w-8 text-destructive"})}),e.jsx(Ut,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(fr,{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(Re,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(be,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Re,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Bn,{className:"h-6 w-6 text-primary"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),e.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),e.jsxs(B,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(be,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Re,{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(Ni,{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(Ni,{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(pa,{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(on,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},Ajs=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(Cu,{children:[e.jsx(Au,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"icon",onClick:t,className:Et("relative transition-colors",s&&"text-primary hover:text-primary",n),children:[e.jsx(jh,{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(ou,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var gVe="Radio",[Tjs,dCt]=Zm(gVe),[Ejs,Mjs]=Tjs(gVe),uCt=j.forwardRef((s,t)=>{const{__scopeRadio:n,name:r,checked:a=!1,required:i,disabled:l,value:o="on",onCheck:c,form:d,...u}=s,[h,m]=j.useState(null),p=ko(t,g=>m(g)),x=j.useRef(!1),y=h?d||!!h.closest("form"):!0;return e.jsxs(Ejs,{scope:n,checked:a,disabled:l,children:[e.jsx(Ua.button,{type:"button",role:"radio","aria-checked":a,"data-state":fCt(a),"data-disabled":l?"":void 0,disabled:l,value:o,...u,ref:p,onClick:ua(s.onClick,g=>{a||c==null||c(),y&&(x.current=g.isPropagationStopped(),x.current||g.stopPropagation())})}),y&&e.jsx(pCt,{control:h,bubbles:!x.current,name:r,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});uCt.displayName=gVe;var hCt="RadioIndicator",mCt=j.forwardRef((s,t)=>{const{__scopeRadio:n,forceMount:r,...a}=s,i=Mjs(hCt,n);return e.jsx(ax,{present:r||i.checked,children:e.jsx(Ua.span,{"data-state":fCt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});mCt.displayName=hCt;var Ljs="RadioBubbleInput",pCt=j.forwardRef(({__scopeRadio:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=j.useRef(null),o=ko(l,i),c=xJ(n),d=iJ(t);return j.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&p){const x=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(x)}},[c,n,r]),e.jsx(Ua.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}})});pCt.displayName=Ljs;function fCt(s){return s?"checked":"unchecked"}var Pjs=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],$3e="RadioGroup",[Ijs,NBn]=Zm($3e,[QE,dCt]),xCt=QE(),gCt=dCt(),[Rjs,Djs]=Ijs($3e),yCt=j.forwardRef((s,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:a,value:i,required:l=!1,disabled:o=!1,orientation:c,dir:d,loop:u=!0,onValueChange:h,...m}=s,p=xCt(n),x=J3(d),[y,g]=Mx({prop:i,defaultProp:a??null,onChange:h,caller:$3e});return e.jsx(Rjs,{scope:n,name:r,required:l,disabled:o,value:y,onValueChange:g,children:e.jsx(e3e,{asChild:!0,...p,orientation:c,dir:x,loop:u,children:e.jsx(Ua.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:x,...m,ref:t})})})});yCt.displayName=$3e;var vCt="RadioGroupItem",bCt=j.forwardRef((s,t)=>{const{__scopeRadioGroup:n,disabled:r,...a}=s,i=Djs(vCt,n),l=i.disabled||r,o=xCt(n),c=gCt(n),d=j.useRef(null),u=ko(t,d),h=i.value===a.value,m=j.useRef(!1);return j.useEffect(()=>{const p=y=>{Pjs.includes(y.key)&&(m.current=!0)},x=()=>m.current=!1;return document.addEventListener("keydown",p),document.addEventListener("keyup",x),()=>{document.removeEventListener("keydown",p),document.removeEventListener("keyup",x)}},[]),e.jsx(t3e,{asChild:!0,...o,focusable:!l,active:h,children:e.jsx(uCt,{disabled:l,required:i.required,checked:h,...c,...a,name:i.name,ref:u,onCheck:()=>i.onValueChange(a.value),onKeyDown:ua(p=>{p.key==="Enter"&&p.preventDefault()}),onFocus:ua(a.onFocus,()=>{var p;m.current&&((p=d.current)==null||p.click())})})})});bCt.displayName=vCt;var Ojs="RadioGroupIndicator",_Ct=j.forwardRef((s,t)=>{const{__scopeRadioGroup:n,...r}=s,a=gCt(n);return e.jsx(mCt,{...a,...r,ref:t})});_Ct.displayName=Ojs;var wCt=yCt,jCt=bCt,Fjs=_Ct;const ob=j.forwardRef(({className:s,...t},n)=>e.jsx(wCt,{className:Et("grid gap-2",s),...t,ref:n}));ob.displayName=wCt.displayName;const eh=j.forwardRef(({className:s,...t},n)=>e.jsx(jCt,{ref:n,className:Et("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(Fjs,{className:"flex items-center justify-center",children:e.jsx(Sx,{className:"h-2.5 w-2.5 fill-current text-current"})})}));eh.displayName=jCt.displayName;const zjs=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=Ns(),[i,l]=j.useState({}),[o,c]=j.useState({}),[d,u]=j.useState([]);j.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const g=s.polls.map(v=>v.id),{data:b}=await U.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",g);if(b){const v={};b.forEach(k=>{v[k.poll_id]||(v[k.poll_id]=[]),v[k.poll_id].push(k.option_id)}),c(v)}},m=(g,b)=>{l(v=>({...v,[g]:b}))},p=(g,b,v)=>{l(k=>{const C=k[g]||[];return v?{...k,[g]:[...C,b]}:{...k,[g]:C.filter(T=>T!==b)}})},x=async g=>{if(!a)return;const b=i[g];if(!b||Array.isArray(b)&&b.length===0){re.error("Please select an option");return}u(v=>[...v,g]);try{await U.from("levelup_brief_poll_responses").delete().eq("poll_id",g).eq("user_id",a.id);const v=Array.isArray(b)?b:[b],k=v.map(T=>({poll_id:g,option_id:T,user_id:a.id})),{error:C}=await U.from("levelup_brief_poll_responses").insert(k);if(C)throw C;c(T=>({...T,[g]:v})),re.success("Response submitted!")}catch(v){console.error("Error submitting poll response:",v),re.error("Failed to submit response")}finally{u(v=>v.filter(k=>k!==g))}},y=g=>(g.includes("mediadelivery.net")||g.includes("bunny"),g);return e.jsx(Fs,{open:t,onOpenChange:g=>!g&&n(),children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[e.jsx("button",{onClick:n,className:"absolute top-3 right-3 p-1.5 rounded-full bg-white/30 hover:bg-white/50 transition-colors","aria-label":"Close",children:e.jsx(dr,{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(jh,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(qe,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx(zs,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(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(g=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(g.url,"_blank"),className:"gap-2",children:[e.jsx(Tr,{className:"h-4 w-4"}),g.title]},g.id))})]}),s.polls.map(g=>{var k,C;const b=((k=o[g.id])==null?void 0:k.length)>0,v=d.includes(g.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:g.question}),b&&e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Rr,{className:"h-3 w-3"}),"Responded"]})]}),g.poll_type==="single"?e.jsx(ob,{value:i[g.id]||((C=o[g.id])==null?void 0:C[0])||"",onValueChange:T=>m(g.id,T),className:"space-y-2",children:g.options.map(T=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:T.id,id:T.id}),e.jsx(se,{htmlFor:T.id,className:"cursor-pointer",children:T.option_text})]},T.id))}):e.jsx("div",{className:"space-y-2",children:g.options.map(T=>{const P=(i[g.id]||o[g.id]||[]).includes(T.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(wi,{id:T.id,checked:P,onCheckedChange:L=>p(g.id,T.id,L)}),e.jsx(se,{htmlFor:T.id,className:"cursor-pointer",children:T.option_text})]},T.id)})}),e.jsx(B,{size:"sm",onClick:()=>x(g.id),disabled:v,children:v?"Submitting...":b?"Update Response":"Submit"})]},g.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"})]})]})})},Bjs=()=>{const{user:s}=Ns(),[t,n]=j.useState(null),[r,a]=j.useState(!1),[i,l]=j.useState(!0),[o,c]=j.useState(!1),d=j.useCallback(async()=>{if(!s){l(!1);return}try{const{data:x,error:y}=await U.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(y||!x){l(!1);return}const{data:g}=await U.from("levelup_brief_views").select("*").eq("brief_id",x.id).eq("user_id",s.id).maybeSingle(),[b,v]=await Promise.all([U.from("levelup_brief_links").select("*").eq("brief_id",x.id).order("sort_order"),U.from("levelup_brief_polls").select("*").eq("brief_id",x.id).order("sort_order")]),k=[];if(v.data)for(const L of v.data){const{data:I}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",L.id).order("sort_order");k.push({...L,options:I||[]})}const C={brief:x,links:b.data||[],polls:k};n(C);const T=!!g,M=(g==null?void 0:g.dismissed_at)!=null,P=localStorage.getItem(`brief-dismissed-${x.id}`)==="true";if(M||P)c(!1),a(!1);else if(!T)a(!0),c(!0);else if(x.show_frequency==="every_login")a(!0),c(!0);else if(x.show_frequency==="daily"){const L=new Date(g.viewed_at);(new Date().getTime()-L.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(x){console.error("Error fetching brief:",x)}finally{l(!1)}},[s]);j.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:x}=await U.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();x?await U.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",x.id):await U.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(x){console.error("Error marking brief as viewed:",x)}};return{currentBrief:t,shouldShowPopup:r,hasUnseenBrief:o,loading:i,openBrief:()=>{a(!0)},closeBrief:()=>{a(!1),u()},dismissBrief:async()=>{if(!(!s||!t)){a(!1),c(!1);try{const{data:x,error:y}=await U.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),x){const{error:g}=await U.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",x.id).eq("user_id",s.id);g&&console.error("Error updating brief dismiss:",g)}else{const{error:g}=await U.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});g&&console.error("Error inserting brief dismiss:",g)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(x){console.error("Error dismissing brief:",x),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function $js(){const[s,t]=j.useState(!1),[n,r]=j.useState(!1),[a,i]=j.useState(null);j.useEffect(()=>{if(localStorage.getItem("install-banner-dismissed")||window.matchMedia("(display-mode: standalone)").matches||!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const h=/iPhone|iPad|iPod/i.test(navigator.userAgent);r(h),t(!0);const m=p=>{p.preventDefault(),i(p)};return window.addEventListener("beforeinstallprompt",m),()=>{window.removeEventListener("beforeinstallprompt",m)}},[]);const l=()=>{localStorage.setItem("install-banner-dismissed","true"),t(!1)},o=async()=>{if(a){await a.prompt();const{outcome:c}=await a.userChoice;c==="accepted"&&l(),i(null)}};return s?e.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-50 p-4 bg-primary text-primary-foreground shadow-lg animate-in slide-in-from-bottom duration-300",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"flex-shrink-0 p-2 bg-primary-foreground/10 rounded-full",children:e.jsx(ii,{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(aK,{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(dr,{className:"h-4 w-4"})})]})]})}):null}const Ujs=({children:s,onRefresh:t})=>{const[n,r]=j.useState(!1),[a,i]=j.useState(0),[l,o]=j.useState(!1),c=j.useRef(null),d=j.useRef(0),u=as(),h=80,m=120,p=j.useCallback(v=>{const k=c.current;k&&k.scrollTop<=0&&(d.current=v.touches[0].clientY,r(!0))},[]),x=j.useCallback(v=>{if(!n||l)return;const k=c.current;if(!k||k.scrollTop>0){r(!1),i(0);return}const T=v.touches[0].clientY-d.current;if(T>0){const P=Math.min(T*.5,m);i(P),P>10&&v.preventDefault()}},[n,l]),y=j.useCallback(async()=>{if(n)if(r(!1),a>=h&&!l){o(!0),i(h);try{t?await t():await u.invalidateQueries()}catch(v){console.error("Refresh failed:",v)}finally{o(!1),i(0)}}else i(0)},[n,a,l,t,u]),g=Math.min(a/h,1),b=g*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:p,onTouchMove:x,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:g},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${b}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(Ki,{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})]})},NCt=()=>{const{user:s}=Ns(),[t,n]=j.useState(!1),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(!0);j.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:p}=await U.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(p){a(!0),n(!1),c(!1);return}const{data:x}=await U.from("profiles").select("login_count").eq("id",s.id).single(),y=(x==null?void 0:x.login_count)||0;l(y);const g=sessionStorage.getItem("review-prompt-dismissed");n(y>=4&&!g)}catch(p){console.error("Error checking review eligibility:",p)}finally{c(!1)}})()},[s]);const d=j.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),n(!1)},[]),u=j.useCallback(async(m,p)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:x}=await U.from("membership_reviews").insert({user_id:s.id,rating:m,review_text:p});if(x)throw x;return a(!0),n(!1),{success:!0,pointsAwarded:25}}catch(x){return console.error("Error submitting review:",x),{success:!1,error:x.message}}},[s]),h=j.useCallback(async()=>{if(s)try{await U.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(m){console.error("Error updating Google review status:",m)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:r,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:u,markPostedToGoogle:h}},qjs="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",Vjs=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=NCt(),[i,l]=j.useState(!1),[o,c]=j.useState("review"),[d,u]=j.useState(0),[h,m]=j.useState(0),[p,x]=j.useState(""),[y,g]=j.useState(!1),[b,v]=j.useState(!1);if(t||!s&&!b)return null;const k=async()=>{if(d===0){ba({title:"Please select a rating",variant:"destructive"});return}g(!0);const M=await r(d,p);g(!1),M.success?(v(!0),ba({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):ba({title:"Error submitting review",description:M.error,variant:"destructive"})},C=async M=>{M&&(await navigator.clipboard.writeText(p||`${d} star rating for LevelUp!`),ba({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(qjs,"_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(Fs,{open:i,onOpenChange:T,children:e.jsx(Os,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs($s,{children:[e.jsx(zs,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(kr,{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(M=>e.jsx("button",{type:"button",onClick:()=>u(M),onMouseEnter:()=>m(M),onMouseLeave:()=>m(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(Wa,{className:Et("h-8 w-8 transition-colors",(h||d)>=M?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},M))}),e.jsx(Ds,{placeholder:"Tell us about your experience (optional)",value:p,onChange:M=>x(M.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($s,{children:[e.jsx(zs,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(kr,{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:()=>C(!1),className:"flex-1",children:"No Thanks"}),e.jsx(B,{onClick:()=>C(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function Hjs(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 g=localStorage.getItem(y);if(!g){const{data:k,error:C}=await U.functions.invoke("get-vapid-public-key",{body:{}});if(C)throw C;if(g=(k==null?void 0:k.vapidPublicKey)??null,!g)throw new Error("Missing VAPID public key");localStorage.setItem(y,g)}u(g);const b=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(b),n(Notification.permission);const v=await b.pushManager.getSubscription();a(!!v)}catch(y){console.error("Error initializing push notifications:",y)}finally{l(!1)}})()},[h]);const m=j.useCallback(async()=>{if(!h||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return re.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const x=await o.pushManager.getSubscription();if(x){try{await x.unsubscribe()}catch(C){console.warn("Failed to unsubscribe existing push subscription:",C)}const{error:k}=await U.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"?re.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):re.error("Notification permission was dismissed. Please try again."),!1}const y=Hjs(d);let g;try{g=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:y})}catch(k){console.error("PushManager.subscribe() failed:",k);const C=(k==null?void 0:k.message)||String(k);return C.includes("permission")?re.error("Push permission denied. Check your browser notification settings."):C.includes("key")||C.includes("VAPID")?re.error("Push configuration error. Please contact support."):C.includes("AbortError")?re.error("Push subscription was cancelled. Please try again."):re.error(`Failed to subscribe: ${C}`),!1}const b=g.toJSON(),{error:v}=await U.from("push_subscriptions").upsert({user_id:s.id,endpoint:b.endpoint,p256dh_key:b.keys.p256dh,auth_key:b.keys.auth},{onConflict:"user_id,endpoint"});if(v)throw console.error("Error saving subscription:",v),re.error("Failed to save notification preferences. Please try again."),v;return a(!0),re.success("Push notifications enabled!"),!0}catch(x){if(console.error("Error subscribing to push notifications:",x),!(x instanceof Error&&x.message.includes("toast"))){const y=x instanceof Error?x.message:"Unknown error";re.error("Failed to enable push notifications: "+y)}return!1}finally{l(!1)}},[h,o,s,d]),p=j.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const x=await o.pushManager.getSubscription();return x&&await x.unsubscribe(),await U.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),re.success("Push notifications disabled"),!0}catch(x){console.error("Error unsubscribing:",x);const y=x instanceof Error?x.message:"Unknown error";return re.error("Failed to disable push notifications: "+y),!1}finally{l(!1)}},[o,s]);return{isSupported:h,permission:t,isSubscribed:r,isLoading:i,vapidPublicKey:d,subscribe:m,unsubscribe:p}}const JMe="push_notification_prompt_dismissed",Gjs=["/dashboard","/admin"],Wjs=()=>{const{user:s}=Ns(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=kCt(),i=$d(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),u=Gjs.some(p=>i.pathname===p||i.pathname.startsWith(`${p}/`));j.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${JMe}_${s.id}`))return;const x=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(x)},[s,t,n,r,u]);const h=async()=>{d(!0);const p=await a();d(!1),p&&(s&&localStorage.setItem(`${JMe}_${s.id}`,"true"),o(!1))},m=()=>{s&&localStorage.setItem(`${JMe}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(Fs,{open:l,onOpenChange:p=>!p&&m(),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{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(Nx,{className:"h-6 w-6 text-primary"})}),e.jsx(zs,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(kr,{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."})]})})},Aat=s=>{let t;const n=new Set,r=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const m=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(p=>p(t,m))}},a=()=>t,o={setState:r,getState:a,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=s(r,a,o);return o},Kjs=s=>s?Aat(s):Aat,Yjs=s=>s;function Zjs(s,t=Yjs){const n=Lt.useSyncExternalStore(s.subscribe,Lt.useCallback(()=>t(s.getState()),[s,t]),Lt.useCallback(()=>t(s.getInitialState()),[s,t]));return Lt.useDebugValue(n),n}const Tat=s=>{const t=Kjs(s),n=r=>Zjs(t,r);return Object.assign(n,t),n},Xjs=s=>s?Tat(s):Tat;function Qjs(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 POe=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return POe(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return POe(r)(n)}}}},Jjs=(s,t)=>(n,r,a)=>{let i={storage:Qjs(()=>window.localStorage),partialize:g=>g,version:0,merge:(g,b)=>({...b,...g}),...t},l=!1,o=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return s((...g)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...g)},r,a);const h=()=>{const g=i.partialize({...r()});return u.setItem(i.name,{state:g,version:i.version})},m=a.setState;a.setState=(g,b)=>(m(g,b),h());const p=s((...g)=>(n(...g),h()),r,a);a.getInitialState=()=>p;let x;const y=()=>{var g,b;if(!u)return;const v=++o;l=!1,c.forEach(C=>{var T;return C((T=r())!=null?T:p)});const k=((b=i.onRehydrateStorage)==null?void 0:b.call(i,(g=r())!=null?g:p))||void 0;return POe(u.getItem.bind(u))(i.name).then(C=>{if(C)if(typeof C.version=="number"&&C.version!==i.version){if(i.migrate){const T=i.migrate(C.state,C.version);return T instanceof Promise?T.then(M=>[!0,M]):[!0,T]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,C.state];return[!1,void 0]}).then(C=>{var T;if(v!==o)return;const[M,P]=C;if(x=i.merge(P,(T=r())!=null?T:p),n(x,!0),M)return h()}).then(()=>{v===o&&(k==null||k(r(),void 0),x=r(),l=!0,d.forEach(C=>C(x)))}).catch(C=>{v===o&&(k==null||k(void 0,C))})};return a.persist={setOptions:g=>{i={...i,...g},g.storage&&(u=g.storage)},clearStorage:()=>{u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>y(),hasHydrated:()=>l,onHydrate:g=>(c.add(g),()=>{c.delete(g)}),onFinishHydration:g=>(d.add(g),()=>{d.delete(g)})},i.skipHydration||y(),x||p},e2s=Jjs,U3e=Xjs()(e2s((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 t2s(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function h0(){const{user:s}=Ns(),{data:t,isLoading:n}=mt({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:r,error:a}=await U.from("lead_sites").select("id, subdomain_slug, custom_domain, site_title, is_active, 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 t2s(r)},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isLoading:n,siteUrl:t?t.custom_domain?`https://${t.custom_domain}`:`https://${t.subdomain_slug}.thelocalmove.com`:null}}const Eat="dashboard-sidebar-collapsed",eLe=j.createContext(!1),Vs=({children:s,title:t})=>{var Ae;const{user:n,signOut:r,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=Ns(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=J4e(),{hasAccess:h}=nVe(),{isImpersonating:m}=Q4e(),x=(c&&!!d?40:0)+(m?40:0),{avatarUrl:y}=I3t(n==null?void 0:n.id),{isTrial:g,isExpired:b,expiresAt:v}=xws(n==null?void 0:n.id),{isInnerCircleEnabled:k,isMarketplaceEnabled:C}=D3t(),{currentBrief:T,shouldShowPopup:M,hasUnseenBrief:P,openBrief:L,closeBrief:I,dismissBrief:O}=Bjs(),{unreadCount:$}=gws(),{openCount:q}=yws(),{data:W}=Hj(),G=!!W,ee=U3e(Xe=>Xe.cartItems).reduce((Xe,Ue)=>Xe+Ue.quantity,0),{leadSite:J,hasLeadSite:le,siteUrl:ue}=h0(),oe=Hn(),ie=$d(),[de,we]=j.useState(null);j.useEffect(()=>{n!=null&&n.id&&U.from("profiles").select("name").eq("id",n.id).single().then(({data:Xe})=>{Xe!=null&&Xe.name&&we(Xe.name)})},[n==null?void 0:n.id]);const je=de||((Ae=n==null?void 0:n.user_metadata)==null?void 0:Ae.name)||(n==null?void 0:n.email)||"User",[xe,fe]=j.useState(()=>typeof window<"u"?localStorage.getItem(Eat)==="true":!1);j.useEffect(()=>{localStorage.setItem(Eat,String(xe))},[xe]);const[Se,Ee]=j.useState({agentos:!0,tools:!0,marketing:!0,learning:!0,community:!0,contacts:!0,website:!0,help:!1}),Le=Xe=>{Ee(Ue=>({...Ue,[Xe]:!Ue[Xe]}))},De=Xe=>Xe.split(" ").map(Ue=>Ue[0]).join("").toUpperCase().slice(0,2),Be=Xe=>ie.pathname===Xe,Ne=Xe=>Xe.some(Ue=>ie.pathname===Ue),Ge=({path:Xe,icon:Ue,label:Ze,badgeCount:Qe})=>{const nt=j.useContext(eLe)?!1:xe,rt=e.jsxs(B,{variant:"ghost",size:"sm",className:Et("text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Be(Xe)&&"bg-sidebar-accent text-sidebar-accent-foreground",nt?"w-10 h-10 p-0 justify-center":"w-full justify-start gap-2"),onClick:()=>oe(Xe),children:[e.jsxs("div",{className:"relative",children:[e.jsx(Ue,{className:"h-4 w-4 shrink-0"}),nt&&Qe!=null&&Qe>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]}),!nt&&Ze,!nt&&Qe!=null&&Qe>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:Qe>9?"9+":Qe})]});return nt?e.jsxs(Cu,{delayDuration:0,children:[e.jsx(Au,{asChild:!0,children:rt}),e.jsxs(ou,{side:"right",className:"flex items-center gap-2",children:[Ze,Qe!=null&&Qe>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:Qe>9?"9+":Qe})]})]}):rt},_e=({id:Xe,label:Ue,icon:Ze,children:Qe,activePaths:Ye,showBetaBadge:nt,defaultPath:rt,badgeCount:Fe})=>{if(j.useContext(eLe)?!1:xe){const pt=rt||Ye[0];return e.jsxs(Cu,{delayDuration:0,children:[e.jsx(Au,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:Et("w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Ne(Ye)&&"text-primary"),onClick:()=>oe(pt),children:e.jsxs("div",{className:"relative",children:[e.jsx(Ze,{className:"h-4 w-4"}),Fe!=null&&Fe>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(ou,{side:"right",className:"flex items-center gap-2",children:[Ue,nt&&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"}),Fe!=null&&Fe>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:Fe>9?"9+":Fe})]})]})}return e.jsxs(i0,{open:Se[Xe],onOpenChange:()=>Le(Xe),children:[e.jsx(o0,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ne(Ye)&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2 font-semibold text-[15px]",children:[e.jsx(Ze,{className:"h-4 w-4"}),Ue,nt&&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:[Fe!=null&&Fe>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:Fe>9?"9+":Fe}),e.jsx(Po,{className:Et("h-4 w-4 transition-transform duration-200",Se[Xe]&&"rotate-180")})]})]})}),e.jsx(l0,{className:"pl-4 space-y-1 mt-1",children:Qe})]})},Oe=({isMobile:Xe=!1})=>{const Ue=Xe?!1:xe;return e.jsx(eLe.Provider,{value:Xe,children:e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:Et("p-3 border-b border-sidebar-border",Ue?"flex flex-col items-center gap-2":"flex items-center justify-between"),children:[Ue?e.jsx("img",{src:kws,alt:"LevelUp",className:"h-8 w-auto"}):e.jsx("img",{src:Nws,alt:"LevelUp",className:"h-8 w-auto"}),!Xe&&e.jsxs(Cu,{delayDuration:0,children:[e.jsx(Au,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>fe(!Ue),children:e.jsx(Cc,{className:Et("h-4 w-4 transition-transform duration-300",Ue&&"rotate-180")})})}),e.jsx(ou,{side:"right",children:Ue?"Expand sidebar":"Collapse sidebar"})]})]}),e.jsx(lo,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:e.jsxs("nav",{className:Et("p-3 space-y-1",Ue&&"flex flex-col items-center"),children:[Xe&&g&&!b&&e.jsx("button",{type:"button",onClick:()=>oe("/subscription"),className:Et("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(yn,{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?"}),v&&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(v).getTime()-Date.now())/864e5)),"d left"]})]})}),e.jsx(Ge,{path:"/dashboard",icon:BR,label:"Dashboard"}),e.jsx(Ge,{path:"/apps",icon:k_,label:"Apps & Tools"}),Ue?e.jsxs(Cu,{delayDuration:0,children:[e.jsx(Au,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/programs"),children:e.jsx(oy,{className:"h-4 w-4 shrink-0"})})}),e.jsx(ou,{side:"right",children:"Programs"})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/programs"),children:[e.jsx(oy,{className:"h-4 w-4 shrink-0"}),"Programs"]}),Ue?e.jsxs(Cu,{delayDuration:0,children:[e.jsx(Au,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/levelup-u"),children:[e.jsx(Uh,{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(ou,{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:Et("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:()=>oe("/levelup-u"),children:[e.jsx(Uh,{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:Vc,label:"Events"}),e.jsxs(_e,{id:"agentos",label:"Agent OS",icon:UT,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:mo,label:"Mission Control"}),u("contacts")&&!Ue&&e.jsxs(i0,{open:Se.contacts,onOpenChange:()=>Le("contacts"),children:[e.jsx(o0,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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(Bn,{className:"h-4 w-4"}),"Contacts"]}),e.jsx(Po,{className:Et("h-3.5 w-3.5 transition-transform duration-200",Se.contacts&&"rotate-180")})]})}),e.jsxs(l0,{className:"pl-4 pr-1 space-y-0.5 mt-0.5",children:[e.jsx(Ge,{path:"/mission-control/contacts",icon:Bn,label:"All Contacts"}),e.jsx(Ge,{path:"/mission-control/relationship-scorecard",icon:vf,label:"Relationship Report"}),e.jsx(Ge,{path:"/mission-control/sphere-gaps",icon:rK,label:"Sphere Gaps"}),e.jsx(Ge,{path:"/mission-control/sent-emails",icon:Dr,label:"Sent Emails"}),e.jsx(Ge,{path:"/mission-control/connect-page",icon:Rc,label:"Connect Page"})]})]}),u("contacts")&&Ue&&e.jsx(Ge,{path:"/mission-control/contacts",icon:Bn,label:"Contacts"}),u("contacts")&&e.jsx(Ge,{path:"/mission-control/plans",icon:Vc,label:"TouchPlans"}),u("pipeline")&&e.jsx(Ge,{path:"/mission-control/pipeline",icon:v3,label:"Deal Pipeline"}),u("pipeline")&&e.jsx(Ge,{path:"/mission-control/transactions",icon:x3,label:"Transactions"}),u("pipeline")&&e.jsx(Ge,{path:"/mission-control/tasks",icon:k4,label:"Tasks"}),u("popbys")&&e.jsx(Ge,{path:"/mission-control/popbys",icon:zo,label:"Popbys"}),u("videos")&&e.jsx(Ge,{path:"/mission-control/video-library",icon:Zr,label:"Video Library"}),u("scorecard")&&e.jsx(Ge,{path:"/mission-control/scorecard",icon:ol,label:"Scorecard"}),u("listings")&&e.jsx(Ge,{path:"/mission-control/listings",icon:Ni,label:"Listing Exchange"}),e.jsx(Ge,{path:"/mission-control/client-portals",icon:yn,label:"Client Portals"}),e.jsx(Ge,{path:"/mission-control/signals",icon:tz,label:"Signals"}),!Ue&&e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/mission-control/smart-drips"),children:[e.jsx(jf,{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"})]}),Ue&&e.jsx(Ge,{path:"/mission-control/smart-drips",icon:jf,label:"Smart Drips"}),e.jsx(Ge,{path:"/email-campaigns/templates",icon:on,label:"Email Templates"})]}),le&&J&&e.jsxs(_e,{id:"website",label:"My Website",icon:Ql,activePaths:[`/admin/lead-sites/${J.id}/edit`],defaultPath:`/admin/lead-sites/${J.id}/edit`,children:[Ue?e.jsxs(Cu,{delayDuration:0,children:[e.jsx(Au,{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(ma,{className:"h-4 w-4"})})}),e.jsx(ou,{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(ma,{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/${J.id}/edit`,icon:Za,label:"Edit Website"}),e.jsx(Ge,{path:"/my-website/mls-listings",icon:ia,label:"MLS Listings"}),e.jsx(Ge,{path:"/my-website/market-report",icon:ol,label:"Market Reports"}),(J==null?void 0:J.mls_provider_id)&&e.jsx(Ge,{path:"/mission-control/cma",icon:P5,label:"CMA Reports"}),e.jsx(Ge,{path:"/mission-control/website-activity",icon:vf,label:"Website Activity"}),e.jsx(Ge,{path:"/m",icon:Jy,label:"Mobile Command"})]}),e.jsxs(_e,{id:"marketing",label:"Marketing",icon:jh,activePaths:["/templates","/social-swag-2","/newsletters","/website-apps","/marketing-studio","/weekly-reels"],defaultPath:"/templates",children:[e.jsx(Ge,{path:"/templates",icon:Ac,label:"Templates"}),e.jsx(Ge,{path:"/marketing-studio",icon:ac,label:"Marketing Studio"}),e.jsx(Ge,{path:"/social-swag-2",icon:Jy,label:"Social Swag"}),Ue?e.jsxs(Cu,{delayDuration:0,children:[e.jsx(Au,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/newsletters"),children:[e.jsx(V_,{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(ou,{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:Et("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:()=>oe("/newsletters"),children:[e.jsx(V_,{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:yn,label:"Website Apps"}),h&&e.jsx(Ge,{path:"/weekly-reels",icon:wh,label:"Weekly Reels"})]}),e.jsxs(_e,{id:"learning",label:"Learning",icon:Op,activePaths:["/academy","/toolbox","/programs"],defaultPath:"/academy",children:[e.jsx(Ge,{path:"/academy",icon:Uh,label:"Academy"}),e.jsx(Ge,{path:"/toolbox",icon:O5,label:"Toolbox"})]}),e.jsxs(_e,{id:"community",label:"Community",icon:ro,activePaths:["/community","/wishlist"],defaultPath:"/community",badgeCount:$,children:[e.jsx(Ge,{path:"/community",icon:Bn,label:"Community",badgeCount:$}),e.jsx(Ge,{path:"/wishlist",icon:xN,label:"Wishlist",badgeCount:q}),!Ue&&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(_e,{id:"goods",label:"The Goods",icon:ib,activePaths:["/marketplace","/reward-store"],defaultPath:"/reward-store",children:[C&&!Ue&&e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ie.pathname.startsWith("/marketplace")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>oe("/marketplace"),children:[e.jsx(ib,{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"})]}),C&&Ue&&e.jsx(Ge,{path:"/marketplace",icon:ib,label:"Marketplace"}),e.jsx(Ge,{path:"/reward-store",icon:ll,label:"Reward Store"}),e.jsx(Ge,{path:"/refer-friends",icon:zo,label:"Refer & Earn"})]}),e.jsxs(_e,{id:"help",label:"Help & Services",icon:c5,activePaths:["/support","/additional-services"],defaultPath:"/support",children:[e.jsx(Ge,{path:"/support",icon:q9,label:"Support"}),e.jsx(Ge,{path:"/additional-services",icon:yn,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:Uh,label:"Coaching"})}),e.jsx(s2s,{}),(n==null?void 0:n.email)==="jeremy@relevelup.com"&&e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ie.pathname.startsWith("/attract")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>oe("/attract"),children:[e.jsx(yn,{className:"h-4 w-4 text-violet-600"}),!Ue&&e.jsx("span",{children:"LevelUp Attract"}),!Ue&&e.jsx("span",{className:"ml-auto text-[9px] font-semibold text-violet-600 uppercase tracking-wider",children:"Beta"})]}),a&&e.jsxs(e.Fragment,{children:[!Ue&&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"})}),Ue?e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(Ge,{path:"/admin",icon:du,label:"Admin Dashboard"})}):e.jsxs(B,{variant:"ghost",size:"sm",className:Et("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",ie.pathname==="/admin"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>oe("/admin"),children:[e.jsx(du,{className:"h-4 w-4"}),"Admin Dashboard"]})]}),(o||i)&&!a&&e.jsxs(e.Fragment,{children:[!Ue&&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"})}),Ue?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:Ni,label:"My Brokerage"}),e.jsx(Ge,{path:"/brokerage/help-board",icon:tN,label:"Help Board"}),e.jsx(Ge,{path:"/brokerage-content",icon:Op,label:"Brokerage Content"})]}),G&&!i&&e.jsx(Ge,{path:"/my-team",icon:Bn,label:"My Team"}),i&&e.jsxs(e.Fragment,{children:[e.jsx(Ge,{path:"/brokerage/dashboard",icon:ic,label:"Manage Brokerages"}),e.jsx(Ge,{path:"/brokerage/teams",icon:Bn,label:"Teams"}),e.jsx(Ge,{path:"/brokerage/recruiting",icon:jh,label:"Recruiting"}),e.jsx(Ge,{path:"/brokerage/vendors",icon:fN,label:"Vendors"}),e.jsx(Ge,{path:"/brokerage-resources",icon:kx,label:"Brokerage Resources"})]})]}):e.jsxs(e.Fragment,{children:[o&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/my-brokerage"),children:[e.jsx(Ni,{className:"h-4 w-4"}),"My Brokerage"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/brokerage/help-board"),children:[e.jsx(tN,{className:"h-4 w-4"}),"Help Board"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/brokerage-content"),children:[e.jsx(Op,{className:"h-4 w-4"}),"Brokerage Content"]})]}),G&&!i&&e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/my-team"),children:[e.jsx(Bn,{className:"h-4 w-4"}),"My Team"]}),i&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/brokerage/dashboard"),children:[e.jsx(ic,{className:"h-4 w-4"}),"Manage Brokerages"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/brokerage/teams"),children:[e.jsx(Bn,{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:Et("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:()=>oe("/brokerage/recruiting"),children:[e.jsx(jh,{className:"h-4 w-4"}),"Recruiting"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/brokerage/vendors"),children:[e.jsx(fN,{className:"h-4 w-4"}),"Vendors"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>oe("/brokerage-resources"),children:[e.jsx(kx,{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:Et("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:()=>oe("/profile"),children:[e.jsx(Eo,{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(UR,{className:"h-4 w-4"}),"Sign Out"]})]})]})})};return e.jsx(RN,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[g&&b&&ie.pathname!=="/subscription"&&e.jsx(Cjs,{}),typeof document<"u"&&Hv.createPortal(e.jsx("aside",{className:Et("hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto transition-[width] duration-300",xe?"w-16":"w-56"),style:{top:`${x}px`,height:`calc(100vh - ${x}px)`},children:e.jsx(Oe,{})}),document.body),e.jsxs("div",{className:Et("flex-1 flex flex-col overflow-hidden transition-all duration-300",xe?"md:ml-16":"md:ml-56"),style:{height:`calc(100vh - ${x}px)`,marginTop:`${x}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(v1,{children:[e.jsx(yJ,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(YT,{className:"h-5 w-5"})})}),e.jsx(rv,{side:"left",className:"w-56 p-0 bg-card",children:e.jsx(Oe,{isMobile:!0})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:Sws,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(Cat,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[g&&!b&&v&&e.jsx(Sjs,{expiresAt:v,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(Cat,{})}),T&&e.jsx(Ajs,{hasUnseenBrief:P,onClick:L}),C&&e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",onClick:()=>oe("/marketplace/cart"),children:[e.jsx(ib,{className:"h-5 w-5"}),ee>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:ee>99?"99+":ee})]}),e.jsx(Qws,{}),e.jsx(EOe,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",je.split(" ")[0],"!"]}),e.jsxs(kd,{children:[e.jsx(Sd,{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(Ra,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(Fi,{src:y||void 0}),e.jsx(Da,{className:"bg-primary text-primary-foreground font-medium text-sm",children:De(je)})]})})}),e.jsxs(xd,{align:"end",className:"w-48",children:[e.jsxs(wa,{onClick:()=>oe("/profile"),className:"cursor-pointer",children:[e.jsx(Eo,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(wa,{onClick:()=>oe("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(R5,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(wa,{onClick:()=>oe("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(R5,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(uy,{}),e.jsxs(wa,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(UR,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(Ujs,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),T&&e.jsx(zjs,{brief:T,open:M,onClose:I,onDismiss:O}),e.jsx($js,{}),e.jsx(Vjs,{}),e.jsx(Wjs,{})]})]})})};function s2s(){const{user:s}=Ns(),t=$d(),n=Hn(),{data:r}=mt({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i}=await U.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(Uh,{className:"h-4 w-4"}),"My Coach"]})})}const Mat="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",n2s="https://tile-portal.lovable.app/mcp-oauth-bridge.html",r2s=[{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 a2s(){const[s,t]=j.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(Mat),t(!0),re.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{re.error("Could not copy URL")}};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(UT,{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(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Use this exact MCP server URL"}),e.jsx(fr,{children:"Paste only this URL into ChatGPT's Server URL field."})]}),e.jsx(Re,{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:Mat}),e.jsx(B,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(To,{className:"h-4 w-4 text-green-600"}):e.jsx(ja,{className:"h-4 w-4"})})]})})]}),e.jsx(be,{className:"border-destructive/30 bg-destructive/5",children:e.jsx(Re,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(hd,{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:n2s}),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(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Quick steps"}),e.jsx(fr,{children:"ChatGPT adds MCP servers as a new plugin / custom tool. Share these steps with any agent who wants to connect."})]}),e.jsx(Re,{children:e.jsx("ol",{className:"space-y-4",children:r2s.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 i2s=()=>{const[s]=dc(),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(be,{className:"max-w-lg w-full",children:[e.jsxs(Ft,{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(To,{className:"w-10 h-10 text-green-500"})}),e.jsx(Ut,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(fr,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Re,{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(on,{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."})})]})]})})},o2s=()=>{const{user:s}=Ns(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(""),o=async h=>{var m;if(!(s!=null&&s.email)){re.error("Please sign in to upgrade");return}n(!0),a(h);try{const{data:p,error:x}=await U.functions.invoke("create-checkout",{body:{tier:h,email:s.email,name:((m=s.user_metadata)==null?void 0:m.full_name)||s.email,couponCode:i.trim()||void 0,skipTrial:!0}});if(x)throw x;if(p!=null&&p.url)window.open(p.url,"_blank","noopener,noreferrer"),re.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(p){console.error("Checkout error:",p),re.error(p.message||"Failed to start checkout. Please try again.")}finally{n(!1),a(null)}},c=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Community forums and support","Exclusive member events and workshops","Deal pipeline & scorecard tracking","Listing exchange access","Social media content library"],d=["Everything in Individual plan","Up to 25 agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"],u=["Everything in Brokerage plan","Unlimited agent seats","Dedicated account manager","Advanced analytics & reporting","White-label options","API access","Custom integrations","Enterprise-level support"];return e.jsx(Vs,{children:e.jsxs("div",{className:"container max-w-6xl py-8 px-4",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Upgrade Your Membership"}),e.jsx("p",{className:"text-muted-foreground text-lg",children:"Choose the plan that's right for you and unlock the full power of LevelUp"})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(se,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(ye,{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(be,{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(Ft,{className:"text-center pb-2",children:[e.jsx("div",{className:"mx-auto mb-3 h-14 w-14 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Bn,{className:"h-7 w-7 text-primary"})}),e.jsx(Ut,{className:"text-xl",children:"Individual Agent"}),e.jsx(fr,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Re,{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(da,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(be,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors",children:[e.jsxs(Ft,{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(Ni,{className:"h-7 w-7 text-amber-600"})}),e.jsx(Ut,{className:"text-xl",children:"Brokerage"}),e.jsx(fr,{children:"For teams and brokerages up to 25 agents"})]}),e.jsxs(Re,{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(da,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ni,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(be,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(Ft,{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(Ni,{className:"h-7 w-7 text-purple-600"})}),e.jsx(Ut,{className:"text-xl",children:"Brokerage 25+"}),e.jsx(fr,{children:"For larger brokerages with 25+ agents"})]}),e.jsxs(Re,{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(da,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ni,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(be,{className:"bg-muted/50",children:e.jsxs(Re,{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(pa,{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(on,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},l2s=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=Ns(),a=Hn(),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(!1);j.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),j.useEffect(()=>{!t&&s&&r&&a("/profile?setup=true")},[s,t,r,a]);const h=async()=>{if(!i.trim()){re.error("Please enter a brokerage name");return}const{data:m}=await U.auth.getSession(),p=m.session;if(!s||!p){re.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!p,userId:s==null?void 0:s.id});const{data:x,error:y}=await U.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:x,error:y}),y)throw y;if(!(x!=null&&x.ok))throw new Error((x==null?void 0:x.error)||"Failed to create brokerage");c(!1),u(!0),re.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(x){console.error("Error creating brokerage:",x),re.error(x.message||"Failed to create brokerage"),c(!1)}};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(be,{className:"max-w-lg w-full",children:[e.jsxs(Ft,{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(Wt,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(Ut,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(fr,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(To,{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(Wt,{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(be,{className:"max-w-lg w-full",children:[e.jsxs(Ft,{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(Ni,{className:"w-10 h-10 text-primary"})}),e.jsx(Ut,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(fr,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Re,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(ye,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:m=>l(m.target.value),onKeyDown:m=>m.key==="Enter"&&h()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(Bn,{className:"w-4 h-4 text-primary"}),"What you can do as a Brokerage Manager:"]}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(To,{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(To,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(To,{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(To,{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(Xa,{className:"w-4 h-4 ml-2"})]})]})]})})},Lat=()=>{const s=Hn(),[t,n]=j.useState("verifying"),[r,a]=j.useState("");j.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await U.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await U.from("profiles").select("login_count").eq("id",o.user.id).single();if(((d==null?void 0:d.login_count)||0)>1){console.log("Account already claimed, redirecting to dashboard"),n("already_claimed");return}console.log("User logged in successfully:",o.user.email),n("success");try{await U.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(u){console.log("Trial claim hook (non-critical):",u)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{n("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),n("already_claimed")}})()},[s]);const i=()=>{window.location.href="https://dashboard.relevelup.com/auth"};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(Ft,{className:"space-y-1 text-center",children:[e.jsxs("div",{className:"mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-primary/10",children:[t==="verifying"&&e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"}),t==="success"&&e.jsx("svg",{className:"h-8 w-8 text-primary",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),t==="already_claimed"&&e.jsx("svg",{className:"h-8 w-8 text-primary",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),t==="error"&&e.jsx("svg",{className:"h-8 w-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})]}),e.jsxs(Ut,{className:"text-2xl",children:[t==="verifying"&&"Claiming Your Account...",t==="success"&&"Account Claimed!",t==="already_claimed"&&"Account Already Claimed",t==="error"&&"Claim Failed"]}),e.jsxs(fr,{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(Re,{children:e.jsx(B,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},c2s=()=>{const[s,t]=j.useState(!1),n=j.useMemo(()=>new URLSearchParams(window.location.search).get("link"),[]),r=j.useMemo(()=>{if(!n)return!1;try{const i=new URL(n);return i.hostname.endsWith(".supabase.co")&&i.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[n]);j.useEffect(()=>{document.title="Reset Your Password"},[]);const a=()=>{!r||!n||(t(!0),window.location.href=n)};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:P3t,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(be,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Ft,{className:"text-center",children:[e.jsx(Ut,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Your Password"}),e.jsx(fr,{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(Re,{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."})]})]})]})})]})},d2s=()=>{const s=Hn(),[t]=dc(),[n,r]=j.useState(t.get("code")||""),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[x,y]=j.useState(!1),[g,b]=j.useState(!1),[v,k]=j.useState(null),[C,T]=j.useState(null),[M,P]=j.useState(null),[L,I]=j.useState(null);j.useEffect(()=>{const W=t.get("code");W&&(r(W),O(W))},[t]);const O=async W=>{y(!0);const{data:G,error:K}=await U.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",W.toUpperCase().trim()).single();if(K||!G){re.error("Invalid invite code"),y(!1);return}if(!G.is_active){re.error("This invite code is no longer active"),y(!1);return}if(G.max_uses&&G.uses_count>=G.max_uses){re.error("This invite code has reached its maximum uses"),y(!1);return}if(G.expires_at&&new Date(G.expires_at){W.preventDefault(),O(n)},q=async W=>{var G;if(W.preventDefault(),!c.trim()){re.error("Please enter your name");return}if(l.length<6){re.error("Password must be at least 6 characters");return}p(!0);try{const K=`${window.location.origin}/`,{data:ee,error:J}=await U.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:K,data:{name:c.trim()}}});if(J){J.message.includes("already registered")?re.error("This email is already registered. Please sign in instead."):re.error(J.message);return}if(ee.user){await U.rpc("add_default_signup_tag",{user_id:ee.user.id});const le=n.toUpperCase().trim();C?await U.functions.invoke("assign-brokerage",{body:{userId:ee.user.id,brokerageId:C,inviteCode:le}}):L?await U.functions.invoke("assign-brokerage",{body:{userId:ee.user.id,trialDays:L,inviteCode:le}}):await U.functions.invoke("assign-brokerage",{body:{userId:ee.user.id,grandfathered:!0,inviteCode:le}}),v&&await U.from("invite_codes").update({uses_count:((G=(await U.from("invite_codes").select("uses_count").eq("id",v).single()).data)==null?void 0:G.uses_count)+1}).eq("id",v),re.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(K){console.error("Signup error:",K),re.error("An unexpected error occurred")}finally{p(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(Ft,{className:"text-center",children:[e.jsx(Ut,{className:"text-2xl font-bold text-primary",children:M?`Join ${M}`:"Join LevelUp"}),e.jsx(fr,{children:g?M?`Create your account to join ${M}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Re,{children:g?e.jsxs("form",{onSubmit:q,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Full Name"}),e.jsx(ye,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:W=>d(W.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:W=>i(W.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{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(n0,{className:"h-4 w-4"}):e.jsx(ma,{className:"h-4 w-4"})})]})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{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(se,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(ye,{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:x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},SJ=()=>{const{user:s,isCoach:t}=Ns();return mt({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:n,error:r}=await U.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return n}})},u2s=()=>{const{data:s}=SJ();return mt({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("coaching_assignments").select("*").eq("coach_id",s.id).order("started_at",{ascending:!1});if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(o=>o.agent_id),{data:i}=await U.from("profiles").select("id, name, email, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>({...o,agent:l.get(o.agent_id)||null}))}})},h2s=()=>{const{user:s}=Ns();return mt({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("coaching_assignments").select("*").eq("agent_id",s.id).eq("status","active").order("started_at",{ascending:!1}).limit(1);if(n)throw n;const r=(t||[])[0];if(!r)return null;const{data:a}=await U.from("coaches").select("*").eq("id",r.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await U.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...r,coach:a,coachProfile:i}}})},m2s=s=>mt({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return null;const{data:r}=await U.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:r}}}),SCt=s=>mt({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(n)throw n;return t||[]}}),CCt=s=>mt({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(n)throw n;return t||[]}}),p2s=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function f2s(){const s=Hn(),{data:t,isLoading:n}=SJ(),{data:r=[],isLoading:a}=u2s();if(n)return e.jsx(Vs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Vs,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Uh,{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."})]})});p2s.map(l=>({...l,items:r.filter(o=>(o.pipeline_stage||"active")===l.key)}));const i=r.filter(l=>l.status==="active").length;return e.jsx(Vs,{title:"Coaching",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-white/80",children:[e.jsx(yn,{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(tLe,{icon:Uh,label:"Active agents",value:i}),e.jsx(tLe,{icon:Vc,label:"This month",value:"—"}),e.jsx(tLe,{icon:Fd,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(be,{children:e.jsx(Re,{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(be,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Re,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(Ra,{className:"h-14 w-14",children:[e.jsx(Fi,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(Da,{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(Xa,{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(qe,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",oc(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function tLe({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 ACt({assignmentId:s}){const{user:t}=Ns(),n=as(),[r,a]=j.useState(""),[i,l]=j.useState(!1),o=j.useRef(null),{data:c=[]}=mt({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await U.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(h)throw h;return u||[]}});j.useEffect(()=>{if(!s)return;const u=U.channel(`coaching-messages-${s}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"coaching_messages",filter:`assignment_id=eq.${s}`},()=>n.invalidateQueries({queryKey:["coaching-messages",s]})).subscribe();return()=>{U.removeChannel(u)}},[s,n]),j.useEffect(()=>{var u;(u=o.current)==null||u.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[c]);const d=async()=>{const u=r.trim();if(!u||!t)return;l(!0);const{error:h}=await U.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:u});l(!1),h||a("")};return e.jsxs(be,{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:Et("flex gap-2",h?"justify-end":"justify-start"),children:[!h&&e.jsx(Ra,{className:"h-8 w-8 mt-1",children:e.jsx(Da,{className:"text-xs",children:(u.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:Et("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:Et("text-[10px] mt-1",h?"text-white/70":"text-muted-foreground"),children:oc(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(Re,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Ds,{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(Dr,{className:"h-4 w-4"})})]})})]})}var yVe="Progress",vVe=100,[x2s,kBn]=Zm(yVe),[g2s,y2s]=x2s(yVe),TCt=j.forwardRef((s,t)=>{const{__scopeProgress:n,value:r=null,max:a,getValueLabel:i=v2s,...l}=s;(a||a===0)&&!Pat(a)&&console.error(b2s(`${a}`,"Progress"));const o=Pat(a)?a:vVe;r!==null&&!Iat(r,o)&&console.error(_2s(`${r}`,"Progress"));const c=Iat(r,o)?r:null,d=XNe(c)?i(c,o):void 0;return e.jsx(g2s,{scope:n,value:c,max:o,children:e.jsx(Ua.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":XNe(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":LCt(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});TCt.displayName=yVe;var ECt="ProgressIndicator",MCt=j.forwardRef((s,t)=>{const{__scopeProgress:n,...r}=s,a=y2s(ECt,n);return e.jsx(Ua.div,{"data-state":LCt(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...r,ref:t})});MCt.displayName=ECt;function v2s(s,t){return`${Math.round(s/t*100)}%`}function LCt(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function XNe(s){return typeof s=="number"}function Pat(s){return XNe(s)&&!isNaN(s)&&s>0}function Iat(s,t){return XNe(s)&&!isNaN(s)&&s<=t&&s>=0}function b2s(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${vVe}\`.`}function _2s(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 ${vVe} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var PCt=TCt,w2s=MCt;const qi=j.forwardRef(({className:s,value:t,...n},r)=>e.jsx(PCt,{ref:r,className:Et("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(w2s,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));qi.displayName=PCt.displayName;function ICt({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:g}=await U.from("scorecard_transactions").select("id, sale_price, commission_amount, close_date, is_win").eq("owner_user_id",s).gte("close_date",n).lte("close_date",r);if(g)throw g;return y||[]}}),{data:i}=mt({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:y}=await U.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,g)=>y+(Number(g.sale_price)||0),0),d=l.reduce((y,g)=>y+(Number(g.commission_amount)||0),0),u=i,h=(u==null?void 0:u.transactions_goal)||0,m=(u==null?void 0:u.volume_goal)||0,p=(u==null?void 0:u.gci_goal)||0,x=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(kl,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(sLe,{icon:cu,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(sLe,{icon:kl,label:"Volume",value:x(c),goal:m,current:c,suffix:m?`of ${x(m)}`:""}),e.jsx(sLe,{icon:Od,label:"GCI",value:x(d),goal:p,current:d,suffix:p?`of ${x(p)}`:""})]}),o===0&&e.jsx(be,{children:e.jsxs(Re,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function sLe({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(be,{children:e.jsxs(Re,{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(qi,{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 RCt({assignmentId:s,canEdit:t}){const n=as(),[r,a]=j.useState(!1),[i,l]=j.useState(null),{data:o=[]}=mt({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await U.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(u)throw u;return d||[]}}),c=()=>n.invalidateQueries({queryKey:["coaching-goals",s]});return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(uu,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(be,{children:e.jsx(Re,{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(be,{children:e.jsxs(Re,{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(qe,{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(Za,{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(qi,{value:m})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",Bs(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(j2s,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function j2s({open:s,onOpenChange:t,assignmentId:n,goal:r,onSaved:a}){var C,T;const[i,l]=j.useState((r==null?void 0:r.title)||""),[o,c]=j.useState((r==null?void 0:r.description)||""),[d,u]=j.useState((r==null?void 0:r.target_metric)||""),[h,m]=j.useState(((C=r==null?void 0:r.target_value)==null?void 0:C.toString())||""),[p,x]=j.useState(((T=r==null?void 0:r.current_value)==null?void 0:T.toString())||"0"),[y,g]=j.useState((r==null?void 0:r.due_date)||""),[b,v]=j.useState(!1);j.useState(()=>{var M,P;l((r==null?void 0:r.title)||""),c((r==null?void 0:r.description)||""),u((r==null?void 0:r.target_metric)||""),m(((M=r==null?void 0:r.target_value)==null?void 0:M.toString())||""),x(((P=r==null?void 0:r.current_value)==null?void 0:P.toString())||"0"),g((r==null?void 0:r.due_date)||"")});const k=async()=>{if(!i.trim())return;v(!0);const M={assignment_id:n,title:i,description:o||null,target_metric:d||null,target_value:h?Number(h):null,current_value:p?Number(p):0,due_date:y||null},{error:P}=r!=null&&r.id?await U.from("coaching_goals").update(M).eq("id",r.id):await U.from("coaching_goals").insert(M);if(v(!1),P)return re.error(P.message);re.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:r!=null&&r.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ye,{placeholder:"Title",value:i,onChange:M=>l(M.target.value)}),e.jsx(Ds,{placeholder:"Description (optional)",rows:2,value:o,onChange:M=>c(M.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(ye,{placeholder:"transactions",value:d,onChange:M=>u(M.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(ye,{type:"number",value:h,onChange:M=>m(M.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(ye,{type:"number",value:p,onChange:M=>x(M.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(ye,{type:"date",value:y,onChange:M=>g(M.target.value)})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:k,disabled:b,children:r!=null&&r.id?"Save":"Create"})]})]})})}function DCt({assignmentId:s}){const t=as(),{user:n}=Ns(),r=j.useRef(null),[a,i]=j.useState(!1),{data:l=[]}=mt({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:h,error:m}=await U.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async h=>{var p;const m=(p=h.target.files)==null?void 0:p[0];if(!(!m||!n)){i(!0);try{const x=`${s}/${Date.now()}-${m.name}`,{error:y}=await U.storage.from("coaching-files").upload(x,m);if(y)throw y;const{error:g}=await U.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:x,file_name:m.name,file_size_bytes:m.size,mime_type:m.type});if(g)throw g;re.success("File uploaded"),o()}catch(x){re.error(x.message||"Upload failed")}finally{i(!1),r.current&&(r.current.value="")}}},d=async h=>{const{data:m,error:p}=await U.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(p||!m)return re.error("Could not get download link");window.open(m.signedUrl,"_blank")},u=async h=>{await Bi("Delete this file?")&&(await U.storage.from("coaching-files").remove([h.file_url]),await U.from("coaching_shared_files").delete().eq("id",h.id),o())};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Shared Files"}),e.jsxs(B,{size:"sm",onClick:()=>{var h;return(h=r.current)==null?void 0:h.click()},disabled:a,children:[e.jsx(Ja,{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(be,{children:e.jsx(Re,{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(be,{children:e.jsxs(Re,{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($r,{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 · `:"",Bs(new Date(h.created_at),"PP")]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(ii,{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(Rn,{className:"h-4 w-4"})})]})},h.id))})]})}function N2s(){var m,p,x,y;const{id:s}=$i(),t=Hn(),n=as(),{data:r,isLoading:a}=m2s(s),{data:i=[]}=SCt(s),{data:l=[]}=CCt(s),[o,c]=j.useState(!1),[d,u]=j.useState(!1);if(a)return e.jsx(Vs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!r)return e.jsx(Vs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const h=r;return e.jsxs(Vs,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(be,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Re,{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(Ra,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(Fi,{src:((m=h.agent)==null?void 0:m.avatar_url)||void 0}),e.jsx(Da,{className:"text-2xl",children:(((p=h.agent)==null?void 0:p.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((x=h.agent)==null?void 0:x.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(y=h.agent)==null?void 0:y.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(qe,{variant:"secondary",className:"capitalize",children:(h.pipeline_stage||"active").replace("_"," ")}),e.jsx(qe,{variant:"outline",className:"capitalize",children:h.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(S2s,{value:h.pipeline_stage||"active",onChange:async g=>{await U.from("coaching_assignments").update({pipeline_stage:g}).eq("id",h.id),n.invalidateQueries({queryKey:["coaching-assignment",h.id]}),n.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsx(k2s,{assignment:h}),e.jsxs(fa,{defaultValue:"sessions",children:[e.jsxs(xa,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(ss,{value:"sessions",children:[e.jsx(ra,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(ss,{value:"actions",children:[e.jsx(zp,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(ss,{value:"goals",children:[e.jsx(uu,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(ss,{value:"kpis",children:[e.jsx(kl,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(ss,{value:"messages",children:[e.jsx(ro,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(ss,{value:"files",children:[e.jsx(ny,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(ss,{value:"notes",children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(ns,{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(Js,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(be,{children:e.jsx(Re,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(g=>e.jsx(be,{children:e.jsx(Re,{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:Bs(new Date(g.scheduled_at),"PPp")}),e.jsx(qe,{variant:"outline",className:"capitalize",children:g.status}),g.template&&e.jsx(qe,{variant:"secondary",children:g.template}),g.zoom_join_url&&e.jsx("a",{href:g.zoom_join_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary underline",children:"Join Zoom"})]}),g.agenda&&e.jsxs("p",{className:"text-sm mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent's agenda:"})," ",g.agenda]}),g.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:g.summary}),g.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(du,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:g.private_notes})]})]})})})},g.id))})]}),e.jsxs(ns,{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(Js,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(be,{children:e.jsx(Re,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(g=>e.jsx(be,{children:e.jsxs(Re,{className:"p-3 flex items-center gap-3",children:[e.jsx(wi,{checked:g.status==="done",onCheckedChange:async b=>{await U.from("coaching_action_items").update({status:b?"done":"open",completed_at:b?new Date().toISOString():null}).eq("id",g.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:g.status==="done"?"line-through text-muted-foreground":"font-medium",children:g.title}),g.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:g.description})]}),g.due_date&&e.jsx(qe,{variant:"outline",children:Bs(new Date(g.due_date),"MMM d")}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:g.priority})]})},g.id))})]}),e.jsx(ns,{value:"goals",children:e.jsx(RCt,{assignmentId:h.id,canEdit:!0})}),e.jsx(ns,{value:"kpis",children:h.agent_id&&e.jsx(ICt,{agentUserId:h.agent_id})}),e.jsx(ns,{value:"messages",children:e.jsx(ACt,{assignmentId:h.id})}),e.jsx(ns,{value:"files",children:e.jsx(DCt,{assignmentId:h.id})}),e.jsx(ns,{value:"notes",className:"space-y-4",children:e.jsx(be,{children:e.jsx(Re,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(C2s,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(A2s,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function k2s({assignment:s}){const t=as(),[n,r]=j.useState(s.sessions_per_month==null?"":String(s.sessions_per_month)),[a,i]=j.useState(!1),l=async()=>{i(!0);const o=n.trim()===""?null:Math.max(1,parseInt(n,10)||1),{error:c}=await U.from("coaching_assignments").update({sessions_per_month:o}).eq("id",s.id);if(i(!1),c)return re.error(c.message);re.success("Session allowance updated"),t.invalidateQueries({queryKey:["coaching-assignment",s.id]})};return e.jsx(be,{children:e.jsxs(Re,{className:"p-4 flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4"})," Monthly session allowance"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank to use your coach default. This agent books these on their My Coach page."})]}),e.jsx(ye,{type:"number",min:1,max:31,placeholder:"Default",value:n,onChange:o=>r(o.target.value),className:"w-28"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:l,disabled:a,children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save"]})]})})}function S2s({value:s,onChange:t}){return e.jsxs(vs,{value:s,onValueChange:t,children:[e.jsx(gs,{className:"w-40",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"onboarding",children:"Onboarding"}),e.jsx(Je,{value:"active",children:"Active"}),e.jsx(Je,{value:"thriving",children:"Thriving"}),e.jsx(Je,{value:"at_risk",children:"At Risk"}),e.jsx(Je,{value:"graduated",children:"Graduated"})]})]})}function C2s({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=j.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=j.useState(60),[c,d]=j.useState("weekly_1on1"),[u,h]=j.useState(""),[m,p]=j.useState(""),[x,y]=j.useState(!1),[g,b]=j.useState(!0),[v,k]=j.useState(null),[C,T]=j.useState(!1),M=async()=>{T(!0);const{data:L,error:I}=await U.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(T(!1),I||L!=null&&L.error)return re.error((L==null?void 0:L.error)||(I==null?void 0:I.message)||"Failed to generate brief");k(L.brief||"No brief returned.")},P=async()=>{y(!0);const{data:L,error:I}=await U.from("coaching_sessions").insert({assignment_id:n,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:u,private_notes:m,status:"completed"}).select("id").maybeSingle();if(I)return y(!1),re.error(I.message);if(re.success("Session saved"),g&&u.trim()&&(L!=null&&L.id)){const{error:O}=await U.functions.invoke("coaching-send-recap",{body:{sessionId:L.id}});O?re.error("Saved, but recap email failed: "+O.message):re.success("Recap emailed to agent")}y(!1),r==null||r(),t(!1),h(""),p(""),k(null)};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(zs,{children:"New Session"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:M,disabled:C,children:[C?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[v&&e.jsxs("div",{className:"rounded-lg border bg-gradient-to-br from-[#406E71]/5 to-[#2a4c64]/5 p-3 text-sm whitespace-pre-wrap max-h-60 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[#406E71] mb-2",children:[e.jsx(yn,{className:"h-3 w-3"})," AI Brief"]}),v]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"When"}),e.jsx(ye,{type:"datetime-local",value:a,onChange:L=>i(L.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(ye,{type:"number",value:l,onChange:L=>o(Number(L.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(vs,{value:c,onValueChange:d,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(Je,{value:"grow",children:"GROW Model"}),e.jsx(Je,{value:"goal_review",children:"Goal Review"}),e.jsx(Je,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Ds,{rows:4,value:u,onChange:L=>h(L.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(du,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Ds,{rows:3,value:m,onChange:L=>p(L.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(wi,{checked:g,onCheckedChange:L=>b(!!L)}),e.jsx(Dr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:P,disabled:x,children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function A2s({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState("medium"),[m,p]=j.useState(!1),x=async()=>{if(!a.trim())return;p(!0);const{error:y}=await U.from("coaching_action_items").insert({assignment_id:n,title:a,description:l||null,due_date:c||null,priority:u});if(p(!1),y)return re.error(y.message);re.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ye,{placeholder:"Title",value:a,onChange:y=>i(y.target.value)}),e.jsx(Ds,{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(ye,{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(vs,{value:u,onValueChange:h,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"low",children:"Low"}),e.jsx(Je,{value:"medium",children:"Medium"}),e.jsx(Je,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:x,disabled:m,children:"Add"})]})]})})}function IOe({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 T2s({coachId:s}){const[t,n]=j.useState([]),[r,a]=j.useState(!0);j.useEffect(()=>{(async()=>{const{data:l}=await U.from("coaching_reviews").select("*").eq("coach_id",s).eq("is_published",!0).order("created_at",{ascending:!1}),o=l||[];if(o.length){const c=o.map(h=>h.agent_id),{data:d}=await U.from("profiles").select("id, name, avatar_url").in("id",c),u=new Map((d||[]).map(h=>[h.id,h]));o.forEach(h=>h.profile=u.get(h.agent_id))}n(o),a(!1)})()},[s]);const i=t.length?t.reduce((l,o)=>l+o.rating,0)/t.length:0;return r||!t.length?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Reviews"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(IOe,{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(be,{children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(Ra,{className:"h-9 w-9",children:[e.jsx(Fi,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(Da,{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(IOe,{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 E2s({coachId:s,assignmentId:t}){const{user:n}=Ns(),[r,a]=j.useState(null),[i,l]=j.useState(0),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(!1);j.useEffect(()=>{n&&(async()=>{const{data:x}=await U.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",n.id).maybeSingle();x&&(a(x),l(x.rating),c(x.title||""),u(x.body||""))})()},[n,s]);const p=async()=>{if(!n)return;if(!i)return re.error("Pick a rating");m(!0);const x={coach_id:s,agent_id:n.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:y}=r?await U.from("coaching_reviews").update(x).eq("id",r.id):await U.from("coaching_reviews").insert(x);if(m(!1),y)return re.error(y.message);re.success("Thanks for your review!"),a({...x,id:r==null?void 0:r.id})};return e.jsx(be,{children:e.jsxs(Re,{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(IOe,{value:i,size:28,onChange:l}),e.jsx(ye,{placeholder:"Title (optional)",value:o,onChange:x=>c(x.target.value)}),e.jsx(Ds,{rows:4,placeholder:"What was your experience like?",value:d,onChange:x=>u(x.target.value)}),e.jsx(B,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":r?"Update review":"Submit review"})]})})}const Ise=async s=>{var r,a;const{data:t,error:n}=await U.functions.invoke("coaching-booking",{body:s});if(n){const i=(r=n==null?void 0:n.context)!=null&&r.text?await n.context.text():n.message;let l=i;try{l=((a=JSON.parse(i))==null?void 0:a.error)||i}catch{}throw new Error(l)}if(t!=null&&t.error)throw new Error(t.error);return t},nLe=s=>Bs(s,"yyyy-MM-dd"),Rat=s=>{const[t,n]=s.split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`};function M2s({assignmentId:s,upcoming:t=[]}){const n=as(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState(!1),{data:p,isLoading:x}=mt({queryKey:["coaching-booking-context",s],queryFn:()=>Ise({action:"context"})});j.useEffect(()=>{var le;!r&&((le=p==null?void 0:p.booking_types)!=null&&le.length)&&a(p.booking_types[0].id)},[p,r]);const y=j.useMemo(()=>new Date,[]),[g,b]=j.useState(()=>Vu(new Date)),v=(p==null?void 0:p.max_advance_days)||30,k=j.useMemo(()=>jd(xm(y),v-1),[y,v]),C=j.useMemo(()=>{const le=Vu(g);return le{const le=Uv(g);return le>k?k:le},[g,k]),M=Math.max(0,Ky(T,C)+1),{data:P={},isFetching:L}=mt({queryKey:["coaching-availability",r,nLe(C),M],enabled:!!r&&M>0,queryFn:async()=>(await Ise({action:"availability",booking_type_id:r,start:nLe(C),days:M})).availability||{}}),I=j.useMemo(()=>{const le=Vu(g),ue=Uv(g).getDate(),oe=le.getDay(),ie=Array.from({length:oe},()=>null);for(let de=0;deObject.entries(P).filter(([,le])=>le.length>0),[P]),$=i?P[i]||[]:[],q=L,W=j.useMemo(()=>{const le=[{label:"Morning",items:[]},{label:"Afternoon",items:[]},{label:"Evening",items:[]}];for(const ue of $){const oe=Number(ue.split(":")[0]);oe<12?le[0].items.push(ue):oe<17?le[1].items.push(ue):le[2].items.push(ue)}return le.filter(ue=>ue.items.length>0)},[$]),G=(p==null?void 0:p.booking_types.find(le=>le.id===r))||null,K=((p==null?void 0:p.sessions_remaining)??0)<=0,ee=async()=>{if(!(!r||!i||!o)){m(!0);try{await Ise({action:"book",booking_type_id:r,date:i,time:o,agenda:d||null}),re.success("Session booked — check your Zoom link below."),c(null),u(""),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-availability"]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(le){re.error(le.message||"Could not book that session")}finally{m(!1)}}},J=async le=>{if(await Bi("Cancel this coaching session?"))try{await Ise({action:"cancel",session_id:le}),re.success("Session cancelled"),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(ue){re.error(ue.message||"Could not cancel")}};return x?e.jsx(be,{children:e.jsxs(Re,{className:"p-8 flex items-center justify-center text-muted-foreground gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Loading your coach's calendar…"]})}):p!=null&&p.scheduler_ready?e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{children:e.jsxs(Re,{className:"p-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Vc,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium",children:[p.sessions_remaining," of ",p.sessions_limit," sessions left this month"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your allowance resets on the 1st."})]})]}),K&&e.jsx(qe,{variant:"secondary",children:"All booked up"})]})}),t.length>0&&e.jsx(be,{children:e.jsxs(Re,{className:"p-4 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Upcoming sessions"}),t.map(le=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-3 rounded-lg border",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:Bs(new Date(le.scheduled_at),"EEE, MMM d · p")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[le.duration_minutes||30," minutes"]})]}),le.zoom_join_url&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:le.zoom_join_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"})," Join"]})}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>J(le.id),children:[e.jsx(Rd,{className:"h-4 w-4 mr-1"})," Cancel"]})]},le.id))]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-4 md:p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{className:"mb-2 block",children:"Session type"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:p.booking_types.map(le=>e.jsxs("button",{onClick:()=>{a(le.id),c(null)},className:`text-left p-3 rounded-lg border transition-colors ${r===le.id?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:"font-medium",children:le.name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1 mt-1",children:[e.jsx(Vr,{className:"h-3 w-3"})," ",le.duration_minutes," min"]}),le.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:le.description})]},le.id))})]}),e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{className:"block",children:"Pick a day"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:GU(g,y),onClick:()=>b(Ax(g,-1)),"aria-label":"Previous month",children:e.jsx(Cc,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium w-28 text-center",children:Bs(g,"MMMM yyyy")}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Vu(Ax(g,1))>k,onClick:()=>b(Ax(g,1)),"aria-label":"Next month",children:e.jsx(Qa,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:["S","M","T","W","T","F","S"].map((le,ue)=>e.jsx("div",{className:"text-[11px] text-muted-foreground text-center py-1",children:le},ue))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:I.map((le,ue)=>{if(!le)return e.jsx("div",{},`b${ue}`);const oe=nLe(le),ie=(P[oe]||[]).length,we=le>=xm(y)&&le<=k&&ie>0,je=i===oe;return e.jsxs("button",{disabled:!we,onClick:()=>{l(oe),c(null)},className:`aspect-square rounded-lg border text-sm flex flex-col items-center justify-center gap-1 transition-colors ${je?"border-primary bg-primary text-primary-foreground":we?"border-primary/30 bg-primary/5 hover:bg-primary/10 font-medium":"border-transparent text-muted-foreground/50 cursor-not-allowed"}`,title:we?`${ie} opening${ie===1?"":"s"}`:"No openings",children:[e.jsx("span",{className:"leading-none",children:Bs(le,"d")}),e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${je?"bg-primary-foreground":we?"bg-primary":"bg-transparent"}`})]},oe)})}),e.jsx("div",{className:"mt-3 flex items-center gap-2 text-xs text-muted-foreground",children:L?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-3 w-3 animate-spin"})," Loading your coach's openings…"]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-3 w-3 text-primary"}),O.length===0?"No openings this month — try the next month.":`${O.length} day${O.length===1?"":"s"} with openings this month`]})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"mb-2 block",children:i?`Available times · ${Bs(new Date(`${i}T12:00:00`),"EEE, MMM d")}`:"Available times"}),i?q?e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Checking availability…"]}):$.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No openings on this day — try another date."}):e.jsx("div",{className:"space-y-3 max-h-[320px] overflow-y-auto pr-1",children:W.map(le=>e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:le.label}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:le.items.map(ue=>e.jsx("button",{onClick:()=>c(ue),className:`py-2 rounded-lg border text-sm transition-colors ${o===ue?"border-primary bg-primary/10 font-medium":"hover:bg-muted/50"}`,children:Rat(ue)},ue))})]},le.label))}):e.jsx("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground text-center",children:"Select a highlighted day to see open times."}),!L&&O.length>0&&e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:O.slice(0,3).map(([le,ue])=>e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{l(le),c(null)},children:[Bs(new Date(`${le}T12:00:00`),"EEE MMM d")," · ",ue.length," open"]},le))})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"agenda",children:"What do you want to work on? (optional)"}),e.jsx(Ds,{id:"agenda",rows:3,value:d,onChange:le=>u(le.target.value),placeholder:"Share context so your coach can prep."})]}),e.jsxs(B,{onClick:ee,disabled:h||K,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[h?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Book ",G==null?void 0:G.name," — ",i&&Bs(new Date(`${i}T12:00:00`),"MMM d")," at ",Rat(o)]}),K&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You've used your sessions for this month. Message your coach if you need more."})]})]})})]}):e.jsx(be,{children:e.jsx(Re,{className:"p-8 text-center text-muted-foreground",children:"Your coach hasn't opened their coaching calendar yet. Check back soon."})})}function L2s(){var m,p,x,y,g,b;const{user:s}=Ns(),{data:t,isLoading:n,refetch:r}=h2s(),a=as(),i=t==null?void 0:t.id,{data:l=[]}=SCt(i),{data:o=[]}=CCt(i);if(j.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&U.functions.invoke("coaching-verify-checkout").then(()=>{r(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[r,a]),n)return e.jsx(Vs,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Vs,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Uh,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're not in a coaching program yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Browse LevelUp Certified Coaches to find a fit (coming soon)."})]})});const c=t,d=o.filter(v=>v.status!=="done"),u=o.length-d.length,h=l.filter(v=>v.status!=="cancelled"&&new Date(v.scheduled_at).getTime()>Date.now());return e.jsx(Vs,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(be,{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(Ra,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(Fi,{src:((m=c.coachProfile)==null?void 0:m.avatar_url)||void 0}),e.jsx(Da,{className:"text-2xl bg-white/20 text-white",children:(((p=c.coachProfile)==null?void 0:p.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80 mb-1",children:[e.jsx(yn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider",children:"Your Coach"})]}),e.jsx("h1",{className:"text-3xl font-bold",children:((x=c.coachProfile)==null?void 0:x.name)||"Your Coach"}),((y=c.coach)==null?void 0:y.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((g=c.coach)==null?void 0:g.is_certified)&&e.jsx(qe,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(qe,{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(rLe,{icon:zp,label:"Open action items",value:d.length}),e.jsx(rLe,{icon:uu,label:"Completed",value:u}),e.jsx(rLe,{icon:ra,label:"Sessions",value:l.length})]}),((b=c.coach)==null?void 0:b.id)&&e.jsx(E2s,{coachId:c.coach.id,assignmentId:i}),e.jsxs(fa,{defaultValue:"book",children:[e.jsxs(xa,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(ss,{value:"book",children:[e.jsx(Wy,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Book"})]}),e.jsxs(ss,{value:"actions",children:[e.jsx(zp,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(ss,{value:"sessions",children:[e.jsx(ra,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(ss,{value:"goals",children:[e.jsx(uu,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(ss,{value:"kpis",children:[e.jsx(kl,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(ss,{value:"messages",children:[e.jsx(ro,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(ss,{value:"files",children:[e.jsx(ny,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(ns,{value:"book",children:e.jsx(M2s,{assignmentId:i,upcoming:h})}),e.jsx(ns,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(be,{children:e.jsx(Re,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(v=>e.jsx(be,{children:e.jsxs(Re,{className:"p-3 flex items-center gap-3",children:[e.jsx(wi,{checked:v.status==="done",onCheckedChange:async k=>{await U.from("coaching_action_items").update({status:k?"done":"open",completed_at:k?new Date().toISOString():null}).eq("id",v.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:v.status==="done"?"line-through text-muted-foreground":"font-medium",children:v.title}),v.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:v.description})]}),v.due_date&&e.jsx(qe,{variant:"outline",children:Bs(new Date(v.due_date),"MMM d")}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:v.priority})]})},v.id))}),e.jsx(ns,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(be,{children:e.jsx(Re,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(v=>e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:Bs(new Date(v.scheduled_at),"PPp")}),e.jsx(qe,{variant:"outline",className:"capitalize",children:v.status})]}),v.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:v.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},v.id))}),e.jsx(ns,{value:"goals",children:e.jsx(RCt,{assignmentId:i,canEdit:!1})}),e.jsx(ns,{value:"kpis",children:s&&e.jsx(ICt,{agentUserId:s.id})}),e.jsx(ns,{value:"messages",children:e.jsx(ACt,{assignmentId:i})}),e.jsx(ns,{value:"files",children:e.jsx(DCt,{assignmentId:i})})]})]})})}function rLe({icon:s,label:t,value:n}){return e.jsx(be,{children:e.jsxs(Re,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}const Dat="coaching_access",aLe=s=>((s==null?void 0:s.name)||(s==null?void 0:s.email)||"?").trim().slice(0,2).toUpperCase(),iLe=s=>!!s.expires_at&&new Date(s.expires_at).getTime()<=Date.now();function P2s(){const s=as(),[t,n]=j.useState(""),[r,a]=j.useState([]),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(""),{data:h=[],isLoading:m}=mt({queryKey:["coaching-entitlements"],queryFn:async()=>{const{data:O,error:$}=await U.from("feature_entitlements").select("id, user_id, enabled, expires_at, tier, notes, enabled_at").eq("feature_key",Dat).order("enabled_at",{ascending:!1});if($)throw $;return O||[]}}),{data:p=[]}=mt({queryKey:["coaching-assigned-agents"],queryFn:async()=>{const{data:O,error:$}=await U.from("coaching_assignments").select("agent_id, coach_id, status").eq("status","active");if($)throw $;return O||[]}}),x=j.useMemo(()=>{const O=new Set;return h.forEach($=>O.add($.user_id)),p.forEach($=>O.add($.agent_id)),Array.from(O)},[h,p]),{data:y={}}=mt({queryKey:["coaching-access-profiles",x.join(",")],enabled:x.length>0,queryFn:async()=>{const O={};for(let $=0;${O[W.id]=W})}return O}});j.useEffect(()=>{const O=t.trim();if(O.length<2){a([]),l(!1);return}l(!0);const $=setTimeout(async()=>{const{data:q}=await U.from("profiles").select("id, name, email, avatar_url").or(`email.ilike.%${O}%,name.ilike.%${O}%`).limit(12);a(q||[]),l(!1)},250);return()=>clearTimeout($)},[t]);const g=j.useMemo(()=>{const O=new Map;return h.forEach($=>O.set($.user_id,$)),O},[h]),b=j.useMemo(()=>new Set(p.map(O=>O.agent_id)),[p]),v=()=>{s.invalidateQueries({queryKey:["coaching-entitlements"]}),s.invalidateQueries({queryKey:["coaching-access-profiles"]}),s.invalidateQueries({queryKey:["coaching-access"]})},k=async(O,$={})=>{var G;const{data:q}=await U.auth.getUser(),{error:W}=await U.from("feature_entitlements").upsert({user_id:O,feature_key:Dat,enabled:$.enabled??!0,expires_at:$.expires_at??null,notes:$.notes??null,tier:$.tier??null,enabled_by:((G=q==null?void 0:q.user)==null?void 0:G.id)??null,enabled_at:new Date().toISOString(),updated_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});return W?(re.error(W.message),!1):(v(),!0)},C=async O=>{await k(O.id)&&re.success(`Coaching access granted to ${O.name||O.email}`),n(""),a([])},T=async(O,$)=>{const{error:q}=await U.from("feature_entitlements").update({enabled:$,updated_at:new Date().toISOString()}).eq("id",O.id);if(q)return re.error(q.message);re.success($?"Access enabled":"Access paused"),v()},M=async O=>{if(!await Bi({title:"Revoke coaching access?",description:`${O.profile.name||O.profile.email||"This member"} will lose access to the coaching area unless they're assigned to a coach.`,confirmText:"Revoke access",destructive:!0}))return;const{error:q}=await U.from("feature_entitlements").delete().eq("id",O.entitlement.id);if(q)return re.error(q.message);re.success("Coaching access revoked"),v()},P=j.useMemo(()=>{const O=d.trim().toLowerCase(),$=h.map(q=>({entitlement:q,profile:y[q.user_id]}));return O?$.filter(({profile:q})=>`${(q==null?void 0:q.name)||""} ${(q==null?void 0:q.email)||""}`.toLowerCase().includes(O)):$},[h,y,d]),L=h.filter(O=>O.enabled&&!iLe(O)).length,I=p.filter(O=>!g.has(O.agent_id));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(oLe,{icon:a0,label:"Granted access",value:L,hint:"Standalone entitlements"}),e.jsx(oLe,{icon:Bn,label:"Coached members",value:b.size,hint:"Active coach assignments"}),e.jsx(oLe,{icon:yn,label:"Total with access",value:new Set([...h.filter(O=>O.enabled&&!iLe(O)).map(O=>O.user_id),...b]).size,hint:"Unique members"})]}),e.jsx(be,{children:e.jsxs(Re,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(b3,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Grant Coaching Access"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Give any member access to the coaching area — meeting notes, one-on-one scheduling and their coach workspace — even before a coach is assigned."}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{className:"pl-9",placeholder:"Search members by name or email…",value:t,onChange:O=>n(O.target.value)})]}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-lg divide-y max-h-80 overflow-auto",children:i?e.jsxs("div",{className:"p-3 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Searching…"]}):r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No members found"}):r.map(O=>{const $=g.get(O.id),q=b.has(O.id);return e.jsxs("div",{className:"flex items-center gap-3 p-2.5 hover:bg-muted/40",children:[e.jsxs(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:O.avatar_url||void 0}),e.jsx(Da,{className:"text-xs",children:aLe(O)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:O.name||O.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:O.email})]}),$?e.jsx(qe,{variant:"outline",className:"shrink-0",children:"Already granted"}):q?e.jsxs(qe,{variant:"outline",className:"shrink-0",children:[e.jsx(Rc,{className:"h-3 w-3 mr-1"}),"Has coach"]}):e.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>c({profile:O}),children:"Options"}),e.jsxs(B,{size:"sm",className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>C(O),children:[e.jsx(Sl,{className:"h-4 w-4 mr-1"})," Grant"]})]})]},O.id)})})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(a0,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Members with granted access"}),e.jsx(qe,{variant:"outline",children:h.length}),e.jsx("div",{className:"ml-auto w-full sm:w-64",children:e.jsx(ye,{placeholder:"Filter list…",value:d,onChange:O=>u(O.target.value)})})]}),m?e.jsxs("div",{className:"p-6 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):P.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground border rounded-lg",children:"No standalone grants yet. Search above to give a member access."}):e.jsx("div",{className:"border rounded-lg divide-y",children:P.map(({entitlement:O,profile:$})=>{const q=iLe(O);return e.jsxs("div",{className:"flex items-center gap-3 p-3 flex-wrap",children:[e.jsxs(Ra,{className:"h-9 w-9",children:[e.jsx(Fi,{src:($==null?void 0:$.avatar_url)||void 0}),e.jsx(Da,{className:"text-xs",children:aLe($)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:($==null?void 0:$.name)||($==null?void 0:$.email)||O.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:$==null?void 0:$.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[q?e.jsx(qe,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:"Expired"}):O.enabled?e.jsx(qe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:"Active"}):e.jsx(qe,{variant:"outline",children:"Paused"}),b.has(O.user_id)&&e.jsxs(qe,{variant:"outline",children:[e.jsx(Rc,{className:"h-3 w-3 mr-1"}),"Has coach"]}),O.tier&&e.jsx(qe,{variant:"outline",children:O.tier}),O.expires_at&&e.jsxs("span",{className:"text-xs text-muted-foreground inline-flex items-center gap-1",children:[e.jsx(ym,{className:"h-3 w-3"}),q?"Expired":"Expires"," ",new Date(O.expires_at).toLocaleDateString()]})]}),O.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic truncate",children:O.notes})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(Mn,{checked:O.enabled&&!q,onCheckedChange:W=>T(O,W)}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>c({profile:$||{id:O.user_id,name:null,email:null},entitlement:O}),children:"Edit"}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600 hover:bg-rose-50",onClick:()=>M({profile:$||{id:O.user_id,name:null,email:null},entitlement:O}),children:e.jsx(dr,{className:"h-4 w-4"})})]})]},O.id)})})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Access through a coach assignment"}),e.jsx(qe,{variant:"outline",children:I.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These members already reach coaching because they're assigned to a coach — no entitlement needed."}),I.length===0?e.jsx("div",{className:"p-6 text-center text-sm text-muted-foreground border rounded-lg",children:"No active assignments."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(O=>{const $=y[O.agent_id];return e.jsxs("div",{className:"flex items-center gap-2 border rounded-full pl-1 pr-3 py-1",children:[e.jsxs(Ra,{className:"h-6 w-6",children:[e.jsx(Fi,{src:($==null?void 0:$.avatar_url)||void 0}),e.jsx(Da,{className:"text-[10px]",children:aLe($)})]}),e.jsx("span",{className:"text-sm",children:($==null?void 0:$.name)||($==null?void 0:$.email)||O.agent_id})]},O.agent_id)})})]})}),e.jsx(I2s,{state:o,onClose:()=>c(null),onSave:async O=>{if(!o)return;await k(o.profile.id,O)&&(re.success("Coaching access saved"),c(null))}})]})}function oLe({icon:s,label:t,value:n,hint:r}){return e.jsx(be,{children:e.jsxs(Re,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-sm font-medium",children:t}),e.jsx("div",{className:"text-xs text-muted-foreground",children:r})]})]})})}function I2s({state:s,onClose:t,onSave:n}){const[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(!1);j.useEffect(()=>{if(!s)return;const x=s.entitlement;a(x!=null&&x.expires_at?x.expires_at.slice(0,10):""),l((x==null?void 0:x.notes)||""),c((x==null?void 0:x.tier)||""),u(x?x.enabled:!0)},[s]);const p=async()=>{m(!0),await n({expires_at:r?new Date(`${r}T23:59:59`).toISOString():null,notes:i.trim()||null,tier:o.trim()||null,enabled:d}),m(!1)};return e.jsx(Fs,{open:!!s,onOpenChange:x=>!x&&t(),children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:s!=null&&s.entitlement?"Edit coaching access":"Grant coaching access"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:(s==null?void 0:s.profile.name)||(s==null?void 0:s.profile.email)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s==null?void 0:s.profile.email})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Access enabled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to pause without removing the grant."})]}),e.jsx(Mn,{checked:d,onCheckedChange:u})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Expires on (optional)"}),e.jsx(ye,{type:"date",value:r,onChange:x=>a(x.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank for ongoing access."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Tier / plan label (optional)"}),e.jsx(ye,{value:o,onChange:x=>c(x.target.value),placeholder:"e.g. Premium, Beta, Comp"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Internal notes"}),e.jsx(Ds,{value:i,onChange:x=>l(x.target.value),rows:3,placeholder:"Why this member has access…"})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(B,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":"Save access"})]})]})})}function R2s(){const s=as(),[t,n]=j.useState(""),[r,a]=j.useState("active"),{data:i=[]}=mt({queryKey:["admin-coaches-lite"],queryFn:async()=>{const{data:p,error:x}=await U.from("coaches").select("id, user_id");if(x)throw x;const y=(p||[]).map(v=>v.user_id);if(!y.length)return[];const{data:g}=await U.from("profiles").select("id, name, email").in("id",y),b=new Map((g||[]).map(v=>[v.id,v]));return(p||[]).map(v=>{var k,C;return{id:v.id,label:((k=b.get(v.user_id))==null?void 0:k.name)||((C=b.get(v.user_id))==null?void 0:C.email)||v.user_id}})}}),{data:l=[],isLoading:o}=mt({queryKey:["admin-coaching-assignments"],queryFn:async()=>{const{data:p,error:x}=await U.from("coaching_assignments").select("*").order("created_at",{ascending:!1});if(x)throw x;const y=[...new Set((p||[]).map(v=>v.agent_id))],{data:g}=y.length?await U.from("profiles").select("id, name, email").in("id",y):{data:[]},b=new Map((g||[]).map(v=>[v.id,v]));return(p||[]).map(v=>({...v,agent:b.get(v.agent_id)}))}}),c=p=>{var x;return((x=i.find(y=>y.id===p))==null?void 0:x.label)||"—"},d=j.useMemo(()=>{const p=t.trim().toLowerCase();return l.filter(x=>{var y,g;return r!=="all"&&x.status!==r?!1:p?(((y=x.agent)==null?void 0:y.name)||"").toLowerCase().includes(p)||(((g=x.agent)==null?void 0:g.email)||"").toLowerCase().includes(p)||c(x.coach_id).toLowerCase().includes(p):!0})},[l,t,r,i]),u=()=>{s.invalidateQueries({queryKey:["admin-coaching-assignments"]}),s.invalidateQueries({queryKey:["coach-roster"]})},h=async(p,x)=>{var b,v;if(x===p.coach_id||!await Bi({title:"Switch coach?",description:`${((b=p.agent)==null?void 0:b.name)||((v=p.agent)==null?void 0:v.email)} will move from ${c(p.coach_id)} to ${c(x)}. Session history stays with the assignment.`,confirmText:"Switch coach"}))return;const{error:g}=await U.from("coaching_assignments").update({coach_id:x}).eq("id",p.id);if(g)return re.error(g.message);re.success("Coach switched"),u()},m=async(p,x)=>{var g,b;if(x==="ended"&&!await Bi({title:"End assignment?",description:`${((g=p.agent)==null?void 0:g.name)||((b=p.agent)==null?void 0:b.email)} will lose access to the coaching workspace unless they have standalone access.`,confirmText:"End assignment",destructive:!0}))return;const{error:y}=await U.from("coaching_assignments").update({status:x,ended_at:x==="ended"?new Date().toISOString():null}).eq("id",p.id);if(y)return re.error(y.message);re.success(x==="ended"?"Assignment ended":"Assignment reactivated"),u()};return e.jsx(be,{children:e.jsxs(Re,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach assignments"}),e.jsx(qe,{variant:"secondary",className:"ml-auto",children:d.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Switch an agent to a different coach, end an assignment, or reactivate a past one."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(ye,{placeholder:"Search by agent or coach…",value:t,onChange:p=>n(p.target.value)}),e.jsxs(vs,{value:r,onValueChange:p=>a(p),children:[e.jsx(gs,{className:"sm:w-40",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"active",children:"Active"}),e.jsx(Je,{value:"ended",children:"Ended"}),e.jsx(Je,{value:"all",children:"All"})]})]})]}),o?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):d.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:"No assignments found."}):e.jsx("div",{className:"divide-y border rounded-md",children:d.map(p=>{var x,y,g;return e.jsxs("div",{className:"p-3 flex flex-col md:flex-row md:items-center gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:((x=p.agent)==null?void 0:x.name)||((y=p.agent)==null?void 0:y.email)||p.agent_id}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[(g=p.agent)==null?void 0:g.email," · ",p.pipeline_stage||"onboarding",p.status==="ended"&&" · ended"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(AW,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(vs,{value:p.coach_id,onValueChange:b=>h(p,b),children:[e.jsx(gs,{className:"w-full md:w-56 h-9",children:e.jsx(bs,{})}),e.jsx(ys,{children:i.map(b=>e.jsx(Je,{value:b.id,children:b.label},b.id))})]}),p.status==="active"?e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>m(p,"ended"),children:[e.jsx(uz,{className:"h-4 w-4 mr-1"})," End"]}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>m(p,"active"),children:[e.jsx(bm,{className:"h-4 w-4 mr-1"})," Reactivate"]})]})]},p.id)})})]})})}function D2s(){const s=as(),[t,n]=j.useState(""),[r,a]=j.useState([]),[i,l]=j.useState(null),{data:o=[],isLoading:c}=mt({queryKey:["admin-coaches"],queryFn:async()=>{const{data:h,error:m}=await U.from("coaches").select("*").order("created_at",{ascending:!1});if(m)throw m;if(!(h!=null&&h.length))return[];const p=h.map(g=>g.user_id),{data:x}=await U.from("profiles").select("id, name, email, avatar_url").in("id",p),y=new Map((x||[]).map(g=>[g.id,g]));return h.map(g=>({...g,profile:y.get(g.user_id)}))}});j.useEffect(()=>{const h=t.trim();if(h.length<2){a([]);return}const m=setTimeout(async()=>{const{data:p}=await U.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(10);a(p||[])},250);return()=>clearTimeout(m)},[t]);const d=async h=>{const{error:m}=await U.functions.invoke("manage-user-roles",{body:{userId:h.id,role:"coach",action:"add"}});if(m)return re.error(m.message);const{error:p}=await U.from("coaches").insert({user_id:h.id});if(p&&!String(p.message).includes("duplicate"))return re.error(p.message);re.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,m)=>{const{error:p}=await U.from("coaches").update({is_certified:m}).eq("id",h);if(p)return re.error(p.message);re.success(m?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(Vs,{title:"Coaching Admin",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Uh,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsxs(fa,{defaultValue:"coaches",className:"space-y-6",children:[e.jsxs(xa,{className:"flex-wrap h-auto",children:[e.jsx(ss,{value:"coaches",children:"Coaches"}),e.jsx(ss,{value:"assignments",children:"Assignments"}),e.jsx(ss,{value:"access",children:"Coaching Access"}),e.jsx(ss,{value:"applications",children:"Applications"}),e.jsx(ss,{value:"settings",children:"Settings"})]}),e.jsx(ns,{value:"assignments",className:"space-y-6",children:e.jsx(R2s,{})}),e.jsx(ns,{value:"access",className:"space-y-6",children:e.jsx(P2s,{})}),e.jsx(ns,{value:"applications",className:"space-y-6",children:e.jsx(z2s,{})}),e.jsx(ns,{value:"settings",className:"space-y-6",children:e.jsx(O2s,{})}),e.jsxs(ns,{value:"coaches",className:"space-y-6",children:[e.jsx(be,{children:e.jsxs(Re,{className:"p-4 space-y-3",children:[e.jsx(ye,{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(Js,{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(be,{children:e.jsx(Re,{className:"p-6 text-center text-muted-foreground",children:"No coaches yet. Search for a user above to promote them."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:o.map(h=>{var m,p,x;return e.jsx(be,{children:e.jsxs(Re,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:((m=h.profile)==null?void 0:m.name)||((p=h.profile)==null?void 0:p.email)||h.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(x=h.profile)==null?void 0:x.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[h.is_certified&&e.jsxs(qe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(yn,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx(qe,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(Sl,{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(Mn,{checked:h.is_certified,onCheckedChange:y=>u(h.id,y)})]})]})},h.id)})})]})]})]})]}),e.jsx(F2s,{coachId:i,onClose:()=>l(null)})]})}function O2s(){const[s,t]=j.useState("1500"),[n,r]=j.useState(!1),[a,i]=j.useState(!1);j.useEffect(()=>{(async()=>{const{data:c}=await U.from("settings").select("value").eq("key","coaching_platform_fee_bps").maybeSingle();c!=null&&c.value&&t(String(c.value)),i(!0)})()},[]);const l=async()=>{const c=parseInt(s,10);if(isNaN(c)||c<0||c>5e3)return re.error("Enter a value between 0 and 5000 bps (0–50%)");r(!0);const{error:d}=await U.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(r(!1),d)return re.error(d.message);re.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(be,{children:e.jsxs(Re,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(QT,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Platform Fee"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"The percentage LevelUp takes from every coaching subscription. Stored as basis points (100 bps = 1%)."}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{children:"Fee (bps)"}),e.jsx(ye,{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 F2s({coachId:s,onClose:t}){const[n,r]=j.useState(""),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=as();j.useEffect(()=>{if(!s){r(""),i([]);return}},[s]),j.useEffect(()=>{const u=n.trim();if(u.length<2){i([]);return}o(!0);const h=setTimeout(async()=>{const{data:m}=await U.from("profiles").select("id, name, email").or(`email.ilike.%${u}%,name.ilike.%${u}%`).limit(15);i(m||[]),o(!1)},250);return()=>clearTimeout(h)},[n]);const d=async u=>{const{error:h}=await U.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(h)return re.error(h.message);re.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(Fs,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Assign Agent"})}),e.jsx(ye,{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(Nr,{children:e.jsx(B,{variant:"outline",onClick:t,children:"Close"})})]})})}function z2s(){const s=as(),[t,n]=j.useState("pending"),[r,a]=j.useState(null),{data:i=[],isLoading:l}=mt({queryKey:["coach-applications",t],queryFn:async()=>{let u=U.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(u=u.eq("status",t));const{data:h,error:m}=await u;if(m)throw m;return h||[]}}),{data:o=0}=mt({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await U.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,h)=>{const{error:m}=await U.from("coach_applications").update({status:h,reviewed_at:new Date().toISOString()}).eq("id",u);if(m)return re.error(m.message);re.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs(qe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs(qe,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(dr,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(qe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(be,{children:[e.jsxs(Re,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(WT,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(qe,{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(on,{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(Fs,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-3",children:[r.full_name,d(r.status)]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(BF,{icon:on,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(BF,{icon:pa,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(BF,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(BF,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(BF,{icon:Tr,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(BF,{icon:Tr,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(lLe,{label:"Specialties",children:r.specialties}),e.jsx(lLe,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(lLe,{label:"Results story",children:r.results_story}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(Ds,{defaultValue:r.admin_notes||"",rows:3,onBlur:async u=>{const h=u.target.value;h!==(r.admin_notes||"")&&(await U.from("coach_applications").update({admin_notes:h}).eq("id",r.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(Nr,{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(dr,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs(B,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(Vr,{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(da,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function BF({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 lLe({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 B2s(){const s=Hn(),{data:t}=SJ(),n=as(),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),{data:d,refetch:u}=mt({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:g}=await U.functions.invoke("coach-stripe-status");return g}}),{data:h=[]}=mt({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:g}=await U.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return g||[]}});j.useEffect(()=>{const g=new URLSearchParams(window.location.search);(g.get("onboarded")||g.get("refresh"))&&u()},[u]);const m=async()=>{var k,C;a(!0);const{data:g,error:b}=await U.functions.invoke("coach-stripe-connect");a(!1);let v=g==null?void 0:g.error;if(!v&&b)try{const T=await((C=(k=b==null?void 0:b.context)==null?void 0:k.json)==null?void 0:C.call(k));v=(T==null?void 0:T.error)||b.message}catch{v=b.message}if(v)return re.error(v,{duration:1e4});g!=null&&g.url&&(window.location.href=g.url)},p=d||{},x=!!(t!=null&&t.use_platform_stripe),y=x||p.connected&&p.charges_enabled;return e.jsx(Vs,{title:"Coaching · Billing",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(_a,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(be,{children:e.jsxs(Re,{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(ty,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:x?"Your coaching sales are billed through the main LevelUp Stripe account.":"Payouts go directly to your bank. LevelUp takes a small platform fee from each charge."})]}),y?e.jsxs(qe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(Rr,{className:"h-3 w-3"})," ",x?"Using LevelUp billing":"Connected"]}):p.connected?e.jsxs(qe,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(po,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(qe,{variant:"outline",children:"Not connected"})]}),!x&&e.jsxs(B,{onClick:m,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[y?"Update Stripe details":p.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(Tr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(be,{children:e.jsxs(Re,{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(Js,{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(g=>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:[g.name,g.is_active&&g.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:["$",(g.price_cents/100).toFixed(0)," / ",g.billing_interval,!g.is_active&&" · Inactive"]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{c(g),l(!0)},children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Bi("Delete this package?")&&(await U.from("coaching_packages").delete().eq("id",g.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(Rn,{className:"h-4 w-4"})})]},g.id))})]})}),e.jsx($2s,{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 $2s({open:s,onOpenChange:t,coachId:n,pkg:r,onSaved:a}){const[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState("month"),[p,x]=j.useState(!0),[y,g]=j.useState(!0),[b,v]=j.useState(!1);j.useEffect(()=>{s&&(l((r==null?void 0:r.name)||""),c((r==null?void 0:r.description)||""),u(r?(r.price_cents/100).toString():""),m((r==null?void 0:r.billing_interval)||"month"),x((r==null?void 0:r.is_active)??!0),g((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const k=async()=>{if(!i.trim()||!d)return re.error("Name and price required");v(!0);const C={coach_id:n,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:h,is_active:p,accepting_clients:y},{error:T}=r!=null&&r.id?await U.from("coaching_packages").update(C).eq("id",r.id):await U.from("coaching_packages").insert(C);if(v(!1),T)return re.error(T.message);re.success("Saved"),a==null||a(),t(!1)};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:r!=null&&r.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ye,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:C=>l(C.target.value)}),e.jsx(Ds,{rows:3,placeholder:"What's included",value:o,onChange:C=>c(C.target.value)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(ye,{type:"number",value:d,onChange:C=>u(C.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"month",children:"Monthly"}),e.jsx(Je,{value:"year",children:"Yearly"}),e.jsx(Je,{value:"one_time",children:"One-time"})]})]})]})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:C=>x(C.target.checked)}),"Active (visible to agents)"]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:y,onChange:C=>g(C.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Accepting new clients"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Uncheck if you're booked full — visitors will still see the package but can't sign up."})]})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:k,disabled:b,children:r!=null&&r.id?"Save":"Create"})]})]})})}function Oat({kind:s,value:t,onChange:n}){const r=j.useRef(null),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=j.useRef(null),h=j.useRef(null),m=j.useRef(null),p=j.useRef([]),[x,y]=j.useState(!1),g=s==="photo"?"image/*":"video/*",b=s==="photo"?10*1024*1024:200*1024*1024,v=async(L,I)=>{var K;const{data:O}=await U.auth.getUser(),$=(K=O.user)==null?void 0:K.id;if(!$)return re.error("Not signed in");if(L.size>b)return re.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const q=`${$}/${s}-${Date.now()}.${I}`,{error:W}=await U.storage.from("coach-media").upload(q,L,{upsert:!0,contentType:L.type||(s==="photo"?"image/jpeg":"video/webm")});if(W)return i(!1),re.error(W.message);const{data:G}=await U.storage.from("coach-media").createSignedUrl(q,60*60*24*365*10);i(!1),G!=null&&G.signedUrl&&(n(G.signedUrl),re.success("Uploaded"),d(null))},k=async L=>{const I=L.name.split(".").pop()||(s==="photo"?"jpg":"webm");await v(L,I)},C=async()=>{try{const L=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});h.current=L,y(!0),setTimeout(()=>{u.current&&(u.current.srcObject=L,u.current.play())},50);const I=new MediaRecorder(L,{mimeType:"video/webm"});p.current=[],I.ondataavailable=O=>O.data.size>0&&p.current.push(O.data),I.onstop=()=>{const O=new Blob(p.current,{type:"video/webm"});d(O),L.getTracks().forEach($=>$.stop())},m.current=I,I.start(),o(!0)}catch(L){re.error(L.message||"Could not access camera")}},T=()=>{var L;(L=m.current)==null||L.stop(),o(!1)},M=()=>{var L;(L=h.current)==null||L.getTracks().forEach(I=>I.stop()),y(!1),o(!1),d(null)},P=async()=>{c&&(await v(c,"webm"),M())};return j.useEffect(()=>()=>{var L;return(L=h.current)==null?void 0:L.getTracks().forEach(I=>I.stop())},[]),e.jsxs("div",{className:"space-y-2",children:[t&&e.jsx("div",{className:"rounded-lg overflow-hidden border bg-muted/30",children:s==="photo"?e.jsx("img",{src:t,alt:"Profile",className:"w-32 h-32 object-cover"}):e.jsx("video",{src:t,controls:!0,className:"w-full max-h-64"})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{ref:r,type:"file",accept:g,className:"hidden",onChange:L=>{var O;const I=(O=L.target.files)==null?void 0:O[0];I&&k(I),L.target.value=""}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var L;return(L=r.current)==null?void 0:L.click()},children:[a?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ja,{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:C,disabled:a||x,children:[e.jsx(s0,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(Rn,{className:"h-4 w-4 mr-1"})," Remove"]})]}),x&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-3 bg-background",children:[c?e.jsx("video",{src:URL.createObjectURL(c),controls:!0,className:"w-full max-h-64 rounded bg-black"}):e.jsx("video",{ref:u,muted:!0,playsInline:!0,className:"w-full max-h-64 rounded bg-black"}),e.jsxs("div",{className:"flex gap-2",children:[!c&&l&&e.jsxs(B,{type:"button",size:"sm",onClick:T,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(H_,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs(B,{type:"button",size:"sm",onClick:()=>{var L;return(L=m.current)==null?void 0:L.start()},children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{type:"button",size:"sm",onClick:P,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ja,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(B,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),C()},children:"Re-record"})]}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:M,children:"Cancel"})]})]})]})}function OCt(){const{user:s}=Ns(),t=as(),n=mt({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:g,error:b}=await U.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(b)throw b;return g},enabled:!!s}),r=mt({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:g,error:b}=await U.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(b)throw b;return g},enabled:!!s}),a=mt({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:g,error:b}=await U.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(b)throw b;return g},enabled:!!s}),i=mt({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:g,error:b}=await U.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(b)throw b;return g},enabled:!!s}),l=mt({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:g,error:b}=await U.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(b)throw b;return g},enabled:!!s}),o=vt({mutationFn:async()=>{const{data:g,error:b}=await U.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(b)throw b;const v=[{name:"Listing Consultation",description:"Get a comprehensive market analysis and listing strategy for your home",duration_minutes:60,color:"#10B981",icon:"Home",sort_order:0},{name:"Buyer Consultation",description:"Discuss your home search criteria, budget, and buying process",duration_minutes:45,color:"#3B82F6",icon:"Search",sort_order:1},{name:"Home Valuation",description:"Find out what your home is worth in today's market",duration_minutes:30,color:"#F59E0B",icon:"DollarSign",sort_order:2},{name:"General Meeting",description:"Coffee chat, check-in, or quick real estate question",duration_minutes:30,color:"#8B5CF6",icon:"Coffee",sort_order:3}],{error:k}=await U.from("agent_booking_types").insert(v.map(M=>({...M,user_id:s.id})));if(k)throw k;const C=[1,2,3,4,5].map(M=>({user_id:s.id,day_of_week:M,start_time:"09:00",end_time:"17:00"})),{error:T}=await U.from("agent_availability_slots").insert(C);if(T)throw T;return g},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),re.success("Scheduler set up successfully!")},onError:g=>re.error(g.message)}),c=vt({mutationFn:async g=>{const{error:b}=await U.from("agent_booking_settings").update(g).eq("user_id",s.id);if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),re.success("Settings updated")},onError:g=>re.error(g.message)}),d=vt({mutationFn:async g=>{const b={...g,user_id:s.id};if(g.id){const{error:v}=await U.from("agent_booking_types").update(b).eq("id",g.id);if(v)throw v}else{const{error:v}=await U.from("agent_booking_types").insert(b);if(v)throw v}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),re.success("Booking type saved")},onError:g=>re.error(g.message)}),u=vt({mutationFn:async g=>{const{error:b}=await U.from("agent_booking_types").delete().eq("id",g);if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),re.success("Booking type deleted")},onError:g=>re.error(g.message)}),h=vt({mutationFn:async g=>{const b={...g,user_id:s.id};if(g.id){const{error:v}=await U.from("agent_availability_slots").update(b).eq("id",g.id);if(v)throw v}else{const{error:v}=await U.from("agent_availability_slots").insert(b);if(v)throw v}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:g=>re.error(g.message)}),m=vt({mutationFn:async g=>{const{error:b}=await U.from("agent_availability_slots").delete().eq("id",g);if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:g=>re.error(g.message)}),p=vt({mutationFn:async g=>{const{error:b}=await U.from("agent_blocked_dates").insert({...g,user_id:s.id});if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]}),re.success("Date blocked")},onError:g=>re.error(g.message)}),x=vt({mutationFn:async g=>{const{error:b}=await U.from("agent_blocked_dates").delete().eq("id",g);if(b)throw b},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:g=>re.error(g.message)}),y=vt({mutationFn:async({id:g,reason:b})=>{const{error:v}=await U.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:b}).eq("id",g);if(v)throw v;await U.functions.invoke("agent-booking",{body:{action:"cancel",booking_id:g}}).catch(k=>console.error("Google calendar cleanup failed:",k))},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),re.success("Booking cancelled")},onError:g=>re.error(g.message)});return{settings:n.data,bookingTypes:r.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:n.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:u,upsertAvailability:h,deleteAvailability:m,addBlockedDate:p,removeBlockedDate:x,cancelBooking:y}}const Fat=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function FCt({slots:s,onSave:t,onDelete:n}){const[r,a]=j.useState(null),[i,l]=j.useState("09:00"),[o,c]=j.useState("17:00"),d=Fat.map((h,m)=>s.filter(p=>p.day_of_week===m)),u=()=>{r!==null&&(t({day_of_week:r,start_time:i,end_time:o,is_active:!0}),a(null),l("09:00"),c("17:00"))};return e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(fr,{children:"Set your available hours for each day"})]}),e.jsx(Re,{className:"space-y-2",children:Fat.map((h,m)=>{const p=d[m];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:h})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):p.map(x=>{var y,g;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(y=x.start_time)==null?void 0:y.slice(0,5),onBlur:b=>t({id:x.id,start_time:b.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(ye,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(g=x.end_time)==null?void 0:g.slice(0,5),onBlur:b=>t({id:x.id,end_time:b.target.value})}),e.jsx(Mn,{checked:x.is_active,onCheckedChange:b=>t({id:x.id,is_active:b})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(x.id),children:e.jsx(Rn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},x.id)}),r===m?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:x=>l(x.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(ye,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:x=>c(x.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(Js,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}function zCt({blockedDates:s,onAdd:t,onRemove:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(""),[o,c]=j.useState(""),d=()=>{i&&(t({blocked_date:i,reason:o||void 0}),a(!1),l(""),c(""))};return e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(D9,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(fr,{children:"Block specific dates (vacations, holidays, etc.)"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," Block Date"]})]}),e.jsxs(Re,{children:[r&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx(ye,{type:"date",value:i,onChange:u=>l(u.target.value),className:"w-40"}),e.jsx(ye,{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:Bs(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(dr,{className:"h-3.5 w-3.5"})})]},u.id))})]})]})}function U2s(){const{settings:s,bookingTypes:t,availability:n,blockedDates:r,isLoading:a,initializeSettings:i,updateSettings:l,upsertBookingType:o,deleteBookingType:c,upsertAvailability:d,deleteAvailability:u,addBlockedDate:h,removeBlockedDate:m}=OCt(),[p,x]=j.useState("1-on-1 Coaching Session"),[y,g]=j.useState(45),b=j.useMemo(()=>t.filter(k=>k.is_coaching_only),[t]);if(a)return e.jsx(be,{children:e.jsxs(Re,{className:"p-6 flex items-center gap-2 text-muted-foreground",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Loading your calendar…"]})});if(!s)return e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ym,{className:"h-5 w-5"})," Coaching calendar"]}),e.jsx(fr,{children:"Set up your scheduler once, then open availability for the members assigned to you."})]}),e.jsx(Re,{children:e.jsxs(B,{onClick:()=>i.mutate(),disabled:i.isPending,children:[i.isPending&&e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Set up my calendar"]})})]});const v=()=>{p.trim()&&(o.mutate({name:p.trim(),description:"Private coaching session",duration_minutes:y,color:"#406E71",icon:"Video",is_active:!0,qualification_enabled:!1,is_coaching_only:!0,sort_order:99}),x("1-on-1 Coaching Session"),g(45))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5"})," Coaching session types"]}),e.jsx(fr,{children:"Only assigned members can book these. They stay hidden from your public booking page."})]}),e.jsxs(Re,{className:"space-y-3",children:[b.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No coaching session type yet — add one below so members can book you."}):b.map(k=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border p-3",children:[e.jsx(ye,{className:"h-9 max-w-[240px]",defaultValue:k.name,onBlur:C=>C.target.value!==k.name&&o.mutate({id:k.id,name:C.target.value})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"number",min:10,max:240,step:5,className:"h-9 w-20",defaultValue:k.duration_minutes,onBlur:C=>o.mutate({id:k.id,duration_minutes:parseInt(C.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{checked:k.is_active,onCheckedChange:C=>o.mutate({id:k.id,is_active:C})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:k.is_active?"Bookable":"Paused"})]}),e.jsx(qe,{variant:"secondary",children:"Coaching only"}),e.jsx(B,{variant:"ghost",size:"sm",className:"ml-auto h-8 w-8 p-0",onClick:async()=>{await Bi({title:"Delete session type?",description:`"${k.name}" will no longer be bookable.`,confirmText:"Delete",destructive:!0})&&c.mutate(k.id)},children:e.jsx(Rn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},k.id)),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 pt-2 border-t",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx(se,{className:"text-xs",children:"New session type"}),e.jsx(ye,{value:p,onChange:k=>x(k.target.value),className:"h-9"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Minutes"}),e.jsx(ye,{type:"number",min:10,max:240,step:5,className:"h-9 w-24",value:y,onChange:k=>g(parseInt(k.target.value)||30)})]}),e.jsxs(B,{onClick:v,disabled:o.isPending,children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," Add"]})]})]})]}),e.jsx(FCt,{slots:n,onSave:k=>d.mutate(k),onDelete:k=>u.mutate(k)}),e.jsx(zCt,{blockedDates:r,onAdd:k=>h.mutate(k),onRemove:k=>m.mutate(k)}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Scheduling rules"}),e.jsx(fr,{children:"Applies to coaching bookings on your calendar."})]}),e.jsxs(Re,{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Buffer between sessions (min)"}),e.jsx(ye,{type:"number",min:0,max:120,step:5,className:"h-9",defaultValue:s.buffer_minutes,onBlur:k=>l.mutate({buffer_minutes:parseInt(k.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Minimum notice (hours)"}),e.jsx(ye,{type:"number",min:0,max:168,className:"h-9",defaultValue:s.min_notice_hours,onBlur:k=>l.mutate({min_notice_hours:parseInt(k.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Bookable up to (days out)"}),e.jsx(ye,{type:"number",min:1,max:365,className:"h-9",defaultValue:s.max_advance_days,onBlur:k=>l.mutate({max_advance_days:parseInt(k.target.value)||30})})]})]})]})]})}async function _H(s,t){const n=s==="agent"?"agent-google-calendar":"coach-google-calendar",{data:r,error:a}=await U.functions.invoke(n,{body:t});if(a){let i=a.message;try{const l=a.context;if(l!=null&&l.json){const o=await l.json();o!=null&&o.error&&(i=o.error)}}catch{}throw new Error(i)}if(r!=null&&r.error)throw new Error(r.error);return r}function q2s(s=!0,t="coach"){const n=as(),r=mt({queryKey:["google-calendar-connection",t],enabled:s,queryFn:async()=>await _H(t,{action:"status"})}),a=()=>n.invalidateQueries({queryKey:["google-calendar-connection",t]}),i=vt({mutationFn:async()=>{const d=await _H(t,{action:"start",origin:window.location.origin}),u=d==null?void 0:d.authorizationUrl;if(!u)throw new Error("Google did not return an authorization link.");try{sessionStorage.setItem("googleCalendarReturnTo",window.location.pathname),sessionStorage.setItem("googleCalendarScope",t)}catch{}window.location.assign(u),await new Promise(h=>setTimeout(h,4e3))},onSuccess:a}),l=vt({mutationFn:()=>_H(t,{action:"disconnect"}),onSuccess:a}),o=vt({mutationFn:d=>_H(t,{action:"settings",...d}),onSuccess:a}),c=vt({mutationFn:()=>_H(t,{action:"refresh_calendars"}),onSuccess:a});return{status:r,connect:i,disconnect:l,updateSettings:o,refreshCalendars:c}}function BCt({scope:s="coach"}){const{status:t,connect:n,disconnect:r,updateSettings:a,refreshCalendars:i}=q2s(!0,s),l=s==="agent";j.useEffect(()=>{const d=new URLSearchParams(window.location.search),u=d.get("google_calendar");if(!u)return;u==="connected"?(re.success("Google Calendar connected"),t.refetch()):re.error(d.get("google_calendar_error")||"Google connection failed."),d.delete("google_calendar"),d.delete("google_calendar_error");const h=d.toString();window.history.replaceState({},"",window.location.pathname+(h?`?${h}`:""))},[]);const o=t.data,c=t.error;return e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(n1,{className:"h-5 w-5"})," Google Calendar"]}),e.jsx(fr,{children:l?"Hide times you're already booked on Google, and push every new booking straight onto your calendar.":"Hide times you're already booked on Google, and push new coaching sessions straight onto your calendar."})]}),(o==null?void 0:o.connected)&&e.jsxs(qe,{className:"bg-emerald-600 hover:bg-emerald-600 shrink-0",children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-1"})," Connected"]})]})}),e.jsxs(Re,{className:"space-y-4",children:[t.isLoading&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Checking your connection…"]}),c&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm",children:[e.jsx(po,{className:"h-4 w-4 mt-0.5 text-destructive shrink-0"}),e.jsx("span",{children:c.message})]}),o&&!o.configured&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-400/50 bg-amber-50 dark:bg-amber-950/20 p-3 text-sm",children:[e.jsx(po,{className:"h-4 w-4 mt-0.5 text-amber-600 shrink-0"}),e.jsx("span",{children:"Google Calendar isn't switched on for LevelUp yet. Once an admin finishes the one-time Google setup, you'll be able to connect right here."})]}),(o==null?void 0:o.configured)&&!o.connected&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Not connected. Your availability comes only from the hours you set in LevelUp."}),e.jsxs(B,{onClick:()=>n.mutate(void 0,{onSuccess:()=>re.success("Google Calendar connected"),onError:d=>re.error(d.message)}),disabled:n.isPending,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[n.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(n1,{className:"h-4 w-4 mr-2"}),n.isPending?"Connecting…":"Connect Google Calendar"]}),n.isError&&e.jsx("p",{className:"text-sm text-destructive",children:n.error.message})]}),(o==null?void 0:o.connected)&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:o.account_email||"Google account"}),o.connected_at&&e.jsxs("div",{className:"text-muted-foreground text-xs",children:["Connected ",new Date(o.connected_at).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l?"Block busy times and add new bookings to Google.":"Block busy times and add booked sessions to Google."})]}),e.jsx(Mn,{checked:o.sync_enabled,onCheckedChange:d=>a.mutate({sync_enabled:d},{onError:u=>re.error(u.message)})})]}),l&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm",children:"Invite the guest"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Send a Google invite when they leave an email address."})]}),e.jsx(Mn,{checked:o.invite_guest!==!1,onCheckedChange:d=>a.mutate({invite_guest:d},{onError:u=>re.error(u.message)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Calendar to use"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:o.selected_calendar_id||"primary",onValueChange:d=>a.mutate({calendar_id:d},{onError:u=>re.error(u.message)}),children:[e.jsx(gs,{className:"h-9",children:e.jsx(bs,{placeholder:"Primary calendar"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"primary",children:"Primary calendar"}),o.calendars.filter(d=>!d.primary).map(d=>e.jsx(Je,{value:d.id,children:d.summary||d.id},d.id))]})]}),e.jsx(B,{variant:"outline",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>i.mutate(void 0,{onSuccess:()=>re.success("Calendars refreshed"),onError:d=>re.error(d.message)}),disabled:i.isPending,children:e.jsx(Ki,{className:`h-4 w-4 ${i.isPending?"animate-spin":""}`})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>n.mutate(void 0,{onSuccess:()=>re.success("Google Calendar reconnected"),onError:d=>re.error(d.message)}),disabled:n.isPending,children:[n.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ki,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-destructive",disabled:r.isPending,onClick:async()=>{await Bi({title:"Disconnect Google Calendar?",description:"Busy times will stop hiding and new sessions won't be added to Google.",confirmText:"Disconnect",destructive:!0})&&r.mutate(void 0,{onSuccess:()=>re.success("Google Calendar disconnected"),onError:u=>re.error(u.message)})},children:[e.jsx(xK,{className:"h-4 w-4 mr-2"})," Disconnect"]})]})]})]})]})}function V2s(){const s=Hn(),{data:t,isLoading:n}=SJ(),r=as(),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(""),[x,y]=j.useState(!1),[g,b]=j.useState([]),[v,k]=j.useState(""),[C,T]=j.useState(2),[M,P]=j.useState(!1);j.useEffect(()=>{if(!t)return;const q=t;i(q.slug||""),o(q.headline||""),d(q.bio||""),h(q.photo_url||""),p(q.intro_video_url||""),y(!!q.accepting_clients),b(q.specialties||[]),T(q.default_sessions_per_month??2)},[t]);const L=async()=>{if(!t)return;P(!0);const{error:q}=await U.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:u||null,intro_video_url:m||null,accepting_clients:x,specialties:g,default_sessions_per_month:C}).eq("id",t.id);if(P(!1),q)return re.error(q.message);re.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},I=()=>{const q=v.trim();if(q){if(g.includes(q))return k("");b([...g,q]),k("")}};if(n)return e.jsx(Vs,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Vs,{title:"Coach Settings",children:e.jsx("div",{className:"max-w-2xl mx-auto p-8 text-center text-muted-foreground",children:"You don't have a coach profile yet."})});const O=t,$=O.slug?`${window.location.origin}/coaches/${O.slug}`:null;return e.jsx(Vs,{title:"Coach Settings",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(_a,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Coach Profile"})]}),e.jsxs("div",{className:"flex gap-2",children:[$&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open($,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(B,{onClick:L,disabled:M,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," ",M?"Saving…":"Save"]})]})]}),O.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(be,{children:e.jsxs(Re,{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(Mn,{checked:x,onCheckedChange:y})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Public URL slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"/coaches/"}),e.jsx(ye,{value:a,onChange:q=>i(q.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Headline"}),e.jsx(ye,{value:l,onChange:q=>o(q.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Bio"}),e.jsx(Ds,{rows:6,value:c,onChange:q=>d(q.target.value),placeholder:"Tell agents who you are, what you've done, how you coach…"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Profile photo"}),e.jsx(Oat,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Intro video"}),e.jsx(Oat,{kind:"video",value:m,onChange:p})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:g.map(q=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[q,e.jsx("button",{onClick:()=>b(g.filter(W=>W!==q)),children:e.jsx(dr,{className:"h-3 w-3"})})]},q))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:v,onChange:q=>k(q.target.value),placeholder:"Add a specialty…",onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),I())}}),e.jsx(B,{type:"button",variant:"outline",onClick:I,children:e.jsx(Js,{className:"h-4 w-4"})})]})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Coaching calendar"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Open availability right here — assigned members book you from their ",e.jsx("strong",{children:"My Coach → Book"})," tab. These session types never show on your public booking page."]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{children:"Sessions each agent can book per month"}),e.jsx(ye,{type:"number",min:1,max:31,value:C,onChange:q=>T(Math.max(1,parseInt(q.target.value)||1)),className:"max-w-[140px]"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"You can override this for individual agents on their workspace page."})]}),e.jsx(B,{variant:"outline",onClick:()=>s("/mission-control/scheduler"),children:"Open full Scheduler"})]})]})}),e.jsx(BCt,{}),e.jsx(U2s,{}),e.jsx(be,{children:e.jsx(Re,{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(H2s,{coachId:O.id})]})})}function H2s({coachId:s}){const[t,n]=j.useState("");as();const{data:r=[],refetch:a}=mt({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await U.from("coaching_invites").select("*").eq("coach_id",s).order("created_at",{ascending:!1});return c||[]}}),i=async()=>{const c=t.trim().toLowerCase();if(!c)return re.error("Email required");const{error:d}=await U.from("coaching_invites").insert({coach_id:s,email:c});if(d)return re.error(d.message);n(""),re.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),re.success("Link copied")},o=async c=>{await Bi("Revoke this invite?")&&(await U.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(be,{children:e.jsxs(Re,{className:"p-6 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(vc,{className:"h-5 w-5"})," Invite agents"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a magic link to onboard agents directly."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{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(Js,{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(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(Rn,{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 G2s="google_calendar";function W2s(){const[s,t]=j.useState("Finishing your Google Calendar connection…"),n=j.useRef(!1);return j.useEffect(()=>{if(n.current)return;n.current=!0;const r=new URLSearchParams(window.location.search),a=(()=>{try{return!!window.opener&&!window.opener.closed}catch{return!1}})(),i=(()=>{try{return sessionStorage.getItem("googleCalendarReturnTo")||"/coaching/settings"}catch{return"/coaching/settings"}})(),l=(u,h)=>{try{sessionStorage.removeItem("googleCalendarReturnTo")}catch{}const m=new URL(i,window.location.origin);m.searchParams.set("google_calendar",u),h&&m.searchParams.set("google_calendar_error",h),window.location.replace(m.toString())},o=(u,h)=>{var m;if(a){(m=window.opener)==null||m.postMessage({type:u,connectorId:G2s,reason:h},window.location.origin),u==="appUserConnectorOAuthComplete"&&window.close();return}l(u==="appUserConnectorOAuthComplete"?"connected":"failed",h)};if(r.get("success")!=="true"){const u=r.get("error")||"Google did not complete the connection.";t(u),o("appUserConnectorOAuthFailed",u);return}const c=r.get("code");if(!c){const u=r.get("offline_access_allowed")==="false"?"This connection cannot be used yet: a workspace admin must enable offline access on the Google Calendar App User Connector client.":"Google finished, but no exchange code was returned.";t(u),o("appUserConnectorOAuthFailed",u);return}const d=(()=>{try{return sessionStorage.getItem("googleCalendarScope")==="agent"?"agent":"coach"}catch{return"coach"}})();U.functions.invoke(d==="agent"?"agent-google-calendar":"coach-google-calendar",{body:{action:"complete",code:c}}).then(({data:u,error:h})=>{if(h)throw h;if(u!=null&&u.error)throw new Error(u.error);t("Connected! You can close this window."),o("appUserConnectorOAuthComplete")}).catch(u=>{const h=(u==null?void 0:u.message)||"Could not finish the connection.";t(h),o("appUserConnectorOAuthFailed",h)})},[]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-8 text-center",children:e.jsxs("div",{className:"space-y-3 max-w-sm",children:[e.jsx(Wt,{className:"h-6 w-6 animate-spin mx-auto text-[#406E71]"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s})]})})}const Rse=[{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 K2s(){const s=Hn(),t=as(),{data:n,isLoading:r}=SJ(),[a,i]=j.useState("pending"),[l,o]=j.useState(""),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,p]=j.useState(""),[x,y]=j.useState(!1),[g,b]=j.useState(""),{data:v=[],isLoading:k}=mt({queryKey:["coaching-waitlist",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:O,error:$}=await U.from("coaching_waitlist").select("*").eq("coach_id",n.id).order("created_at",{ascending:!1});if($)throw $;return O||[]}}),C=j.useMemo(()=>v.filter(O=>{if(a!=="all"&&O.status!==a)return!1;if(l){const $=l.toLowerCase();return(O.name||"").toLowerCase().includes($)||(O.email||"").toLowerCase().includes($)||(O.brokerage||"").toLowerCase().includes($)}return!0}),[v,a,l]),T=j.useMemo(()=>{const O={all:v.length};for(const $ of Rse)O[$.value]=0;for(const $ of v)O[$.status]=(O[$.status]||0)+1;return O},[v]),M=async(O,$)=>{const{error:q}=await U.from("coaching_waitlist").update($).eq("id",O);if(q)return re.error(q.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===O&&d(W=>({...W,...$}))},P=async O=>{if(!await Bi("Remove this person from the waitlist?"))return;const{error:$}=await U.from("coaching_waitlist").delete().eq("id",O);if($)return re.error($.message);re.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},L=async()=>{if(!c)return;const{data:O,error:$}=await U.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:m}});if($||O!=null&&O.error)return re.error((O==null?void 0:O.error)||($==null?void 0:$.message)||"Could not send invite");re.success(`Invite sent to ${c.name}`),h(!1),p(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})},I=async()=>{if(!n)return;const{data:O,error:$}=await U.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:g}});if($||O!=null&&O.error)return re.error((O==null?void 0:O.error)||($==null?void 0:$.message)||"Could not notify");re.success(`Notified ${(O==null?void 0:O.count)||0} agents`),y(!1),b(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx(Vs,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs(Vs,{title:"Coaching Waitlist",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"mb-2 -ml-2",onClick:()=>s("/coaching"),children:[e.jsx(_a,{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(r1,{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(H9,{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,")"]}),Rse.map(O=>e.jsxs("button",{onClick:()=>i(O.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===O.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[O.label," (",T[O.value]||0,")"]},O.value))]}),e.jsx(ye,{placeholder:"Search by name, email, brokerage…",value:l,onChange:O=>o(O.target.value),className:"max-w-md"}),k?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):C.length===0?e.jsx(be,{children:e.jsx(Re,{className:"p-10 text-center text-muted-foreground",children:"No entries here yet."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:C.map(O=>{const $=Rse.find(q=>q.value===O.status);return e.jsx(be,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(O),children:e.jsxs(Re,{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:O.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:O.email}),O.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:O.brokerage})]}),e.jsx(qe,{className:($==null?void 0:$.tone)||"",children:($==null?void 0:$.label)||O.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",oc(new Date(O.created_at),{addSuffix:!0})]}),O.preferred_package&&e.jsxs("span",{className:"truncate ml-2",children:["→ ",O.preferred_package]})]})]})},O.id)})})]}),e.jsx(Fs,{open:!!c,onOpenChange:O=>!O&&d(null),children:e.jsx(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:c.name}),e.jsxs(kr,{children:["Joined ",oc(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(wH,{label:"Email",value:c.email}),e.jsx(wH,{label:"Phone",value:c.phone}),e.jsx(wH,{label:"Brokerage",value:c.brokerage}),e.jsx(wH,{label:"Years",value:c.years_in_business}),e.jsx(wH,{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 ",oc(new Date(c.invited_at),{addSuffix:!0})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Status"}),e.jsxs(vs,{value:c.status,onValueChange:O=>M(c.id,{status:O}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Rse.map(O=>e.jsx(Je,{value:O.value,children:O.label},O.value))})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Private notes"}),e.jsx(Ds,{rows:3,defaultValue:c.coach_notes||"",onBlur:O=>{O.target.value!==(c.coach_notes||"")&&M(c.id,{coach_notes:O.target.value})}})]})]}),e.jsxs(Nr,{className:"flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"text-destructive",onClick:()=>P(c.id),children:[e.jsx(Rn,{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(on,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{p(""),h(!0)},children:[e.jsx(Dr,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(Fs,{open:u,onOpenChange:h,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Invite to subscribe"}),e.jsxs(kr,{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(Ds,{rows:4,placeholder:"Hey! A spot just opened up and I'd love to work with you…",value:m,onChange:O=>p(O.target.value)})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:L,children:[e.jsx(Dr,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(Fs,{open:x,onOpenChange:y,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Notify all pending applicants"}),e.jsx(kr,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(Ds,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:g,onChange:O=>b(O.target.value)}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:I,children:[e.jsx(H9,{className:"h-4 w-4 mr-1"})," Send to ",T.pending||0," agents"]})]})]})})]}):e.jsx(Vs,{title:"Waitlist",children:e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"You need a coach profile to view this page."})})}function wH({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 Y2s(){const{data:s=[],isLoading:t}=mt({queryKey:["coaches-directory"],queryFn:async()=>{const{data:n,error:r}=await U.from("coaches").select("id, slug, headline, bio, specialties, photo_url, is_certified, accepting_clients, user_id").not("slug","is",null);if(r)throw r;const a=(n||[]).map(o=>o.user_id);if(a.length===0)return[];const{data:i}=await U.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(n||[]).map(o=>({...o,profile:l.get(o.user_id)}))}});return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 py-20 md:py-28 text-center",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(yn,{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(Rr,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ll,{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(Yn,{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(yn,{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(Xa,{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(yn,{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(Rr,{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(Rr,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Rr,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(Yn,{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(Xa,{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 Z2s=iS({name:Cl().trim().min(1,"Name required").max(120),email:Cl().trim().email("Invalid email").max(255),phone:Cl().trim().max(40).optional().or(Xg("")),brokerage:Cl().trim().max(160).optional().or(Xg("")),years_in_business:Cl().max(40).optional().or(Xg("")),biggest_challenge:Cl().trim().max(1e3).optional().or(Xg("")),preferred_package:Cl().max(120).optional().or(Xg("")),message:Cl().trim().max(1500).optional().or(Xg(""))});function X2s({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=Ns(),[l,o]=j.useState(!1),[c,d]=j.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(m,p)=>d(x=>({...x,[m]:p})),h=async()=>{var x;const m=Z2s.safeParse(c);if(!m.success){re.error(((x=m.error.issues[0])==null?void 0:x.message)||"Please check your entries");return}o(!0);const{error:p}=await U.from("coaching_waitlist").insert({coach_id:n,agent_user_id:(i==null?void 0:i.id)||null,name:c.name.trim(),email:c.email.trim().toLowerCase(),phone:c.phone||null,brokerage:c.brokerage||null,years_in_business:c.years_in_business||null,biggest_challenge:c.biggest_challenge||null,preferred_package:c.preferred_package||null,message:c.message||null,status:"pending"});if(o(!1),p){re.error(p.message||"Could not join waitlist");return}re.success(`You're on the waitlist${r?` for ${r}`:""}. We'll be in touch when a spot opens.`),t(!1),d({...c,biggest_challenge:"",message:""})};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(kr,{children:"Tell us a bit about you. The coach will reach out as soon as a spot opens."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Name *"}),e.jsx(ye,{value:c.name,onChange:m=>u("name",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email *"}),e.jsx(ye,{type:"email",value:c.email,onChange:m=>u("email",m.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:c.phone,onChange:m=>u("phone",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Brokerage"}),e.jsx(ye,{value:c.brokerage,onChange:m=>u("brokerage",m.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Years in business"}),e.jsxs(vs,{value:c.years_in_business,onValueChange:m=>u("years_in_business",m),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select…"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(Je,{value:"1-3 years",children:"1-3 years"}),e.jsx(Je,{value:"4-7 years",children:"4-7 years"}),e.jsx(Je,{value:"8-15 years",children:"8-15 years"}),e.jsx(Je,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(se,{children:"Preferred package"}),e.jsxs(vs,{value:c.preferred_package,onValueChange:m=>u("preferred_package",m),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Any"})}),e.jsx(ys,{children:a.map(m=>e.jsx(Je,{value:m.name,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Biggest challenge right now"}),e.jsx(Ds,{rows:2,value:c.biggest_challenge,onChange:m=>u("biggest_challenge",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Anything else?"}),e.jsx(Ds,{rows:2,value:c.message,onChange:m=>u("message",m.target.value)})]})]}),e.jsxs(Nr,{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 Q2s(){var y;const{slug:s}=$i(),t=Hn(),{user:n}=Ns(),[r,a]=j.useState(null),[i,l]=j.useState(!1),{data:o,isLoading:c}=mt({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const g=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),b=U.from("coaches").select("*"),{data:v}=g?await b.eq("id",s).maybeSingle():await b.eq("slug",s).maybeSingle();if(!v)return null;const[{data:k},{data:C}]=await Promise.all([U.from("profiles").select("id, name, avatar_url").eq("id",v.user_id).maybeSingle(),U.from("coaching_packages").select("*").eq("coach_id",v.id).eq("is_active",!0).order("sort_order")]);return{coach:v,profile:k,packages:C||[]}}}),d=async g=>{if(!n){re.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(g);const{data:b,error:v}=await U.functions.invoke("create-coaching-checkout",{body:{packageId:g}});if(a(null),v||b!=null&&b.error){re.error((b==null?void 0:b.error)||(v==null?void 0:v.message)||"Checkout failed");return}b!=null&&b.url&&(window.location.href=b.url)};if(c)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(o!=null&&o.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:u,profile:h,packages:m}=o,p=u,x=(g,b)=>{const v=(g/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return b==="one_time"?v:`${v} / ${b}`};return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("div",{className:"bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 md:py-20",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(_a,{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(Ra,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(Fi,{src:p.photo_url||(h==null?void 0:h.avatar_url)}),e.jsx(Da,{className:"text-3xl bg-white/20",children:((h==null?void 0:h.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[p.is_certified&&e.jsxs("div",{className:"inline-flex items-center gap-1 bg-yellow-400/20 border border-yellow-300/30 text-yellow-100 px-2 py-1 rounded-full text-xs mb-2",children:[e.jsx(yn,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(h==null?void 0:h.name)||"Coach"}),p.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:p.headline}),((y=p.specialties)==null?void 0:y.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:p.specialties.map(g=>e.jsx(qe,{className:"bg-white/15 text-white border-white/20",children:g},g))})]})]})]})}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[p.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:p.intro_video_url,controls:!0,className:"w-full h-full"})}),p.bio&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-3",children:"About"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap leading-relaxed",children:p.bio})]}),e.jsx(T2s,{coachId:p.id})]}),e.jsxs("div",{className:"space-y-4 md:sticky md:top-6 md:self-start",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Choose a plan"}),m.length===0?e.jsx(be,{children:e.jsx(Re,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):m.map(g=>{const b=g.accepting_clients===!1;return e.jsx(be,{className:`border-2 transition-colors ${b?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Re,{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:g.name}),b&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-bold px-2 py-1 rounded-full bg-amber-500 text-white shrink-0",children:"Booked Full"})]}),g.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:g.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:x(g.price_cents,g.billing_interval)}),b?e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx("div",{className:"rounded-md bg-amber-100 border border-amber-200 text-amber-900 px-3 py-2.5 text-sm text-center",children:"Currently not accepting new clients."}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>l(!0),children:[e.jsx(r1,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs(B,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(g.id),disabled:r===g.id,children:[r===g.id?"Loading…":"Get Started",e.jsx(da,{className:"h-4 w-4 ml-1"})]})]})},g.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(r1,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(X2s,{open:i,onOpenChange:l,coachId:p.id,coachName:h==null?void 0:h.name,packages:m.map(g=>({id:g.id,name:g.name}))})]})}const J2s=iS({full_name:Cl().trim().min(2,"Please enter your full name").max(100),email:Cl().trim().email("Enter a valid email").max(255),phone:Cl().trim().max(40).optional().or(Xg("")),brokerage:Cl().trim().max(150).optional().or(Xg("")),years_experience:Cl().trim().max(40).optional().or(Xg("")),specialties:Cl().trim().max(500).optional().or(Xg("")),why_coach:Cl().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:Cl().trim().max(2e3).optional().or(Xg("")),website_url:Cl().trim().max(300).optional().or(Xg("")),linkedin_url:Cl().trim().max(300).optional().or(Xg(""))});function eNs(){const s=Hn(),[t,n]=j.useState(!1),[r,a]=j.useState(!1),[i,l]=j.useState({full_name:"",email:"",phone:"",brokerage:"",years_experience:"",specialties:"",why_coach:"",results_story:"",website_url:"",linkedin_url:""}),o=(d,u)=>l(h=>({...h,[d]:u})),c=async d=>{var m;d.preventDefault();const u=J2s.safeParse(i);if(!u.success){const p=(m=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:m[0];return re.error(p||"Please check the form and try again")}n(!0);const{error:h}=await U.from("coach_applications").insert(u.data);if(n(!1),h)return re.error(h.message||"Could not submit application");a(!0),window.scrollTo({top:0,behavior:"smooth"})};return r?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-xl text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center h-20 w-20 rounded-full bg-gradient-to-br from-yellow-400 to-yellow-300 text-[#1c3447] mb-6 shadow-2xl",children:e.jsx(Rr,{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(Yn,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(_a,{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(yn,{className:"h-3.5 w-3.5 text-yellow-300"}),"Coach Application — By Invitation & Application Only"]}),e.jsx("h1",{className:"text-4xl md:text-6xl font-bold tracking-tight leading-[1.05] max-w-3xl",children:"Join the most respected coaching program in real estate."}),e.jsx("p",{className:"text-white/80 mt-6 max-w-2xl text-lg leading-relaxed",children:"LevelUp Coaches don't just teach — they transform careers. We hand-pick top-producing agents and proven mentors who are ready to multiply their impact, build a recurring revenue stream, and help thousands of agents finally break through."}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-4 mt-12",children:[e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(Bn,{className:"h-6 w-6 text-yellow-300 mb-3"}),e.jsx("h3",{className:"font-semibold text-lg",children:"Premium client base"}),e.jsx("p",{className:"text-sm text-white/70 mt-1",children:"Get matched with motivated, vetted agents who are serious about leveling up."})]}),e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(kl,{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(cu,{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(Rr,{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(ll,{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(yk,{label:"Full name *",children:e.jsx(ye,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(yk,{label:"Email *",children:e.jsx(ye,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(yk,{label:"Phone",children:e.jsx(ye,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(yk,{label:"Current brokerage",children:e.jsx(ye,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(yk,{label:"Years in real estate",children:e.jsx(ye,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(yk,{label:"Coaching specialties",children:e.jsx(ye,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(yk,{label:"Website",children:e.jsx(ye,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(yk,{label:"LinkedIn",children:e.jsx(ye,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(yk,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Ds,{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(yk,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Ds,{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 yk({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const tNs="/assets/testimonial-avatar-1-BsCQFauB.jpg",sNs="/assets/testimonial-avatar-2-B6VPVc2t.jpg",nNs="/assets/testimonial-avatar-3-GuEFwYUE.jpg",rNs="/assets/testimonial-avatar-4-98iKMtkB.jpg",aNs="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",iNs=[tNs,sNs,nNs,rNs,aNs],oNs=iS({name:Cl().trim().min(2,"Name must be at least 2 characters").max(100),email:Cl().trim().email("Please enter a valid email address").max(255),phone:Cl().trim().min(10,"Please enter a valid phone number").max(20).optional().or(Xg("")),brokerage:Cl().trim().max(200).optional().or(Xg(""))}),lNs=[{icon:vh,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:Ac,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ra,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Yd,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:$r,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:zo,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],cNs=[{icon:Bn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:yn,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:pa,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Wm,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:oi,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:ol,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:mo,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:jf,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],dNs=[{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."}],uNs=()=>{const s=Hn(),[t,n]=j.useState(!1),[r,a]=j.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=j.useState({}),o=async c=>{var u,h;c.preventDefault(),l({});const d=oNs.safeParse(r);if(!d.success){const m={};d.error.issues.forEach(p=>{p.path[0]&&(m[p.path[0]]=p.message)}),l(m);return}n(!0);try{const m=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:p,error:x}=await U.functions.invoke("create-trial-signup",{body:{name:r.name.trim(),email:r.email.trim().toLowerCase(),phone:((u=r.phone)==null?void 0:u.trim())||void 0,brokerage:((h=r.brokerage)==null?void 0:h.trim())||void 0,referral_code:m}});if(x){console.error("Trial signup error:",x),re.error(x.message||"Something went wrong. Please try again.");return}if(p!=null&&p.error){re.error(p.error);return}re.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),typeof window<"u"&&window.fbq&&window.fbq("track","Lead",{content_name:"Trial Signup",value:0,currency:"USD"}),s("/trial/success")}catch(m){console.error("Trial signup error:",m),re.error("Something went wrong. Please try again.")}finally{n(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(ql,{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:GNe,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(yn,{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(Rr,{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(Rr,{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:iNs.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(be,{className:"bg-white shadow-2xl border-0",children:e.jsxs(Re,{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(oy,{className:"h-8 w-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-foreground font-sans",children:"Start Your Free Trial"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Get instant access • No credit card needed"})]}),e.jsxs("form",{onSubmit:o,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Full Name *"}),e.jsx(ye,{id:"name",type:"text",placeholder:"John Smith",value:r.name,onChange:c=>a({...r,name:c.target.value}),required:!0}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email Address *"}),e.jsx(ye,{id:"email",type:"email",placeholder:"john@example.com",value:r.email,onChange:c=>a({...r,email:c.target.value}),required:!0}),i.email&&e.jsx("p",{className:"text-sm text-destructive",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"phone",children:"Phone Number"}),e.jsx(ye,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:r.phone,onChange:c=>a({...r,phone:c.target.value})}),i.phone&&e.jsx("p",{className:"text-sm text-destructive",children:i.phone})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(ye,{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(Wt,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(Xa,{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:lNs.map((c,d)=>e.jsxs(be,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Ft,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(c.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Ut,{className:"text-xl font-sans",children:c.title})]}),e.jsx(Re,{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(yn,{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:cNs.map((c,d)=>e.jsxs(be,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(c.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Ut,{className:"text-lg font-semibold text-white",children:c.title})]}),e.jsx(Re,{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:dNs.map((c,d)=>e.jsx(be,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Re,{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(_f,{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(jf,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Fast Setup"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Start in 2 minutes"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Bn,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Expert Support"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Real estate pros"})]})]})]})})}),e.jsx("section",{id:"free-trial",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs(be,{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(Re,{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(Xa,{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:CNe,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."})]})})})]})]})},hNs=()=>{const s=Hn();return e.jsxs(e.Fragment,{children:[e.jsx(ql,{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:GNe,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(be,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Re,{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(Rr,{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(bf,{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(on,{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(Xa,{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:CNe,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},mNs=iS({viewerName:Cl().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:Cl().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:Cl().max(20,"Phone must be less than 20 characters").optional(),message:Cl().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function pNs({shareToken:s,agentName:t,hasContact:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),d=D3e({resolver:O3e(mNs),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async h=>{a(!0),c(null);try{const{data:m,error:p}=await U.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:h.viewerName,viewerEmail:h.viewerEmail,viewerPhone:h.viewerPhone||void 0,message:h.message}});if(p)throw new Error(p.message);if(!(m!=null&&m.success))throw new Error((m==null?void 0:m.error)||"Failed to send reply");l(!0)}catch(m){console.error("Failed to submit reply:",m),c(m.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(be,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Re,{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(Rr,{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(be,{children:[e.jsxs(Ft,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Yd,{className:"h-5 w-5 text-primary"}),e.jsx(Ut,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(fr,{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(Re,{children:e.jsx(F3e,{...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(Np,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Your Name *"}),e.jsx(Um,{children:e.jsx(ye,{placeholder:"John Smith",...h})}),e.jsx(Kv,{})]})}),e.jsx(Np,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Email *"}),e.jsx(Um,{children:e.jsx(ye,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(Kv,{})]})})]}),!n&&e.jsx(Np,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Phone (optional)"}),e.jsx(Um,{children:e.jsx(ye,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(Kv,{})]})}),e.jsx(Np,{control:d.control,name:"message",render:({field:h})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Message *"}),e.jsx(Um,{children:e.jsx(Ds,{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(Kv,{})]})}),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(Wt,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const fNs=()=>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(y3,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),xNs=()=>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(yn,{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(yn,{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(y3,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),gNs=()=>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(oN,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(oN,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(oN,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(oN,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(mo,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(mo,{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(mo,{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"})]}),yNs=()=>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(cu,{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(cu,{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"}})]}),vNs=()=>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(oN,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(oN,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(F9,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),bNs=()=>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(OR,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(OR,{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(yn,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(yn,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),_Ns=()=>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(rE,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(rE,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(rE,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(gj,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(gj,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(gj,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(gj,{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"})]}),wNs=()=>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(mo,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(mo,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),jNs=()=>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(yn,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(bf,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(bf,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),NNs=()=>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(yn,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(yn,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),kNs=()=>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(a3,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(a3,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(a3,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(a3,{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"})]})]})]}),SNs=()=>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(cu,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(cu,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(y3,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),CNs=()=>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(Wm,{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(bf,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(zo,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),ANs=()=>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(mo,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(mo,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(mo,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(mo,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(mo,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(mo,{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(mo,{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(mo,{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"})]}),TNs=()=>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(Aj,{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(Aj,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(yn,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(Aj,{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"})]}),ENs=()=>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(ia,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(ia,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(gb,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(gb,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(mo,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(mo,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(yn,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(bf,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),MNs=()=>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(bf,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(bf,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(gb,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(ia,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(yn,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(yn,{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"})]}),LNs=()=>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(gb,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(gb,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(gb,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(ia,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(bf,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(yn,{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"})]}),PNs=()=>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(ia,{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(gb,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(mo,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(yn,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(wj,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),zat=()=>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"})]}),INs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(mo,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(mo,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(mo,{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(mo,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),RNs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(wj,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(yn,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(ia,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),DNs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(xb,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(K9,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(xb,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),jH=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(yn,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(bf,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(yn,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),Bat=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(ia,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(yn,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(ia,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),ROe=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(yn,{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(mo,{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(INs,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(MW,{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(jH,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(xb,{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(DNs,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(ol,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Market Update for ${s}`:"Market Update",subText:"The latest insights from your local market",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-sky-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-sky-950/20",accentColor:"blue"},{id:"referral_thank_you",name:"Referral Thank You",description:"Thank someone for a referral",icon:e.jsx(Bn,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Thank You for the Referral, ${s}!`:"Thank You for the Referral!",subText:"Your trust in me means everything",gradientClasses:"from-emerald-50/70 via-green-50/50 to-teal-50/40 dark:from-emerald-950/30 dark:via-green-950/20 dark:to-teal-950/20",accentColor:"emerald",decorativeElement:e.jsx(jH,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(cu,{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(zat,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(oi,{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(Bat,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(K9,{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(jH,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(Wm,{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(CNs,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(mo,{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(ANs,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(Aj,{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(TNs,{})},{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(jNs,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(F9,{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(vNs,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(oN,{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(gNs,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(cu,{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(yNs,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(y3,{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(fNs,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(Fd,{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(xNs,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(cu,{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(SNs,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(OR,{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(bNs,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(mo,{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(wNs,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(rE,{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(_Ns,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(yn,{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(NNs,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(a3,{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(kNs,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(ia,{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(ENs,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(bf,{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(MNs,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(ra,{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(Bat,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(Od,{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(jH,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(vN,{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(wj,{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(RNs,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(gb,{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(LNs,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(ia,{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(PNs,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(mg,{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(jH,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(cu,{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(zat,{})}],ONs=[{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 FNs(s){return ROe.filter(t=>t.category===s)}function jz(s){return ROe.find(t=>t.id===s)||ROe[0]}function $at(){const{shareToken:s,recipientToken:t}=$i(),[n,r]=j.useState(null),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(!0),[u,h]=j.useState(null),[m,p]=j.useState(!0),x=j.useRef(null),y=j.useRef(0),g=j.useRef(0),b=(()=>{const q=new URLSearchParams(window.location.search);return t||q.get("rt")||null})(),v=j.useCallback((q,W=!1)=>{if(!b||q<=0)return;const G=Math.max(1,Math.round(q));if(G<=g.current)return;const ee=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(b)}&e=watch&ws=${G}`;W&&navigator.sendBeacon?navigator.sendBeacon(ee):fetch(ee,{method:"GET",keepalive:W}).catch(()=>{}),g.current=Math.max(g.current,G)},[b]);j.useEffect(()=>{var le;if(!m||!(n!=null&&n.playback_url)||!b)return;let q=!1;const W=()=>{y.current>0&&v(y.current,!0)},G=()=>{document.visibilityState==="hidden"&&W()},K=()=>{W()},ee=()=>{var oe;if(q||!x.current||!((oe=window.playerjs)!=null&&oe.Player))return;const ue=new window.playerjs.Player(x.current);ue.on("timeupdate",ie=>{const de=Math.floor(Number((ie==null?void 0:ie.seconds)??0));!Number.isFinite(de)||de<=0||(y.current=Math.max(y.current,de))}),ue.on("pause",()=>{y.current>0&&v(y.current)}),ue.on("ended",()=>{y.current>0&&v(y.current,!0)})},J=document.querySelector('script[data-bunny-playerjs="true"]');if((le=window.playerjs)!=null&&le.Player)ee();else if(J)J.addEventListener("load",ee,{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=ee,document.body.appendChild(ue)}return document.addEventListener("visibilitychange",G),window.addEventListener("beforeunload",K),()=>{q=!0,document.removeEventListener("visibilitychange",G),window.removeEventListener("beforeunload",K),W()}},[m,n==null?void 0:n.playback_url,b,v]),j.useEffect(()=>{y.current=0,g.current=0},[b,s]),j.useEffect(()=>{const q=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="msgsndr"]',"[data-chat-widget]"].forEach(ee=>{document.querySelectorAll(ee).forEach(J=>{J.style.display="none"})})};q();const W=[setTimeout(q,500),setTimeout(q,1500),setTimeout(q,3e3)],G=new MutationObserver(q);return G.observe(document.body,{childList:!0,subtree:!0}),()=>{W.forEach(clearTimeout),G.disconnect()}},[]),j.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:W,error:G}=await U.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id, contact_id, page_template, recipient_name").eq("share_token",s).eq("is_deleted",!1).single();if(G||!W){h("Video not found or has been removed"),d(!1);return}r(W);try{await U.rpc("log_video_view",{p_video_id:W.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(K){console.warn("Failed to log video view:",K)}if(W.owner_user_id){const{data:K}=await U.from("profiles").select("id, name, email, phone").eq("id",W.owner_user_id).single();if(K){i(K);try{const{data:ee}=await U.storage.from("avatars").list(`${W.owner_user_id}`);if(ee&&ee.length>0){const{data:J}=U.storage.from("avatars").getPublicUrl(`${W.owner_user_id}/${ee[0].name}`);o(J.publicUrl)}}catch{}}}d(!1)})()},[s]);const k=q=>{if(!q)return"0:00";const W=Math.floor(q/60),G=q%60;return`${W}:${G.toString().padStart(2,"0")}`},C=q=>q.includes("iframe.mediadelivery.net/play/")?q.replace("/play/","/embed/")+"?autoplay=true&responsive=true":q,T=q=>{if(!q)return"?";const W=q.split(" ");return W.length>=2?`${W[0][0]}${W[1][0]}`.toUpperCase():q.substring(0,2).toUpperCase()},M=jz((n==null?void 0:n.page_template)||"default"),P=(n==null?void 0:n.recipient_name)||null,L=M.headerText(P),O=`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(Wt,{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(be,{className:"max-w-md w-full",children:e.jsxs(Re,{className:"py-12 text-center",children:[e.jsx(Zr,{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 $=M.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(ql,{children:[e.jsx("title",{children:L}),e.jsx("meta",{name:"description",content:M.subText}),e.jsx("meta",{property:"og:title",content:L}),e.jsx("meta",{property:"og:description",content:M.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:O}),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:L}),e.jsx("meta",{name:"twitter:description",content:M.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:Et("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",M.gradientClasses),children:[$&&M.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:Et("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",M.accentColor==="primary"&&"bg-primary/10 text-primary",M.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",M.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",M.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",M.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",M.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",M.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",M.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",M.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",M.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",M.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",M.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",M.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:M.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:L}),e.jsx("p",{className:"text-muted-foreground",children:M.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(Ra,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(Fi,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(Da,{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(pa,{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(on,{className:"h-4 w-4"})})})]})]}),e.jsx(be,{className:"overflow-hidden shadow-lg",children:m&&n.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:x,src:C(n.playback_url),title:n.title||"Video message",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>p(!0),children:[n.preview_url||n.thumbnail_url?e.jsx("img",{src:n.preview_url||n.thumbnail_url||"",alt:n.title?`${n.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:q=>{var G;q.currentTarget.style.display="none";const W=(G=q.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(Zr,{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(fd,{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:()=>p(!0),className:"gap-2",children:[e.jsx(fd,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(pNs,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function zNs(){return j.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(Gjt,{})}function BNs(){const{token:s}=$i();return j.useEffect(()=>{if(!s)return;const t=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/video-og-image?token=${s}`;window.location.replace(t)},[s]),e.jsx("main",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(Wt,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const $Ns={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},UNs=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function qNs(){var de;const[s]=dc(),t=s.get("r"),n=s.get("m"),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!0),[d,u]=j.useState(0),[h,m]=j.useState(!1),[p,x]=j.useState(""),[y,g]=j.useState(""),[b,v]=j.useState(""),[k,C]=j.useState(""),[T,M]=j.useState("tour"),[P,L]=j.useState(!1),[I,O]=j.useState(!1),$=async()=>{if(!p.trim()||!y.trim()){re.error("Please enter your name and email");return}L(!0);try{const je=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({r:t,m:n,name:p.trim(),email:y.trim(),phone:b.trim()||null,message:k.trim()||null,intent:T})}),xe=await je.json();if(!je.ok||!(xe!=null&&xe.success))throw new Error((xe==null?void 0:xe.error)||"Could not send");O(!0),re.success("Sent! The agent will be in touch shortly.")}catch(we){re.error((we==null?void 0:we.message)||"Could not send")}finally{L(!1)}};if(j.useEffect(()=>{if(!t||!n){l("Invalid link"),c(!1);return}const we=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(n)}`;fetch(we).then(je=>je.json()).then(je=>{je.error?l("This private listing link is no longer valid."):a({listing:je.listing,agent:je.agent})}).catch(()=>l("Unable to load listing.")).finally(()=>c(!1))},[t,n]),o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50",children:e.jsx("div",{className:"text-slate-500",children:"Loading…"})});if(i||!r)return e.jsxs(e.Fragment,{children:[e.jsx(ql,{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(du,{className:"h-10 w-10 text-slate-400 mx-auto mb-3"}),e.jsx("h1",{className:"text-xl font-semibold text-slate-900",children:"Private listing unavailable"}),e.jsx("p",{className:"text-slate-600 mt-2",children:i||"This link has expired or was not shared with you."})]})})]});const{listing:q,agent:W}=r,G=(de=q.photos)!=null&&de.length?q.photos:[],K=G[0],ee=$Ns[q.status]||q.status,J=(W==null?void 0:W.sender_name)||(W==null?void 0:W.name)||"Your Agent",le=(W==null?void 0:W.sender_email)||null,ue=encodeURIComponent(`Interested in ${q.address}`),oe=encodeURIComponent(`Hi ${J}, I'd love to learn more about ${q.address}, ${q.city}. Thanks!`),ie=W!=null&&W.booking_slug?`https://dashboard.relevelup.com/book/${W.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(ql,{children:[e.jsxs("title",{children:["Private Listing · ",q.address]}),e.jsx("meta",{name:"robots",content:"noindex,nofollow,noarchive,nosnippet"}),e.jsx("meta",{name:"googlebot",content:"noindex,nofollow,noarchive,nosnippet"})]}),e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsxs("div",{className:"bg-gradient-to-r from-indigo-600 to-indigo-500 text-white text-center text-xs sm:text-sm py-2 px-4 flex items-center justify-center gap-2",children:[e.jsx(du,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",J]})]}),e.jsxs("div",{className:"relative",children:[K?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),m(!0)},children:e.jsx("img",{src:K,alt:q.address,className:"w-full h-[42vh] md:h-[60vh] object-cover"})}):e.jsx("div",{className:"w-full h-[42vh] md:h-[60vh] bg-slate-200 flex items-center justify-center text-slate-400",children:"No photos available"}),e.jsx("div",{className:"absolute top-4 left-4",children:e.jsx(qe,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:ee})}),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(be,{className:"shadow-xl border-slate-200",children:e.jsxs(Re,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-slate-900",children:q.address}),e.jsxs("p",{className:"text-slate-600 mt-1 flex items-center gap-1.5",children:[e.jsx(oi,{className:"h-4 w-4"}),q.city,", ",q.state," ",q.zip]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-3xl sm:text-4xl font-bold text-indigo-600",children:UNs(q.price)})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[q.bedrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(U_,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:q.bedrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Beds"})]}):null,q.bathrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(t0,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:q.bathrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Baths"})]}):null,q.sqft?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(H_,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:q.sqft.toLocaleString()}),e.jsx("p",{className:"text-xs text-slate-500",children:"Sq Ft"})]}):null]}),q.description&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900 mb-2",children:"About this property"}),e.jsx("p",{className:"text-slate-700 leading-relaxed whitespace-pre-line",children:q.description})]}),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((we,je)=>e.jsx("button",{type:"button",onClick:()=>{u(je),m(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:we,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},je))})]})]})}),e.jsxs(be,{className:"mt-6 shadow-lg border-slate-200 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-indigo-600 to-indigo-500 px-6 py-4 text-white",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Request more info or a private tour"}),e.jsxs("p",{className:"text-indigo-100 text-sm",children:[J," will get back to you personally."]})]}),e.jsx(Re,{className:"p-6 sm:p-8",children:I?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(Rr,{className:"h-12 w-12 text-emerald-500 mb-3"}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Message sent"}),e.jsxs("p",{className:"text-slate-600 mt-1",children:[J," just got your request and will reach out shortly."]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{id:"tour",label:"Private tour"},{id:"info",label:"More info"},{id:"offer",label:"Make an offer"}].map(we=>e.jsx("button",{type:"button",onClick:()=>M(we.id),className:`px-3 py-2 rounded-lg border text-sm font-medium transition ${T===we.id?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-700 border-slate-200 hover:border-indigo-300"}`,children:we.label},we.id))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-name",children:"Your name *"}),e.jsx(ye,{id:"pl-name",value:p,onChange:we=>x(we.target.value),placeholder:"Jane Doe",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-email",children:"Email *"}),e.jsx(ye,{id:"pl-email",type:"email",value:y,onChange:we=>g(we.target.value),placeholder:"you@email.com",maxLength:255})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(ye,{id:"pl-phone",value:b,onChange:we=>v(we.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Ds,{id:"pl-msg",value:k,onChange:we=>C(we.target.value),placeholder:`I'd love to see ${q.address}…`,rows:4,maxLength:2e3})]}),e.jsx(B,{onClick:$,disabled:P,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:P?"Sending…":"Send to "+J.split(" ")[0]}),e.jsx("p",{className:"text-xs text-slate-500 text-center",children:"By submitting, you agree to be contacted about this property."})]})})]}),e.jsx(be,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(Re,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-center sm:items-start gap-5",children:[W!=null&&W.avatar_url?e.jsx("img",{src:W.avatar_url,alt:J,className:"h-20 w-20 rounded-full object-cover ring-2 ring-indigo-100"}):e.jsx("div",{className:"h-20 w-20 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600 text-2xl font-bold",children:J.charAt(0)}),e.jsxs("div",{className:"flex-1 text-center sm:text-left",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-500",children:"Shared by"}),e.jsx("h3",{className:"text-xl font-bold text-slate-900",children:J}),(W==null?void 0:W.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:W.brokerage_name}),e.jsx("p",{className:"text-slate-600 text-sm mt-2",children:"Want a private tour or more info? Reach out — I'm happy to help."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 mt-6",children:[le&&e.jsx(B,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${le}?subject=${ue}&body=${oe}`,children:[e.jsx(on,{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(pa,{className:"h-4 w-4 mr-1.5"}),W.phone]})}),ie&&e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:ie,target:"_blank",rel:"noreferrer",children:[e.jsx(ym,{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(dr,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute left-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(we=>(we-1+G.length)%G.length),"aria-label":"Previous",children:e.jsx(Cc,{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(we=>(we+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 VNs(){var i;const{slug:s}=$i(),{data:t,isLoading:n,error:r}=n5t(s);if(j.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),j.useEffect(()=>{t!=null&&t.id&&Uc(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(gn,{className:"h-28 w-28 rounded-full"}),e.jsx(gn,{className:"h-6 w-48"}),e.jsx(gn,{className:"h-4 w-36"})]}),e.jsx(gn,{className:"h-12 w-full"}),e.jsx(gn,{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(ql,{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(rqe,{card:t})]})}const HNs="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",GNs="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",WNs="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",KNs="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",YNs="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",ZNs="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",Sje={"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:ZNs},"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:HNs},"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:GNs},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:WNs},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:KNs},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:YNs}},XNs=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function $Ct(s){return s&&s in Sje?Sje[s]:Sje["minimal-mono"]}function QNs(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 UCt({slugOverride:s}={}){var Gs;const{slug:t}=$i(),n=s||t,[r]=dc(),a=r.get("t"),[i,l]=j.useState(!0),[o,c]=j.useState(null),[d,u]=j.useState(null),h=j.useRef(null),m=j.useRef(null),[p,x]=j.useState(null),[y,g]=j.useState(null),[b,v]=j.useState(!1),[k,C]=j.useState(!1),[T,M]=j.useState(0),[P,L]=j.useState(!1),[I,O]=j.useState(""),[$,q]=j.useState(""),[W,G]=j.useState(""),[K,ee]=j.useState(""),[J,le]=j.useState(""),[ue,oe]=j.useState(""),[ie,de]=j.useState(""),[we,je]=j.useState(""),[xe,fe]=j.useState(""),[Se,Ee]=j.useState(""),[Le,De]=j.useState(""),[Be,Ne]=j.useState(""),[Ge,_e]=j.useState(""),[Oe,Ae]=j.useState([]),[Xe,Ue]=j.useState([]),[Ze,Qe]=j.useState(""),[Ye,nt]=j.useState(""),[rt,Fe]=j.useState(""),[dt,Dt]=j.useState([]);j.useEffect(()=>{pt()},[n,a]);const pt=async()=>{if(!n)return;l(!0);const{data:Ls,error:sn}=await U.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(sn||!Ls){L(!0),l(!1);return}u(Ls),m.current=Ls;const{data:Hs}=await U.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Ls.user_id).single();if(Hs){let nn;if(Hs.brokerage_id){const{data:Cn}=await U.from("brokerages").select("name").eq("id",Hs.brokerage_id).single();nn=(Cn==null?void 0:Cn.name)||void 0}let tn=Hs.avatar_url||null;if(!tn){const{data:Cn}=U.storage.from("avatars").getPublicUrl(`${Ls.user_id}/avatar.jpg`);Cn!=null&&Cn.publicUrl&&(tn=`${Cn.publicUrl}?t=${Date.now()}`)}const _n={...Hs,avatar_url:tn,brokerage_name:nn};c(_n),h.current=_n}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",Ls.id);const{data:nn,error:tn}=await U.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:Ls.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:nn,resolveErr:tn}),!tn&&(nn!=null&&nn.contact_id)){g(nn.contact_id);const _n=nn.contact;_n&&(x(_n),O(_n.first_name||""),q(_n.last_name||""),G(_n.email||""),ee(_n.phone||""),le(_n.address||""),oe(_n.city||""),de(_n.state||""),je(_n.zip||""),fe(_n.birthday||""),Ee(_n.home_anniversary||""))}}catch(nn){console.error("Failed to resolve token:",nn)}l(!1)},zt=async()=>{var Ls,sn;if(!I.trim()){re.error("Please enter your first name");return}if(!n){re.error("Invalid page. Please refresh.");return}C(!0);try{let Hs=(Ls=m.current)==null?void 0:Ls.id,nn=(sn=m.current)==null?void 0:sn.user_id;if(!Hs||!nn){const{data:Cn}=await U.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!Cn){re.error("This page is no longer active. Please contact the agent directly."),C(!1);return}Hs=Cn.id,nn=Cn.user_id}const tn={intake_page_id:Hs,agent_user_id:nn,existing_contact_id:y,first_name:I.trim(),last_name:$.trim()||null,email:W.trim()||null,phone:K.trim()||null,address:J.trim()||null,city:ue.trim()||null,state:ie.trim()||null,zip:we.trim()||null,birthday:xe||null,home_anniversary:Se||null,real_estate_interest:Le||null,message:Be.trim()||null,life_events:{spouse_name:Ge.trim()||null,kids:Oe.filter(Cn=>Cn.name.trim()),pets:Xe.filter(Cn=>Cn.name.trim()),favorite_spots:Ze.trim()||null,dream_neighborhood:Ye.trim()||null,wedding_anniversary:rt||null},referrals:dt.filter(Cn=>Cn.name.trim()&&Cn.contact.trim())},{error:_n}=await U.from("contact_intake_submissions").insert(tn);if(console.log("[ConnectPage] Insert result:",{error:_n}),_n)throw _n;a&&await U.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const Cn=[I.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:nn,contactName:Cn,contactEmail:W.trim()||null,contactPhone:K.trim()||null,slug:n})})}catch(Cn){console.warn("Connect page notification failed (non-blocking):",Cn)}v(!0)}catch(Hs){console.error(Hs),re.error("Something went wrong. Please try again.")}finally{C(!1)}};if(i)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-slate-400"})});if(P)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("h1",{className:"text-2xl font-semibold text-slate-700",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This connect page doesn't exist or is no longer active."})]})});if(b)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50 p-4",children:[e.jsx(ql,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(br.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"max-w-md w-full text-center space-y-6 p-8",children:[e.jsx(br.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",delay:.2},className:"mx-auto w-20 h-20 rounded-full bg-emerald-100 flex items-center justify-center",children:e.jsx(Rr,{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(mo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const Gt=!!a&&!!p,qs=(d==null?void 0:d.show_little_things)??!0,As=[{title:Gt?"Confirm Your Info":"Let's Get Connected",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"First Name *"}),e.jsx("input",{type:"text",value:I,onChange:Ls=>O(Ls.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:Ls=>q(Ls.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:Ls=>G(Ls.target.value),placeholder:"jane@email.com",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Phone"}),e.jsx("input",{type:"tel",value:K,onChange:Ls=>ee(Ls.target.value),placeholder:"(555) 123-4567",className:"connect-input"})]})]})},{title:"A Little More About You",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Street Address"}),e.jsx("input",{type:"text",value:J,onChange:Ls=>le(Ls.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:Ls=>oe(Ls.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:ie,onChange:Ls=>de(Ls.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:we,onChange:Ls=>je(Ls.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:xe,onChange:Ls=>fe(Ls.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:Ls=>Ee(Ls.target.value),className:"connect-input"})]})]})]})},...qs?[{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:Ls=>_e(Ls.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:Ls=>Fe(Ls.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(Ls=>[...Ls,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(Js,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Oe.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Oe.map((Ls,sn)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ls.name,onChange:Hs=>Ae(nn=>nn.map((tn,_n)=>_n===sn?{...tn,name:Hs.target.value}:tn)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ls.age,onChange:Hs=>Ae(nn=>nn.map((tn,_n)=>_n===sn?{...tn,age:Hs.target.value}:tn)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>Ae(Hs=>Hs.filter((nn,tn)=>tn!==sn)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(dr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},sn))]})]}),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:()=>Ue(Ls=>[...Ls,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(Js,{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((Ls,sn)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ls.name,onChange:Hs=>Ue(nn=>nn.map((tn,_n)=>_n===sn?{...tn,name:Hs.target.value}:tn)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ls.kind,onChange:Hs=>Ue(nn=>nn.map((tn,_n)=>_n===sn?{...tn,kind:Hs.target.value}:tn)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>Ue(Hs=>Hs.filter((nn,tn)=>tn!==sn)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(dr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},sn))]})]}),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:Ze,onChange:Ls=>Qe(Ls.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:Ye,onChange:Ls=>nt(Ls.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."})]}),dt.length<3&&e.jsxs("button",{type:"button",onClick:()=>Dt(Ls=>[...Ls,{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(Js,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:dt.map((Ls,sn)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ls.name,onChange:Hs=>Dt(nn=>nn.map((tn,_n)=>_n===sn?{...tn,name:Hs.target.value}:tn)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ls.contact,onChange:Hs=>Dt(nn=>nn.map((tn,_n)=>_n===sn?{...tn,contact:Hs.target.value}:tn)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>Dt(Hs=>Hs.filter((nn,tn)=>tn!==sn)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(dr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},sn))})]})]})}]:[],{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(Ls=>e.jsxs("button",{type:"button",onClick:()=>De(Le===Ls.value?"":Ls.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Le===Ls.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:Ls.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Ls.desc})]},Ls.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:Ls=>Ne(Ls.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],Bt=As.length,At=$Ct(d==null?void 0:d.theme),Is=QNs(At,(d==null?void 0:d.accent_color)||null),jt=(d==null?void 0:d.cover_image_url)||At.defaultCover,Qs=(d==null?void 0:d.headline)||"Let's stay connected",cn=(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)||""),qt=["deep-luxe"].includes((d==null?void 0:d.theme)||"");return e.jsxs("div",{className:"min-h-screen connect-shell",style:Is,children:[e.jsxs(ql,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${Qs} — ${(o==null?void 0:o.name)||"your agent"}`}),jt&&e.jsx("meta",{property:"og:image",content:jt}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:Qs}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsx("style",{children:` .connect-shell { font-family: var(--c-body-font); color: var(--c-text); } .connect-shell h1, .connect-shell h2 { font-family: var(--c-heading-font); } .connect-input { width: 100%; padding: 0.75rem 1rem; border-radius: 0.75rem; border: 1px solid var(--c-border); background: var(--c-surface); color: var(--c-text); font-family: var(--c-body-font); font-size: 0.95rem; transition: border-color 150ms, box-shadow 150ms; } .connect-input::placeholder { color: var(--c-text-muted); opacity: 0.7; } .connect-input:focus { outline: none; border-color: var(--c-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c-accent) 25%, transparent); } `}),e.jsxs("div",{className:"relative w-full overflow-hidden",style:{height:"clamp(200px, 30vh, 320px)"},children:[e.jsx(br.img,{src:jt,alt:"",initial:{scale:1.08},animate:{scale:1},transition:{duration:1.4,ease:"easeOut"},className:"absolute inset-0 w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,0) 20%, rgba(0,0,0,0.55) 100%)"}}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-6 pb-16 text-center",children:[e.jsx(br.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:At.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Qs}),cn&&e.jsx(br.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:cn})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(br.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.25},className:"text-center mb-6",children:[o!=null&&o.avatar_url?e.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-24 h-24 rounded-full object-cover mx-auto shadow-xl",style:{border:"4px solid var(--c-surface)"}}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center shadow-xl",style:{background:At.accent,color:At.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((Gs=o==null?void 0:o.name)==null?void 0:Gs.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(pa,{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(on,{className:"h-4 w-4"})})]})]}),e.jsx(br.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.35},className:"text-center mb-6 px-2 leading-relaxed text-sm",style:{color:"var(--c-text-muted)"},children:(d==null?void 0:d.welcome_message)||"I'd love to stay in touch — just a few quick details."}),e.jsx("div",{className:"flex gap-1.5 mb-6 px-2",children:Array.from({length:Bt}).map((Ls,sn)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:sn<=T?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},sn))}),e.jsxs(br.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.4},className:"rounded-2xl p-6 sm:p-8",style:{background:"var(--c-surface)",border:"1px solid var(--c-border)",boxShadow:qt?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(QU,{mode:"wait",children:e.jsxs(br.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:As[T].title})]}),As[T].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:As[T].subtitle})]}),As[T].fields]},T)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[T>0?e.jsx("button",{type:"button",onClick:()=>M(Ls=>Ls-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&&!I.trim()){re.error("Please enter your first name");return}M(Ls=>Ls+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:()=>zt(),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(Wt,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),T>0&&TM(Ls=>Ls+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(mo,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const eq=()=>({trackEngagement:j.useCallback(async(t,n,r,a="view")=>{try{const{data:{user:i}}=await U.auth.getUser();if(!i)return;await U.from("content_engagement_logs").insert({user_id:i.id,resource_type:t,resource_id:n,resource_title:r,action_type:a})}catch(i){console.error("Error tracking engagement:",i)}},[])});function NH({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=j.useState(0),[i,l]=j.useState(!1),{trackEngagement:o}=eq(),c=j.useCallback(p=>{o("newsletter",p.id,p.title,"click_link")},[o]),d=j.useCallback(()=>{a(p=>(p+1)%s.length)},[s.length]),u=j.useCallback(()=>{a(p=>(p-1+s.length)%s.length)},[s.length]),h=j.useCallback(p=>{a(p)},[]);if(j.useEffect(()=>{if(s.length<=1||i)return;const p=setInterval(d,t);return()=>clearInterval(p)},[s.length,i,t,d]),!s||s.length===0)return null;const m=s[r];return e.jsxs("div",{className:Et("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:Et("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(Cc,{className:"h-6 w-6"})}),e.jsx(B,{variant:"ghost",size:"icon",className:Et("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((p,x)=>e.jsx("button",{onClick:()=>h(x),className:Et("w-2 h-2 rounded-full transition-all duration-300",x===r?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${x+1}`},x))})]}),e.jsxs("div",{className:"bg-foreground rounded-b-xl px-5 py-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm md:text-base font-semibold text-background truncate",children:m.title}),m.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:m.description})]}),m.link_url&&e.jsx("a",{href:m.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(m),children:e.jsx(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 JNs(s){return"EST"}function rZ(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=JNs();return`${n} ${r}`}function Nz(s){const t=new Date,n=new Date(s),r=ant(n,-15),a=ant(n,30);return t>a?"ended":Z2(t,{start:n,end:a})?"live":Z2(t,{start:r,end:n})?"starting_soon":"upcoming"}function bVe(s){const t=Nz(s);return t==="starting_soon"||t==="live"}const Uat=bVe,eks=({events:s,registrations:t,onNavigateToEvents:n})=>{const[r,a]=j.useState(new Date);j.useEffect(()=>{const p=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(p)},[]);const i=s.filter(p=>bVe(p.event_date));if(i.length===0)return null;const l=i[0],o=Nz(l.event_date),c=t.find(p=>p.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,u=!!c,h=o==="live",m=h?{container:"from-red-500/10 via-red-500/5 to-primary/10 border-red-500/30",pulse:"from-red-500/5",indicator:"bg-red-500",text:"text-red-500",button:"bg-red-500 hover:bg-red-600",outlineButton:"border-red-500/50 text-red-500 hover:bg-red-500/10"}:{container:"from-amber-500/10 via-amber-500/5 to-primary/10 border-amber-500/30",pulse:"from-amber-500/5",indicator:"bg-amber-500",text:"text-amber-500",button:"bg-amber-500 hover:bg-amber-600",outlineButton:"border-amber-500/50 text-amber-500 hover:bg-amber-500/10"};return e.jsxs("div",{className:`relative mb-8 overflow-hidden rounded-xl bg-gradient-to-r ${m.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${m.pulse} to-transparent animate-pulse`}),e.jsx("div",{className:"relative p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex items-center justify-center",children:[e.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${m.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${m.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${m.text} font-bold text-sm uppercase tracking-wider`,children:h?e.jsxs(e.Fragment,{children:[e.jsx(iy,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(Vr,{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 ${rZ(new Date(l.event_date))}`:`Starts at ${rZ(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(Bn,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function Tf(){const{user:s}=Ns(),{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 U.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 U.from("user_verified_senders").select("email, status").eq("user_id",s.id).eq("status","verified").order("verified_at",{ascending:!1}).limit(1).maybeSingle();return h}}),i=!!(t!=null&&t.is_active),l=(t==null?void 0:t.gmail_email)||null,o=!!(r!=null&&r.email),c=(r==null?void 0:r.email)||null;return{isGmailConnected:i,gmailEmail:l,hasVerifiedSes:o,sesEmail:c,canSendEmail:i||o,sendMethod:i?"gmail":o?"mass_email":"none",isLoading:n||a}}function tks(){const{user:s}=Ns(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=Tf(),[a,i]=j.useState(!1),[l,o]=j.useState(!1);j.useEffect(()=>{s!=null&&s.id&&U.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle().then(({data:b})=>{i(!!b),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,v,k,C,T]=await Promise.all([U.from("profiles").select("avatar_url, phone, bio, name").eq("id",s.id).maybeSingle(),U.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),U.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),U.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),U.from("events").select("id, title, event_date, image_url").eq("is_published",!0).gte("event_date",new Date().toISOString()).or("title.ilike.%onboarding%,title.ilike.%new member%,title.ilike.%welcome%,description.ilike.%new member onboarding%").order("event_date",{ascending:!0}).limit(1).maybeSingle()]),M=b.data,P=!!(M!=null&&M.avatar_url&&(M!=null&&M.phone)&&(M!=null&&M.bio)),L=v.count||0,I=(k.count||0)>0,O=C.count||0;return{profile:M,profileComplete:P,contactsCount:L,contactsComplete:L>=5,eventsRegistered:I,communityComplete:O>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(b=>b.complete).length,p=h.length;return{steps:h,completedCount:m,totalCount:p,allComplete:m===p,dismissed:a,dismiss:async()=>{s!=null&&s.id&&(i(!0),await U.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(i(!1),await U.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:c,isGmailConnected:t,hasVerifiedSes:n,loading:d||r||!l}}const sks={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:Eo,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:on,accent:"from-[#406E71] to-[#5b9ea1]",cta:"Connect Email"},contacts:{title:"Add Your First Contacts",description:"Import your database or add contacts one at a time to start building your Inner Circle.",icon:Bn,accent:"from-[#c9a84c] to-[#e8c76f]",cta:"Add Contacts"},event:{title:"Register for New Member Onboarding",description:"Join our live LevelUp onboarding session to hit the ground running.",icon:ra,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:ro,accent:"from-[#ec4899] to-[#f472b6]",cta:"Visit Community"}};function nks(){var y,g;const s=Hn(),{user:t}=Ns(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=tks(),[u,h]=j.useState(!0);if(d||l||i)return null;const m=(((y=c==null?void 0:c.profile)==null?void 0:y.name)||((g=t==null?void 0:t.user_metadata)==null?void 0:g.name)||"there").split(" ")[0],p=r/a*100,x=async b=>{switch(b){case"profile":s("/profile");break;case"email":s("/mission-control/integrations");break;case"contacts":s("/mission-control/contacts");break;case"event":{const v=c==null?void 0:c.nextOnboardingEvent;if(!v){s("/events");return}if(!(t!=null&&t.id))return;const{error:k}=await U.from("event_registrations").insert({user_id:t.id,event_id:v.id});k&&!String(k.message).toLowerCase().includes("duplicate")?(re.error("Could not register — opening events page."),s("/events")):re.success(`You're registered for ${v.title}!`);break}case"community":s("/community");break}};return e.jsxs(be,{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(dr,{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(yn,{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(qi,{value:p,className:"h-2 bg-white/20 [&>div]:bg-[#f5f0e0]"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3",children:[e.jsxs(B,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(Xa,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(b=>!b),className:"text-sm text-white/80 hover:text-white flex items-center gap-1",children:u?e.jsxs(e.Fragment,{children:["Hide steps ",e.jsx(Qy,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(Po,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(Re,{className:"p-4 md:p-6 bg-gradient-to-b from-background to-muted/30",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:n.map(b=>{const v=sks[b.id],k=v.icon;return e.jsx("div",{className:Et("relative rounded-xl border p-4 transition-all group",b.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!b.complete&&x(b.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Et("h-10 w-10 rounded-lg flex items-center justify-center shrink-0 bg-gradient-to-br text-white",b.complete?"from-emerald-500 to-emerald-600":v.accent),children:b.complete?e.jsx(Rr,{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:Et("font-semibold text-sm",b.complete&&"text-muted-foreground line-through"),children:v.title})}),e.jsx("p",{className:Et("text-xs text-muted-foreground mt-1 leading-relaxed",b.complete&&"line-through"),children:v.description}),b.id==="event"&&!b.complete&&(c==null?void 0:c.nextOnboardingEvent)&&e.jsxs("div",{className:"mt-2 text-xs font-medium text-primary",children:[new Date(c.nextOnboardingEvent.event_date).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:"America/New_York"})," ","ET"]}),!b.complete&&e.jsxs(B,{size:"sm",variant:"ghost",className:"mt-2 h-7 px-2 -ml-2 text-primary hover:text-primary hover:bg-primary/10",onClick:C=>{C.stopPropagation(),x(b.id)},children:[v.cta," ",e.jsx(Xa,{className:"h-3 w-3 ml-1"})]})]}),b.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},b.id)})})})]})}const lw=()=>mt({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await U.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),av=s=>{const t=ei(),n=1e3,r=async a=>{const i=[];let l=0;for(;;){const{data:o,error:c}=await a.range(l,l+n-1);if(c)throw c;const d=o??[];if(i.push(...d),d.length{let a=U.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("owner_user_id",t).order("created_at",{ascending:!1}).order("first_name");return await r(a)},enabled:!!t})},rks=s=>mt({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:n}=await U.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),qCt=()=>{const s=ei();return mt({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:n}=await U.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(n)throw n;const r={};return t==null||t.forEach(a=>{var i;(i=a.tags)==null||i.forEach(l=>{r[l.relationship_type_id]=(r[l.relationship_type_id]||0)+1})}),r},enabled:!!s})},q3e=()=>{const s=as(),t=ei();return vt({mutationFn:async n=>{const{tagIds:r,...a}=n,i={...a,birthday:a.birthday||null,home_anniversary:a.home_anniversary||null,spouse_birthday:a.spouse_birthday||null,owner_user_id:t},{data:l,error:o}=await U.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(r&&r.length>0){const{error:c}=await U.from("innercircle_contact_tags").insert(r.map(d=>({contact_id:l.id,relationship_type_id:d})));if(c)throw c}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ba({title:"Contact created successfully"})},onError:n=>{ba({title:"Error creating contact",description:n.message,variant:"destructive"})}})},_Ve=()=>{const s=as();return vt({mutationFn:async({id:t,...n})=>{const{tagIds:r,tags:a,...i}=n,l=["birthday","home_anniversary","spouse_birthday","wedding_anniversary","last_contacted_at","next_touch_date"],o={...i};for(const u of Object.keys(o)){const h=o[u];(h===""||typeof h=="string"&&l.includes(u)&&h.trim()==="")&&(o[u]=null)}const{data:c,error:d}=await U.from("innercircle_contacts").update(o).eq("id",t).select().single();if(d)throw d;if(r!==void 0&&(await U.from("innercircle_contact_tags").delete().eq("contact_id",t),r.length>0)){const{error:u}=await U.from("innercircle_contact_tags").insert(r.map(h=>({contact_id:t,relationship_type_id:h})));if(u)throw u}return c},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ba({title:"Contact updated successfully"})},onError:t=>{ba({title:"Error updating contact",description:t.message,variant:"destructive"})}})},VCt=()=>{const s=as();return vt({mutationFn:async({contactId:t,spouseContactId:n})=>{if(n){const{error:r}=await U.from("innercircle_contacts").update({spouse_contact_id:n}).eq("id",t);if(r)throw r;const{error:a}=await U.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",n);if(a)throw a}else{const{data:r}=await U.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=r==null?void 0:r.spouse_contact_id,{error:i}=await U.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await U.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",a);if(l)throw l}}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-spouse"]}),ba({title:"Spouse link updated"})},onError:t=>{ba({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},wVe=()=>{const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("innercircle_contacts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ba({title:"Contact deleted successfully"})},onError:t=>{ba({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},tq=()=>mt({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await U.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),aks=s=>mt({queryKey:["action-scripts",s],queryFn:async()=>{let t=U.from("action_scripts").select("*, action_type:action_types(*)");const{data:n,error:r}=await t;if(r)throw r;return n}}),iks=()=>mt({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await U.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),oks=()=>{const s=as(),t=ei();return vt({mutationFn:async({name:n,description:r})=>{const{data:a,error:i}=await U.from("touchpoint_plans").insert({name:n,description:r,owner_user_id:t,active:!0,is_template:!1}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ba({title:"Plan created successfully"})},onError:n=>{ba({title:"Error creating plan",description:n.message,variant:"destructive"})}})},lks=()=>{const s=as(),t=ei();return vt({mutationFn:async({sourcePlanId:n,newName:r})=>{const{data:a,error:i}=await U.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",n).single();if(i)throw i;if(!a)throw new Error("Source plan not found");const{data:l,error:o}=await U.from("touchpoint_plans").insert({name:r,description:a.description,owner_user_id:t,active:!0,is_template:!1}).select().single();if(o)throw o;if(a.items&&a.items.length>0){const c=a.items.map(u=>({plan_id:l.id,month_number:u.month_number,action_type_id:u.action_type_id,default_script_id:u.default_script_id,notes:u.notes})),{error:d}=await U.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ba({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:n=>{ba({title:"Error duplicating plan",description:n.message,variant:"destructive"})}})},cks=()=>{const s=as();return vt({mutationFn:async({id:t,name:n,description:r})=>{const{data:a,error:i}=await U.from("touchpoint_plans").update({name:n,description:r}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ba({title:"Plan updated successfully"})}})},dks=()=>{const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("touchpoint_plans").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ba({title:"Plan deleted successfully"})}})},uks=()=>{const s=as();return vt({mutationFn:async({planId:t,items:n})=>{if(await U.from("touchpoint_plan_items").delete().eq("plan_id",t),n.length>0){const{error:r}=await U.from("touchpoint_plan_items").insert(n.map(a=>({plan_id:t,month_number:a.month_number,action_type_id:a.action_type_id,default_script_id:a.default_script_id||null,notes:a.notes})));if(r)throw r}},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),ba({title:"Plan schedule updated"})}})},hks=()=>{const s=as();return vt({mutationFn:async({actionTypeId:t,title:n,scriptBody:r,emailSubject:a,tone:i})=>{const{data:{user:l}}=await U.auth.getUser(),{data:o,error:c}=await U.from("action_scripts").insert({action_type_id:t,title:n,script_body:r,email_subject:a||null,tone:i||null,active:!0,user_id:l==null?void 0:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["action-scripts"]}),ba({title:"Script created successfully"})},onError:t=>{ba({title:"Error creating script",description:t.message,variant:"destructive"})}})},mks=()=>{const s=ei();return mt({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:n}=await U.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(n)throw n;return t},enabled:!!s})},pks=()=>{const s=as(),t=ei();return vt({mutationFn:async({planId:n,relationshipTypeId:r,active:a})=>{const{data:i}=await U.from("user_plan_enrollments").select("id").eq("plan_id",n).eq("relationship_type_id",r).maybeSingle();if(i){const{error:l}=await U.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await U.from("user_plan_enrollments").insert({owner_user_id:t,plan_id:n,relationship_type_id:r,active:!0,start_date:new Date().toISOString().split("T")[0]});if(l)throw l}},onSuccess:()=>{s.invalidateQueries({queryKey:["user-plan-enrollments"]}),ba({title:"Plan enrollment updated"})}})},sq=(s=7)=>{const t=ei();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 U.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",t).gte("completed_at",n.toISOString()).order("completed_at",{ascending:!1});if(a)throw a;return r},enabled:!!t})},HCt=()=>{const s=ei();return mt({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",s).order("completed_at",{ascending:!1});if(n)throw n;const r={};return t==null||t.forEach(a=>{r[a.contact_id]||(r[a.contact_id]=a.completed_at)}),r},enabled:!!s})},fks=(s=90)=>{const{data:t}=av(),{data:n}=HCt();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=ei();return vt({mutationFn:async({contactId:n,actionTypeId:r,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await U.from("contact_touch_logs").insert({owner_user_id:t,contact_id:n,action_type_id:r,script_used_id:a,notes:i,completed_at:l||new Date().toISOString()}).select().single();if(c)throw c;return o},onSuccess:async(n,r)=>{var a,i;s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),ba({title:"Action completed!"});try{const[l,o]=await Promise.all([U.from("innercircle_contacts").select("email").eq("id",r.contactId).single(),U.from("action_types").select("name").eq("id",r.actionTypeId).single()]),c=(a=l.data)==null?void 0:a.email,d=((i=o.data)==null?void 0:i.name)||"Touch";/pop[\s-]?by/i.test(d)&&U.from("popby_logs").insert({owner_user_id:t,contact_id:r.contactId,notes:r.notes??null,completed_at:r.completedAt||n.completed_at}).then(()=>{s.invalidateQueries({queryKey:["popby-logs"]})}),c&&U.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:c,touch_type:d,touch_notes:r.notes||null,touch_date:r.completedAt||n.completed_at}}).catch(()=>{})}catch{}}})},GCt="agentos_weekly_touch_goal",qat=20,QNe=()=>{if(typeof window>"u")return qat;const s=localStorage.getItem(GCt);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return qat},WCt=s=>{localStorage.setItem(GCt,s.toString())},jVe=()=>{const{data:s}=sq(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=QNe();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},xks=()=>{const s=ei();return mt({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(n)throw n;return t},enabled:!!s})},gks=()=>{const s=as();return ei(),vt({mutationFn:async()=>{var c;const{data:t}=await U.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:n}=await U.auth.getUser(),r=(c=n==null?void 0:n.user)==null?void 0:c.id;if(!r)return;const{data:a}=await U.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",r);if(!a)return;const{data:i}=await U.from("contact_plan_cycles").select("contact_id, plan_id"),l=new Set((i==null?void 0:i.map(d=>`${d.contact_id}-${d.plan_id}`))||[]),o=[];for(const d of a)for(const u of d.tags||[]){const h=t.find(m=>m.relationship_type_id===u.relationship_type_id);h&&!l.has(`${d.id}-${h.plan_id}`)&&o.push({contact_id:d.id,plan_id:h.plan_id,relationship_type_id:u.relationship_type_id})}if(o.length>0){const{error:d}=await U.from("contact_plan_cycles").insert(o);if(d)throw d}return o.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&ba({title:`${t} contact(s) enrolled in plans`})}})},KCt=()=>{const s=ei(),{data:t}=xks(),{data:n}=sq(30);return mt({queryKey:["today-actions",s,t==null?void 0:t.length,n==null?void 0:n.length],queryFn:async()=>{var x;if(!t||t.length===0)return[];const{data:r}=await U.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((r==null?void 0:r.map(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(!((x=y.plan)!=null&&x.items)||y.plan.items.length===0||!y.contact||a.has(y.contact_id))continue;const g=new Date(y.cycle_start_date),v=Math.floor((i.getTime()-g.getTime())/(30.44*24*60*60*1e3))%12+1,k=y.plan.items.find(C=>C.month_number===v);if(k&&k.action_type){const C=`${y.contact_id}-${k.action_type_id}`;if(!c.has(C)){const{data:T}=await U.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:v})}}}const d=5,u=i.getDate(),h=l.sort((y,g)=>y.contact.first_name.localeCompare(g.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 yks(){const s=Hn(),{data:t,isLoading:n}=KCt(),{data:r}=av(),a=jVe(),[i,l]=j.useState(QNe()),[o,c]=j.useState(""),[d,u]=j.useState(!1);j.useEffect(()=>{l(QNe())},[]);const h=()=>{const M=parseInt(o,10);if(isNaN(M)||M<1){ba({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}l(M),WCt(M),u(!1),ba({title:"Goal updated",description:`Weekly touch goal set to ${M}`})},m=()=>{c(i.toString()),u(!0)},p=xm(new Date),x=jd(p,7),y=M=>{if(!M)return null;const P=M.split(/[-/T]/);if(P.length<3)return null;const L=parseInt(P[1],10)-1,I=parseInt(P[2],10);return isNaN(L)||isNaN(I)?null:new Date(p.getFullYear(),L,I)},g=(r==null?void 0:r.map(M=>{const P=y(M.birthday),L=y(M.home_anniversary),I=[];return P&&P>=p&&P<=x&&I.push({contact:M,type:"birthday",date:P,isToday:pd(P,p)}),L&&L>=p&&L<=x&&I.push({contact:M,type:"anniversary",date:L,isToday:pd(L,p)}),I}).flat().sort((M,P)=>M.date.getTime()-P.date.getTime()).slice(0,3))||[],b=(r==null?void 0:r.filter(M=>{const P=y(M.birthday),L=y(M.home_anniversary);return P&&pd(P,p)||L&&pd(L,p)}).length)||0,v=(t==null?void 0:t.length)||0,k=b+v,C=(a==null?void 0:a.actionsThisWeek)||0,T=(a==null?void 0:a.streak)||0;return n?e.jsx(be,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:e.jsx(Re,{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(be,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:[e.jsxs(Ft,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5 text-primary"}),"Agent OS"]}),e.jsx("div",{className:"flex items-center gap-2",children:T>0&&e.jsxs(qe,{variant:"secondary",className:"gap-1 bg-orange-500/10 text-orange-600 border-orange-200",children:[e.jsx(Fd,{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",C>0&&e.jsxs("span",{className:"ml-2",children:["• ",e.jsx("span",{className:"text-emerald-600 font-medium",children:C})," touches this week"]})]})]}),e.jsxs(Re,{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:M=>{M.stopPropagation(),s("/mission-control/contacts?new=true")},children:[e.jsx(Sl,{className:"h-3.5 w-3.5"}),"Add Contact"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:M=>{M.stopPropagation(),s("/mission-control")},children:[e.jsx(pa,{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:M=>{M.stopPropagation(),s("/mission-control/video/record")},children:[e.jsx(Zr,{className:"h-3.5 w-3.5"}),"Quick Video"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:M=>{M.stopPropagation(),s("/mission-control/popbys")},children:[e.jsx(oi,{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:M=>{M.stopPropagation(),s("/mission-control/pipeline")},children:[e.jsx(v3,{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(uu,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Weekly Goal"}),e.jsxs(Fs,{open:d,onOpenChange:u,children:[e.jsx(Io,{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(ic,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-primary"})})}),e.jsxs(Os,{className:"sm:max-w-[360px]",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Set Weekly Goal"}),e.jsx(kr,{children:"How many touches do you want to complete each week?"})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"weekly-goal",children:"Weekly touch goal"}),e.jsx(ye,{id:"weekly-goal",type:"number",min:"1",value:o,onChange:M=>c(M.target.value),placeholder:"20",onKeyDown:M=>{M.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:C}),e.jsxs("span",{className:"text-muted-foreground",children:[" / ",i," touches"]})]})]}),e.jsx(qi,{value:Math.min(C/i*100,100),className:"h-2 bg-muted [&>div]:bg-primary"}),C>=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."]}),C0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1.5",children:[i-C," more to hit your weekly goal"]})]}),g.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(Wm,{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:g.map((M,P)=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${M.isToday?"bg-pink-500/10 hover:bg-pink-500/15":"bg-muted/50 hover:bg-muted"}`,onClick:L=>{L.stopPropagation(),s(`/mission-control/contacts/${M.contact.id}`)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[M.type==="birthday"?e.jsx(Wm,{className:"h-3.5 w-3.5 text-pink-500"}):e.jsx(ia,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsxs("span",{className:"text-sm",children:[M.contact.first_name," ",M.contact.last_name]}),M.isToday&&e.jsx(qe,{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:M.isToday?M.type==="birthday"?"🎂":"🏠":Bs(M.date,"EEE, MMM d")}),e.jsx(Qa,{className:"h-3 w-3"})]})]},`${M.contact.id}-${M.type}-${P}`))})]}),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(Xa,{className:"h-4 w-4"})]})]})]})}function vks(s){return mt({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(n)throw n;return t},enabled:!!s})}function bks(s,t){return mt({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let n=U.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t&&(n=n.eq("category_id",t));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!s})}function _ks(s,t=4){return mt({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:n,error:r}=await U.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(t);if(r)throw r;return n},enabled:!!s})}function wks(s){const t=as();return vt({mutationFn:async n=>{const{data:r,error:a}=await U.from("brokerage_content").insert(n).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content"]}),t.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function jks(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("brokerage_content").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function Nks(s){const t=as();return vt({mutationFn:async n=>{const{data:r,error:a}=await U.from("brokerage_content_categories").insert({...n,brokerage_id:s}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function kks(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("brokerage_content_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function Sks(s){const t=as();return vt({mutationFn:async()=>{const n=[{name:"Events",icon:"📅",sort_order:0,is_default:!0,brokerage_id:s},{name:"Videos",icon:"🎥",sort_order:1,is_default:!0,brokerage_id:s},{name:"Documents",icon:"📄",sort_order:2,is_default:!0,brokerage_id:s},{name:"Resources",icon:"🔗",sort_order:3,is_default:!0,brokerage_id:s},{name:"Graphics",icon:"🎨",sort_order:4,is_default:!0,brokerage_id:s}],{error:r}=await U.from("brokerage_content_categories").upsert(n,{onConflict:"brokerage_id,name"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const Cks={video:fd,pdf:$r,link:Rc,event:ra,graphic:Ac},Aks={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 Tks(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 Eks(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 Mks({item:s}){const t=Hn(),n=Cks[s.content_type]||Rc,r=Aks[s.content_type]||"",[a,i]=j.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?Tks(s.url):null);j.useEffect(()=>{l||!s.url||s.content_type!=="video"||!Eks(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(be,{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(Re,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(qe,{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:Bs(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function Lks(){const{brokerageId:s}=Ns(),t=Hn(),{data:n=[],isLoading:r}=_ks(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(Ni,{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(Xa,{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(Mks,{item:a},a.id))})]})}const YCt=()=>mt({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await U.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),ZCt=s=>{const{user:t,brokerageId:n}=Ns();return mt({queryKey:["listings",s,n],queryFn:async()=>{let r=U.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0);s!=null&&s.status&&(r=r.eq("status",s.status)),s!=null&&s.propertyType&&(r=r.eq("property_type",s.propertyType)),s!=null&&s.city&&(r=r.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(r=r.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(r=r.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(r=r.eq("open_to_referrals",!0));const{data:a,error:i}=await r;if(i)throw i;let l=a||[];if(n){const{data:o}=await U.from("profiles").select("id").eq("brokerage_id",n);if(o&&o.length>0){const c=o.map(h=>h.id);let d=U.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("share_with_brokerage",!0).eq("is_public",!1).in("agent_id",c);s!=null&&s.status&&(d=d.eq("status",s.status)),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data:u}=await d;if(u){const h=new Set(l.map(p=>p.id)),m=u.filter(p=>!h.has(p.id));l=[...l,...m]}}}switch(s==null?void 0:s.sortBy){case"updated":l.sort((o,c)=>new Date(c.updated_at).getTime()-new Date(o.updated_at).getTime());break;case"price_asc":l.sort((o,c)=>o.price-c.price);break;case"price_desc":l.sort((o,c)=>c.price-o.price);break;default:l.sort((o,c)=>new Date(c.created_at).getTime()-new Date(o.created_at).getTime())}return l}})},XCt=()=>{const{user:s}=Ns();return mt({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})},NVe=s=>{const{user:t}=Ns();return mt({queryKey:["listing",s],queryFn:async()=>{const{data:n,error:r}=await U.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds) `).eq("id",s).single();if(r)throw r;return t&&await U.from("listing_views").insert({listing_id:s,viewer_id:t.id}),n},enabled:!!s})},Pks=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("listings").insert({...n,agent_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Iks=()=>{const s=as();return vt({mutationFn:async({agentId:t,...n})=>{const{data:r,error:a}=await U.from("listings").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["brokerage-listings"]})}})},Rks=()=>{const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("listings").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},QCt=()=>{const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("listings").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Dks=()=>{const s=as();return vt({mutationFn:async({listingId:t,photoUrl:n,isPrimary:r=!1})=>{const{data:a,error:i}=await U.from("listing_photos").insert({listing_id:t,photo_url:n,is_primary:r}).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t.listing_id]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Oks=()=>{const s=as();return vt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await U.from("listing_photos").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Fks=()=>{const s=as();return vt({mutationFn:async({photos:t})=>{var i;const n=t.map(l=>U.from("listing_photos").update({sort_order:l.sort_order,is_primary:l.is_primary}).eq("id",l.id)),a=(i=(await Promise.all(n)).find(l=>l.error))==null?void 0:i.error;if(a)throw a;return t},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},zks=()=>{const s=as();return vt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await U.from("listing_photos").update({is_primary:!1}).eq("listing_id",n);if(r)throw r;const{error:a}=await U.from("listing_photos").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Bks=()=>{const{user:s}=Ns();return mt({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("listing_saves").select(` *, listing:listings( *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id) ) `).eq("agent_id",s.id);if(n)throw n;return t},enabled:!!s})},JCt=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await U.from("listing_saves").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await U.from("listing_saves").delete().eq("id",r.id),{saved:!1}):(await U.from("listing_saves").insert({listing_id:n,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},eAt=s=>{const{user:t}=Ns();return mt({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await U.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},$ks=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await U.from("listing_follows").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await U.from("listing_follows").delete().eq("id",r.id),{following:!1}):(await U.from("listing_follows").insert({listing_id:n,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},Uks=s=>{const{user:t}=Ns();return mt({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await U.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},qks=()=>{const{user:s}=Ns();return vt({mutationFn:async({listingId:t,shareType:n})=>{if(!s)throw new Error("Not authenticated");const{error:r}=await U.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:n});if(r)throw r}})},Vks=()=>{const{user:s}=Ns();return mt({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,n]=await Promise.all([U.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),U.from("listing_referrals").select(` *, sender:profiles!listing_referrals_sender_agent_id_fkey(id, name, email), listing:listings(*,photos:listing_photos(*)) `).eq("listing_agent_id",s.id).order("created_at",{ascending:!1})]);return{sent:t.data||[],received:n.data||[]}},enabled:!!s})},Hks=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async({listingId:n,listingAgentId:r,buyerName:a,buyerType:i,notes:l})=>{if(!t)throw new Error("Not authenticated");const{data:o,error:c}=await U.from("listing_referrals").insert({listing_id:n,sender_agent_id:t.id,listing_agent_id:r,buyer_name:a,buyer_type:i,notes:l}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["my-referrals"]})}})},Gks=()=>mt({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await U.from("listing_shares").select("sharing_agent_id, profiles!listing_shares_agent_id_fkey(name)").order("created_at",{ascending:!1}),t=new Map;s==null||s.forEach(l=>{var d;const o=l.sharing_agent_id;if(!o)return;const c=t.get(o);c?c.count++:t.set(o,{name:((d=l.profiles)==null?void 0:d.name)||"Unknown",count:1})});const n=Array.from(t.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10),{data:r}=await U.from("listings").select("agent_id, agent:profiles!listings_agent_id_fkey(name)").eq("is_approved",!0),a=new Map;r==null||r.forEach(l=>{var c;const o=a.get(l.agent_id);o?o.count++:a.set(l.agent_id,{name:((c=l.agent)==null?void 0:c.name)||"Unknown",count:1})});const i=Array.from(a.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10);return{topSharers:n,topListers:i}}}),Wks=()=>{const{user:s,brokerageId:t}=Ns();return mt({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:n}=await U.from("profiles").select("id").eq("brokerage_id",t);if(!n||n.length===0)return[];const r=n.map(l=>l.id),{data:a,error:i}=await U.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).in("agent_id",r).eq("is_approved",!0).order("created_at",{ascending:!1});if(i)throw i;return a},enabled:!!s&&!!t})},tAt=({className:s,variant:t="default"})=>e.jsx(qe,{variant:"outline",className:Et("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"}),Kks={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"},Yks={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function Zks(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function Xks(){const s=Hn(),{data:t,isLoading:n}=YCt(),{data:r,isLoading:a}=ZCt({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(be,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Re,{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(tAt,{})]}),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(Xa,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsx(Re,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ia,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No listings available yet"}),e.jsx(B,{variant:"link",size:"sm",onClick:()=>s("/mission-control/listings/new"),className:"mt-2",children:"Add the first listing"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:c.map(u=>{var m,p;const h=((m=u.photos)==null?void 0:m.find(x=>x.is_primary))||((p=u.photos)==null?void 0:p[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${u.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[h!=null&&h.photo_url?e.jsx("img",{src:h.photo_url,alt:`${u.city}, ${u.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ia,{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(qe,{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(qe,{className:`text-[10px] px-1.5 py-0.5 ${Kks[u.status]}`,children:Yks[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:Zks(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 sAt(s=10,t){return mt({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:n}=await U.from("user_roles").select("user_id").eq("role","admin"),r=new Set((n==null?void 0:n.map(m=>m.user_id))||[]);let a=null;if(t){const{data:m}=await U.from("profiles").select("id").eq("brokerage_id",t);a=new Set((m==null?void 0:m.map(p=>p.id))||[])}const{data:i,error:l}=await U.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+r.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(m=>!r.has(m.user_id));a&&(o=o.filter(m=>a.has(m.user_id)));const c=o.slice(0,s),d=c.map(m=>m.user_id),{data:u}=await U.from("profiles").select("id, name").in("id",d),h=new Map((u==null?void 0:u.map(m=>[m.id,{name:m.name}]))||[]);return c.map(m=>({user_id:m.user_id,total_points:m.total_points,total_events_attended:m.total_events_attended,current_streak:m.current_streak,profile:h.get(m.user_id)||null}))}})}function nAt(s){return mt({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return t},enabled:!!s})}function rAt(s){return mt({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function aAt(s,t){return mt({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:n}=await U.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!n)return null;const{data:r}=await U.from("user_roles").select("user_id").eq("role","admin"),a=new Set((r==null?void 0:r.map(c=>c.user_id))||[]),{data:i,error:l}=await U.from("agent_attendance_stats").select("user_id, total_points").gt("total_points",n.total_points);if(l)throw l;let o=(i==null?void 0:i.filter(c=>!a.has(c.user_id)))||[];if(t){const{data:c}=await U.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(u=>u.id))||[]);o=o.filter(u=>d.has(u.user_id))}return o.length+1},enabled:!!s})}function Qks(){const{user:s,brokerageId:t,isAdmin:n}=Ns();Hn();const r=!!t,[a,i]=j.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=sAt(5,l()),{data:d}=nAt(s==null?void 0:s.id),{data:u}=aAt(s==null?void 0:s.id,l()),{data:h}=rAt(s==null?void 0:s.id),m=n||r,p=()=>n?"Agent Leaderboard":r?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(ll,{className:"h-4 w-4 text-yellow-500"}),p()]})}),e.jsx(Re,{children:e.jsx("div",{className:"space-y-2",children:[...Array(m?5:3)].map((y,g)=>e.jsx(gn,{className:"h-10 w-full"},g))})})]});const x=y=>y===0?e.jsx(ll,{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(be,{children:[e.jsxs(Ft,{className:"pb-2",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(ll,{className:"h-4 w-4 text-yellow-500"}),p()]}),!n&&r&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx(B,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx(B,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(Re,{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((g,b)=>{var v,k,C;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${g.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":b===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:x(b)}),e.jsx(Ra,{className:"h-6 w-6",children:e.jsx(Da,{className:"text-xs",children:((k=(v=g.profile)==null?void 0:v.name)==null?void 0:k.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((C=g.profile)==null?void 0:C.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:g.total_points})]},g.user_id)}),y.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(Yn,{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(zo,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Qa,{className:"h-4 w-4"})]})]})]})}return e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(ll,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Re,{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(Fd,{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(cu,{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(Yn,{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(zo,{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(Yn,{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(zo,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(Qa,{className:"h-4 w-4"})]})]})})]})}const gO=()=>mt({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await U.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),kVe=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async n=>{const{data:r}=await U.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",n.trim()),a=(r||[]).find(o=>o.name.toLowerCase()===n.trim().toLowerCase()&&!0);if(a)throw new Error(`Lead source "${a.name}" already exists`);const{data:i,error:l}=await U.from("lead_sources").insert({name:n,owner_user_id:t==null?void 0:t.id,sort_order:100}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),re.success("Lead source added")},onError:n=>{re.error("Failed to add lead source"),console.error(n)}})},Jks=()=>{const s=as();return vt({mutationFn:async({id:t,name:n})=>{const{error:r}=await U.from("lead_sources").update({name:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),re.success("Lead source updated")},onError:t=>{re.error(t.message||"Failed to update lead source")}})},e5s=()=>{const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("lead_sources").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),re.success("Lead source removed")},onError:t=>{re.error(t.message||"Failed to remove lead source")}})},SVe=(s,t)=>{const{user:n,isAdmin:r}=Ns(),a=r&&t?t:n==null?void 0:n.id;return mt({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=U.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",a).order("close_date",{ascending:!1});s&&(i=i.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:l,error:o}=await i;if(o)throw o;return l},enabled:!!a})},CVe=s=>{const{user:t,isAdmin:n}=Ns(),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 U.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",r).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!r})},V3e=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async n=>{const{data:r,error:a}=await U.from("scorecard_transactions").insert({...n,owner_user_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),re.success("Transaction added")},onError:n=>{re.error("Failed to add transaction"),console.error(n)}})},t5s=()=>{const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("scorecard_transactions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),re.success("Transaction updated")},onError:t=>{re.error("Failed to update transaction"),console.error(t)}})},s5s=()=>{const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("scorecard_transactions").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),re.success("Transaction deleted")},onError:t=>{re.error("Failed to delete transaction"),console.error(t)}})},iAt=(s,t)=>{const{user:n,isAdmin:r}=Ns(),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 U.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},n5s=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async n=>{const{data:r,error:a}=await U.from("scorecard_goals").upsert({...n,owner_user_id:t.id},{onConflict:"owner_user_id,year"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["scorecard-goals",r.year]}),re.success("Goals saved")},onError:n=>{re.error("Failed to save goals"),console.error(n)}})},H3e=()=>{const{user:s}=Ns();return mt({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t},enabled:!!(s!=null&&s.id)})},r5s=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async n=>{const{data:r,error:a}=await U.from("scorecard_settings").upsert({...n,user_id:t.id},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-settings"]}),re.success("Settings saved")},onError:n=>{re.error("Failed to save settings"),console.error(n)}})},oAt=(s,t)=>{const{data:n,isLoading:r}=SVe(s,t),{data:a,isLoading:i}=CVe(t),{data:l}=H3e(),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,M)=>T+Number(M.sale_price),0),p=d.reduce((T,M)=>T+(Number(M.commission_amount)||0),0),x=d.reduce((T,M)=>{const P=Number(M.commission_amount)||0;if(!P)return T;let L=P;return M.brokerage_split_pct&&(L-=P*(M.brokerage_split_pct/100)),M.team_split_pct&&(L-=P*(M.team_split_pct/100)),M.franchise_fee_pct&&(L-=P*(M.franchise_fee_pct/100)),M.referral_fee_pct&&(L-=P*(M.referral_fee_pct/100)),M.transaction_fee&&(L-=M.transaction_fee),T+Math.max(0,L)},0),y={};d.forEach(T=>{var P;const M=((P=T.lead_source)==null?void 0:P.name)||"Unknown";y[M]=(y[M]||0)+1});const g=Object.entries(y).map(([T,M])=>({name:T,count:M})).sort((T,M)=>M.count-T.count),b=g[0]||null,v={};d.forEach(T=>{const M=Ic(T.close_date).toLocaleString("default",{month:"short"});v[M]=(v[M]||0)+1});const C=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(T=>({month:T,count:v[T]||0}));return{totalTransactions:d.length,buyerCount:u,sellerCount:h,totalVolume:m,averagePrice:d.length>0?m/d.length:0,totalCommission:o?p:0,totalNetToAgent:o?x:0,topLeadSource:b,transactionsByMonth:C,leadSourceBreakdown:g}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},a5s=()=>{const{isAdmin:s}=Ns();return mt({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:n}=await U.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(n)throw n;const r=[...new Set(t.map(l=>l.owner_user_id))],{data:a,error:i}=await U.from("profiles").select("id, name, email").in("id",r);if(i)throw i;return a},enabled:s})},uA={recency:40,touchpoints:30,transactions:20,referrals:10},Vat={warm:70,cooling:40};function i5s(s){return s===null?0:s<=14?uA.recency:s<=30?uA.recency*.85:s<=60?uA.recency*.65:s<=90?uA.recency*.4:s<=180?uA.recency*.2:uA.recency*.05}function o5s(s){const t=Math.min(s/12,1);return Math.round(uA.touchpoints*t)}function l5s(s){return s?uA.transactions:0}function c5s(){return 0}function d5s(s){return s>=Vat.warm?"warm":s>=Vat.cooling?"cooling":"at-risk"}function G3e(){const{data:s,isLoading:t}=av(),{data:n}=HCt(),{data:r}=sq(365),{data:a}=CVe(),i=j.useMemo(()=>{if(!s)return[];const o=new Date,c=e8(o,12),d={};r==null||r.forEach(h=>{new Date(h.completed_at)>=c&&(d[h.contact_id]=(d[h.contact_id]||0)+1)});const u=new Set((a==null?void 0:a.filter(h=>h.contact_id).map(h=>h.contact_id))||[]);return s.map(h=>{const m=(n==null?void 0:n[h.id])||null,p=m?Fj(o,new Date(m)):null,x=d[h.id]||0,y=u.has(h.id),g=i5s(p),b=o5s(x),v=l5s(y),k=c5s(),C=Math.round(g+b+v+k),T={score:C,status:d5s(C),breakdown:{recency:Math.round(g),touchpoints:Math.round(b),transactions:Math.round(v),referrals:Math.round(k)},lastTouchDate:m,daysSinceTouch:p,touchCountLast12Months:x,hasTransaction:y};return{...h,relationshipScore:T}})},[s,n,r,a]),l=j.useMemo(()=>{const o=i.filter(m=>m.relationshipScore.status==="warm").length,c=i.filter(m=>m.relationshipScore.status==="cooling").length,d=i.filter(m=>m.relationshipScore.status==="at-risk").length,u=i.length,h=u>0?Math.round(i.reduce((m,p)=>m+p.relationshipScore.score,0)/u):0;return{warm:o,cooling:c,atRisk:d,total:u,averageScore:h}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function lAt(){const s=Hn(),{stats:t,contactsWithScores:n,isLoading:r}=G3e();if(r)return e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(gn,{className:"h-5 w-40"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsx(gn,{className:"h-20 w-full"}),e.jsx(gn,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[e.jsx(kl,{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(Re,{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(qi,{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(qi,{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(qi,{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(vN,{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 u5s=()=>{var ee;const{user:s,isAdmin:t}=Ns(),n=Hn(),[r,a]=j.useState([]),[i,l]=j.useState([]),[o,c]=j.useState([]),[d,u]=j.useState([]),[h,m]=j.useState([]),[p,x]=j.useState([]),[y,g]=j.useState(new Set),[b,v]=j.useState([]),[k,C]=j.useState([]),[T,M]=j.useState([]),[P,L]=j.useState(null),[I,O]=j.useState(!0);j.useEffect(()=>{$()},[s]);const $=async()=>{var J,le,ue,oe,ie;try{const[de,we,je,xe,fe,Se,Ee,Le,De,Be,Ne]=await Promise.all([U.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),U.from("app_tiles").select("*").order("name"),U.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),U.from("events").select("*").order("event_date",{ascending:!0}),U.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),U.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),U.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),U.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),U.from("additional_services").select("id, name, description, preview_image_url, signup_link_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),U.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),U.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(J=Ne.data)!=null&&J.name&&L(Ne.data.name);const Ge=((le=de.data)==null?void 0:le.map(Ze=>Ze.tag))||[],_e=new Set(((ue=je.data)==null?void 0:ue.map(Ze=>Ze.app_id))||[]);g(_e);const Ae=(((oe=we.data)==null?void 0:oe.filter(Ze=>!Ze.required_tags||Ze.required_tags.length===0?!0:Ze.required_tags.some(Qe=>Ge.includes(Qe))))||[]).sort((Ze,Qe)=>Ze.name==="LevelUp Members Portal"?-1:Qe.name==="LevelUp Members Portal"?1:0);a(Ae.slice(0,6));const Xe=((ie=xe.data)==null?void 0:ie.filter(Ze=>Nz(Ze.event_date)!=="ended"))||[];l(Xe.slice(0,4)),v(fe.data||[]),c(Se.data||[]),u(Ee.data||[]),m(Le.data||[]),x(De.data||[]);const Ue=Be.data||[];C(Ue.filter(Ze=>Ze.placement==="top")),M(Ue.filter(Ze=>Ze.placement==="between"))}catch(de){console.error("Error loading dashboard:",de),re.error("Failed to load dashboard data")}finally{O(!1)}},q=async J=>{var ue;const le=window.open("about:blank","_blank");try{await U.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:J.app_id,app_name:J.name,user_agent:navigator.userAgent});const{data:oe,error:ie}=await U.functions.invoke("sso-launch",{body:{app_id:J.app_id}});if(ie)throw ie;oe!=null&&oe.redirect_url?le&&!le.closed?(le.location.href=oe.redirect_url,(ue=le.focus)==null||ue.call(le)):window.location.assign(oe.redirect_url):(le==null||le.close(),re.error("Launch link unavailable"))}catch(oe){le==null||le.close(),console.error("Error launching app:",oe),re.error("Failed to launch app")}},W=J=>b==null?void 0:b.some(le=>le.event_id===J),G=J=>{const le=b==null?void 0:b.find(ue=>ue.event_id===J);return le==null?void 0:le.zoom_join_url};if(I)return e.jsx(Vs,{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 K=J=>T.filter(le=>le.section_after===J);return e.jsxs(Vs,{title:"Dashboard",children:[e.jsx(eks,{events:i,registrations:b,onNavigateToEvents:()=>n("/events")}),k.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(NH,{banners:k})}),e.jsx(nks,{}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("h2",{className:"text-2xl font-bold text-foreground",children:["Welcome back, ",(P||((ee=s==null?void 0:s.user_metadata)==null?void 0:ee.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(yks,{}),e.jsx(lAt,{}),e.jsx(Qks,{})]}),e.jsx(Lks,{}),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(Xa,{className:"h-4 w-4"})]})]}),i.length===0?e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsx(Re,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ra,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No 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(J=>{const le=W(J.id),ue=G(J.id)||J.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 ${Uat(J.event_date)?"bg-red-500/5 border-l-2 border-l-red-500":""}`,onClick:()=>n("/events"),children:[Uat(J.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(iy,{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(J.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(J.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:J.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(J.event_date))," at ",rZ(new Date(J.event_date))]})]}),e.jsx("div",{className:"hidden sm:flex flex-shrink-0",children:le?e.jsxs(B,{size:"sm",variant:"default",className:"gap-1",onClick:oe=>{oe.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"})]})})]},J.id)})})]}),K("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(NH,{banners:K("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(Xa,{className:"h-4 w-4"})]})]}),h.length===0?e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsx(Re,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(vh,{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(J=>e.jsxs("div",{onClick:()=>n(`/academy/${J.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:[J.thumbnail_url?e.jsx("img",{src:J.thumbnail_url,alt:J.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(vh,{className:"h-8 w-8 text-muted-foreground/50"})}),J.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:J.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:J.title})})]},J.id))})]}),K("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(NH,{banners:K("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(Xa,{className:"h-4 w-4"})]})]}),d.length===0?e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsx(Re,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ny,{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(J=>e.jsxs("div",{onClick:()=>n(`/toolbox/${J.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:J.featured_image_url?e.jsx("img",{src:J.featured_image_url,alt:J.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(ny,{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:J.name})})]},J.id))})]}),K("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(NH,{banners:K("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(Xa,{className:"h-4 w-4"})]})]}),o.length===0?e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsx(Re,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(g3,{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(J=>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:J.preview_image_url?e.jsx("img",{src:J.preview_image_url,alt:J.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(g3,{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:J.name})})]},J.id))})]}),K("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(NH,{banners:K("templates")})}),e.jsx("div",{className:"mb-10",children:e.jsx(Xks,{})}),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(Xa,{className:"h-4 w-4"})]})]}),r.length===0?e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsx(Re,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(s1,{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(J=>{const le=y.has(J.id);return e.jsxs("div",{onClick:()=>q(J),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:J.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:J.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:J.description})]}),le&&e.jsx(s1,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},J.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(Xa,{className:"h-4 w-4"})]})]}),p.length===0?e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsx(Re,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(yn,{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:p.map(J=>e.jsxs("div",{onClick:()=>window.open(J.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:J.preview_image_url?e.jsx("img",{src:J.preview_image_url,alt:J.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(yn,{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:J.name}),J.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:J.description})]})]},J.id))})]})]})},h5s=[{key:"contacts",label:"Contacts",icon:pa,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:BR,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:ny,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:Zr,description:"View and upload videos"},{key:"listings",label:"Listings",icon:ia,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:r1,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:oi,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:ty,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:Op,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:yb,description:"Create and manage smart presentations"}];function m5s(){var P;const{user:s}=Ns(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState({email:"",name:"",password:""}),[p,x]=j.useState("create"),[y,g]=j.useState(!1),[b,v]=j.useState(null);j.useEffect(()=>{s&&k()},[s]);const k=async()=>{if(s){a(!0);try{const{data:L,error:I}=await U.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(I)throw I;if(L&&L.length>0){const O=L.map(W=>W.assistant_id),{data:$}=await U.from("profiles").select("id, name, email").in("id",O),q=L.map(W=>{const G=$==null?void 0:$.find(K=>K.id===W.assistant_id);return{...W,permissions:W.permissions,assistant_profile:G?{name:G.name||"",email:G.email||""}:void 0}});n(q)}else n([])}catch(L){console.error("Error loading assistants:",L)}finally{a(!1)}}},C=async()=>{if(s){if(p==="link"){if(!h.email.trim()){re.error("Please enter the assistant's email");return}g(!0);try{const{data:{session:L}}=await U.auth.getSession();if(!L)throw new Error("Not authenticated");const{data:I,error:O}=await U.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(O||!I){re.error("No account found with that email. Try creating a new assistant instead.");return}const{data:$}=await U.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",I.id);if($&&$.length>0){re.error("This assistant is already assigned to you");return}const q=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.access_token}`},body:JSON.stringify({userId:I.id,role:"assistant",action:"add",agentId:s.id})}),W=await q.json();if(!q.ok)throw new Error(W.error||"Failed to assign assistant role");const{error:G}=await U.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:I.id,permissions:{contacts:!0,pipeline:!0,videos:!1,listings:!1,scorecard:!1,popbys:!1,digital_card:!1,client_portal:!1,guest_book:!1,presentations:!1}});if(G)throw G;re.success(`${I.name||I.email} linked as your assistant`),l(!1),m({email:"",name:"",password:""}),k()}catch(L){console.error("Error linking assistant:",L),re.error(L.message||"Failed to link assistant")}finally{g(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){re.error("Please fill in all fields");return}if(h.password.length<6){re.error("Password must be at least 6 characters");return}g(!0);try{const{data:{session:L}}=await U.auth.getSession();if(!L)throw new Error("Not authenticated");const I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.access_token}`},body:JSON.stringify({email:h.email.trim(),password:h.password,name:h.name.trim(),purpose:"assistant"})}),O=await I.json();if(!I.ok)throw new Error(O.error||"Failed to create assistant account");const $=O.userId||O.id;if(!$)throw new Error("No user ID returned");const q=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.access_token}`},body:JSON.stringify({userId:$,role:"assistant",action:"add",agentId:s.id})}),W=await q.json();if(!q.ok)throw new Error(W.error||"Failed to assign assistant role");const{error:G}=await U.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;re.success(`Assistant account created for ${h.name.trim()}`),l(!1),m({email:"",name:"",password:""}),k()}catch(L){console.error("Error adding assistant:",L),re.error(L.message||"Failed to add assistant")}finally{g(!1)}}},T=async()=>{if(!(!d||!s))try{const{data:{session:L}}=await U.auth.getSession();if(!L)throw new Error("Not authenticated");const{error:I}=await U.from("agent_assistant_assignments").delete().eq("id",d.id);if(I)throw I;const{data:O}=await U.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!O||O.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${L.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),re.success("Assistant removed"),c(!1),u(null),k()}catch(L){console.error("Error removing assistant:",L),re.error(L.message||"Failed to remove assistant")}},M=async(L,I,O)=>{v(L);try{const $=t.find(G=>G.id===L);if(!$)return;const q={...$.permissions,[I]:O},{error:W}=await U.from("agent_assistant_assignments").update({permissions:q}).eq("id",L);if(W)throw W;n(G=>G.map(K=>K.id===L?{...K,permissions:q}:K))}catch($){console.error("Error updating permissions:",$),re.error("Failed to update permissions")}finally{v(null)}};return r?e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Re,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(fr,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(B,{size:"sm",onClick:()=>{x("create"),l(!0)},children:[e.jsx(Js,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Re,{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(L=>{var I,O,$,q;return e.jsxs("div",{className:"border rounded-lg p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ra,{className:"h-10 w-10",children:e.jsx(Da,{children:((O=(I=L.assistant_profile)==null?void 0:I.name)==null?void 0:O.split(" ").map(W=>W[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:(($=L.assistant_profile)==null?void 0:$.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((q=L.assistant_profile)==null?void 0:q.email)||""})]}),e.jsxs(qe,{variant:"secondary",className:"ml-2",children:[e.jsx(_f,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{u(L),c(!0)},children:e.jsx(Rn,{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:h5s.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(Mn,{checked:L.permissions[W.key]||!1,onCheckedChange:K=>M(L.id,W.key,K),disabled:b===L.id})]},W.key)})})]})]},L.id)})})})]}),e.jsx(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Add Assistant"}),e.jsx(kr,{children:p==="create"?"Create a new account for your assistant.":"Link an existing assistant account by their email."})]}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsxs(B,{variant:p==="create"?"default":"outline",size:"sm",onClick:()=>x("create"),children:[e.jsx(Js,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(B,{variant:p==="link"?"default":"outline",size:"sm",onClick:()=>x("link"),children:[e.jsx(vc,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[p==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"assistant-name",children:"Name"}),e.jsx(ye,{id:"assistant-name",value:h.name,onChange:L=>m({...h,name:L.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"assistant-email",children:"Email"}),e.jsx(ye,{id:"assistant-email",type:"email",value:h.email,onChange:L=>m({...h,email:L.target.value}),placeholder:"assistant@email.com"})]}),p==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(ye,{id:"assistant-password",type:"password",value:h.password,onChange:L=>m({...h,password:L.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(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:C,disabled:y,children:[y&&e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),p==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Nl,{open:o,onOpenChange:c,children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Remove Assistant?"}),e.jsxs(xl,{children:["This will remove ",(P=d==null?void 0:d.assistant_profile)==null?void 0:P.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:T,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function U0(s){this.content=s}U0.prototype={constructor:U0,find:function(s){for(var t=0;t>1}};U0.from=function(s){if(s instanceof U0)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new U0(t)};function cAt(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=cAt(a.content,i.content,n+1);if(l!=null)return l}n+=a.nodeSize}}function dAt(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 Lv(r,a)}cutByIndex(t,n){return t==n?Lv.empty:t==0&&n==this.content.length?this:new Lv(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 Lv(a,i)}addToStart(t){return new Lv([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new Lv(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?Dse(n+1,i):Dse(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 Lv.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Lv(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return Lv.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}};_h.none=[];class eke extends Error{}class di{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=hAt(this.content,t+this.openStart,n);return r&&new di(r,this.openStart,this.openEnd)}removeBetween(t,n){return new di(uAt(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 di.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 di(Aa.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 di(t,r,a)}}di.empty=new di(Aa.empty,0,0);function uAt(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(uAt(i.content,t-a-1,n-a-1)))}function hAt(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=hAt(l.content,t-i-1,n,l);return o&&s.replaceChild(a,l.copy(o))}function p5s(s,t,n){if(n.openStart>s.depth)throw new eke("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new eke("Inconsistent open depths");return mAt(s,t,n,0)}function mAt(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 IK(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&&(JR(s.nodeAfter,r),i++));for(let o=i;oa&&OOe(s,t,a+1),l=r.depth>a&&OOe(n,r,a+1),o=[];return IK(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(pAt(i,l),JR(eD(i,fAt(s,t,n,r,a+1)),o)):(i&&JR(eD(i,tke(s,t,a+1)),o),IK(t,n,a,o),l&&JR(eD(l,tke(n,r,a+1)),o)),IK(r,null,a,o),new Aa(o)}function tke(s,t,n){let r=[];if(IK(null,s,n,r),s.depth>n){let a=OOe(s,t,n+1);JR(eD(a,tke(s,t,n+1)),r)}return IK(t,null,n,r),new Aa(r)}function f5s(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(Aa.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class aZ{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 ske(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 aZ(n,r,i)}static resolveCached(t,n){let r=Hat.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()+")"),xAt(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=Aa.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=Aa.fromJSON(t,n.content),i=t.nodeType(n.type).create(n.attrs,a,r);return i.type.checkAttrs(i.attrs),i}};dE.prototype.text=void 0;class nke extends dE{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):xAt(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 nke(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new nke(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 xAt(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}class LD{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new v5s(t,n);if(r.next==null)return LD.empty;let a=gAt(r);r.next&&r.err("Unexpected trailing text");let i=S5s(k5s(a));return C5s(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(` `)}}LD.empty=new LD(!0);class v5s{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 gAt(s){let t=[];do t.push(b5s(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function b5s(s){let t=[];do t.push(_5s(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function _5s(s){let t=N5s(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=w5s(s,t);else break;return t}function Gat(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function w5s(s,t){let n=Gat(s),r=n;return s.eat(",")&&(s.next!="}"?r=Gat(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function j5s(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 N5s(s){if(s.eat("(")){let t=gAt(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=j5s(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 k5s(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 LD(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:bAt(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new dE(this,this.computeAttrs(t),Aa.from(n),_h.setFrom(r))}createChecked(t=null,n,r){return n=Aa.from(n),this.checkContent(n),new dE(this,this.computeAttrs(t),n,_h.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=Aa.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(Aa.empty,!0);return i?new dE(this,t,n.append(i),_h.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 jAt(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 A5s(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 T5s{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?A5s(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class W3e{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=wAt(t,a.attrs),this.excluded=null;let i=vAt(this.attrs);this.instance=i?new _h(this,i):null}create(t=null){return!t&&this.instance?this.instance:new _h(this,bAt(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new W3e(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}class NAt{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=U0.from(t.nodes),n.marks=U0.from(t.marks||{}),this.nodes=Kat.compile(this.spec.nodes,this),this.marks=W3e.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]=LD.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?Yat(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==""?[]:Yat(this,l.split(" "))}this.nodeFromJSON=a=>dE.fromJSON(this,a),this.markFromJSON=a=>_h.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 Kat){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 nke(r,r.defaultAttrs,t,_h.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 Yat(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 E5s(s){return s.tag!=null}function M5s(s){return s.style!=null}let RK=class zOe{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(E5s(a))this.tags.push(a);else if(M5s(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 Xat(this,n,!1);return r.addAll(t,_h.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new Xat(this,n,!0);return r.addAll(t,_h.none,n.from,n.to),di.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=Qat(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=Qat(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new zOe(t,zOe.schemaRules(t)))}};const kAt={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},L5s={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},SAt={ol:!0,ul:!0},iZ=1,BOe=2,DK=4;function Zat(s,t,n){return t!=null?(t?iZ:0)|(t==="full"?BOe:0):s&&s.whitespace=="pre"?iZ|BOe:n&~DK}class Ose{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=_h.none,this.match=i||(l&DK?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Aa.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&iZ)){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=Aa.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(Aa.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&&!kAt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class Xat{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=Zat(null,n.preserveWhitespace,0)|(r?DK:0);a?i=new Ose(a.type,a.attrs,_h.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new Ose(null,null,_h.none,!0,null,l):i=new Ose(t.schema.topNodeType,null,_h.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&BOe?"full":this.localPreserveWS||(a.options&iZ)>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):Jat(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new Ose(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|=iZ)}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 P5s(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&SAt.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function I5s(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function Qat(s){let t={};for(let n in s)t[n]=s[n];return t}function Jat(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&&Cje(dLe(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return Cje(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new yO(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=eit(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return eit(t.marks)}}function eit(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function dLe(s){return s.document||window.document}const tit=new WeakMap;function R5s(s){let t=tit.get(s);return t===void 0&&tit.set(s,t=D5s(s)),t}function D5s(s){let t=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")t||(t=[]),t.push(r);else for(let a=0;a-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let l=a.indexOf(" ");l>0&&(n=a.slice(0,l),a=a.slice(l+1));let o,c=n?s.createElementNS(n,a):s.createElement(a),d=t[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let h in d)if(d[h]!=null){let m=h.indexOf(" ");m>0?c.setAttributeNS(h.slice(0,m),h.slice(m+1),d[h]):h=="style"&&c.style?c.style.cssText=d[h]:c.setAttribute(h,d[h])}}for(let h=u;hu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:p,contentDOM:x}=Cje(s,m,n,r);if(c.appendChild(p),x){if(o)throw new RangeError("Multiple content holes");o=x}}}return{dom:c,contentDOM:o}}const CAt=65535,AAt=Math.pow(2,16);function O5s(s,t){return s+t*AAt}function sit(s){return s&CAt}function F5s(s){return(s-(s&CAt))/AAt}const TAt=1,EAt=2,Aje=4,MAt=8;class $Oe{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&MAt)>0}get deletedBefore(){return(this.delInfo&(TAt|Aje))>0}get deletedAfter(){return(this.delInfo&(EAt|Aje))>0}get deletedAcross(){return(this.delInfo&Aje)>0}}class I_{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&I_.empty)return I_.empty}recover(t){let n=0,r=sit(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],u=this.ranges[o+l],h=c+d;if(t<=h){let m=d?t==c?-1:t==h?1:n:n,p=c+a+(m<0?0:u);if(r)return p;let x=t==(n<0?c:h)?null:O5s(o/3,t-c),y=t==c?EAt:t==h?TAt:Aje;return(n<0?t!=c:t!=h)&&(y|=MAt),new $Oe(p,y,x)}a+=u-d}return r?t+a:new $Oe(t+a,0,null)}touches(t,n){let r=0,a=sit(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 oZ;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 wx.fromReplace(t,this.from,this.to,i)}invert(){return new _5(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 _T(n.pos,r.pos,this.mark)}merge(t){return t instanceof _T&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new _T(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 _T(n.from,n.to,t.markFromJSON(n.mark))}}iv.jsonID("addMark",_T);class _5 extends iv{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 di(AVe(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return wx.fromReplace(t,this.from,this.to,r)}invert(){return new _T(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 _5(n.pos,r.pos,this.mark)}merge(t){return t instanceof _5&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new _5(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 _5(n.from,n.to,t.markFromJSON(n.mark))}}iv.jsonID("removeMark",_5);class wT extends iv{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return wx.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return wx.fromReplace(t,this.pos,this.pos+1,new di(Aa.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 c0(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 c0(n.from,n.to,n.gapFrom,n.gapTo,di.fromJSON(t,n.slice),n.insert,!!n.structure)}}iv.jsonID("replaceAround",c0);function UOe(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 z5s(s,t,n,r){let a=[],i=[],l,o;s.doc.nodesBetween(t,n,(c,d,u)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&u.type.allowsMarkType(r.type)){let m=Math.max(d,t),p=Math.min(d+c.nodeSize,n),x=r.addToSet(h);for(let y=0;ys.step(c)),i.forEach(c=>s.step(c))}function B5s(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 W3e){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 _5(l.from,l.to,l.style)))}function TVe(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 $5s(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function nq(s){let n=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let r=s.depth,a=0,i=0;;--r){let l=s.$from.node(r),o=s.$from.index(r)+a,c=s.$to.indexAfter(r)-i;if(rn;x--)y||r.index(x)>0?(y=!0,u=Aa.from(r.node(x).copy(u)),h++):c--;let m=Aa.empty,p=0;for(let x=i,y=!1;x>n;x--)y||a.after(x+1)=0;l--){if(r.size){let o=n[l].type.contentMatch.matchFragment(r);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=Aa.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new c0(a,i,a,i,new di(r,0,0),n.length,!0))}function G5s(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)&&W5s(s.doc,s.mapping.slice(i).map(o),r)){let d=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",x=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!x?d=!1:!p&&x&&(d=!0)}d===!1&&PAt(s,l,o,i),TVe(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 c0(h,m,h+1,m-1,new di(Aa.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&LAt(s,l,o,i),!1}})}function LAt(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 PAt(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 W5s(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function K5s(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 c0(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new di(Aa.from(l),0,0),1,!0))}function kz(s,t,n=1,r){let a=s.resolve(t),i=a.depth-n,l=r&&r[r.length-1]||a.parent;if(i<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,u=n-2;d>i;d--,u--){let h=a.node(d),m=a.index(d);if(h.type.spec.isolating)return!1;let p=h.content.cutByIndex(m,h.childCount),x=r&&r[u+1];x&&(p=p.replaceChild(0,x.type.create(x.attrs)));let y=r&&r[u]||h;if(!h.canReplace(m+1,h.childCount)||!y.type.validContent(p))return!1}let o=a.indexAfter(i),c=r&&r[0];return a.node(i).canReplaceWith(o,o,c?c.type:a.node(i+1).type)}function Y5s(s,t,n=1,r){let a=s.doc.resolve(t),i=Aa.empty,l=Aa.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=Aa.from(a.node(o).copy(i));let u=r&&r[d];l=Aa.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new yx(t,t,new di(i.append(l),n,n),!0))}function a6(s,t){let n=s.resolve(t),r=n.index();return IAt(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function Z5s(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&&IAt(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 X5s(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);PAt(s,u.node(),u.before(),o)}l.inlineContent&&TVe(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 yx(d,c.map(t+n,-1),di.empty,!0)),r===!0){let u=s.doc.resolve(d);LAt(s,u.node(),u.before(),s.steps.length)}return s}function Q5s(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 Y3e(s,t,n=t,r=di.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return DAt(a,i,r)?new yx(t,n,r):new J5s(a,i,r).fit()}function DAt(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class J5s{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Aa.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=Aa.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 di(i,l,o);return t>-1?new c0(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new yx(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=hLe(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(Aa.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=hLe(t,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new di(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=hLe(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new di(PG(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new di(PG(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=g,u.push(OAt(y.mark(m.allowedMarks(y.marks)),d==1?c:0,d==o.childCount?p:-1)))}let x=d==o.childCount;x||(p=-1),this.placed=IG(this.placed,n,Aa.from(u)),this.frontier[n].match=h,x&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let y=0,g=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=mLe(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=IG(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=IG(this.placed,this.depth,Aa.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Aa.empty,!0);n.childCount&&(this.placed=IG(this.placed,this.frontier.length,n))}}function PG(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(PG(s.firstChild.content,t-1,n)))}function IG(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(IG(s.lastChild.content,t-1,n)))}function hLe(s,t){for(let n=0;n1&&(r=r.replaceChild(0,OAt(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(Aa.empty,!0)))),s.copy(r)}function mLe(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&&!eSs(n,i.content,l)?o:null}function eSs(s,t,n){for(let r=n;r0;m--,p--){let x=a.node(m).type.spec;if(x.defining||x.definingAsContext||x.isolating)break;l.indexOf(m)>-1?o=m:a.before(m)==p&&l.splice(1,0,-m)}let c=l.indexOf(o),d=[],u=r.openStart;for(let m=r.content,p=0;;p++){let x=m.firstChild;if(d.push(x),p==r.openStart)break;m=x.content}for(let m=u-1;m>=0;m--){let p=d[m],x=tSs(p.type);if(x&&!p.sameMarkup(a.node(Math.abs(o)-1)))u=m;else if(x||!p.type.isTextblock)break}for(let m=r.openStart;m>=0;m--){let p=(m+u+1)%(r.openStart+1),x=d[p];if(x)for(let y=0;y=0&&(s.replace(t,n,r),!(s.steps.length>h));m--){let p=l[m];p<0||(t=a.before(p),n=i.after(p))}}function FAt(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(Aa.empty,!0))}return s}function nSs(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=Q5s(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new di(Aa.from(r),0,0))}function rSs(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=zAt(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 zAt(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 Sz extends iv{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 wx.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 wx.fromReplace(t,this.pos,this.pos+1,new di(Aa.from(a),0,n.isLeaf?0:1))}getMap(){return I_.empty}invert(t){return new Sz(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 Sz(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 Sz(n.pos,n.attr,n.value)}}iv.jsonID("attr",Sz);class lZ extends iv{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 wx.ok(r)}getMap(){return I_.empty}invert(t){return new lZ(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 lZ(n.attr,n.value)}}iv.jsonID("docAttr",lZ);let k$=class extends Error{};k$=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};k$.prototype=Object.create(Error.prototype);k$.prototype.constructor=k$;k$.prototype.name="TransformError";let MVe=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new oZ}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new k$(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=di.empty){let a=Y3e(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new di(Aa.from(r),0,0))}delete(t,n){return this.replace(t,n,di.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return sSs(this,t,n,r),this}replaceRangeWith(t,n,r){return nSs(this,t,n,r),this}deleteRange(t,n){return rSs(this,t,n),this}lift(t,n){return U5s(this,t,n),this}join(t,n=1){return X5s(this,t,n),this}wrap(t,n){return H5s(this,t,n),this}setBlockType(t,n=t,r,a=null){return G5s(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return K5s(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new Sz(t,n,r)),this}setDocAttribute(t,n){return this.step(new lZ(t,n)),this}addNodeMark(t,n){return this.step(new wT(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 _h)n.isInSet(r.marks)&&this.step(new PD(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new PD(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 Y5s(this,t,n,r),this}addMark(t,n,r){return z5s(this,t,n,r),this}removeMark(t,n,r){return B5s(this,t,n,r),this}clearIncompatible(t,n,r){return TVe(this,t,n,r),this}};const pLe=Object.create(null);class il{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new BAt(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?M7(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):M7(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 Lj(t.node(0))}static atStart(t){return M7(t,t,0,0,1)||new Lj(t)}static atEnd(t){return M7(t,t,t.content.size,t.childCount,-1)||new Lj(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=pLe[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 pLe)throw new RangeError("Duplicate use of selection JSON ID "+t);return pLe[t]=n,n.prototype.jsonID=t,n}getBookmark(){return Go.between(this.$anchor,this.$head).getBookmark()}}il.prototype.visible=!0;class BAt{constructor(t,n){this.$from=t,this.$to=n}}let rit=!1;function ait(s){!rit&&!s.parent.inlineContent&&(rit=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class Go extends il{constructor(t,n=t){ait(t),ait(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 il.near(r);let a=t.resolve(n.map(this.anchor));return new Go(a.parent.inlineContent?a:r,r)}replace(t,n=di.empty){if(super.replace(t,n),n==di.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof Go&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new Z3e(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 Go(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=il.findFrom(n,r,!0)||il.findFrom(n,-r,!0);if(i)n=i.$head;else return il.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(il.findFrom(t,-r,!0)||il.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&&Bo.isSelectable(o))return Bo.create(s,n-(a<0?o.nodeSize:0))}else{let c=M7(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function iit(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(il.near(s.doc.resolve(l),n))}const oit=1,Fse=2,lit=4;class iSs extends MVe{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|=Fse,this}ensureMarks(t){return _h.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&Fse)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~Fse,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)||_h.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(il.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|=lit,this}get scrolledIntoView(){return(this.updated&lit)>0}}function cit(s,t){return!t||!s?s:s.bind(t)}class RG{constructor(t,n,r){this.name=t,this.init=cit(n.init,r),this.apply=cit(n.apply,r)}}const oSs=[new RG("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new RG("selection",{init(s,t){return s.selection||il.atStart(t.doc)},apply(s){return s.selection}}),new RG("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new RG("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class fLe{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=oSs.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 RG(r.key,r.spec.state,r))})}}class u9{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 fLe(t.schema,t.plugins),i=new u9(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=dE.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=il.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 $At(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=$At(a,t,{})),n[r]=a}return n}class yg{constructor(t){this.spec=t,this.props={},t.props&&$At(t.props,this,this.props),this.key=t.key?t.key.key:UAt("plugin")}getState(t){return t[this.key]}}const xLe=Object.create(null);function UAt(s){return s in xLe?s+"$"+ ++xLe[s]:(xLe[s]=0,s+"$")}class ov{constructor(t="key"){this.key=UAt(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const K0=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},S$=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let qOe=null;const x4=function(s,t,n){let r=qOe||(qOe=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},lSs=function(){qOe=null},ID=function(s,t,n,r){return n&&(dit(s,t,n,r,-1)||dit(s,t,n,r,1))},cSs=/^(img|br|input|textarea|hr)$/i;function dit(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:lj(s))){let l=s.parentNode;if(!l||l.nodeType!=1||AJ(s)||cSs.test(s.nodeName)||s.contentEditable=="false")return!1;t=K0(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?lj(s):0}else return!1}}function lj(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function dSs(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=lj(s)}else if(s.parentNode&&!AJ(s))t=K0(s),s=s.parentNode;else return null}}function uSs(s,t){for(;;){if(s.nodeType==3&&t2),nj=C$||(Z5?/Mac/.test(Z5.platform):!1),HAt=Z5?/Win/.test(Z5.platform):!1,o3=/Android \d/.test(i6),TJ=!!uit&&"webkitFontSmoothing"in uit.documentElement.style,fSs=TJ?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function xSs(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 KS(s,t){return typeof s=="number"?s:s[t]}function gSs(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 hit(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=S$(l);continue}let o=l,c=o==i.body,d=c?xSs(i):gSs(o),u=0,h=0;if(t.topd.bottom-KS(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+KS(a,"top")-d.top:t.bottom-d.bottom+KS(a,"bottom")),t.leftd.right-KS(r,"right")&&(u=t.right-d.right+KS(a,"right")),u||h)if(c)i.defaultView.scrollBy(u,h);else{let p=o.scrollLeft,x=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let y=o.scrollLeft-p,g=o.scrollTop-x;t={left:t.left-y,top:t.top-g,right:t.right-y,bottom:t.bottom-g}}let m=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(m))break;l=m=="absolute"?l.offsetParent:S$(l)}}function ySs(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:GAt(s.dom)}}function GAt(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=S$(r));return t}function vSs({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;WAt(n,r==0?0:r-t)}function WAt(s,t){for(let n=0;n=o){l=Math.max(x.bottom,l),o=Math.min(x.top,o);let y=x.left>t.left?x.left-t.left:x.right=(x.left+x.right)/2?1:0));continue}}else x.top>t.top&&!c&&x.left<=t.left&&x.right>=t.left&&(c=u,d={left:Math.max(x.left,Math.min(x.right,t.left)),top:x.top});!n&&(t.left>=x.right&&t.top>=x.top||t.left>=x.left&&t.top>=x.bottom)&&(i=h+1)}}return!n&&c&&(n=c,a=d,r=0),n&&n.nodeType==3?_Ss(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:KAt(n,a)}function _Ss(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 PVe(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function wSs(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 NSs(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 YAt(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;TJ&&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=NSs(s,r,a,t))}o==null&&(o=jSs(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function mit(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,kH(JC(x4(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==lj(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return gLe(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==lj(r))){let c=r.childNodes[a-1],d=c.nodeType==3?x4(c,lj(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return kH(JC(d,1),!1)}if(i==null&&a=0)}function kH(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 gLe(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 XAt(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 CSs(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return XAt(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=ZAt(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=x4(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 ASs=/[\u0590-\u08ac]/;function TSs(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?!ASs.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:XAt(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),m=o.caretBidiLevel;o.modify("move",n,"character");let p=r.depth?s.docView.domAfterPos(r.before()):s.dom,{focusNode:x,focusOffset:y}=s.domSelectionRange(),g=x&&!p.contains(x.nodeType==1?x:x.parentNode)||c==x&&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),g}):r.pos==r.start()||r.pos==r.end()}let pit=null,fit=null,xit=!1;function ESs(s,t,n){return pit==t&&fit==n?xit:(pit=t,fit=n,xit=n=="up"||n=="down"?CSs(s,t,n):TSs(s,t,n))}const Ij=0,git=1,r8=2,X5=3;class EJ{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=Ij,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;nK0(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 JAt){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 QAt&&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?K0(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=K0(m.dom)+1;break}t-=m.size}a==-1&&(a=0)}if(a>-1&&(d>n||o==this.children.length-1)){n=d;for(let u=o+1;ux&&ln){let x=o;o=c,c=x}let p=document.createRange();p.setEnd(c.node,c.offset),p.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(p)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,n){for(let r=0,a=0;a=r:tr){let o=r+i.border,c=l-i.border;if(t>=o&&n<=c){this.dirty=t==r||n==l?r8:git,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=X5:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?r8:X5}r=l}this.dirty=r8}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?r8:git;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==Ij&&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 MSs extends EJ{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 RD extends EJ{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=yO.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new RD(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&X5||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=X5&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=Ij){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=KOe(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}=yO.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=sTt(u,r,n),d?c=new LSs(t,n,r,a,u,h||null,m,d,i,l+1):n.isText?new Q3e(t,n,r,a,u,m,i):new hE(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=()=>Aa.empty)}return t}matchesNode(t,n,r){return this.dirty==Ij&&t.eq(this.node)&&rke(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 ISs(this,l&&l.node,t);OSs(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?_h.none:this.node.child(u).marks,r,t,u),c.placeWidget(d,t,a)},(d,u,h,m)=>{c.syncToMarks(d.marks,r,t,m);let p;c.findNodeMatch(d,u,h,m)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,u,h,p,t)||c.updateNextNode(d,u,h,t,m,a)||c.addNode(d,u,h,t,a),a+=d.nodeSize}),c.syncToMarks([],r,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==r8)&&(l&&this.protectLocalComposition(t,l),eTt(this.contentDOM,this.children,t),C$&&FSs(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof Go)||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=zSs(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 MSs(this,i,n,a);t.input.compositionNodes.push(l),this.children=KOe(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==X5||!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=Ij}updateOuterDeco(t){if(rke(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=tTt(this.dom,this.nodeDOM,WOe(this.outerDeco,this.node,n),WOe(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 yit(s,t,n,r,a){sTt(r,t,s);let i=new hE(void 0,s,t,n,r,r,r,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class Q3e extends hE{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==X5||this.dirty!=Ij&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=Ij||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=Ij,!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 Q3e(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=X5)}get domAtom(){return!1}isText(t){return this.node.text==t}}class JAt extends EJ{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==Ij&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class LSs extends hE{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==X5)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 eTt(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=RD.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 RD)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 DSs(s,t){return s.type.side-t.type.side}function OSs(s,t,n,r){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let x=i+m.nodeSize;if(m.isText){let g=x;l!g.inline):o.slice();r(m,y,t.forChild(i,m),p),i=x}}function FSs(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 zSs(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 KOe(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 IVe(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(X3e(n)){for(c=l;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&Bo.isSelectable(h)&&a.parent&&!(h.isInline&&hSs(n.focusNode,n.focusOffset,a.dom))){let m=a.posBefore;d=new Bo(l==m?o:r.resolve(m))}}else{if(n instanceof s.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=l,m=l;for(let p=0;p{(n.anchorNode!=r||n.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!nTt(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function $Ss(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,K0(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&_b&&uE<=11&&(n.disabled=!0,n.disabled=!1)}function rTt(s,t){if(t instanceof Bo){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(jit(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else jit(s)}function jit(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function RVe(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||Go.between(t,n,r)}function Nit(s){return s.editable&&!s.hasFocus()?!1:aTt(s)}function aTt(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 USs(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return ID(t.node,t.offset,n.anchorNode,n.anchorOffset)}function YOe(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&&il.findFrom(i,t)}function hA(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function kit(s,t,n){let r=s.state.selection;if(r instanceof Go)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 hA(s,new Go(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=YOe(s.state,t);return a&&a instanceof Bo?hA(s,a):!1}else if(!(nj&&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?Bo.isSelectable(i)?hA(s,new Bo(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):TJ?hA(s,new Go(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof Bo&&r.node.isInline)return hA(s,new Go(t>0?r.$to:r.$from));{let a=YOe(s.state,t);return a?hA(s,a):!1}}}function ake(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function FK(s,t){let n=s.pmViewDesc;return n&&n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function UF(s,t){return t<0?qSs(s):VSs(s)}function qSs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(Pj&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(FK(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(iTt(n))break;{let o=n.previousSibling;for(;o&&FK(o,-1);)a=n.parentNode,i=K0(o),o=o.previousSibling;if(o)n=o,r=ake(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?ZOe(s,n,r):a&&ZOe(s,a,i)}function VSs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=ake(n),i,l;for(;;)if(r{s.state==a&&k3(s)},50)}function Sit(s,t){let n=s.state.doc.resolve(t);if(!(J0||HAt)&&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 Cit(s,t,n){let r=s.state.selection;if(r instanceof Go&&!r.empty||n.indexOf("s")>-1||nj&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=YOe(s.state,t);if(l&&l instanceof Bo)return hA(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof Lj?il.near(l,t):il.findFrom(l,t);return o?hA(s,o):!1}return!1}function Ait(s,t){if(!(s.state.selection instanceof Go))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 Tit(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function WSs(s){if(!tv||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;Tit(s,r,"true"),setTimeout(()=>Tit(s,r,"false"),20)}return!1}function KSs(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function YSs(s,t){let n=t.keyCode,r=KSs(t);if(n==8||nj&&n==72&&r=="c")return Ait(s,-1)||UF(s,-1);if(n==46&&!t.shiftKey||nj&&n==68&&r=="c")return Ait(s,1)||UF(s,1);if(n==13||n==27)return!0;if(n==37||nj&&n==66&&r=="c"){let a=n==37?Sit(s,s.state.selection.from)=="ltr"?-1:1:-1;return kit(s,a,r)||UF(s,a)}else if(n==39||nj&&n==70&&r=="c"){let a=n==39?Sit(s,s.state.selection.from)=="ltr"?1:-1:1;return kit(s,a,r)||UF(s,a)}else{if(n==38||nj&&n==80&&r=="c")return Cit(s,-1,r)||UF(s,-1);if(n==40||nj&&n==78&&r=="c")return WSs(s)||Cit(s,1,r)||UF(s,1);if(r==(nj?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function DVe(s,t){s.someProp("transformCopied",p=>{t=p(t,s)});let n=[],{content:r,openStart:a,openEnd:i}=t;for(;a>1&&i>1&&r.childCount==1&&r.firstChild.childCount==1;){a--,i--;let p=r.firstChild;n.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let l=s.someProp("clipboardSerializer")||yO.fromSchema(s.state.schema),o=hTt(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=uTt[d.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let x=o.createElement(u[p]);for(;c.firstChild;)x.appendChild(c.firstChild);c.appendChild(x),h++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${a} ${i}${h?` -${h}`:""} ${JSON.stringify(n)}`);let m=s.someProp("clipboardTextSerializer",p=>p(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:m,slice:t}}function oTt(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 di(Aa.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",m=>{o=m(o,s,!0)}),o;let h=s.someProp("clipboardTextParser",m=>m(t,a,r,s));if(h)o=h;else{let m=a.marks(),{schema:p}=s.state,x=yO.fromSchema(p);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(y=>{let g=l.appendChild(document.createElement("p"));y&&g.appendChild(x.serializeNode(p.text(y,m)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=JSs(n),TJ&&e4s(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")||RK.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(m){return m.nodeName=="BR"&&!m.nextSibling&&m.parentNode&&!ZSs.test(m.parentNode.nodeName)?{ignore:!0}:null}})),u)o=t4s(Eit(o,+u[1],+u[2]),u[4]);else if(o=di.maxOpen(XSs(o.content,a),!0),o.openStart||o.openEnd){let h=0,m=0;for(let p=o.content.firstChild;h{o=h(o,s,c)}),o}const ZSs=/^(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 XSs(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&&cTt(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=dTt(l[l.length-1],i.length));let u=lTt(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return Aa.from(l)}return s}function lTt(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,Aa.from(s));return s}function cTt(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(Aa.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function Eit(s,t,n){return tn})),vLe.createHTML(s)):s}function JSs(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=hTt().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(s),a;if((a=r&&uTt[r[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),n.innerHTML=QSs(s),a)for(let i=0;i=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;a=Aa.from(c.create(r[o+1],a)),i++,l++}return new di(a,i,l)}const h1={},m1={},s4s={touchstart:!0,touchmove:!0};class n4s{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 r4s(s){for(let t in h1){let n=h1[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{i4s(s,r)&&!OVe(s,r)&&(s.editable||!(r.type in m1))&&n(s,r)},s4s[t]?{passive:!0}:void 0)}tv&&s.dom.addEventListener("input",()=>null),QOe(s)}function jT(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function a4s(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 QOe(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>OVe(s,r))})}function OVe(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function i4s(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 o4s(s,t){!OVe(s,t)&&h1[t.type]&&(s.editable||!(t.type in m1))&&h1[t.type](s,t)}m1.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!pTt(s,n)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(o3&&J0&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),C$&&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,HI(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||YSs(s,n)?n.preventDefault():jT(s,"key")};m1.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};m1.keypress=(s,t)=>{let n=t;if(pTt(s,n)||!n.charCode||n.ctrlKey&&!n.altKey||nj&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof Go)||!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 J3e(s){return{left:s.clientX,top:s.clientY}}function l4s(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function FVe(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 Cz(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 c4s(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&Bo.isSelectable(r)?(Cz(s,new Bo(n)),!0):!1}function d4s(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof Bo&&(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(Bo.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?(Cz(s,Bo.create(s.state.doc,a)),!0):!1}function u4s(s,t,n,r,a){return FVe(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?d4s(s,n):c4s(s,n))}function h4s(s,t,n,r){return FVe(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function m4s(s,t,n,r){return FVe(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||p4s(s,n,r)}function p4s(s,t,n){if(n.button!=0)return!1;let r=s.state.doc;if(t==-1)return r.inlineContent?(Cz(s,Go.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)Cz(s,Go.create(r,o+1,o+1+l.content.size));else if(Bo.isSelectable(l))Cz(s,Bo.create(r,o));else continue;return!0}}function zVe(s){return ike(s)}const mTt=nj?"metaKey":"ctrlKey";h1.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=zVe(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&l4s(n,s.input.lastClick)&&!n[mTt]&&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(J3e(n));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new f4s(s,l,n,!!r)):(i=="doubleClick"?h4s:m4s)(s,l.pos,l.inside,n)?n.preventDefault():jT(s,"pointer"))};class f4s{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[mTt],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 Bo&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Pj&&!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)),jT(t,"pointer")}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>k3(this.view)),this.view.input.mouseDown=null}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(J3e(t))),this.updateAllowDefault(t),this.allowDefault||!n?jT(this.view,"pointer"):u4s(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||tv&&this.mightDrag&&!this.mightDrag.node.isAtom||J0&&!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)?(Cz(this.view,il.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):jT(this.view,"pointer")}move(t){this.updateAllowDefault(t),jT(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)}}h1.touchstart=s=>{s.input.lastTouch=Date.now(),zVe(s),jT(s,"pointer")};h1.touchmove=s=>{s.input.lastTouch=Date.now(),jT(s,"pointer")};h1.contextmenu=s=>zVe(s);function pTt(s,t){return s.composing?!0:tv&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const x4s=o3?5e3:-1;m1.compositionstart=m1.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof Go&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||J0&&HAt&&g4s(s)))s.markCursor=s.state.storedMarks||n.marks(),ike(s,!0),s.markCursor=null;else if(ike(s,!t.selection.empty),Pj&&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}fTt(s,x4s)};function g4s(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"}m1.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++,fTt(s,20))};function fTt(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>ike(s),t))}function xTt(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=v4s());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function y4s(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=dSs(t.focusNode,t.focusOffset),r=uSs(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 v4s(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function ike(s,t=!1){if(!(o3&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),xTt(s),t||s.docView&&s.docView.dirty){let n=IVe(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 b4s(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 cZ=_b&&uE<15||C$&&fSs<604;h1.copy=m1.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=cZ?null:n.clipboardData,l=r.content(),{dom:o,text:c}=DVe(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):b4s(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function _4s(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function w4s(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?dZ(s,r.value,null,a,t):dZ(s,r.textContent,r.innerHTML,a,t)},50)}function dZ(s,t,n,r,a){let i=oTt(s,t,n,r,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||di.empty)))return!0;if(!i)return!1;let l=_4s(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 gTt(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," "):""}m1.paste=(s,t)=>{let n=t;if(s.composing&&!o3)return;let r=cZ?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&dZ(s,gTt(r),r.getData("text/html"),a,n)?n.preventDefault():w4s(s,n)};class yTt{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const j4s=nj?"altKey":"ctrlKey";function vTt(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[j4s]}h1.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(J3e(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof Bo?a.to-1:a.to))){if(r&&r.mightDrag)l=Bo.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=Bo.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=DVe(s,o);(!n.dataTransfer.files.length||!J0||VAt>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(cZ?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",cZ||n.dataTransfer.setData("text/plain",d),s.dragging=new yTt(u,vTt(s,n),l)};h1.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};m1.dragover=m1.dragenter=(s,t)=>t.preventDefault();m1.drop=(s,t)=>{try{N4s(s,t,s.dragging)}finally{s.dragging=null}};function N4s(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(J3e(t));if(!r)return;let a=s.state.doc.resolve(r.pos),i=n&&n.slice;i?s.someProp("transformPasted",p=>{i=p(i,s,!1)}):i=oTt(s,gTt(t.dataTransfer),cZ?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&vTt(s,t));if(s.someProp("handleDrop",p=>p(s,t,i||di.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?RAt(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:p}=n;p?p.replace(c):c.deleteSelection()}let d=c.mapping.map(o),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,h=c.doc;if(u?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(h))return;let m=c.doc.resolve(d);if(u&&Bo.isSelectable(i.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new Bo(m));else{let p=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((x,y,g,b)=>p=b),c.setSelection(RVe(s,m,c.doc.resolve(p)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}h1.focus=s=>{s.input.lastFocus=Date.now(),s.focused||(s.domObserver.stop(),s.dom.classList.add("ProseMirror-focused"),s.domObserver.start(),s.focused=!0,setTimeout(()=>{s.docView&&s.hasFocus()&&!s.domObserver.currentSelection.eq(s.domSelectionRange())&&k3(s)},20))};h1.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)};h1.beforeinput=(s,t)=>{if(J0&&o3&&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,HI(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 m1)h1[s]=m1[s];function uZ(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 oke{constructor(t,n){this.toDOM=t,this.spec=n||tD,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 Yv(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof oke&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&uZ(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class mE{constructor(t,n){this.attrs=t,this.spec=n||tD}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 Yv(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==$y||t.maps.length==0?this:this.mapInner(t,n,0,0,r||tD)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=_Tt(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 mE){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,tD));return SA.from(r)}forChild(t,n){if(n.isLeaf)return mf.empty;let r=[];for(let a=0;an instanceof mf)?t:t.reduce((n,r)=>n.concat(r instanceof mf?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let g=y-x-(p-m);for(let b=0;bv+u-h)continue;let k=o[b]+u-h;p>=k?o[b+1]=m<=k?-2:-1:m>=u&&g&&(o[b]+=g,o[b+1]+=g)}h+=g}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d=r.content.size){c=!0;continue}let m=n.map(s[d+1]+i,-1),p=m-a,{index:x,offset:y}=r.content.findIndex(h),g=r.maybeChild(x);if(g&&y==h&&y+g.nodeSize==p){let b=o[d+2].mapInner(n,g,u+1,s[d]+i+1,l);b!=$y?(o[d]=h,o[d+1]=p,o[d+2]=b):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=S4s(o,s,t,n,a,i,l),u=lke(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=_Tt(s,o,c+n);if(d){i=!0;let u=lke(d,o,n+c+1,r);u!=$y&&a.push(c,c+o.nodeSize,u)}});let l=bTt(i?wTt(s):s,-n).sort(sD);for(let o=0;o0;)t++;s.splice(t,0,n)}function bLe(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=$y&&t.push(r)}),s.cursorWrapper&&t.push(mf.create(s.state.doc,[s.cursorWrapper.deco])),SA.from(t)}const C4s={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},A4s=_b&&uE<=11;class T4s{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 E4s{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new T4s,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():tv&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),A4s&&(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,C4s)),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(Nit(this.view)){if(this.suppressingSelectionUpdates)return k3(this.view);if(_b&&uE<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&ID(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=S$(i))n.add(i);for(let i=t.anchorNode;i;i=S$(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)&&Nit(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(Pj&&c.length){let u=c.filter(h=>h.nodeName=="BR");if(u.length==2){let[h,m]=u;h.parentNode&&h.parentNode.parentNode==m.parentNode?m.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let m of u){let p=m.parentNode;p&&p.nodeName=="LI"&&(!h||P4s(t,h)!=p)&&m.remove()}}}let d=null;i<0&&a&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)-1||a)&&(i>-1&&(t.docView.markDirty(i,l),M4s(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,I4s(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||k3(t),this.currentSelection.set(r))}registerMutation(t,n){if(n.indexOf(t.target)>-1)return null;let r=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(r==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!r||r.ignoreMutation(t))return null;if(t.type=="childList"){for(let u=0;ua;g--){let b=r.childNodes[g-1],v=b.pmViewDesc;if(b.nodeName=="BR"&&!v){i=g;break}if(!v||v.size)break}let h=s.state.doc,m=s.someProp("domParser")||RK.fromSchema(s.state.schema),p=h.resolve(l),x=null,y=m.parse(r,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:a,to:i,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:D4s,context:p});if(d&&d[0].pos!=null){let g=d[0].pos,b=d[1]&&d[1].pos;b==null&&(b=g),x={anchor:g+l,head:b+l}}return{doc:y,sel:x,from:l,to:o}}function D4s(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(tv&&/^(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||tv&&/^(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 O4s=/^(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 F4s(s,t,n,r,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let P=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,L=IVe(s,P);if(L&&!s.state.selection.eq(L)){if(J0&&o3&&s.input.lastKeyCode===13&&Date.now()-100O(s,HI(13,"Enter"))))return;let I=s.state.tr.setSelection(L);P=="pointer"?I.setMeta("pointer",!0):P=="key"&&I.scrollIntoView(),i&&I.setMeta("composition",i),s.dispatch(I)}return}let l=s.state.doc.resolve(t),o=l.sharedDepth(n);t=l.before(o+1),n=s.state.doc.resolve(n).after(o+1);let c=s.state.selection,d=R4s(s,t,n),u=s.state.doc,h=u.slice(d.from,d.to),m,p;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||o3)&&a.some(P=>P.nodeType==1&&!O4s.test(P.nodeName))&&(!x||x.endA>=x.endB)&&s.someProp("handleKeyDown",P=>P(s,HI(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!x)if(r&&c instanceof Go&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))x={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let P=Dit(s,s.state.doc,d.sel);if(P&&!P.eq(s.state.selection)){let L=s.state.tr.setSelection(P);i&&L.setMeta("composition",i),s.dispatch(L)}}return}s.state.selection.froms.state.selection.from&&x.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?x.start=s.state.selection.from:x.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(x.endB+=s.state.selection.to-x.endA,x.endA=s.state.selection.to)),_b&&uE<=11&&x.endB==x.start+1&&x.endA==x.start&&x.start>d.from&&d.doc.textBetween(x.start-d.from-1,x.start-d.from+1)=="  "&&(x.start--,x.endA--,x.endB--);let y=d.doc.resolveNoCache(x.start-d.from),g=d.doc.resolveNoCache(x.endB-d.from),b=u.resolve(x.start),v=y.sameParent(g)&&y.parent.inlineContent&&b.end()>=x.endA;if((C$&&s.input.lastIOSEnter>Date.now()-225&&(!v||a.some(P=>P.nodeName=="DIV"||P.nodeName=="P"))||!v&&y.posP(s,HI(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>x.start&&B4s(u,x.start,x.endA,y,g)&&s.someProp("handleKeyDown",P=>P(s,HI(8,"Backspace")))){o3&&J0&&s.domObserver.suppressSelectionUpdates();return}J0&&x.endB==x.start&&(s.input.lastChromeDelete=Date.now()),o3&&!v&&y.start()!=g.start()&&g.parentOffset==0&&y.depth==g.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==x.endA&&(x.endB-=2,g=d.doc.resolveNoCache(x.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(P){return P(s,HI(13,"Enter"))})},20));let k=x.start,C=x.endA,T=P=>{let L=P||s.state.tr.replace(k,C,d.doc.slice(x.start-d.from,x.endB-d.from));if(d.sel){let I=Dit(s,L.doc,d.sel);I&&!(J0&&s.composing&&I.empty&&(x.start!=x.endB||s.input.lastChromeDeletek3(s),20));let P=T(s.state.tr.delete(k,C)),L=u.resolve(x.start).marksAcross(u.resolve(x.endA));L&&P.ensureMarks(L),s.dispatch(P)}else if(x.endA==x.endB&&(M=z4s(y.parent.content.cut(y.parentOffset,g.parentOffset),b.parent.content.cut(b.parentOffset,x.endA-b.start())))){let P=T(s.state.tr);M.type=="add"?P.addMark(k,C,M.mark):P.removeMark(k,C,M.mark),s.dispatch(P)}else if(y.parent.child(y.index()).isText&&y.index()==g.index()-(g.textOffset?0:1)){let P=y.parent.textBetween(y.parentOffset,g.parentOffset),L=()=>T(s.state.tr.insertText(P,k,C));s.someProp("handleTextInput",I=>I(s,k,C,P,L))||s.dispatch(L())}else s.dispatch(T());else s.dispatch(T())}function Dit(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:RVe(s,t.resolve(n.anchor),t.resolve(n.head))}function z4s(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||_Le(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 $4s(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 jTt{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 n4s,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(Uit),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=Bit(this),zit(this),this.nodeViews=$it(this),this.docView=yit(this.state.doc,Fit(this),bLe(this),this.dom,this),this.domObserver=new E4s(this,(r,a,i,l)=>F4s(this,r,a,i,l)),this.domObserver.start(),r4s(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&&QOe(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(Uit),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&&(xTt(this),l=!0),this.state=t;let o=a.plugins!=t.plugins||this._props.plugins!=n.plugins;if(o||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let p=$it(this);q4s(p,this.nodeViews)&&(this.nodeViews=p,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&QOe(this),this.editable=Bit(this),zit(this);let c=bLe(this),d=Fit(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&&ySs(this);if(l){this.domObserver.stop();let p=h&&(_b||J0)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&U4s(a.selection,t.selection);if(h){let x=J0?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=y4s(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=yit(t.doc,d,c,this.dom,this)),x&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&USs(this))?k3(this,p):(rTt(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&&vSs(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 Bo){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&hit(this,n.getBoundingClientRect(),t)}else hit(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 kSs(this,t)}coordsAtPos(t,n=1){return ZAt(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 ESs(this,n||this.state,t)}pasteHTML(t,n){return dZ(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return dZ(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return DVe(this,t)}destroy(){this.docView&&(a4s(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],bLe(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,lSs())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return o4s(this,t)}domSelectionRange(){let t=this.domSelection();return t?tv&&this.root.nodeType===11&&mSs(this.dom.ownerDocument)==this.dom&&L4s(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}jTt.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function Fit(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"),[Yv.node(0,s.state.doc.content.size,t)]}function zit(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:Yv.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function Bit(s){return!s.someProp("editable",t=>t(s.state)===!1)}function U4s(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 $it(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 q4s(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 Uit(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 IE={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:"'"},cke={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},V4s=typeof navigator<"u"&&/Mac/.test(navigator.platform),H4s=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var Y0=0;Y0<10;Y0++)IE[48+Y0]=IE[96+Y0]=String(Y0);for(var Y0=1;Y0<=24;Y0++)IE[Y0+111]="F"+Y0;for(var Y0=65;Y0<=90;Y0++)IE[Y0]=String.fromCharCode(Y0+32),cke[Y0]=String.fromCharCode(Y0);for(var wLe in IE)cke.hasOwnProperty(wLe)||(cke[wLe]=IE[wLe]);function G4s(s){var t=V4s&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||H4s&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?cke:IE)[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 W4s=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),K4s=typeof navigator<"u"&&/Win/.test(navigator.platform);function Y4s(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 NTt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const J4s=(s,t,n)=>{let r=NTt(s,n);if(!r)return!1;let a=qVe(r);if(!a){let l=r.blockRange(),o=l&&nq(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(ATt(s,a,t,-1))return!0;if(r.parent.content.size==0&&(A$(i,"end")||Bo.isSelectable(i)))for(let l=r.depth;;l--){let o=Y3e(s.doc,r.before(l),r.after(l),di.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},e3s=(s,t,n)=>{let r=NTt(s,n);if(!r)return!1;let a=qVe(r);return a?kTt(s,a,t):!1},t3s=(s,t,n)=>{let r=STt(s,n);if(!r)return!1;let a=VVe(r);return a?kTt(s,a,t):!1};function kTt(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=Y3e(s.doc,i,c,di.empty);if(!d||d.from!=i||d instanceof yx&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(Go.create(u.doc,i)),n(u.scrollIntoView())}return!0}function A$(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 s3s=(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=qVe(r)}let l=i&&i.nodeBefore;return!l||!Bo.isSelectable(l)?!1:(t&&t(s.tr.setSelection(Bo.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function qVe(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 STt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=STt(s,n);if(!r)return!1;let a=VVe(r);if(!a)return!1;let i=a.nodeAfter;if(ATt(s,a,t,1))return!0;if(r.parent.content.size==0&&(A$(i,"start")||Bo.isSelectable(i))){let l=Y3e(s.doc,r.before(),r.after(),di.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 Bo,a;if(r){if(n.node.isTextblock||!a6(s.doc,n.from))return!1;a=n.from}else if(a=K3e(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection(Bo.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},i3s=(s,t)=>{let n=s.selection,r;if(n instanceof Bo){if(n.node.isTextblock||!a6(s.doc,n.to))return!1;r=n.to}else if(r=K3e(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},o3s=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&nq(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},l3s=(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 CTt(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=CTt(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(il.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},d3s=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof Lj||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=CTt(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(kz(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&nq(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)},h3s=(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(Bo.create(s.doc,a))),!0)};function m3s(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||a6(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function ATt(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&m3s(s,t,n))return!0;let d=!c&&t.parent.canReplace(t.index(),t.index()+1);if(d&&(l=(o=a.contentMatchAt(a.childCount)).findWrapping(i.type))&&o.matchType(l[0]||i.type).validEnd){if(n){let p=t.pos+i.nodeSize,x=Aa.empty;for(let b=l.length-1;b>=0;b--)x=Aa.from(l[b].create(null,x));x=Aa.from(a.copy(x));let y=s.tr.step(new c0(t.pos-1,p,t.pos,p,new di(x,1,0),l.length,!0)),g=y.doc.resolve(p+2*l.length);g.nodeAfter&&g.nodeAfter.type==a.type&&a6(y.doc,g.pos)&&y.join(g.pos),n(y.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:il.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),m=h&&nq(h);if(m!=null&&m>=t.depth)return n&&n(s.tr.lift(h,m).scrollIntoView()),!0;if(d&&A$(i,"start",!0)&&A$(a,"end")){let p=a,x=[];for(;x.push(p),!p.isTextblock;)p=p.lastChild;let y=i,g=1;for(;!y.isTextblock;y=y.firstChild)g++;if(p.canReplace(p.childCount,p.childCount,y.content)){if(n){let b=Aa.empty;for(let k=x.length-1;k>=0;k--)b=Aa.from(x[k].copy(b));let v=s.tr.step(new c0(t.pos-x.length,t.pos+i.nodeSize,t.pos+g,t.pos+i.nodeSize-g,new di(b,x.length,0),0,!0));n(v.scrollIntoView())}return!0}}return!1}function TTt(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(Go.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const p3s=TTt(-1),f3s=TTt(1);function x3s(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&EVe(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function qit(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 ske(c,c,t.depth),t.endIndex=0;u--)i=Aa.from(n[u].type.create(n[u].attrs,i));s.step(new c0(t.start-(r?2:0),t.end,t.start,t.end,new di(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?_3s(t,n,s,i):w3s(t,n,i):!0:!1}}function _3s(s,t,n,r){let a=s.tr,i=r.end,l=r.$to.end(r.depth);iy;x--)p-=a.child(x).nodeSize,r.delete(p-1,p+1);let i=r.doc.resolve(n.start),l=i.nodeAfter;if(r.mapping.map(n.end)!=n.start+i.nodeAfter.nodeSize)return!1;let o=n.startIndex==0,c=n.endIndex==a.childCount,d=i.node(-1),u=i.index(-1);if(!d.canReplace(u+(o?0:1),u+1,l.content.append(c?Aa.empty:Aa.from(a))))return!1;let h=i.pos,m=h+l.nodeSize;return r.step(new c0(h-(o?1:0),m+(c?1:0),h+1,m-1,new di((o?Aa.empty:Aa.from(a.copy(Aa.empty))).append(c?Aa.empty:Aa.from(a.copy(Aa.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function j3s(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=Aa.from(d?s.create():null),h=new di(Aa.from(s.create(null,Aa.from(o.type.create(null,u)))),d?3:1,0),m=i.start,p=i.end;n(t.tr.step(new c0(m-(d?3:1),p,m,p,h,1,!0)).scrollIntoView())}return!0}}function eCe(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 tCe=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:n,state:r}=this,{view:a}=n,{tr:i}=r,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...u)=>{const h=c(...u)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,u=()=>(!c&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(m=>m===!0)),h={...Object.fromEntries(Object.entries(r).map(([m,p])=>[m,(...y)=>{const g=this.buildProps(d,n),b=p(...y)(g);return o.push(b),h}])),run:u};return h}createCan(t){const{rawCommands:n,state:r}=this,a=!1,i=t||r.tr,l=this.buildProps(i,a);return{...Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...u)=>d(...u)({...l,dispatch:void 0})])),chain:()=>this.createChain(i,a)}}buildProps(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o={tr:t,editor:a,view:l,state:eCe({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}},N3s=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 so(s,t,n){return s.config[t]===void 0&&s.parent?so(s.parent,t,n):typeof s.config[t]=="function"?s.config[t].bind({...n,parent:s.parent?so(s.parent,t,n):null}):s.config[t]}function sCe(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 ETt(s){const t=[],{nodeExtensions:n,markExtensions:r}=sCe(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=so(l,"addGlobalAttributes",o);if(!c)return;c().forEach(u=>{u.types.forEach(h=>{Object.entries(u.attributes).forEach(([m,p])=>{t.push({type:h,name:m,attribute:{...i,...p}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=so(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 u0(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 Ym(...s){return s.filter(t=>!!t).reduce((t,n)=>{const r={...t};return Object.entries(n).forEach(([a,i])=>{if(!r[a]){r[a]=i;return}if(a==="class"){const o=i?String(i).split(" "):[],c=r[a]?r[a].split(" "):[],d=o.filter(u=>!c.includes(u));r[a]=[...c,...d].join(" ")}else if(a==="style"){const o=i?i.split(";").map(u=>u.trim()).filter(Boolean):[],c=r[a]?r[a].split(";").map(u=>u.trim()).filter(Boolean):[],d=new Map;c.forEach(u=>{const[h,m]=u.split(":").map(p=>p.trim());d.set(h,m)}),o.forEach(u=>{const[h,m]=u.split(":").map(p=>p.trim());d.set(h,m)}),r[a]=Array.from(d.entries()).map(([u,h])=>`${u}: ${h}`).join("; ")}else r[a]=i}),r},{})}function JOe(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)=>Ym(n,r),{})}function MTt(s){return typeof s=="function"}function gc(s,t=void 0,...n){return MTt(s)?t?s.bind(t)(...n):s(...n):s}function k3s(s={}){return Object.keys(s).length===0&&s.constructor===Object}function S3s(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function Vit(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):S3s(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function Hit(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&k3s(n)?!1:n!=null))}function C3s(s,t){var n;const r=ETt(s),{nodeExtensions:a,markExtensions:i}=sCe(s),l=(n=a.find(d=>so(d,"topNode")))===null||n===void 0?void 0:n.name,o=Object.fromEntries(a.map(d=>{const u=r.filter(b=>b.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((b,v)=>{const k=so(v,"extendNodeSchema",h);return{...b,...k?k(d):{}}},{}),p=Hit({...m,content:gc(so(d,"content",h)),marks:gc(so(d,"marks",h)),group:gc(so(d,"group",h)),inline:gc(so(d,"inline",h)),atom:gc(so(d,"atom",h)),selectable:gc(so(d,"selectable",h)),draggable:gc(so(d,"draggable",h)),code:gc(so(d,"code",h)),whitespace:gc(so(d,"whitespace",h)),linebreakReplacement:gc(so(d,"linebreakReplacement",h)),defining:gc(so(d,"defining",h)),isolating:gc(so(d,"isolating",h)),attrs:Object.fromEntries(u.map(b=>{var v;return[b.name,{default:(v=b==null?void 0:b.attribute)===null||v===void 0?void 0:v.default}]}))}),x=gc(so(d,"parseHTML",h));x&&(p.parseDOM=x.map(b=>Vit(b,u)));const y=so(d,"renderHTML",h);y&&(p.toDOM=b=>y({node:b,HTMLAttributes:JOe(b,u)}));const g=so(d,"renderText",h);return g&&(p.toText=g),[d.name,p]})),c=Object.fromEntries(i.map(d=>{const u=r.filter(g=>g.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((g,b)=>{const v=so(b,"extendMarkSchema",h);return{...g,...v?v(d):{}}},{}),p=Hit({...m,inclusive:gc(so(d,"inclusive",h)),excludes:gc(so(d,"excludes",h)),group:gc(so(d,"group",h)),spanning:gc(so(d,"spanning",h)),code:gc(so(d,"code",h)),attrs:Object.fromEntries(u.map(g=>{var b;return[g.name,{default:(b=g==null?void 0:g.attribute)===null||b===void 0?void 0:b.default}]}))}),x=gc(so(d,"parseHTML",h));x&&(p.parseDOM=x.map(g=>Vit(g,u)));const y=so(d,"renderHTML",h);return y&&(p.toDOM=g=>y({mark:g,HTMLAttributes:JOe(g,u)})),[d.name,p]}));return new NAt({topNode:l,nodes:o,marks:c})}function NLe(s,t){return t.nodes[s]||t.marks[s]||null}function Git(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function HVe(s,t){const n=yO.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const A3s=(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 GVe(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class nCe{constructor(t){this.find=t.find,this.handler=t.handler}}const T3s=(s,t)=>{if(GVe(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 zse(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=A3s(d)+i;return l.forEach(m=>{if(u)return;const p=T3s(h,m.find);if(!p)return;const x=c.state.tr,y=eCe({state:c.state,transaction:x}),g={from:r-(p[0].length-i.length),to:a},{commands:b,chain:v,can:k}=new tCe({editor:n,state:y});m.handler({state:y,range:g,match:p,commands:b,chain:v,can:k})===null||!x.steps.length||(x.setMeta(o,{transform:x,from:r,to:a,text:i}),c.dispatch(x),u=!0)}),u}function E3s(s){const{editor:t,rules:n}=s,r=new yg({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=HVe(Aa.from(u),l.schema);const{from:h}=c,m=h+u.length;zse({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 zse({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&zse({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?zse({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function M3s(s){return Object.prototype.toString.call(s).slice(8,-1)}function Bse(s){return M3s(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function rCe(s,t){const n={...s};return Bse(s)&&Bse(t)&&Object.keys(t).forEach(r=>{Bse(t[r])&&Bse(s[r])?n[r]=rCe(s[r],t[r]):n[r]=t[r]}),n}class AN{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=gc(so(this,"addOptions",{name:this.name}))),this.storage=gc(so(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new AN(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>rCe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new AN(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=gc(so(n,"addOptions",{name:n.name})),n.storage=gc(so(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 L3s(s){return typeof s=="number"}class P3s{constructor(t){this.find=t.find,this.handler=t.handler}}const I3s=(s,t,n)=>{if(GVe(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 R3s(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new tCe({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(p,x)=>{if(!p.isTextblock||p.type.spec.code)return;const y=Math.max(r,x),g=Math.min(a,x+p.content.size),b=p.textBetween(y-x,g-x,void 0,"");I3s(b,i.find,l).forEach(k=>{if(k.index===void 0)return;const C=y+k.index+1,T=C+k[0].length,M={from:n.tr.mapping.map(C),to:n.tr.mapping.map(T)},P=i.handler({state:n,range:M,match:k,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(P)})}),h.every(p=>p!==null)}let $se=null;const D3s=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 O3s(s){const{editor:t,rules:n}=s;let r=null,a=!1,i=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:u,from:h,to:m,rule:p,pasteEvt:x})=>{const y=u.tr,g=eCe({state:u,transaction:y});if(!(!R3s({editor:t,state:g,from:Math.max(h-1,0),to:m.b-1,rule:p,pasteEvent:x,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 yg({view(h){const m=x=>{var y;r=!((y=h.dom.parentElement)===null||y===void 0)&&y.contains(x.target)?h.dom.parentElement:null,r&&($se=t)},p=()=>{$se&&($se=null)};return window.addEventListener("dragstart",m),window.addEventListener("dragend",p),{destroy(){window.removeEventListener("dragstart",m),window.removeEventListener("dragend",p)}}},props:{handleDOMEvents:{drop:(h,m)=>{if(i=r===h.dom.parentElement,o=m,!i){const p=$se;p!=null&&p.isEditable&&setTimeout(()=>{const x=p.state.selection;x&&p.commands.deleteRange({from:x.from,to:x.to})},10)}return!1},paste:(h,m)=>{var p;const x=(p=m.clipboardData)===null||p===void 0?void 0:p.getData("text/html");return l=m,a=!!(x!=null&&x.includes("data-pm-slice")),!1}}},appendTransaction:(h,m,p)=>{const x=h[0],y=x.getMeta("uiEvent")==="paste"&&!a,g=x.getMeta("uiEvent")==="drop"&&!i,b=x.getMeta("applyPasteRules"),v=!!b;if(!y&&!g&&!v)return;if(v){let{text:T}=b;typeof T=="string"?T=T:T=HVe(Aa.from(T),p.schema);const{from:M}=b,P=M+T.length,L=D3s(T);return c({rule:u,state:p,from:M,to:{b:P},pasteEvt:L})}const k=m.doc.content.findDiffStart(p.doc.content),C=m.doc.content.findDiffEnd(p.doc.content);if(!(!L3s(k)||!C||k===C.b))return c({rule:u,state:p,from:k,to:C,pasteEvt:l})}}))}function F3s(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class h9{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=h9.resolve(t),this.schema=C3s(this.extensions,n),this.setupExtensions()}static resolve(t){const n=h9.sort(h9.flatten(t)),r=F3s(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=so(n,"addExtensions",r);return a?[n,...this.flatten(a())]:n}).flat(10)}static sort(t){return t.sort((r,a)=>{const i=so(r,"priority")||100,l=so(a,"priority")||100;return i>l?-1:i{const r={name:n.name,options:n.options,storage:n.storage,editor:this.editor,type:NLe(n.name,this.schema)},a=so(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=h9.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:NLe(l.name,this.schema)},c=[],d=so(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&so(l,"exitable",o)&&(u.ArrowRight=()=>AN.handleExit({editor:t,mark:l})),d){const y=Object.fromEntries(Object.entries(d()).map(([g,b])=>[g,()=>b({editor:t})]));u={...u,...y}}const h=X4s(u);c.push(h);const m=so(l,"addInputRules",o);Git(l,t.options.enableInputRules)&&m&&r.push(...m());const p=so(l,"addPasteRules",o);Git(l,t.options.enablePasteRules)&&p&&a.push(...p());const x=so(l,"addProseMirrorPlugins",o);if(x){const y=x();c.push(...y)}return c}).flat();return[E3s({editor:t,rules:r}),...O3s({editor:t,rules:a}),...i]}get attributes(){return ETt(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=sCe(this.extensions);return Object.fromEntries(n.filter(r=>!!so(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:u0(r.name,this.schema)},l=so(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,m)=>{const p=JOe(c,a);return l()({node:c,view:d,getPos:u,decorations:h,innerDecorations:m,editor:t,extension:r,HTMLAttributes:p})};return[r.name,o]}))}setupExtensions(){this.extensions.forEach(t=>{var n;this.editor.extensionStorage[t.name]=t.storage;const r={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:NLe(t.name,this.schema)};t.type==="mark"&&(!((n=gc(so(t,"keepOnSplit",r)))!==null&&n!==void 0)||n)&&this.splittableMarks.push(t.name);const a=so(t,"onBeforeCreate",r),i=so(t,"onCreate",r),l=so(t,"onUpdate",r),o=so(t,"onSelectionUpdate",r),c=so(t,"onTransaction",r),d=so(t,"onFocus",r),u=so(t,"onBlur",r),h=so(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 my{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=gc(so(this,"addOptions",{name:this.name}))),this.storage=gc(so(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new my(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>rCe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new my({...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=gc(so(n,"addOptions",{name:n.name})),n.storage=gc(so(n,"addStorage",{name:n.name,options:n.options})),n}}function LTt(s,t,n){const{from:r,to:a}=t,{blockSeparator:i=` `,textSerializers:l={}}=n||{};let o="";return s.nodesBetween(r,a,(c,d,u,h)=>{var m;c.isBlock&&d>r&&(o+=i);const p=l==null?void 0:l[c.type.name];if(p)return u&&(o+=p({node:c,pos:d,parent:u,index:h,range:t})),!1;c.isText&&(o+=(m=c==null?void 0:c.text)===null||m===void 0?void 0:m.slice(Math.max(r,d)-d,a-d))}),o}function PTt(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const z3s=my.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new yg({key:new ov("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=PTt(n);return LTt(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),B3s=()=>({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),$3s=(s=!1)=>({commands:t})=>t.setContent("",s),U3s=()=>({state:s,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:a}=r;return n&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:u}=t,h=d.resolve(u.map(c)),m=d.resolve(u.map(c+o.nodeSize)),p=h.blockRange(m);if(!p)return;const x=nq(p);if(o.type.isTextblock){const{defaultType:y}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(p.start,y)}(x||x===0)&&t.lift(p,x)})}),!0},q3s=s=>t=>s(t),V3s=()=>({state:s,dispatch:t})=>d3s(s,t),H3s=(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 Go(r.doc.resolve(Math.max(l-1,0)))),!0},G3s=()=>({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},W3s=s=>({tr:t,state:n,dispatch:r})=>{const a=u0(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},K3s=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},Y3s=()=>({state:s,dispatch:t})=>Q4s(s,t),Z3s=()=>({commands:s})=>s.keyboardShortcut("Enter"),X3s=()=>({state:s,dispatch:t})=>c3s(s,t);function dke(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:GVe(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function ITt(s,t,n={}){return s.find(r=>r.type===t&&dke(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function Wit(s,t,n={}){return!!ITt(s,t,n)}function WVe(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),!ITt([...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&&Wit([...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=o6(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=WVe(c,i,t);if(h&&h.from<=d&&h.to>=u){const m=Go.create(l,h.from,h.to);n.setSelection(m)}}return!0},J3s=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=()=>{(uke()||Kit())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),eCs()&&!uke()&&!Kit()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!RTt(n.state.selection))return l(),!0;const o=DTt(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},sCs=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),nCs=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),OTt=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&&OTt(r)}return s};function Use(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return OTt(n)}function hZ(s,t,n){if(s instanceof dE||s instanceof Aa)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 Aa.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),hZ("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new NAt({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?RK.fromSchema(c).parseSlice(Use(s),n.parseOptions):RK.fromSchema(c).parse(Use(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=RK.fromSchema(t);return n.slice?i.parseSlice(Use(s),n.parseOptions).content:i.parse(Use(s),n.parseOptions)}return hZ("",t,n)}function rCs(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(il.near(s.doc.resolve(l),n))}const aCs=s=>!("type"in s),iCs=(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=g=>{i.emit("contentError",{editor:i,error:g,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{hZ(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(g){c(g)}try{o=hZ(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=n.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(g){return c(g),!1}let{from:u,to:h}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},m=!0,p=!0;if((aCs(o)?o:[o]).forEach(g=>{g.check(),m=m?g.isText&&g.marks.length===0:!1,p=p?g.isBlock:!1}),u===h&&p){const{parent:g}=r.doc.resolve(u);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(u-=1,h+=1)}let y;if(m){if(Array.isArray(t))y=t.map(g=>g.text||"").join("");else if(t instanceof Aa){let g="";t.forEach(b=>{b.text&&(g+=b.text)}),y=g}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&&rCs(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},oCs=()=>({state:s,dispatch:t})=>a3s(s,t),lCs=()=>({state:s,dispatch:t})=>i3s(s,t),cCs=()=>({state:s,dispatch:t})=>J4s(s,t),dCs=()=>({state:s,dispatch:t})=>n3s(s,t),uCs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=K3e(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},hCs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=K3e(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},mCs=()=>({state:s,dispatch:t})=>e3s(s,t),pCs=()=>({state:s,dispatch:t})=>t3s(s,t);function FTt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function fCs(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=fCs(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 mZ(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?u0(t,s.schema):null,o=[];s.doc.nodesBetween(r,a,(h,m)=>{if(h.isText)return;const p=Math.max(r,m),x=Math.min(a,m+h.nodeSize);o.push({node:h,from:p,to:x})});const c=a-r,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>dke(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,m)=>h+m.to-m.from,0)>=c}const gCs=(s,t={})=>({state:n,dispatch:r})=>{const a=u0(s,n.schema);return mZ(n,a,t)?o3s(n,r):!1},yCs=()=>({state:s,dispatch:t})=>u3s(s,t),vCs=s=>({state:t,dispatch:n})=>{const r=u0(s,t.schema);return b3s(r)(t,n)},bCs=()=>({state:s,dispatch:t})=>l3s(s,t);function aCe(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function Yit(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 _Cs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=aCe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=u0(s,r.schema)),o==="mark"&&(l=o6(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,Yit(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(Yit(h.attrs,t)))})})}),!0):!1},wCs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),jCs=()=>({tr:s,dispatch:t})=>{if(t){const n=new Lj(s.doc);s.setSelection(n)}return!0},NCs=()=>({state:s,dispatch:t})=>s3s(s,t),kCs=()=>({state:s,dispatch:t})=>r3s(s,t),SCs=()=>({state:s,dispatch:t})=>h3s(s,t),CCs=()=>({state:s,dispatch:t})=>f3s(s,t),ACs=()=>({state:s,dispatch:t})=>p3s(s,t);function eFe(s,t,n={},r={}){return hZ(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const TCs=(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=eFe(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 zTt(s,t){const n=o6(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 ECs(s,t){const n=new MVe(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function MCs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function BTt(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 KVe(s){return t=>BTt(t.$from,s)}function PCs(s,t){const n={from:0,to:s.content.size};return LTt(s,n,t)}function ICs(s,t){const n=u0(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 $Tt(s,t){const n=aCe(typeof t=="string"?t:t.name,s.schema);return n==="node"?ICs(s,t):n==="mark"?zTt(s,t):{}}function RCs(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 DCs(s){const t=RCs(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 OCs(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}})})}),DCs(r)}function YVe(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=WVe(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 Tje(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 tFe(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?o6(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>dke(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:m})=>{const p=h.pos,x=m.pos;s.doc.nodesBetween(p,x,(y,g)=>{if(!y.isText&&!y.marks.length)return;const b=Math.max(p,g),v=Math.min(x,g+y.nodeSize),k=v-b;l+=k,o.push(...y.marks.map(C=>({mark:C,from:b,to:v})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>dke(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 FCs(s,t,n={}){if(!t)return mZ(s,null,n)||tFe(s,null,n);const r=aCe(t,s.schema);return r==="node"?mZ(s,t,n):r==="mark"?tFe(s,t,n):!1}function Zit(s,t){const{nodeExtensions:n}=sCe(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=gc(so(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function ZVe(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&&(ZVe(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function zCs(s){return s instanceof Bo}function BCs(s,t,n){var r;const{selection:a}=t;let i=null;if(RTt(a)&&(i=a.$cursor),i){const o=(r=s.storedMarks)!==null&&r!==void 0?r:i.marks();return!!n.isInSet(o)||!o.some(c=>c.type.excludes(n))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(n):!1;return s.doc.nodesBetween(o.pos,c.pos,(u,h,m)=>{if(d)return!1;if(u.isInline){const p=!m||m.type.allowsMarkType(n),x=!!n.isInSet(u.marks)||!u.marks.some(y=>y.type.excludes(n));d=p&&x}return!d}),d})}const $Cs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=o6(s,r.schema);if(a)if(l){const d=zTt(r,c);n.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const u=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(u,h,(m,p)=>{const x=Math.max(p,u),y=Math.min(p+m.nodeSize,h);m.marks.find(b=>b.type===c)?m.marks.forEach(b=>{c===b.type&&n.addMark(x,y,c.create({...b.attrs,...t}))}):n.addMark(x,y,c.create(t))})});return BCs(r,n,c)},UCs=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),qCs=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=u0(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})=>qit(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>qit(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},VCs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=i8(s,0,r.content.size),i=Bo.create(r,a);t.setSelection(i)}return!0},HCs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=Go.atStart(r).from,o=Go.atEnd(r).to,c=i8(a,l,o),d=i8(i,l,o),u=Go.create(r,c,d);t.setSelection(u)}return!0},GCs=s=>({state:t,dispatch:n})=>{const r=u0(s,t.schema);return j3s(r)(t,n)};function Xit(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 WCs=({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=Tje(d,o.node().type.name,o.node().attrs);if(i instanceof Bo&&i.node.isBlock)return!o.parentOffset||!kz(l,o.pos)?!1:(r&&(s&&Xit(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:MCs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let p=h&&m?[{type:m,attrs:u}]:void 0,x=kz(t.doc,t.mapping.map(o.pos),1,p);if(!p&&!x&&kz(t.doc,t.mapping.map(o.pos),1,m?[{type:m}]:void 0)&&(x=!0,p=m?[{type:m,attrs:u}]:void 0),r){if(x&&(i instanceof Go&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,p),m&&!h&&!o.parentOffset&&o.parent.type!==m)){const y=t.mapping.map(o.before()),g=t.doc.resolve(y);o.node(-1).canReplaceWith(g.index(),g.index()+1,m)&&t.setNodeMarkup(t.mapping.map(o.before()),m)}s&&Xit(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return x},KCs=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=u0(s,r.schema),{$from:c,$to:d}=r.selection,u=r.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const h=c.node(-1);if(h.type!==o)return!1;const m=i.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==o||c.index(-2)!==c.node(-2).childCount-1)return!1;if(a){let b=Aa.empty;const v=c.index(-1)?1:c.index(-2)?2:3;for(let L=c.depth-v;L>=c.depth-3;L-=1)b=Aa.from(c.node(L).copy(b));const k=c.indexAfter(-1){if(P>-1)return!1;L.isTextblock&&L.content.size===0&&(P=I+1)}),P>-1&&n.setSelection(Go.near(n.doc.resolve(P))),n.scrollIntoView()}return!0}const p=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,x={...Tje(m,h.type.name,h.attrs),...t},y={...Tje(m,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const g=p?[{type:o,attrs:x},{type:p,attrs:y}]:[{type:o,attrs:x}];if(!kz(n.doc,c.pos,2))return!1;if(a){const{selection:b,storedMarks:v}=r,{splittableMarks:k}=i.extensionManager,C=v||b.$to.parentOffset&&b.$from.marks();if(n.split(c.pos,2,g).scrollIntoView(),!C||!a)return!0;const T=C.filter(M=>k.includes(M.type.name));n.ensureMarks(T)}return!0},kLe=(s,t)=>{const n=KVe(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)&&a6(s.doc,n.pos)&&s.join(n.pos),!0},SLe=(s,t)=>{const n=KVe(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)&&a6(s.doc,r)&&s.join(r),!0},YCs=(s,t,n,r={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:u})=>{const{extensions:h,splittableMarks:m}=a.extensionManager,p=u0(s,l.schema),x=u0(t,l.schema),{selection:y,storedMarks:g}=l,{$from:b,$to:v}=y,k=b.blockRange(v),C=g||y.$to.parentOffset&&y.$from.marks();if(!k)return!1;const T=KVe(M=>Zit(M.type.name,h))(y);if(k.depth>=1&&T&&k.depth-T.depth<=1){if(T.node.type===p)return d.liftListItem(x);if(Zit(T.node.type.name,h)&&p.validContent(T.node.content)&&o)return c().command(()=>(i.setNodeMarkup(T.pos,p),!0)).command(()=>kLe(i,p)).command(()=>SLe(i,p)).run()}return!n||!C||!o?c().command(()=>u().wrapInList(p,r)?!0:d.clearNodes()).wrapInList(p,r).command(()=>kLe(i,p)).command(()=>SLe(i,p)).run():c().command(()=>{const M=u().wrapInList(p,r),P=C.filter(L=>m.includes(L.type.name));return i.ensureMarks(P),M?!0:d.clearNodes()}).wrapInList(p,r).command(()=>kLe(i,p)).command(()=>SLe(i,p)).run()},ZCs=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=o6(s,r.schema);return tFe(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},XCs=(s,t,n={})=>({state:r,commands:a})=>{const i=u0(s,r.schema),l=u0(t,r.schema),o=mZ(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})},QCs=(s,t={})=>({state:n,commands:r})=>{const a=u0(s,n.schema);return mZ(n,a,t)?r.lift(a):r.wrapIn(a,t)},JCs=()=>({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},eAs=()=>({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},tAs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=o6(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:m,to:p}=o;const x=(i=d.marks().find(g=>g.type===c))===null||i===void 0?void 0:i.attrs,y=WVe(d,c,x);y&&(m=y.from,p=y.to),n.removeMark(m,p,c)}else h.forEach(m=>{n.removeMark(m.$from.pos,m.$to.pos,c)});return n.removeStoredMark(c),!0},sAs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=aCe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=u0(s,r.schema)),o==="mark"&&(l=o6(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,m,p,x;n.selection.empty?r.doc.nodesBetween(d,u,(y,g)=>{i&&i===y.type&&(p=Math.max(g,d),x=Math.min(g+y.nodeSize,u),h=g,m=y)}):r.doc.nodesBetween(d,u,(y,g)=>{g=d&&g<=u&&(i&&i===y.type&&n.setNodeMarkup(g,void 0,{...y.attrs,...t}),l&&y.marks.length&&y.marks.forEach(b=>{if(l===b.type){const v=Math.max(g,d),k=Math.min(g+y.nodeSize,u);n.addMark(v,k,l.create({...b.attrs,...t}))}}))}),m&&(h!==void 0&&n.setNodeMarkup(h,void 0,{...m.attrs,...t}),l&&m.marks.length&&m.marks.forEach(y=>{l===y.type&&n.addMark(p,x,l.create({...y.attrs,...t}))}))}),!0):!1},nAs=(s,t={})=>({state:n,dispatch:r})=>{const a=u0(s,n.schema);return x3s(a,t)(n,r)},rAs=(s,t={})=>({state:n,dispatch:r})=>{const a=u0(s,n.schema);return g3s(a,t)(n,r)};var aAs=Object.freeze({__proto__:null,blur:B3s,clearContent:$3s,clearNodes:U3s,command:q3s,createParagraphNear:V3s,cut:H3s,deleteCurrentNode:G3s,deleteNode:W3s,deleteRange:K3s,deleteSelection:Y3s,enter:Z3s,exitCode:X3s,extendMarkRange:Q3s,first:J3s,focus:tCs,forEach:sCs,insertContent:nCs,insertContentAt:iCs,joinBackward:cCs,joinDown:lCs,joinForward:dCs,joinItemBackward:uCs,joinItemForward:hCs,joinTextblockBackward:mCs,joinTextblockForward:pCs,joinUp:oCs,keyboardShortcut:xCs,lift:gCs,liftEmptyBlock:yCs,liftListItem:vCs,newlineInCode:bCs,resetAttributes:_Cs,scrollIntoView:wCs,selectAll:jCs,selectNodeBackward:NCs,selectNodeForward:kCs,selectParentNode:SCs,selectTextblockEnd:CCs,selectTextblockStart:ACs,setContent:TCs,setMark:$Cs,setMeta:UCs,setNode:qCs,setNodeSelection:VCs,setTextSelection:HCs,sinkListItem:GCs,splitBlock:WCs,splitListItem:KCs,toggleList:YCs,toggleMark:ZCs,toggleNode:XCs,toggleWrap:QCs,undoInputRule:JCs,unsetAllMarks:eAs,unsetMark:tAs,updateAttributes:sAs,wrapIn:nAs,wrapInList:rAs});const iAs=my.create({name:"commands",addCommands(){return{...aAs}}}),oAs=my.create({name:"drop",addProseMirrorPlugins(){return[new yg({key:new ov("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),lAs=my.create({name:"editable",addProseMirrorPlugins(){return[new yg({key:new ov("editable"),props:{editable:()=>this.editor.options.editable}})]}}),cAs=new ov("focusEvents"),dAs=my.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new yg({key:cAs,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}}}})]}}),uAs=my.create({name:"keymap",addKeyboardShortcuts(){const s=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:o})=>{const{selection:c,doc:d}=o,{empty:u,$anchor:h}=c,{pos:m,parent:p}=h,x=h.parent.isTextblock&&m>0?o.doc.resolve(m-1):h,y=x.parent.type.spec.isolating,g=h.pos-h.parentOffset,b=y&&x.parent.childCount===1?g===h.pos:il.atStart(d).from===m;return!u||!p.type.isTextblock||p.textContent.length||!b||b&&h.parent.type.name==="paragraph"?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:s,"Mod-Backspace":s,"Shift-Backspace":s,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},a={...r},i={...r,"Ctrl-h":s,"Alt-Backspace":s,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return uke()||FTt()?i:a},addProseMirrorPlugins(){return[new yg({key:new ov("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=il.atStart(t.doc).from,d=il.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!ZVe(n.doc))return;const m=n.tr,p=eCe({state:n,transaction:m}),{commands:x}=new tCe({editor:this.editor,state:p});if(x.clearNodes(),!!m.steps.length)return m}})]}}),hAs=my.create({name:"paste",addProseMirrorPlugins(){return[new yg({key:new ov("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),mAs=my.create({name:"tabindex",addProseMirrorPlugins(){return[new yg({key:new ov("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class GI{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 GI(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 GI(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 GI(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 GI(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new GI(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 pAs=`.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 fAs(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 xAs extends N3s{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=fAs(pAs,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=MTt(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?[lAs,z3s.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),iAs,dAs,uAs,mAs,oAs,hAs].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 h9(a,this)}createCommandManager(){this.commandManager=new tCe({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=eFe(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=eFe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=DTt(n,this.options.autofocus);this.view=new jTt(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:u9.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 $Tt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return FCs(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return HVe(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return PCs(this.state.doc,{blockSeparator:n,textSerializers:{...PTt(this.schema),...r}})}get isEmpty(){return ZVe(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 GI(n,this)}get $doc(){return this.$pos(0)}}function T$(s){return new nCe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=gc(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(YVe(n.from,n.to,t.doc).filter(p=>p.mark.type.excluded.find(y=>y===s.type&&y!==p.mark.type)).filter(p=>p.to>d).length)return null;un.from&&i.delete(n.from+c,d);const m=n.from+c+l.length;i.addMark(n.from+c,m,s.type.create(a||{})),i.removeStoredMark(s.type)}}})}function UTt(s){return new nCe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=gc(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 sFe(s){return new nCe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=gc(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 pZ(s){return new nCe({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=gc(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&EVe(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:h,storedMarks:m}=t,{splittableMarks:p}=s.editor.extensionManager,x=m||h.$to.parentOffset&&h.$from.marks();if(x){const y=x.filter(g=>p.includes(g.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&&a6(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let lv=class nFe{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=gc(so(this,"addOptions",{name:this.name}))),this.storage=gc(so(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new nFe(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>rCe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new nFe(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=gc(so(n,"addOptions",{name:n.name})),n.storage=gc(so(n,"addStorage",{name:n.name,options:n.options})),n}};function DD(s){return new P3s({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=gc(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(YVe(n.from,n.to,t.doc).filter(x=>x.mark.type.excluded.find(g=>g===s.type&&g!==x.mark.type)).filter(x=>x.to>h).length)return null;mn.from&&l.delete(n.from+u,h),d=n.from+u+o.length,l.addMark(n.from+u,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function gAs(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof Bo){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 yAs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var qTt={exports:{}},CLe={};/** * @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 Qit;function vAs(){if(Qit)return CLe;Qit=1;var s=Lt;function t(h,m){return h===m&&(h!==0||1/h===1/m)||h!==h&&m!==m}var n=typeof Object.is=="function"?Object.is:t,r=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(h,m){var p=m(),x=r({inst:{value:p,getSnapshot:m}}),y=x[0].inst,g=x[1];return i(function(){y.value=p,y.getSnapshot=m,c(y)&&g({inst:y})},[h,p,m]),a(function(){return c(y)&&g({inst:y}),h(function(){c(y)&&g({inst:y})})},[h]),l(p),p}function c(h){var m=h.getSnapshot;h=h.value;try{var p=m();return!n(h,p)}catch{return!0}}function d(h,m){return m()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return CLe.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,CLe}qTt.exports=vAs();var XVe=qTt.exports;const bAs=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},_As=({contentComponent:s})=>{const t=XVe.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Lt.createElement(Lt.Fragment,null,Object.values(t))};function wAs(){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]:cUe.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 jAs extends Lt.Component{constructor(t){var n;super(t),this.editorContentRef=Lt.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=wAs(),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 Lt.createElement(Lt.Fragment,null,Lt.createElement("div",{ref:bAs(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&Lt.createElement(_As,{contentComponent:t.contentComponent}))}}const NAs=j.forwardRef((s,t)=>{const n=Lt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Lt.createElement(jAs,{key:n,innerRef:t,...s})}),QVe=Lt.memo(NAs);var kAs=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},SAs=yAs(kAs),VTt={exports:{}},ALe={};/** * @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 Jit;function CAs(){if(Jit)return ALe;Jit=1;var s=Lt,t=XVe;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 ALe.useSyncExternalStoreWithSelector=function(d,u,h,m,p){var x=i(null);if(x.current===null){var y={hasValue:!1,value:null};x.current=y}else y=x.current;x=o(function(){function b(M){if(!v){if(v=!0,k=M,M=m(M),p!==void 0&&y.hasValue){var P=y.value;if(p(P,M))return C=P}return C=M}if(P=C,r(k,M))return P;var L=m(M);return p!==void 0&&p(P,L)?P:(k=M,C=L)}var v=!1,k,C,T=h===void 0?null:h;return[function(){return b(u())},T===null?void 0:function(){return b(T())}]},[u,h,m,p]);var g=a(d,x[0],x[1]);return l(function(){y.hasValue=!0,y.value=g},[g]),c(g),g},ALe}VTt.exports=CAs();var AAs=VTt.exports;const TAs=typeof window<"u"?j.useLayoutEffect:j.useEffect;class EAs{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 MAs(s){var t;const[n]=j.useState(()=>new EAs(s.editor)),r=AAs.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:SAs);return TAs(()=>n.watch(s.editor),[s.editor,n]),j.useDebugValue(r),r}const LAs=!1,rFe=typeof window>"u",PAs=rFe||!!(typeof window<"u"&&window.next);class JVe{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 rFe||PAs?null:this.createEditor();if(this.options.current.immediatelyRender&&rFe&&LAs)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 xAs(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?JVe.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 eHe(s={},t=[]){const n=j.useRef(s);n.current=s;const[r]=j.useState(()=>new JVe(n)),a=XVe.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return j.useDebugValue(a),j.useEffect(r.onRender(t)),MAs({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const IAs=j.createContext({editor:null});IAs.Consumer;const RAs=j.createContext({onDragStart:void 0}),DAs=()=>j.useContext(RAs);Lt.forwardRef((s,t)=>{const{onDragStart:n}=DAs(),r=s.as||"div";return Lt.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const OAs=/^\s*>\s$/,FAs=lv.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",Ym(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[pZ({find:OAs,type:this.type})]}}),zAs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,BAs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,$As=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,UAs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,qAs=AN.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",Ym(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[T$({find:zAs,type:this.type}),T$({find:$As,type:this.type})]},addPasteRules(){return[DD({find:BAs,type:this.type}),DD({find:UAs,type:this.type})]}}),VAs="listItem",eot="textStyle",tot=/^\s*([-+*])\s$/,HAs=lv.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",Ym(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(VAs,this.editor.getAttributes(eot)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=pZ({find:tot,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=pZ({find:tot,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(eot),editor:this.editor})),[s]}}),GAs=/(^|[^`])`([^`]+)`(?!`)/,WAs=/(^|[^`])`([^`]+)`(?!`)/g,KAs=AN.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",Ym(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[T$({find:GAs,type:this.type})]},addPasteRules(){return[DD({find:WAs,type:this.type})]}}),YAs=/^```([a-z]+)?[\s\n]$/,ZAs=/^~~~([a-z]+)?[\s\n]$/,XAs=lv.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",Ym(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(il.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[sFe({find:YAs,type:this.type,getAttributes:s=>({language:s[1]})}),sFe({find:ZAs,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new yg({key:new ov("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(Go.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),QAs=lv.create({name:"doc",topNode:!0,content:"block+"});function JAs(s={}){return new yg({view(t){return new eTs(t,s)}})}class eTs{constructor(t,n){var r;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(a=>{let i=l=>{this[a](l)};return t.dom.addEventListener(a,i),{name:a,handler:i}})}destroy(){this.handlers.forEach(({name:t,handler:n})=>this.editorView.dom.removeEventListener(t,n))}update(t,n){this.cursorPos!=null&&n.doc!=t.state.doc&&(this.cursorPos>t.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),n=!t.parent.inlineContent,r,a=this.editorView.dom,i=a.getBoundingClientRect(),l=i.width/a.offsetWidth,o=i.height/a.offsetHeight;if(n){let h=t.nodeBefore,m=t.nodeAfter;if(h||m){let p=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(p){let x=p.getBoundingClientRect(),y=h?x.bottom:x.top;h&&m&&(y=(y+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*o;r={left:x.left,right:x.right,top:y-g,bottom:y+g}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),m=this.width/2*l;r={left:h.left-m,right:h.left+m,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let h=c.getBoundingClientRect(),m=h.width/c.offsetWidth,p=h.height/c.offsetHeight;d=h.left-c.scrollLeft*m,u=h.top-c.scrollTop*p}this.element.style.left=(r.left-d)/l+"px",this.element.style.top=(r.top-u)/o+"px",this.element.style.width=(r.right-r.left)/l+"px",this.element.style.height=(r.bottom-r.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}dragover(t){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),a=r&&r.type.spec.disableDropCursor,i=typeof a=="function"?a(this.editorView,n,t):a;if(n&&!i){let l=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=RAt(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 tTs=my.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[JAs(this.options)]}});class pf extends il{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return pf.valid(r)?new pf(r):il.near(r)}content(){return di.empty}eq(t){return t instanceof pf&&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 pf(t.resolve(n.pos))}getBookmark(){return new tHe(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!sTs(t)||!nTs(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&&pf.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(pf.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!Bo.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(pf.valid(o))return o}return null}}}pf.prototype.visible=!1;pf.findFrom=pf.findGapCursorFrom;il.jsonID("gapcursor",pf);class tHe{constructor(t){this.pos=t}map(t){return new tHe(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return pf.valid(n)?new pf(n):il.near(n)}}function HTt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function sTs(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||HTt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function nTs(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||HTt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function rTs(){return new yg({props:{decorations:lTs,createSelectionBetween(s,t,n){return t.pos==n.pos&&pf.valid(n)?new pf(n):null},handleClick:iTs,handleKeyDown:aTs,handleDOMEvents:{beforeinput:oTs}}})}const aTs=UVe({ArrowLeft:qse("horiz",-1),ArrowRight:qse("horiz",1),ArrowUp:qse("vert",-1),ArrowDown:qse("vert",1)});function qse(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 Go){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=pf.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new pf(d))),!0):!1}}function iTs(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!pf.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&Bo.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new pf(r))),!0)}function oTs(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof pf))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=Aa.empty;for(let l=r.length-1;l>=0;l--)a=Aa.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new di(a,0,0));return i.setSelection(Go.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function lTs(s){if(!(s.selection instanceof pf))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",mf.create(s.doc,[Yv.widget(s.selection.head,t,{key:"gapcursor"})])}const cTs=my.create({name:"gapCursor",addProseMirrorPlugins(){return[rTs()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=gc(so(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),dTs=lv.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",Ym(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()}}}),uTs=lv.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]}`,Ym(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=>sFe({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var hke=200,d0=function(){};d0.prototype.append=function(t){return t.length?(t=d0.from(t),!this.length&&t||t.length=n?d0.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};d0.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};d0.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)};d0.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};d0.from=function(t){return t instanceof d0?t:t&&t.length?new GTt(t):d0.empty};var GTt=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<=hke)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=hke)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}(d0);d0.empty=new GTt([]);var hTs=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}(d0);const mTs=500;class aN{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 IC(h.map));let p=h.step.map(a.slice(i)),x;p&&l.maybeStep(p).doc&&(x=l.mapping.maps[l.mapping.maps.length-1],d.push(new IC(x,void 0,void 0,d.length+u.length))),i--,x&&a.appendMap(x,i)}else l.maybeStep(h.step);if(h.selection)return o=a?h.selection.map(a.slice(i)):h.selection,c=new aN(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;ufTs&&(o=pTs(o,d),l-=d),new aN(o.append(i),l)}remapping(t,n){let r=new oZ;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 aN(this.items.append(t.map(n=>new IC(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(m=>{m.selection&&o--},a);let c=n;this.items.forEach(m=>{let p=i.getMirror(--c);if(p==null)return;l=Math.min(l,p);let x=i.maps[p];if(m.step){let y=t.steps[p].invert(t.docs[p]),g=m.selection&&m.selection.map(i.slice(c+1,p));g&&o++,r.push(new IC(x,y,g))}else r.push(new IC(x))},a);let d=[];for(let m=n;mmTs&&(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 IC(d.invert(),c,u),m,p=a.length-1;(m=a.length&&a[p].merge(h))?a[p]=m:a.push(h)}}else l.map&&r--},this.items.length,0),new aN(d0.from(a.reverse()),i)}}aN.empty=new aN(d0.empty,0);function pTs(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let IC=class WTt{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 WTt(n.getMap().invert(),n,this.selection)}}};class mA{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const fTs=20;function xTs(s,t,n,r){let a=n.getMeta(nD),i;if(a)return a.historyState;n.getMeta(vTs)&&(s=new mA(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(nD))return l.getMeta(nD).redo?new mA(s.done.addTransform(n,void 0,r,Eje(t)),s.undone,sot(n.mapping.maps),s.prevTime,s.prevComposition):new mA(s.done,s.undone.addTransform(n,void 0,r,Eje(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||!gTs(n,s.prevRanges)),d=l?TLe(s.prevRanges,n.mapping):sot(n.mapping.maps);return new mA(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,Eje(t)),aN.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new mA(s.done.rebased(n,i),s.undone.rebased(n,i),TLe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new mA(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),TLe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function gTs(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 sot(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 TLe(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=nD.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=yTs(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const YTt=KTt(!1,!0),ZTt=KTt(!0,!0),_Ts=my.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>YTt(s,t),redo:()=>({state:s,dispatch:t})=>ZTt(s,t)}},addProseMirrorPlugins(){return[bTs(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()}}}),wTs=lv.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",Ym(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!gAs(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}):zCs(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(Go.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(Bo.create(l.doc,d.pos)):l.setSelection(Go.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(Go.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[UTt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),jTs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,NTs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,kTs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,STs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,CTs=AN.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",Ym(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[T$({find:jTs,type:this.type}),T$({find:kTs,type:this.type})]},addPasteRules(){return[DD({find:NTs,type:this.type}),DD({find:STs,type:this.type})]}}),ATs=lv.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",Ym(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)}}}),TTs="listItem",rot="textStyle",aot=/^(\d+)\.\s$/,ETs=lv.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",Ym(this.options.HTMLAttributes,n),0]:["ol",Ym(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(TTs,this.editor.getAttributes(rot)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=pZ({find:aot,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=pZ({find:aot,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(rot)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),MTs=lv.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",Ym(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),LTs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,PTs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,ITs=AN.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",Ym(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[T$({find:LTs,type:this.type})]},addPasteRules(){return[DD({find:PTs,type:this.type})]}}),RTs=lv.create({name:"text",group:"inline"}),sHe=my.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(qAs.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(FAs.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(HAs.configure(this.options.bulletList)),this.options.code!==!1&&s.push(KAs.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(XAs.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(QAs.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(tTs.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(cTs.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(dTs.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(uTs.configure(this.options.heading)),this.options.history!==!1&&s.push(_Ts.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(wTs.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(CTs.configure(this.options.italic)),this.options.listItem!==!1&&s.push(ATs.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(ETs.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(MTs.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(ITs.configure(this.options.strike)),this.options.text!==!1&&s.push(RTs.configure(this.options.text)),s}}),DTs="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",OTs="ελ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",aFe="numeric",iFe="ascii",oFe="alpha",zK="asciinumeric",DG="alphanumeric",lFe="domain",XTt="emoji",FTs="scheme",zTs="slashscheme",MLe="whitespace";function BTs(s,t){return s in t||(t[s]=[]),t[s]}function o8(s,t,n){t[aFe]&&(t[zK]=!0,t[DG]=!0),t[iFe]&&(t[zK]=!0,t[oFe]=!0),t[zK]&&(t[DG]=!0),t[oFe]&&(t[DG]=!0),t[DG]&&(t[lFe]=!0),t[XTt]&&(t[lFe]=!0);for(const r in t){const a=BTs(r,n);a.indexOf(s)<0&&a.push(s)}}function $Ts(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function rb(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}rb.groups={};rb.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),sf=(s,t,n,r,a)=>s.tr(t,n,r,a),iot=(s,t,n,r,a)=>s.ts(t,n,r,a),Ma=(s,t,n,r,a)=>s.tt(t,n,r,a),c4="WORD",cFe="UWORD",QTt="ASCIINUMERICAL",JTt="ALPHANUMERICAL",fZ="LOCALHOST",dFe="TLD",uFe="UTLD",Mje="SCHEME",P7="SLASH_SCHEME",nHe="NUM",hFe="WS",rHe="NL",BK="OPENBRACE",$K="CLOSEBRACE",mke="OPENBRACKET",pke="CLOSEBRACKET",fke="OPENPAREN",xke="CLOSEPAREN",gke="OPENANGLEBRACKET",yke="CLOSEANGLEBRACKET",vke="FULLWIDTHLEFTPAREN",bke="FULLWIDTHRIGHTPAREN",_ke="LEFTCORNERBRACKET",wke="RIGHTCORNERBRACKET",jke="LEFTWHITECORNERBRACKET",Nke="RIGHTWHITECORNERBRACKET",kke="FULLWIDTHLESSTHAN",Ske="FULLWIDTHGREATERTHAN",Cke="AMPERSAND",Ake="APOSTROPHE",Tke="ASTERISK",pA="AT",Eke="BACKSLASH",Mke="BACKTICK",Lke="CARET",CA="COLON",aHe="COMMA",Pke="DOLLAR",Dk="DOT",Ike="EQUALS",iHe="EXCLAMATION",Kw="HYPHEN",UK="PERCENT",Rke="PIPE",Dke="PLUS",Oke="POUND",qK="QUERY",oHe="QUOTE",eEt="FULLWIDTHMIDDLEDOT",lHe="SEMI",Ok="SLASH",VK="TILDE",Fke="UNDERSCORE",tEt="EMOJI",zke="SYM";var sEt=Object.freeze({__proto__:null,ALPHANUMERICAL:JTt,AMPERSAND:Cke,APOSTROPHE:Ake,ASCIINUMERICAL:QTt,ASTERISK:Tke,AT:pA,BACKSLASH:Eke,BACKTICK:Mke,CARET:Lke,CLOSEANGLEBRACKET:yke,CLOSEBRACE:$K,CLOSEBRACKET:pke,CLOSEPAREN:xke,COLON:CA,COMMA:aHe,DOLLAR:Pke,DOT:Dk,EMOJI:tEt,EQUALS:Ike,EXCLAMATION:iHe,FULLWIDTHGREATERTHAN:Ske,FULLWIDTHLEFTPAREN:vke,FULLWIDTHLESSTHAN:kke,FULLWIDTHMIDDLEDOT:eEt,FULLWIDTHRIGHTPAREN:bke,HYPHEN:Kw,LEFTCORNERBRACKET:_ke,LEFTWHITECORNERBRACKET:jke,LOCALHOST:fZ,NL:rHe,NUM:nHe,OPENANGLEBRACKET:gke,OPENBRACE:BK,OPENBRACKET:mke,OPENPAREN:fke,PERCENT:UK,PIPE:Rke,PLUS:Dke,POUND:Oke,QUERY:qK,QUOTE:oHe,RIGHTCORNERBRACKET:wke,RIGHTWHITECORNERBRACKET:Nke,SCHEME:Mje,SEMI:lHe,SLASH:Ok,SLASH_SCHEME:P7,SYM:zke,TILDE:VK,TLD:dFe,UNDERSCORE:Fke,UTLD:uFe,UWORD:cFe,WORD:c4,WS:hFe});const YS=/[a-z]/,SH=new RegExp("\\p{L}","u"),LLe=new RegExp("\\p{Emoji}","u"),ZS=/\d/,PLe=/\s/,oot="\r",ILe=` `,UTs="️",qTs="‍",RLe="";let Vse=null,Hse=null;function VTs(s=[]){const t={};rb.groups=t;const n=new rb;Vse==null&&(Vse=lot(DTs)),Hse==null&&(Hse=lot(OTs)),Ma(n,"'",Ake),Ma(n,"{",BK),Ma(n,"}",$K),Ma(n,"[",mke),Ma(n,"]",pke),Ma(n,"(",fke),Ma(n,")",xke),Ma(n,"<",gke),Ma(n,">",yke),Ma(n,"(",vke),Ma(n,")",bke),Ma(n,"「",_ke),Ma(n,"」",wke),Ma(n,"『",jke),Ma(n,"』",Nke),Ma(n,"<",kke),Ma(n,">",Ske),Ma(n,"&",Cke),Ma(n,"*",Tke),Ma(n,"@",pA),Ma(n,"`",Mke),Ma(n,"^",Lke),Ma(n,":",CA),Ma(n,",",aHe),Ma(n,"$",Pke),Ma(n,".",Dk),Ma(n,"=",Ike),Ma(n,"!",iHe),Ma(n,"-",Kw),Ma(n,"%",UK),Ma(n,"|",Rke),Ma(n,"+",Dke),Ma(n,"#",Oke),Ma(n,"?",qK),Ma(n,'"',oHe),Ma(n,"/",Ok),Ma(n,";",lHe),Ma(n,"~",VK),Ma(n,"_",Fke),Ma(n,"\\",Eke),Ma(n,"・",eEt);const r=sf(n,ZS,nHe,{[aFe]:!0});sf(r,ZS,r);const a=sf(r,YS,QTt,{[zK]:!0}),i=sf(r,SH,JTt,{[DG]:!0}),l=sf(n,YS,c4,{[iFe]:!0});sf(l,ZS,a),sf(l,YS,l),sf(a,ZS,a),sf(a,YS,a);const o=sf(n,SH,cFe,{[oFe]:!0});sf(o,YS),sf(o,ZS,i),sf(o,SH,o),sf(i,ZS,i),sf(i,YS),sf(i,SH,i);const c=Ma(n,ILe,rHe,{[MLe]:!0}),d=Ma(n,oot,hFe,{[MLe]:!0}),u=sf(n,PLe,hFe,{[MLe]:!0});Ma(n,RLe,u),Ma(d,ILe,c),Ma(d,RLe,u),sf(d,PLe,u),Ma(u,oot),Ma(u,ILe),sf(u,PLe,u),Ma(u,RLe,u);const h=sf(n,LLe,tEt,{[XTt]:!0});Ma(h,"#"),sf(h,LLe,h),Ma(h,UTs,h);const m=Ma(h,qTs);Ma(m,"#"),sf(m,LLe,h);const p=[[YS,l],[ZS,a]],x=[[YS,null],[SH,o],[ZS,i]];for(let y=0;yy[0]>g[0]?1:-1);for(let y=0;y=0?v[lFe]=!0:YS.test(g)?ZS.test(g)?v[zK]=!0:v[iFe]=!0:v[aFe]=!0,iot(n,g,g,v)}return iot(n,"localhost",fZ,{ascii:!0}),n.jd=new rb(zke),{start:n,tokens:Object.assign({groups:t},sEt)}}function nEt(s,t){const n=HTs(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 HTs(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 RC(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 xZ={defaultProtocol:"http",events:null,format:cot,formatHref:cot,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function cHe(s,t=null){let n=Object.assign({},xZ);s&&(n=Object.assign(n,s instanceof cHe?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=xZ.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 iCe(s,t){class n extends rEt{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 dot=iCe("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),uot=iCe("text"),GTs=iCe("nl"),Gse=iCe("url",{isLink:!0,toHref(s=xZ.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==fZ&&s[1].t===CA}}),Dw=s=>new rb(s);function WTs({groups:s}){const t=s.domain.concat([Cke,Tke,pA,Eke,Mke,Lke,Pke,Ike,Kw,nHe,UK,Rke,Dke,Oke,Ok,zke,VK,Fke]),n=[Ake,CA,aHe,Dk,iHe,UK,qK,oHe,lHe,gke,yke,BK,$K,pke,mke,fke,xke,vke,bke,_ke,wke,jke,Nke,kke,Ske],r=[Cke,Ake,Tke,Eke,Mke,Lke,Pke,Ike,Kw,BK,$K,UK,Rke,Dke,Oke,qK,Ok,zke,VK,Fke],a=Dw(),i=Ma(a,VK);xc(i,r,i),xc(i,s.domain,i);const l=Dw(),o=Dw(),c=Dw();xc(a,s.domain,l),xc(a,s.scheme,o),xc(a,s.slashscheme,c),xc(l,r,i),xc(l,s.domain,l);const d=Ma(l,pA);Ma(i,pA,d),Ma(o,pA,d),Ma(c,pA,d);const u=Ma(i,Dk);xc(u,r,i),xc(u,s.domain,i);const h=Dw();xc(d,s.domain,h),xc(h,s.domain,h);const m=Ma(h,Dk);xc(m,s.domain,h);const p=Dw(dot);xc(m,s.tld,p),xc(m,s.utld,p),Ma(d,fZ,p);const x=Ma(h,Kw);Ma(x,Kw,x),xc(x,s.domain,h),xc(p,s.domain,h),Ma(p,Dk,m),Ma(p,Kw,x);const y=Ma(p,CA);xc(y,s.numeric,dot);const g=Ma(l,Kw),b=Ma(l,Dk);Ma(g,Kw,g),xc(g,s.domain,l),xc(b,r,i),xc(b,s.domain,l);const v=Dw(Gse);xc(b,s.tld,v),xc(b,s.utld,v),xc(v,s.domain,l),xc(v,r,i),Ma(v,Dk,b),Ma(v,Kw,g),Ma(v,pA,d);const k=Ma(v,CA),C=Dw(Gse);xc(k,s.numeric,C);const T=Dw(Gse),M=Dw();xc(T,t,T),xc(T,n,M),xc(M,t,T),xc(M,n,M),Ma(v,Ok,T),Ma(C,Ok,T);const P=Ma(o,CA),L=Ma(c,CA),I=Ma(L,Ok),O=Ma(I,Ok);xc(o,s.domain,l),Ma(o,Dk,b),Ma(o,Kw,g),xc(c,s.domain,l),Ma(c,Dk,b),Ma(c,Kw,g),xc(P,s.domain,T),Ma(P,Ok,T),Ma(P,qK,T),xc(O,s.domain,T),xc(O,t,T),Ma(O,Ok,T);const $=[[BK,$K],[mke,pke],[fke,xke],[gke,yke],[vke,bke],[_ke,wke],[jke,Nke],[kke,Ske]];for(let q=0;q<$.length;q++){const[W,G]=$[q],K=Ma(T,W);Ma(M,W,K),Ma(K,G,T);const ee=Dw(Gse);xc(K,t,ee);const J=Dw();xc(K,n),xc(ee,t,ee),xc(ee,n,J),xc(J,t,ee),xc(J,n,J),Ma(ee,G,T),Ma(J,G,T)}return Ma(a,fZ,v),Ma(a,rHe,GTs),{start:a,tokens:sEt}}function KTs(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(DLe(uot,t,l)),l=[]),a-=m,u-=m;const p=h.t,x=n.slice(a-u,a);i.push(DLe(p,t,x))}}return l.length>0&&i.push(DLe(uot,t,l)),i}function DLe(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 YTs=typeof console<"u"&&console&&console.warn||(()=>{}),ZTs="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",cm={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function XTs(){return rb.groups={},cm.scanner=null,cm.parser=null,cm.tokenQueue=[],cm.pluginQueue=[],cm.customSchemes=[],cm.initialized=!1,cm}function hot(s,t=!1){if(cm.initialized&&YTs(`linkifyjs: already initialized - will not register custom scheme "${s}" ${ZTs}`),!/^[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`);cm.customSchemes.push([s,t])}function QTs(){cm.scanner=VTs(cm.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=ECs(n.doc,[...t]);if(OCs(o).forEach(({newRange:d})=>{const u=LCs(r.doc,d,p=>p.isTextblock);let h,m;if(u.length>1)h=u[0],m=r.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(u.length){const p=r.doc.textBetween(d.from,d.to," "," ");if(!eEs.test(p))return;h=u[0],m=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&m){const p=m.split(JTs).filter(Boolean);if(p.length<=0)return!1;const x=p[p.length-1],y=h.pos+m.lastIndexOf(x);if(!x)return!1;const g=dHe(x).map(b=>b.toObject(s.defaultProtocol));if(!sEs(g))return!1;g.filter(b=>b.isLink).map(b=>({...b,from:y+b.start+1,to:y+b.end+1})).filter(b=>r.schema.marks.code?!r.doc.rangeHasMark(b.from,b.to,r.schema.marks.code):!0).filter(b=>s.validate(b.value)).filter(b=>s.shouldAutoLink(b.value)).forEach(b=>{YVe(b.from,b.to,r.doc).some(v=>v.mark.type===s.type)||l.addMark(b.from,b.to,s.type.create({href:b.href}))})}}),!!l.steps.length)return l}})}function rEs(s){return new yg({key:new ov("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=$Tt(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 aEs(s){return new yg({key:new ov("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=aEt(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 cM(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(tEs,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const hHe=AN.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"){hot(s);return}hot(s.scheme,s.optionalSlashes)})},onDestroy(){XTs()},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)=>!!cM(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=>!!cM(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=>!!cM(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Ym(this.options.HTMLAttributes,s),0]:["a",Ym(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!cM(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=>!!cM(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[DD({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=aEt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!cM(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(nEs({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!cM(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(rEs({type:this.type})),this.options.linkOnPaste&&s.push(aEs({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),mHe=my.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")}}}),iEs=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}`)})},pHe=AN.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&iEs(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",Ym(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}}}}),oEs=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,lEs=lv.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",Ym(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[UTt({find:oEs,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let mFe,pFe;if(typeof WeakMap<"u"){let s=new WeakMap;mFe=t=>s.get(t),pFe=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;mFe=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var xf=class{constructor(s,t,n,r){this.width=s,this.height=t,this.map=n,this.problems=r}findCell(s){for(let t=0;t=n){(i||(i=[])).push({type:"overlong_rowspan",pos:u,n:b-k});break}const C=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 uEs(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 mEs(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 DN(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 oCe(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=OD(t.$head)||pEs(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function pEs(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 fFe(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function fEs(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function fHe(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function iEt(s,t,n){const r=s.node(-1),a=xf.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 FD(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 oEt(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 BAt(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(fFe(r)&&fFe(a)&&fHe(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?d4.rowSelection(r,a):i&&this.isColSelection()?d4.colSelection(r,a):new d4(r,a)}return Go.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=xf.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||g>0){let b=x.attrs;if(y>0&&(b=FD(b,0,y)),g>0&&(b=FD(b,b.colspan-g,g)),p.lefta.bottom){const b={...x.attrs,rowspan:Math.min(p.bottom,a.bottom)-Math.max(p.top,a.top)};p.top0)return!1;const r=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,a)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){const r=t.node(-1),a=xf.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 d4&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=xf.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(Yv.node(r,r+n.nodeSize,{class:"selectedCell"}))}),mf.create(s.doc,t)}function vEs({$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 bEs({$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 _Es(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof Bo&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=Vh.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=Vh.rowSelection(o,o)}else if(!n){const o=xf.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=Vh.create(a,c+1,d)}}else r instanceof Go&&vEs(r)?i=Go.create(a,r.from):r instanceof Go&&bEs(r)&&(i=Go.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const wEs=new ov("fix-tables");function cEt(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=jEs(s,a,i,n))};return t?t.doc!=s.doc&&cEt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function jEs(s,t,n,r){const a=xf.get(t);if(!a.problems)return r;r||(r=s.tr);const i=[];for(let c=0;c0){let p="cell";u.firstChild&&(p=u.firstChild.type.spec.tableRole);const x=[];for(let g=0;g0?-1:0;xEs(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;AEs(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=mot(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new Vh(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function fot(s,t){const n=sv(s.schema);return IEs(({node:r})=>n[r.type.spec.tableRole])(s,t)}function IEs(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof Vh){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=mEs(r.$from),!a)return!1;i=(l=OD(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=lS(t),h=t.tr;for(let p=0;p{l.attrs[s]!==t&&i.setNodeMarkup(o,null,{...l.attrs,[s]:t})}):i.setNodeMarkup(a.pos,null,{...a.nodeAfter.attrs,[s]:t}),r(i)}return!0}}function DEs(s){return function(t,n){if(!DN(t))return!1;if(n){const r=sv(t.schema),a=lS(t),i=t.tr,l=a.map.cellsInRect(s=="column"?{left:a.left,top:0,right:a.right,bottom:a.map.height}:s=="row"?{left:0,top:a.top,right:a.map.width,bottom:a.bottom}:a),o=l.map(c=>a.table.nodeAt(c));for(let c=0;c{const p=m+i.tableStart,x=l.doc.nodeAt(p);x&&l.setNodeMarkup(p,h,x.attrs)}),r(l)}return!0}}gZ("row",{useDeprecatedLogic:!0});gZ("column",{useDeprecatedLogic:!0});const OEs=gZ("cell",{useDeprecatedLogic:!0});function FEs(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 Wse(s,t){const n=s.selection;if(!(n instanceof Vh))return!1;if(t){const r=s.tr,a=sv(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 di(a,0,0))}),r.docChanged&&t(r)}return!0}function BEs(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(Aa.empty),n[a]r&&(m=m.type.createChecked(FD(m.attrs,m.attrs.colspan,u+m.attrs.colspan-r),m.content)),d.push(m),u+=m.attrs.colspan;for(let p=1;pa&&(h=h.type.create({...h.attrs,rowspan:Math.max(1,a-h.attrs.rowspan)},h.content)),c.push(h)}i.push(Aa.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function qEs(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=sv(o);let d,u;if(a>t.width)for(let h=0,m=0;ht.height){const h=[];for(let x=0,y=(t.height-1)*t.width;x=t.width?!1:n.nodeAt(t.map[y+x]).type==c.header_cell;h.push(g?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const m=c.row.create(null,Aa.from(h)),p=[];for(let x=t.height;x{if(!a)return!1;const i=n.selection;if(i instanceof Vh)return Lje(n,r,il.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=mEt(a,s,t);if(l==null)return!1;if(s=="horiz")return Lje(n,r,il.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=iEt(o,s,t);let d;return c?d=il.near(c,1):t<0?d=il.near(n.doc.resolve(o.before(-1)),-1):d=il.near(n.doc.resolve(o.after(-1)),1),Lje(n,r,d)}}}function Yse(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof Vh)l=i;else{const c=mEt(a,s,t);if(c==null)return!1;l=new Vh(n.doc.resolve(c))}const o=iEt(l.$headCell,s,t);return o?Lje(n,r,new Vh(l.$anchorCell,o)):!1}}function HEs(s,t){const n=s.state.doc,r=OD(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new Vh(r))),!0):!1}function GEs(s,t,n){if(!DN(s.state))return!1;let r=BEs(n);const a=s.state.selection;if(a instanceof Vh){r||(r={width:1,height:1,rows:[Aa.from(xFe(sv(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=xf.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=UEs(r,o.right-o.left,o.bottom-o.top),bot(s.state,s.dispatch,l,o,r),!0}else if(r){const i=oCe(s.state),l=i.start(-1);return bot(s.state,s.dispatch,l,xf.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function WEs(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=_ot(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof Vh)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=OD(s.state.selection.$anchor))!=null&&((n=OLe(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=OLe(s,d);const h=AA.getState(s.state)==null;if(!u||!fHe(c,u))if(h)u=c;else return;const m=new Vh(c,u);if(h||!s.state.selection.eq(m)){const p=s.state.tr.setSelection(m);h&&p.setMeta(AA,c.pos),s.dispatch(p)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),AA.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(AA,-1))}function o(c){const d=c,u=AA.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(_ot(s,d.target)!=r&&(h=OLe(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 mEt(s,t,n){if(!(s.state.selection instanceof Go))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 _ot(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function OLe(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&&OD(s.state.doc.resolve(r))||OD(s.state.doc.resolve(a))}var KEs=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")),gFe(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,gFe(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function gFe(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 ZEs(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=R_.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{XEs(l,o,s,a)},mouseleave:l=>{QEs(l)},mousedown:(l,o)=>{JEs(l,o,t,n)}},decorations:l=>{const o=R_.getState(l);if(o&&o.activeHandle>-1)return r6s(l,o.activeHandle)},nodeViews:{}}});return i}var ZEs=class Pje{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(R_);if(r&&r.setHandle!=null)return new Pje(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new Pje(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return fFe(t.doc.resolve(a))||(a=-1),new Pje(a,n.dragging)}return n}};function XEs(s,t,n,r){if(!s.editable)return;const a=R_.getState(s.state);if(a&&!a.dragging){const i=t6s(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=wot(s,t,"left",n):c-t.clientX<=n&&(l=wot(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=xf.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}pEt(s,l)}}}function QEs(s){if(!s.editable)return;const t=R_.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&pEt(s,-1)}function JEs(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=R_.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=e6s(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(R_,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const m=R_.getState(s.state);m!=null&&m.dragging&&(s6s(s,m.activeHandle,jot(m.dragging,h,n)),s.dispatch(s.state.tr.setMeta(R_,{setDragging:null})))}function u(h){if(!h.which)return d(h);const m=R_.getState(s.state);if(m&&m.dragging){const p=jot(m.dragging,h,n);Not(s,m.activeHandle,p,r)}}return Not(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function e6s(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 c6s(s,t,n,r,a){const i=l6s(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!d6s(t))return!1;let n=0;const r=BTt(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},u6s=lv.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:i6s,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}=o6s(s,this.options.cellMinWidth),i=["table",Ym(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=c6s(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(Go.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>NEs(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>kEs(s,t),deleteColumn:()=>({state:s,dispatch:t})=>CEs(s,t),addRowBefore:()=>({state:s,dispatch:t})=>TEs(s,t),addRowAfter:()=>({state:s,dispatch:t})=>EEs(s,t),deleteRow:()=>({state:s,dispatch:t})=>LEs(s,t),deleteTable:()=>({state:s,dispatch:t})=>zEs(s,t),mergeCells:()=>({state:s,dispatch:t})=>pot(s,t),splitCell:()=>({state:s,dispatch:t})=>fot(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>gZ("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>gZ("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>OEs(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>pot(s,t)?!0:fot(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>REs(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>got(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>got(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&dEt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=Vh.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:Zse,"Mod-Backspace":Zse,Delete:Zse,"Mod-Delete":Zse}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[YEs({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],a6s({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:gc(so(s,"tableRole",t))}}}),h6s=lv.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",Ym(this.options.HTMLAttributes,s),0]}}),m6s=lv.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",Ym(this.options.HTMLAttributes,s),0]}}),p6s=lv.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",Ym(this.options.HTMLAttributes,s),0]}});function Kj({content:s,onChange:t,placeholder:n="Enter content...",minHeight:r="150px",compact:a=!1}){const[i,l]=j.useState(!1),[o,c]=j.useState(""),[d,u]=j.useState(!0),h=eHe({extensions:[sHe,hHe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),mHe.configure({types:["heading","paragraph"]}),pHe,lEs.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}),u6s.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}),h6s.extend({addAttributes(){var y;return{...(y=this.parent)==null?void 0:y.call(this),style:{default:null}}}}),m6s.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}}}}),p6s.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,g)=>{var v;const b=(v=g.clipboardData)==null?void 0:v.items;if(!b)return!1;for(const k of Array.from(b))if(k.type.startsWith("image/")){g.preventDefault();const C=k.getAsFile();if(!C)continue;const T=new FileReader;return T.onload=M=>{var L;const P=(L=M.target)==null?void 0:L.result;y.dispatch(y.state.tr.replaceSelectionWith(y.state.schema.nodes.image.create({src:P})))},T.readAsDataURL(C),!0}return!1}}});j.useEffect(()=>{h&&s!==h.getHTML()&&h.commands.setContent(s)},[s,h]);const m=()=>{if(!h)return;const y=h.getAttributes("link").href||"",g=h.getAttributes("link").target;c(y),u(g==="_blank"),l(!0)},p=()=>{h&&(o===""?h.chain().focus().extendMarkRange("link").unsetLink().run():h.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},x=()=>{h&&h.chain().focus().extendMarkRange("link").unsetLink().run()};return h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx(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(B9,{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($9,{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(BT,{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(KT,{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(ug,{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(kj,{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(ER,{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(TR,{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(MR,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:m,className:h.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(vc,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:x,title:"Remove Link",children:e.jsx(vc,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().undo().run(),disabled:!h.can().undo(),title:"Undo",children:e.jsx(aE,{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(eE,{className:"h-4 w-4"})})]}),e.jsx(QVe,{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(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"link-url",children:"URL"}),e.jsx(ye,{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(Mn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(se,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:p,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var f6s=Object.defineProperty,x6s=(s,t,n)=>t in s?f6s(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,zm=(s,t,n)=>x6s(s,typeof t!="symbol"?t+"":t,n);const Bke={x:0,y:0,width:0,height:0,unit:"px"},qF=(s,t,n)=>Math.min(Math.max(s,t),n),g6s=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),Cot=(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 y6s(s,t,n,r){const a=Fk(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==="%"?fA(a,n,r):a}function v6s(s,t,n){const r=Fk(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?fA(r,t,n):r}function fA(s,t,n){return s.unit==="%"?{...Bke,...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 Fk(s,t,n){return s.unit?s.unit==="px"?{...Bke,...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}:{...Bke,...s,unit:"px"}}function Aot(s,t,n,r,a,i=0,l=0,o=r,c=a){const d={...s};let u=Math.min(i,r),h=Math.min(l,a),m=Math.min(o,r),p=Math.min(c,a);t&&(t>1?(u=l?l*t:u,h=u/t,m=o*t):(h=i?i/t:h,u=h*t,p=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,h),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,u),d.x=0);const x=r-(d.x+d.width);x<0&&(d.x=Math.min(d.x,r-u),d.width+=x);const y=a-(d.y+d.height);if(y<0&&(d.y=Math.min(d.y,a-h),d.height+=y),d.widthm&&((n==="sw"||n=="nw")&&(d.x-=m-d.width),d.width=m),d.height>p&&((n==="nw"||n=="ne")&&(d.y-=p-d.height),d.height=p),t){const g=d.width/d.height;if(gt){const b=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=b-d.width),d.width=b}}return d}function b6s(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 VF={capture:!0,passive:!1};let _6s=0;const eA=class S2 extends j.PureComponent{constructor(){super(...arguments),zm(this,"docMoveBound",!1),zm(this,"mouseDownOnCrop",!1),zm(this,"dragStarted",!1),zm(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),zm(this,"componentRef",j.createRef()),zm(this,"mediaRef",j.createRef()),zm(this,"resizeObserver"),zm(this,"initChangeCalled",!1),zm(this,"instanceId",`rc-${_6s++}`),zm(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),zm(this,"onCropPointerDown",t=>{const{crop:n,disabled:r}=this.props,a=this.getBox();if(!n)return;const i=Fk(n,a.width,a.height);if(r)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const l=t.target.dataset.ord,o=!!l;let c=t.clientX,d=t.clientY,u=i.x,h=i.y;if(l){const m=t.clientX-a.x,p=t.clientY-a.y;let x=0,y=0;l==="ne"||l=="e"?(x=m-(i.x+i.width),y=p-i.y,u=i.x,h=i.y+i.height):l==="se"||l==="s"?(x=m-(i.x+i.width),y=p-(i.y+i.height),u=i.x,h=i.y):l==="sw"||l=="w"?(x=m-i.x,y=p-(i.y+i.height),u=i.x+i.width,h=i.y):(l==="nw"||l=="n")&&(x=m-i.x,y=p-i.y,u=i.x+i.width,h=i.y+i.height),c=u+a.x+x,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})}),zm(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(Fk(u,o.width,o.height),fA(u,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),zm(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(),Cot(n,c)||a(Fk(c,l.width,l.height),fA(c,l.width,l.height))}),zm(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)?S2.nudgeStepLarge:t.shiftKey?S2.nudgeStepMedium:S2.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=qF(d.x,0,c.width-d.width),d.y=qF(d.y,0,c.height-d.height);const h=Fk(d,c.width,c.height),m=fA(d,c.width,c.height);a(h,m),i&&i(h,m)}}),zm(this,"onHandlerKeyDown",(t,n)=>{const{aspect:r=0,crop:a,disabled:i,minWidth:l=0,minHeight:o=0,maxWidth:c,maxHeight:d,onChange:u,onComplete:h}=this.props,m=this.getBox();if(i||!a)return;if(t.key==="ArrowUp"||t.key==="ArrowDown"||t.key==="ArrowLeft"||t.key==="ArrowRight")t.stopPropagation(),t.preventDefault();else return;const p=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?S2.nudgeStepLarge:t.shiftKey?S2.nudgeStepMedium:S2.nudgeStep,x=Fk(a,m.width,m.height),y=b6s(x,t.key,p,n),g=Aot(y,r,n,m.width,m.height,l,o,c,d);if(!Cot(a,g)){const b=fA(g,m.width,m.height);u(g,b),h&&h(g,b)}}),zm(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(Fk(n,l.width,l.height),fA(n,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),zm(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(Fk(n,a,i),fA(n,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,VF),this.document.addEventListener("pointerup",this.onDocPointerDone,VF),this.document.addEventListener("pointercancel",this.onDocPointerDone,VF),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,VF),this.document.removeEventListener("pointerup",this.onDocPointerDone,VF),this.document.removeEventListener("pointercancel",this.onDocPointerDone,VF),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=qF(t.startCropX+a,0,n.width-r.width),r.y=qF(t.startCropY+i,0,n.height-r.height),r}getPointRegion(t,n,r,a){const{evData:i}=this,l=i.clientX-t.x,o=i.clientY-t.y;let c;a&&n?c=n==="nw"||n==="n"||n==="ne":c=o1?i?[i,i/n]:[l*n,l]:l?[l*n,l]:[i,i/n]}resizeCrop(){const{evData:t}=this,{aspect:n=0,maxWidth:r,maxHeight:a}=this.props,i=this.getBox(),[l,o]=this.resolveMinDimensions(i,n,this.props.minWidth,this.props.minHeight);let c=this.makePixelCrop(i);const d=this.getPointRegion(i,t.ord,l,o),u=t.ord||d;let h=t.clientX-t.startClientX,m=t.clientY-t.startClientY;(l&&u==="nw"||u==="w"||u==="sw")&&(h=Math.min(h,-l)),(o&&u==="nw"||u==="n"||u==="ne")&&(m=Math.min(m,-o));const p={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(p.x=t.startCropX,p.width=h,n?(p.height=p.width/n,p.y=t.startCropY-p.height):(p.height=Math.abs(m),p.y=t.startCropY-p.height)):d==="se"?(p.x=t.startCropX,p.y=t.startCropY,p.width=h,n?p.height=p.width/n:p.height=m):d==="sw"?(p.x=t.startCropX+h,p.y=t.startCropY,p.width=Math.abs(h),n?p.height=p.width/n:p.height=m):d==="nw"&&(p.x=t.startCropX+h,p.width=Math.abs(h),n?(p.height=p.width/n,p.y=t.startCropY-p.height):(p.height=Math.abs(m),p.y=t.startCropY+m));const x=Aot(p,n,d,i.width,i.height,l,o,r,a);return n||S2.xyOrds.indexOf(u)>-1?c=x:S2.xOrds.indexOf(u)>-1?(c.x=x.x,c.width=x.width):S2.yOrds.indexOf(u)>-1&&(c.y=x.y,c.height=x.height),c.x=qF(c.x,0,i.width-c.width),c.y=qF(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=S2.defaultProps.ariaLabels,disabled:n,locked:r,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return Lt.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!n&&!r&&Lt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Lt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Lt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Lt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Lt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Lt.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"}),Lt.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"}),Lt.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"}),Lt.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"}),Lt.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"}),Lt.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"}),Lt.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"}),Lt.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&&Lt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&Lt.createElement(Lt.Fragment,null,Lt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Lt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const n={...Bke,...this.props.crop||{}};return Fk(n,t.width,t.height)}render(){const{aspect:t,children:n,circularCrop:r,className:a,crop:i,disabled:l,locked:o,style:c,ruleOfThirds:d}=this.props,{cropIsActive:u,newCropIsBeingDrawn:h}=this.state,m=i?this.renderCropSelection():null,p=g6s("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 Lt.createElement("div",{ref:this.componentRef,className:p,style:c},Lt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},n),i?Lt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Lt.createElement("defs",null,Lt.createElement("mask",{id:`hole-${this.instanceId}`},Lt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),r?Lt.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"}):Lt.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),Lt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,m)}};zm(eA,"xOrds",["e","w"]),zm(eA,"yOrds",["n","s"]),zm(eA,"xyOrds",["nw","ne","se","sw"]),zm(eA,"nudgeStep",1),zm(eA,"nudgeStepMedium",10),zm(eA,"nudgeStepLarge",100),zm(eA,"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 w6s=eA;function j6s(s,t,n){return v6s(y6s({unit:"%",width:90},n,s,t),s,t)}const xHe=({open:s,onClose:t,imageSrc:n,onCropComplete:r,aspectRatio:a=1})=>{const i=j.useRef(null),[l,o]=j.useState(),[c,d]=j.useState(),[u,h]=j.useState(1),[m,p]=j.useState(0),x=j.useCallback(b=>{const{width:v,height:k}=b.currentTarget;o(j6s(v,k,a))},[a]),y=j.useCallback(async()=>{const b=i.current;if(!b||!c)return;const v=document.createElement("canvas"),k=v.getContext("2d");if(!k)return;const C=b.naturalWidth/b.width,T=b.naturalHeight/b.height,M=400;v.width=M,v.height=M,k.imageSmoothingQuality="high";const P=c.x*C,L=c.y*T,I=c.width*C,O=c.height*T,$=m*Math.PI/180,q=v.width/2,W=v.height/2;return k.save(),k.translate(q,W),k.rotate($),k.scale(u,u),k.translate(-q,-W),k.drawImage(b,P,L,I,O,0,0,M,M),k.restore(),new Promise((G,K)=>{v.toBlob(ee=>{ee?G(ee):K(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,m]),g=async()=>{try{const b=await y();b&&(r(b),t())}catch(b){console.error("Error cropping image:",b)}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx($s,{children:e.jsx(zs,{children:"Crop Your Photo"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative max-h-[400px] overflow-hidden rounded-lg bg-muted flex items-center justify-center",children:e.jsx(w6s,{crop:l,onChange:(b,v)=>o(v),onComplete:b=>d(b),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:n,alt:"Crop preview",style:{transform:`scale(${u}) rotate(${m}deg)`,maxHeight:"400px",width:"auto"},onLoad:x})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(pz,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Qf,{value:[u],min:.5,max:3,step:.1,onValueChange:([b])=>h(b),className:"flex-1"}),e.jsx(iE,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(WR,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Qf,{value:[m],min:-180,max:180,step:1,onValueChange:([b])=>p(b),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[m,"°"]})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(B,{onClick:g,children:"Save Photo"})]})]})})},Tot="I agree to receive recurring SMS/MMS text messages from LevelUp, including new lead alerts, account notifications, service updates, and customer support. Message frequency varies. Message and data rates may apply. Reply STOP to opt out and HELP for help. Consent is not a condition of purchase.";function N6s(s){const t=s.replace(/\D/g,"");return s.trim().startsWith("+")?t.length>=8?`+${t}`:null:t.length===10?`+1${t}`:t.length===11&&t.startsWith("1")?`+${t}`:null}function k6s(){const{user:s}=Ns(),{toast:t}=pi(),[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(""),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState(null),[x,y]=j.useState(!1);j.useEffect(()=>{s!=null&&s.id&&(async()=>{const{data:v}=await U.from("profiles").select("phone, phone_e164, sms_consent, sms_consent_at").eq("id",s.id).maybeSingle(),k=v;k&&(o(k.phone_e164||k.phone||""),h(!!k.sms_consent),d(!!k.sms_consent),p(k.sms_consent_at||null)),r(!1)})()},[s==null?void 0:s.id]);const g=async()=>{const v=N6s(l);if(!v){t({title:"Invalid number",description:"Enter a valid mobile number, e.g. (555) 123-4567.",variant:"destructive"});return}if(!c){t({title:"Consent required",description:"Please check the consent box to opt in to text messages.",variant:"destructive"});return}i(!0);const{error:k}=await U.from("profiles").update({phone_e164:v,sms_consent:!0,sms_consent_at:new Date().toISOString(),sms_consent_text:Tot,sms_consent_source:"profile_page",sms_opted_out_at:null}).eq("id",s.id);if(i(!1),k){t({title:"Error",description:k.message,variant:"destructive"});return}h(!0),p(new Date().toISOString()),t({title:"You're opted in",description:"You'll now receive text alerts for new leads and account notifications."})},b=async()=>{i(!0);const{error:v}=await U.from("profiles").update({sms_consent:!1,sms_opted_out_at:new Date().toISOString()}).eq("id",s.id);if(i(!1),v){t({title:"Error",description:v.message,variant:"destructive"});return}h(!1),d(!1),t({title:"Opted out",description:"You will no longer receive text messages from LevelUp."})};return e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ro,{className:"h-5 w-5"}),"Text Message (SMS) Alerts",u&&e.jsx(qe,{variant:"secondary",children:"Opted in"})]}),e.jsx(fr,{children:"Get a text the moment a new lead comes in, plus important account notifications."})]}),e.jsx(Re,{className:"space-y-4",children:n?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3",children:e.jsx("p",{className:"text-sm font-medium",children:"SMS is completely optional. It is not required to create an account, save your profile, purchase, access, or use LevelUp. You may leave this blank or decline."})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"sms-mobile",children:"Mobile Number (optional)"}),e.jsx(ye,{id:"sms-mobile",type:"tel",value:l,onChange:v=>o(v.target.value),placeholder:"(555) 123-4567",maxLength:30,autoComplete:"tel"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only needed if you choose to opt in. Must be a mobile number that can receive text messages."})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(wi,{id:"sms-consent",checked:c,onCheckedChange:v=>d(v===!0),disabled:u,className:"mt-0.5"}),e.jsx(se,{htmlFor:"sms-consent",className:"text-sm font-normal leading-relaxed cursor-pointer",children:Tot})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Message types: new lead alerts, account notifications, service updates, customer support. Frequency varies. Msg & data rates may apply. Reply STOP to opt out, HELP for help. No mobile information will be shared with third parties or affiliates for marketing purposes."}),u&&m&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Consent recorded on ",new Date(m).toLocaleString("en-US",{timeZone:"America/New_York"}),"."]}),x&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You chose not to enroll in text alerts. Nothing was saved and your account is unaffected."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:g,disabled:a||u&&!l,children:[a&&e.jsx(Wt,{className:"mr-2 h-4 w-4 animate-spin"}),u?"Update Number":"Opt in to SMS"]}),u?e.jsx(B,{variant:"outline",onClick:b,disabled:a,children:"Opt out"}):e.jsx(B,{variant:"outline",type:"button",disabled:a,onClick:()=>{o(""),d(!1),y(!0),t({title:"SMS skipped",description:"No consent was recorded. You can keep using LevelUp normally."})},children:"Skip SMS / Continue without text alerts"})]})]})})]})}const Eot="#2a4c64",Mot="#B8965A",Lot="Inter",Pot="Inter";function I7(s){if(typeof s!="string")return null;const t=s.trim();return t.length?t:null}function B1(s,t=null){for(const[n,r]of s){const a=I7(r);if(a)return{value:a,source:n}}return{value:t,source:"default"}}function S6s(s){const t=s.agent??{},n=s.brokerage??{},r=s.legacy??{},a=!!n.lock_colors,i=!!n.lock_logo,l=(M,P,L)=>a?[["brokerage",P],["agent",M],["legacy",L]]:[["agent",M],["brokerage",P],["legacy",L]],o=B1(l(t.brand_color,n.primary_color,r.brand_color),Eot),c=B1(l(t.accent_color,n.accent_color,r.accent_color),Mot),d=B1([["brokerage",n.secondary_color]]),u=i?[["brokerage",n.logo_url],["agent",t.logo_url],["legacy",r.brokerage_logo_url||r.team_logo_url]]:[["agent",t.logo_url],["legacy",r.team_logo_url],["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]],h=B1(u),m=B1([["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]]),p=B1([["agent",t.headshot_url],["legacy",r.avatar_url]]),x=B1([["agent",t.tagline],["legacy",r.tagline||r.title]]),y=B1([["agent",t.preferred_font],["brokerage",n.heading_font]],Lot),g=B1([["brokerage",n.body_font]],Pot),b=B1([["agent",t.license_number],["legacy",r.license_number]]),v=B1([["agent",t.license_state],["legacy",r.license_state],["brokerage",n.license_state]]),k=B1([["agent",t.website_url],["legacy",r.website_url]]),C=B1([["brokerage",n.legal_name],["legacy",r.brokerage_name]]),T=B1([["brokerage",n.compliance_line]]);return{agent_name:I7(r.name),brokerage_name:C.value,brand_color:o.value??Eot,secondary_color:d.value,accent_color:c.value??Mot,heading_font:y.value??Lot,body_font:g.value??Pot,logo_url:h.value,logo_dark_url:I7(n.logo_dark_url),brokerage_logo_url:m.value,icon_mark_url:I7(n.icon_mark_url),headshot_url:p.value,tagline:x.value,license_number:b.value,license_state:v.value,website_url:k.value,email:I7(r.email),phone:I7(r.phone),compliance_line:T.value,show_equal_housing:!!n.show_equal_housing,show_realtor_logo:!!n.show_realtor_logo,locked:{colors:a,logo:i},sources:{brand_color:o.source,accent_color:c.source,secondary_color:d.source,logo_url:h.source,brokerage_logo_url:m.source,headshot_url:p.source,tagline:x.source,heading_font:y.source,body_font:g.source,license_number:b.source,license_state:v.source,website_url:k.source,brokerage_name:C.source,compliance_line:T.source}}}function C6s(){const{user:s}=Ns();return mt({queryKey:["agent-brand-profile",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("agent_brand_profiles").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t??null}})}function A6s(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");const{data:r,error:a}=await U.from("agent_brand_profiles").upsert({user_id:s.id,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-brand-profile",s==null?void 0:s.id]}),t.invalidateQueries({queryKey:["brand-kit",s==null?void 0:s.id]})}})}function T6s(s){return mt({queryKey:["brokerage-brand-profile",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("brokerage_brand_profiles").select("*").eq("brokerage_id",s).maybeSingle();if(n)throw n;return t??null}})}function E6s(s){const{user:t}=Ns(),n=as();return vt({mutationFn:async r=>{if(!s)throw new Error("No brokerage selected");const{data:a,error:i}=await U.from("brokerage_brand_profiles").upsert({brokerage_id:s,updated_by:(t==null?void 0:t.id)??null,...r},{onConflict:"brokerage_id"}).select().single();if(i)throw i;return a},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-brand-profile",s]}),n.invalidateQueries({queryKey:["brand-kit"]})}})}function M6s(){const{user:s}=Ns();return mt({queryKey:["brand-kit",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{var m;const t=s.id,[n,r,a,i]=await Promise.all([U.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),U.from("agent_brand_profiles").select("*").eq("user_id",t).maybeSingle(),U.from("agent_cards").select("brokerage_display_name, brokerage_logo_url, team_logo_url, display_email, title, positioning_statement").eq("user_id",t).maybeSingle(),U.from("lead_sites").select("brand_color, accent_color, agent_license_number, license_state, brokerage_legal_name, team_logo_url, is_active, created_at").eq("agent_id",t).order("created_at",{ascending:!0}).limit(5)]),l=n.data??{},o=a.data??{},c=i.data??[],d=c.find(p=>p.is_active)??c[0]??{};let u=null,h=null;if(l.brokerage_id){const[p,x]=await Promise.all([U.from("brokerage_brand_profiles").select("*").eq("brokerage_id",l.brokerage_id).maybeSingle(),U.from("brokerages").select("name").eq("id",l.brokerage_id).maybeSingle()]);u=p.data??null,h=((m=x.data)==null?void 0:m.name)??null}return S6s({agent:r.data??null,brokerage:u,legacy:{name:l.name??null,email:o.display_email||l.email||s.email||null,phone:l.phone??null,avatar_url:l.avatar_url??null,website_url:l.website_url??null,title:l.title??null,brokerage_name:l.brokerage_name||o.brokerage_display_name||d.brokerage_legal_name||h,brokerage_logo_url:o.brokerage_logo_url??null,team_logo_url:o.team_logo_url||d.team_logo_url||null,brand_color:d.brand_color??null,accent_color:d.accent_color??null,license_number:d.agent_license_number??null,license_state:d.license_state??null,tagline:o.positioning_statement??null}})}})}async function fEt(s,t,n){var l;const r=((l=t.name.split(".").pop())==null?void 0:l.toLowerCase())||"png",a=`${s}/brand-${n}-${Date.now()}.${r}`,{error:i}=await U.storage.from("card-logos").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;return U.storage.from("card-logos").getPublicUrl(a).data.publicUrl}const L6s=["Inter","Playfair Display","Montserrat","Poppins","Lora","Work Sans"];function P6s(){const{user:s}=Ns(),{toast:t}=pi(),{data:n,isLoading:r}=C6s(),{data:a}=M6s(),i=A6s(),l=j.useRef(null),[o,c]=j.useState(!1),[d,u]=j.useState({brand_color:"",accent_color:"",logo_url:"",tagline:"",preferred_font:"",license_number:"",license_state:"",website_url:""});j.useEffect(()=>{n&&u({brand_color:n.brand_color||"",accent_color:n.accent_color||"",logo_url:n.logo_url||"",tagline:n.tagline||"",preferred_font:n.preferred_font||"",license_number:n.license_number||"",license_state:n.license_state||"",website_url:n.website_url||""})},[n]);const h=!!(a!=null&&a.locked.colors),m=!!(a!=null&&a.locked.logo),p=(g,b)=>u(v=>({...v,[g]:b})),x=async g=>{if(s){c(!0);try{const b=await fEt(s.id,g,"logo");p("logo_url",b),t({title:"Logo uploaded"})}catch(b){t({title:"Upload failed",description:b.message,variant:"destructive"})}finally{c(!1)}}},y=async()=>{try{await i.mutateAsync({brand_color:d.brand_color||null,accent_color:d.accent_color||null,logo_url:d.logo_url||null,tagline:d.tagline||null,preferred_font:d.preferred_font||null,license_number:d.license_number||null,license_state:d.license_state||null,website_url:d.website_url||null}),t({title:"Brand kit saved"})}catch(g){t({title:"Could not save",description:g.message,variant:"destructive"})}};return e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Ac,{className:"h-5 w-5"}),"Brand Kit"]}),e.jsx(fr,{children:"Used by AI tools (ChatGPT via the LevelUp connector), flyers, presentations and your public pages. Anything you leave blank falls back to your brokerage's brand, then LevelUp defaults."})]}),e.jsx(Re,{className:"space-y-6",children:r?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:["Brand color",h&&e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(du,{className:"h-3 w-3"})," Set by brokerage"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{type:"color",className:"h-10 w-14 p-1",value:d.brand_color||(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:g=>p("brand_color",g.target.value)}),e.jsx(ye,{value:d.brand_color,placeholder:(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:g=>p("brand_color",g.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Accent color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{type:"color",className:"h-10 w-14 p-1",value:d.accent_color||(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:g=>p("accent_color",g.target.value)}),e.jsx(ye,{value:d.accent_color,placeholder:(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:g=>p("accent_color",g.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:["Personal / team logo",m&&e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(du,{className:"h-3 w-3"})," Brokerage logo required"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[d.logo_url&&e.jsx("img",{src:d.logo_url,alt:"Your logo",className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:g=>{var b;return((b=g.target.files)==null?void 0:b[0])&&x(g.target.files[0])}}),e.jsxs(B,{type:"button",variant:"outline",disabled:o||m,onClick:()=>{var g;return(g=l.current)==null?void 0:g.click()},children:[o?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ja,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload logo"})]}),d.logo_url&&e.jsx(B,{type:"button",variant:"ghost",onClick:()=>p("logo_url",""),disabled:m,children:"Remove"})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"brand-tagline",children:"Tagline"}),e.jsx(ye,{id:"brand-tagline",value:d.tagline,placeholder:(a==null?void 0:a.tagline)||"Your positioning statement",onChange:g=>p("tagline",g.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"brand-font",children:"Preferred font"}),e.jsx(ye,{id:"brand-font",list:"brand-font-options",value:d.preferred_font,placeholder:(a==null?void 0:a.heading_font)||"Inter",onChange:g=>p("preferred_font",g.target.value)}),e.jsx("datalist",{id:"brand-font-options",children:L6s.map(g=>e.jsx("option",{value:g},g))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"brand-license",children:"License number"}),e.jsx(ye,{id:"brand-license",value:d.license_number,placeholder:(a==null?void 0:a.license_number)||"DRE #01234567",onChange:g=>p("license_number",g.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"brand-license-state",children:"License state"}),e.jsx(ye,{id:"brand-license-state",value:d.license_state,placeholder:(a==null?void 0:a.license_state)||"CA",onChange:g=>p("license_state",g.target.value)})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(se,{htmlFor:"brand-website",children:"Website"}),e.jsx(ye,{id:"brand-website",value:d.website_url,placeholder:(a==null?void 0:a.website_url)||"https://yoursite.com",onChange:g=>p("website_url",g.target.value)})]})]}),(a==null?void 0:a.compliance_line)&&e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Required disclaimer from your brokerage: "}),a.compliance_line]}),e.jsxs(B,{onClick:y,disabled:i.isPending,children:[i.isPending?e.jsx(Wt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"mr-2 h-4 w-4"}),"Save brand kit"]})]})})]})}const I6s=()=>{const{user:s}=Ns(),{toast:t}=pi(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(null);j.useEffect(()=>{s&&c()},[s]);const c=async()=>{r(!0);try{const{data:h}=await U.from("profiles").select("subscription_status, subscription_product_id, subscription_end_date, is_grandfathered").eq("id",s==null?void 0:s.id).single();h&&o({status:h.subscription_status||"none",productId:h.subscription_product_id,endDate:h.subscription_end_date,isGrandfathered:h.is_grandfathered||!1})}catch(h){console.error("Error loading subscription:",h)}finally{r(!1)}},d=async()=>{i(!0);try{const{data:{session:h}}=await U.auth.getSession();if(!h)throw new Error("Not authenticated");const{data:m,error:p}=await U.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${h.access_token}`}});if(p)throw p;m!=null&&m.url&&window.open(m.url,"_blank")}catch(h){console.error("Error opening customer portal:",h),t({title:"Error",description:h.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},u=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(qe,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(qe,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(qe,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(qe,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(qe,{variant:"secondary",children:"Canceled"});default:return e.jsx(qe,{variant:"outline",children:"No Subscription"})}};return n?e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ty,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Re,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ty,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(fr,{children:"Manage your subscription and billing"})]}),e.jsxs(Re,{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(Wt,{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."})]})]})},R6s=()=>{const{user:s}=Ns(),t=Hn(),{toast:n}=pi(),[r]=dc(),a=r.get("setup")==="true",i=r.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:u}=kCt(),[h,m]=j.useState(!1),[p,x]=j.useState(""),[y,g]=j.useState(!1),[b,v]=j.useState(!1),[k,C]=j.useState(""),[T,M]=j.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}),[P,L]=j.useState(!1),[I,O]=j.useState(!1),[$,q]=j.useState(!1),[W,G]=j.useState(!1),[K,ee]=j.useState(!1),[J,le]=j.useState({newPassword:"",confirmPassword:""});j.useEffect(()=>{s&&ue()},[s]),j.useEffect(()=>{i&&s&&setTimeout(()=>{var je;(je=document.getElementById("change-password-section"))==null||je.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const ue=async()=>{var je,xe,fe,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:Ee,error:Le}=await U.from("profiles").select("name, email, phone, digest_opt_out, event_invite_opt_out, title, bio, areas_served, years_experience, brokerage_id, brokerage_name, instagram_url, facebook_url, linkedin_url, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(Le)throw console.error("Profile query error:",Le),Le;if(Ee){console.log("Profile loaded successfully:",Ee);const Be=((je=Ee.brokerages)==null?void 0:je.name)||"";L(!!Ee.brokerage_id),M({name:Ee.name||"",email:Ee.email||"",phone:Ee.phone||"",title:Ee.title||"",bio:Ee.bio||"",areas_served:Ee.areas_served||"",years_experience:((xe=Ee.years_experience)==null?void 0:xe.toString())||"",brokerage_name:Ee.brokerage_id?Be:Ee.brokerage_name||"",instagram_url:Ee.instagram_url||"",facebook_url:Ee.facebook_url||"",linkedin_url:Ee.linkedin_url||"",email_signature:Ee.email_signature||"",use_email_signature:Ee.use_email_signature||!1}),O(Ee.digest_opt_out||!1),G(Ee.event_invite_opt_out||!1)}else console.warn("No profile found for user"),M({name:((fe=s.user_metadata)==null?void 0:fe.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:De}=await U.storage.from("avatars").list(`${s.id}`);if(De&&De.length>0){const{data:Be}=U.storage.from("avatars").getPublicUrl(`${s.id}/${De[0].name}`);x(Be.publicUrl)}}catch(Ee){console.error("Error loading profile:",Ee),n({title:"Error",description:Ee.message||"Failed to load profile",variant:"destructive"})}},oe=je=>{var Se;const xe=(Se=je.target.files)==null?void 0:Se[0];if(!xe)return;const fe=new FileReader;fe.onloadend=()=>{C(fe.result),v(!0)},fe.readAsDataURL(xe),je.target.value=""},ie=async je=>{if(s){g(!0);try{const{data:xe}=await U.storage.from("avatars").list(`${s.id}`);xe&&xe.length>0&&await U.storage.from("avatars").remove(xe.map(Be=>`${s.id}/${Be.name}`));const Se=`${s.id}/avatar.jpg`,{error:Ee}=await U.storage.from("avatars").upload(Se,je,{upsert:!0,contentType:"image/jpeg"});if(Ee)throw Ee;const{data:Le}=U.storage.from("avatars").getPublicUrl(Se),De=Le.publicUrl;x(`${De}?t=${Date.now()}`),await U.from("profiles").update({avatar_url:De}).eq("id",s.id),n({title:"Success",description:"Profile photo updated successfully"})}catch(xe){console.error("Error uploading avatar:",xe),n({title:"Error",description:xe.message||"Failed to upload photo",variant:"destructive"})}finally{g(!1)}}},de=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:je}=await U.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,...P?{}:{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(je)throw je;n({title:"Success",description:"Profile updated successfully"})}catch(je){console.error("Error updating profile:",je),n({title:"Error",description:je.message||"Failed to update profile",variant:"destructive"})}finally{m(!1)}},we=async()=>{if(!J.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(J.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(J.newPassword!==J.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}m(!0);try{const{error:je}=await U.auth.updateUser({password:J.newPassword});if(je)throw je;n({title:"Success",description:"Password updated successfully"}),le({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(je){console.error("Error updating password:",je),n({title:"Error",description:je.message||"Failed to update password",variant:"destructive"})}finally{m(!1)}};return e.jsx(Vs,{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 je;(je=document.getElementById("change-password-section"))==null||je.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(b3,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Profile Photo"}),e.jsx(fr,{children:"Upload a professional photo for your profile"})]}),e.jsxs(Re,{className:"flex items-center gap-6",children:[e.jsxs(Ra,{className:"h-24 w-24",children:[e.jsx(Fi,{src:p}),e.jsx(Da,{className:"text-2xl",children:T.name.split(" ").map(je=>je[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:oe,disabled:y}),e.jsxs(B,{variant:"outline",onClick:()=>{var je;return(je=document.getElementById("avatar-upload"))==null?void 0:je.click()},disabled:y,children:[e.jsx(Ja,{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(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Personal Information"}),e.jsx(fr,{children:"Update your profile details"})]}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",value:T.name,onChange:je=>M({...T,name:je.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",value:T.email,onChange:je=>M({...T,email:je.target.value}),maxLength:255})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"phone",children:"Phone Number"}),e.jsx(ye,{id:"phone",type:"tel",value:T.phone,onChange:je=>M({...T,phone:je.target.value}),placeholder:"e.g., +14155551234",maxLength:20}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used for SMS lead notifications from your website — if you have a local authority site"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Job Title"}),e.jsx(ye,{id:"title",value:T.title,onChange:je=>M({...T,title:je.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"bio",children:"Bio"}),e.jsx(Ds,{id:"bio",value:T.bio,onChange:je=>M({...T,bio:je.target.value}),placeholder:"A short description about yourself",maxLength:500,className:"min-h-[120px] resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(ye,{id:"areas_served",value:T.areas_served,onChange:je=>M({...T,areas_served:je.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(ye,{id:"years_experience",type:"number",min:"0",value:T.years_experience,onChange:je=>M({...T,years_experience:je.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"brokerage_name",children:["Brokerage ",P&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(ye,{id:"brokerage_name",value:T.brokerage_name,onChange:je=>M({...T,brokerage_name:je.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:P,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:P?"Your brokerage is managed by your office and can't be changed here.":"Used as your brokerage name across ReelFlow, branding, and email signatures."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(ye,{value:T.linkedin_url,onChange:je=>M({...T,linkedin_url:je.target.value}),placeholder:"LinkedIn URL"}),e.jsx(ye,{value:T.instagram_url,onChange:je=>M({...T,instagram_url:je.target.value}),placeholder:"Instagram URL"}),e.jsx(ye,{value:T.facebook_url,onChange:je=>M({...T,facebook_url:je.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs(B,{onClick:de,disabled:h,children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(sN,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(fr,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Re,{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(Mn,{checked:T.use_email_signature,onCheckedChange:je=>M({...T,use_email_signature:je})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Signature"}),e.jsx(Kj,{content:T.email_signature,onChange:je=>M({...T,email_signature:je}),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:de,disabled:h,children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsx(P6s,{}),e.jsxs(be,{id:"change-password-section",children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:a?"Set Your Password":"Change Password"}),e.jsx(fr,{children:a?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"newPassword",children:"New Password"}),e.jsx(ye,{id:"newPassword",type:"password",value:J.newPassword,onChange:je=>le({...J,newPassword:je.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(ye,{id:"confirmPassword",type:"password",value:J.confirmPassword,onChange:je=>le({...J,confirmPassword:je.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(B,{onClick:we,disabled:h,children:[e.jsx(Jo,{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(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[o?e.jsx(Nx,{className:"h-5 w-5"}):e.jsx(L5,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(fr,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Re,{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(Mn,{checked:o,onCheckedChange:je=>{je?d():u()},disabled:c})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsx(k6s,{}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[I?e.jsx(W9,{className:"h-5 w-5"}):e.jsx(on,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(fr,{children:"Manage your email subscription settings"})]}),e.jsxs(Re,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:I?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(Mn,{checked:!I,onCheckedChange:async je=>{q(!0);try{const{error:xe}=await U.from("profiles").update({digest_opt_out:!je}).eq("id",s==null?void 0:s.id);if(xe)throw xe;O(!je),n({title:je?"Subscribed":"Unsubscribed",description:je?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(xe){n({title:"Error",description:xe.message||"Failed to update preference",variant:"destructive"})}finally{q(!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(Mn,{checked:!W,onCheckedChange:async je=>{ee(!0);try{const{error:xe}=await U.from("profiles").update({event_invite_opt_out:!je}).eq("id",s==null?void 0:s.id);if(xe)throw xe;G(!je),n({title:je?"Subscribed":"Unsubscribed",description:je?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(xe){n({title:"Error",description:xe.message||"Failed to update preference",variant:"destructive"})}finally{ee(!1)}},disabled:K})]})]})]}),e.jsx(m5s,{}),e.jsx(I6s,{})]}),e.jsx(xHe,{open:b,onClose:()=>v(!1),imageSrc:k,onCropComplete:ie,aspectRatio:1})]})})};var D6s="AspectRatio",xEt=j.forwardRef((s,t)=>{const{ratio:n=1/1,style:r,...a}=s;return e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:`${100/n}%`},"data-radix-aspect-ratio-wrapper":"",children:e.jsx(Ua.div,{...a,ref:t,style:{...r,position:"absolute",top:0,right:0,bottom:0,left:0}})})});xEt.displayName=D6s;var O6s=xEt;const F6s=O6s;function z6s(){const{user:s}=Ns(),t=as(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),{data:l,isLoading:o}=mt({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:x,error:y}=await U.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(y)throw y;return x},enabled:!!s&&a}),c=vt({mutationFn:async()=>{const x=new Uint8Array(12);crypto.getRandomValues(x);const y=btoa(String.fromCharCode(...x)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:g}=await U.from("profiles").update({calendar_token:y}).eq("id",s==null?void 0:s.id);if(g)throw g;return y},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),re.success("Calendar subscription URL generated!")},onError:x=>{re.error("Failed to generate calendar URL: "+x.message)}}),d=l!=null&&l.calendar_token?`https://dashboard.relevelup.com/api/calendar/${l.calendar_token}.ics`:null,u=async()=>{d&&(await navigator.clipboard.writeText(d),r(!0),re.success("Calendar URL copied to clipboard!"),setTimeout(()=>r(!1),2e3))},h=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},m=()=>{if(d){const x=d.replace("https://","webcal://"),y=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(x)}`;window.open(y,"_blank")}},p=()=>{if(d){const x=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(x,"_blank")}};return e.jsxs(Fs,{open:a,onOpenChange:i,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(ra,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(ra,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(kr,{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(Wt,{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(ye,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx(B,{variant:"outline",size:"icon",onClick:u,children:n?e.jsx(da,{className:"h-4 w-4 text-green-500"}):e.jsx(ja,{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:p,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M7.88 12.04q0 .45-.11.87-.1.41-.33.74-.22.33-.58.52-.37.2-.87.2t-.85-.2q-.35-.21-.57-.55-.22-.33-.33-.75-.1-.42-.1-.86t.1-.87q.1-.43.34-.76.22-.34.59-.54.36-.2.87-.2t.86.2q.35.21.57.55.22.34.31.77.1.43.1.88zM24 12v9.38q0 .46-.33.8-.33.32-.8.32H7.13q-.46 0-.8-.33-.32-.33-.32-.8V18H1q-.41 0-.7-.3-.3-.29-.3-.7V7q0-.41.3-.7Q.58 6 1 6h6.5V2.55q0-.44.3-.75.3-.3.75-.3h12.9q.44 0 .75.3.3.3.3.75V12zm-6-8.25v3h3v-3zm0 4.5v3h3v-3zm0 4.5v1.83l3.05-1.83zm-5.25-9v3h3.75v-3zm0 4.5v3h3.75v-3zm0 4.5v2.03l2.41 1.5 1.34-.81v-2.72zM9 3.75V6h2l.13.01.12.04v-2.3zM5.98 15.98q.9 0 1.6-.3.7-.32 1.19-.86.48-.55.73-1.28.25-.74.25-1.61 0-.83-.25-1.55-.24-.71-.71-1.24t-1.15-.83q-.68-.3-1.55-.3-.92 0-1.64.3-.71.3-1.2.85-.5.54-.75 1.3-.25.74-.25 1.63 0 .85.26 1.56.26.72.74 1.23.48.52 1.17.81.69.3 1.56.3zM7.5 21h12.39L12 16.08V17q0 .41-.3.7-.29.3-.7.3H7.5zm15-.13v-7.24l-5.9 3.54Z"})}),"Add to Outlook",e.jsx(Tr,{className:"h-3 w-3 ml-auto opacity-50"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center pt-2",children:"Events sync automatically. If your membership expires, the calendar will show as empty."})]}):e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate your personal calendar subscription URL to get started."}),e.jsx(B,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ra,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const B6s={first_timer:Wa,regular:_3,dedicated:cu,veteran:ll,streak_master:Fd,century:ll},$6s={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 Iot(s){return s===1?e.jsx(ll,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(_3,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(cu,{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 gEt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=Ns(),{data:i,isLoading:l}=sAt(t?5:10,n),{data:o}=nAt(a==null?void 0:a.id),{data:c}=aAt(a==null?void 0:a.id),{data:d}=rAt(a==null?void 0:a.id);return l?e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ll,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsx(Re,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,h)=>e.jsx(gn,{className:"h-12 w-full"},h))})})]}):e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ll,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsxs(Re,{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(qe,{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(Fd,{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=B6s[u.badge_type]||Wa;return e.jsxs(qe,{variant:"outline",className:`text-xs ${$6s[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(qe,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(fa,{defaultValue:"points",className:"w-full",children:[e.jsxs(xa,{className:"w-full mb-3",children:[e.jsx(ss,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(ss,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(ns,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,h)=>{var m,p,x;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:Iot(h+1)}),e.jsx(Ra,{className:"h-8 w-8",children:e.jsx(Da,{className:"text-xs",children:((p=(m=u.profile)==null?void 0:m.name)==null?void 0:p.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((x=u.profile)==null?void 0:x.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_events_attended," events"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold text-primary",children:u.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"pts"})]})]},u.user_id)}),(!i||i.length===0)&&e.jsx("div",{className:"text-center text-muted-foreground py-4 text-sm",children:"No attendance data yet. Attend an event to get on the leaderboard!"})]})}),e.jsx(ns,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((u,h)=>h.total_events_attended-u.total_events_attended).map((u,h)=>{var m,p,x;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:Iot(h+1)}),e.jsx(Ra,{className:"h-8 w-8",children:e.jsx(Da,{className:"text-xs",children:((p=(m=u.profile)==null?void 0:m.name)==null?void 0:p.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((x=u.profile)==null?void 0:x.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_points," points"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold",children:u.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"events"})]})]},u.user_id)})})})]})]})]})}function U6s(){const s=Hn(),{user:t,isAdmin:n}=Ns(),r=as(),{data:a,isLoading:i}=mt({queryKey:["public-events"],queryFn:async()=>{const{data:y,error:g}=await U.from("events").select("*").order("event_date",{ascending:!0});if(g)throw g;return y}}),{data:l}=mt({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:y,error:g}=await U.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(g)throw g;return y},enabled:!!t}),{data:o}=mt({queryKey:["event-registration-counts"],queryFn:async()=>{let y=[],g=0;const b=1e3;for(;;){const{data:k,error:C}=await U.from("event_registrations").select("event_id").range(g,g+b-1);if(C)throw C;if(!k||k.length===0||(y=y.concat(k),k.length{v[k.event_id]=(v[k.event_id]||0)+1}),v}}),c=vt({mutationFn:async y=>{await U.auth.refreshSession();const{data:g,error:b}=await U.functions.invoke("zoom-register",{body:{event_id:y}});if(b)throw b;if(g!=null&&g.error)throw new Error(g.error);return g},onSuccess:y=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),y!=null&&y.join_url?re.success("Successfully registered! You'll receive a Zoom confirmation email."):re.success("Successfully registered for the event!")},onError:y=>{re.error("Failed to register: "+y.message)}}),d=vt({mutationFn:async y=>{const{data:g,error:b}=await U.functions.invoke("zoom-unregister",{body:{event_id:y}});if(b)throw b;if(g!=null&&g.error)throw new Error(g.error);return g},onSuccess:()=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),re.success("Registration cancelled and removed from Zoom")},onError:y=>{re.error("Failed to cancel: "+y.message)}}),u=y=>l==null?void 0:l.some(g=>g.event_id===y),h=y=>{const g=l==null?void 0:l.find(b=>b.event_id===y);return g==null?void 0:g.zoom_join_url},m=y=>y.capacity?((o==null?void 0:o[y.id])||0)>=y.capacity:!1,p=(a==null?void 0:a.filter(y=>Nz(y.event_date)!=="ended"))||[],x=(a==null?void 0:a.filter(y=>Nz(y.event_date)==="ended"))||[];return e.jsx(Vs,{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(z6s,{}),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..."}):p.length===0?e.jsx(be,{className:"text-center py-12",children:e.jsx(Re,{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:p.map(y=>{const g=Nz(y.event_date),b=bVe(y.event_date),v=g==="live",k=g==="starting_soon";return e.jsxs(be,{className:`flex flex-col overflow-hidden cursor-pointer hover:shadow-lg transition-all ${v?"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:[b&&e.jsxs("div",{className:`${v?"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"})]}),v?e.jsxs(e.Fragment,{children:[e.jsx(iy,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(Vr,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),y.image_url&&e.jsxs(F6s,{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(Ft,{children:[e.jsx(Ut,{className:"line-clamp-2",children:y.title}),y.description&&e.jsx(fr,{className:"line-clamp-2",children:y.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Re,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ra,{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(Vr,{className:"h-4 w-4"}),rZ(new Date(y.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Bn,{className:"h-4 w-4"}),(o==null?void 0:o[y.id])||0," registered",y.capacity&&` / ${y.capacity} spots`]})]}),e.jsx(MK,{className:"flex gap-2",onClick:C=>C.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(dr,{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(da,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},y.id)})}),x.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:x.map(y=>e.jsx(be,{className:"opacity-60 cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>s(`/events/${y.id}`),children:e.jsxs(Ft,{children:[e.jsx(Ut,{className:"text-base line-clamp-1",children:y.title}),e.jsx(fr,{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(gEt,{showUserStats:!0})})]})]})})}const FLe=[{value:"all",label:"All Roles",icon:Bn},{value:"newest",label:"Newest Members",icon:Vr},{value:"brokerage_manager",label:"Brokerage Managers",icon:gK},{value:"admin",label:"Admins",icon:_f}];function q6s({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var De,Be;const{user:i,isAdmin:l,isBrokerageManager:o}=Ns(),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,p]=j.useState([]),[x,y]=j.useState([]),[g,b]=j.useState(""),[v,k]=j.useState(""),[C,T]=j.useState(""),[M,P]=j.useState(!1),[L,I]=j.useState(!1),[O,$]=j.useState("agents"),[q,W]=j.useState("all"),[G,K]=j.useState({}),ee=l||o;j.useEffect(()=>{s&&i&&(l?J():le())},[s,i,l]),j.useEffect(()=>{s||(p([]),y([]),b(""),k(""),T(""),$("agents"),W("all"))},[s]);const J=async()=>{if(i){P(!0);try{const{data:Ne,error:Ge}=await U.from("brokerages").select("id, name").order("name");if(Ge)throw Ge;const _e=1e3,Oe={};let Ae=0,Xe=!0;for(;Xe;){const{data:Qe,error:Ye}=await U.from("profiles").select("brokerage_id").range(Ae*_e,(Ae+1)*_e-1);if(Ye)throw Ye;Qe==null||Qe.forEach(nt=>{nt.brokerage_id&&(Oe[nt.brokerage_id]=(Oe[nt.brokerage_id]||0)+1)}),Xe=(Qe==null?void 0:Qe.length)===_e,Ae++}h((Ne==null?void 0:Ne.map(Qe=>({...Qe,agent_count:Oe[Qe.id]||0})))||[]);const Ue=[];for(Ae=0,Xe=!0;Xe;){const{data:Qe,error:Ye}=await U.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Ae*_e,(Ae+1)*_e-1);if(Ye)throw Ye;Qe&&Ue.push(...Qe),Xe=(Qe==null?void 0:Qe.length)===_e,Ae++}const Ze={};for(Ae=0,Xe=!0;Xe;){const{data:Qe,error:Ye}=await U.from("user_roles").select("user_id, role").range(Ae*_e,(Ae+1)*_e-1);if(Ye)throw Ye;Qe==null||Qe.forEach(nt=>{Ze[nt.user_id]||(Ze[nt.user_id]=[]),Ze[nt.user_id].push(nt.role)}),Xe=(Qe==null?void 0:Qe.length)===_e,Ae++}K(Ze),d(Ue.map(Qe=>{var Ye;return{id:Qe.id,name:Qe.name,email:Qe.email,brokerage_name:((Ye=Qe.brokerages)==null?void 0:Ye.name)||"No Brokerage",roles:Ze[Qe.id]||[],created_at:Qe.created_at}}))}catch(Ne){console.error("Error loading data:",Ne),re.error("Failed to load agents and brokerages")}finally{P(!1)}}},le=async()=>{if(i){P(!0);try{const{data:Ne}=await U.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(Ne!=null&&Ne.brokerage_id)){re.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Ge,error:_e}=await U.from("profiles").select("id, name, email").eq("brokerage_id",Ne.brokerage_id).neq("id",i.id).order("name");if(_e)throw _e;d(Ge||[])}catch(Ne){console.error("Error loading agents:",Ne),re.error("Failed to load agents")}finally{P(!1)}}},ue=c.filter(Ne=>{var _e;const Ge=Ne.name.toLowerCase().includes(g.toLowerCase())||Ne.email.toLowerCase().includes(g.toLowerCase())||((_e=Ne.brokerage_name)==null?void 0:_e.toLowerCase().includes(g.toLowerCase()));if(l&&q!=="all"&&q!=="newest"){const Oe=G[Ne.id]||[];return Ge&&Oe.includes(q)}return Ge}).sort((Ne,Ge)=>q==="newest"?(Ge.created_at||"").localeCompare(Ne.created_at||""):0),oe=u.filter(Ne=>Ne.name.toLowerCase().includes(v.toLowerCase())),ie=()=>{m.length===ue.length?p([]):p(ue.map(Ne=>Ne.id))},de=()=>{x.length===oe.length?y([]):y(oe.map(Ne=>Ne.id))},we=Ne=>{if(!ee){p([Ne]);return}p(Ge=>Ge.includes(Ne)?Ge.filter(_e=>_e!==Ne):[...Ge,Ne])},je=Ne=>{y(Ge=>Ge.includes(Ne)?Ge.filter(_e=>_e!==Ne):[...Ge,Ne])},xe=async()=>{if(!(m.length>0||x.length>0)){re.error("Please select at least one agent or brokerage to share with");return}I(!0);try{const{data:Ge,error:_e}=await U.functions.invoke("send-share-notification",{body:{recipientIds:m,brokerageIds:x,resourceType:n,resourceId:r,resourceTitle:a,message:C.trim()||void 0}});if(_e)throw _e;const Oe=(Ge==null?void 0:Ge.sharesCreated)||m.length;re.success(`Shared with ${Oe} agent${Oe!==1?"s":""}`),t(!1)}catch(Ge){console.error("Error sharing resource:",Ge),re.error("Failed to share resource")}finally{I(!1)}},fe=Ne=>Ne.split(" ").map(Ge=>Ge[0]).join("").toUpperCase().slice(0,2),Se=Ne=>{const Ge=G[Ne]||[];return Ge.includes("admin")?e.jsx(qe,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Ge.includes("brokerage_manager")?e.jsx(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},Ee=m.length+x.length,Le=q!=="all"&&q!=="newest"?ue.length:null;return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs($s,{className:"flex-shrink-0",children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(kr,{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(fa,{value:O,onValueChange:$,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(xa,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(ss,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),m.length>0&&e.jsx(qe,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:m.length})]}),e.jsxs(ss,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(Ni,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),x.length>0&&e.jsx(qe,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:x.length})]})]}),e.jsxs(ns,{value:"agents",className:"flex-1 flex flex-col space-y-3 mt-3 overflow-hidden",children:[e.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or brokerage...",value:g,onChange:Ne=>b(Ne.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:q,onValueChange:W,children:[e.jsxs(gs,{className:"w-[180px]",children:[e.jsx(Nj,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(bs,{placeholder:"Filter by role"})]}),e.jsx(ys,{children:FLe.map(Ne=>e.jsx(Je,{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:ie,className:"text-xs h-8",disabled:ue.length===0,children:[e.jsx(Bn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===ue.length&&ue.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Le!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Le," ",(De=FLe.find(Ne=>Ne.value===q))==null?void 0:De.label]}),e.jsxs("span",{className:"font-medium",children:[m.length," selected"]})]})]}),e.jsx(lo,{className:"h-[300px] border rounded-lg",children:M?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ue.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Bn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:q!=="all"?`No ${(Be=FLe.find(Ne=>Ne.value===q))==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:()=>we(Ne.id),children:[e.jsx(wi,{checked:m.includes(Ne.id),onCheckedChange:()=>we(Ne.id),className:"flex-shrink-0"}),e.jsx(Ra,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Da,{className:"text-xs bg-primary/10 text-primary",children:fe(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(ns,{value:"brokerages",className:"flex-1 flex flex-col space-y-3 mt-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search brokerages...",value:v,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:de,className:"text-xs h-8",disabled:oe.length===0,children:[e.jsx(Ni,{className:"h-3.5 w-3.5 mr-1.5"}),x.length===oe.length&&oe.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[x.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground px-1 flex-shrink-0",children:"Selecting a brokerage will send to all agents in that brokerage."}),e.jsx(lo,{className:"h-[250px] border rounded-lg",children:M?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):oe.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(Ni,{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:oe.map(Ne=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${x.includes(Ne.id)?"bg-accent":""}`,onClick:()=>je(Ne.id),children:[e.jsx(wi,{checked:x.includes(Ne.id),onCheckedChange:()=>je(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(Ni,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:g,onChange:Ne=>b(Ne.target.value),className:"pl-9"})]}),ee&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:ie,className:"text-xs h-8",disabled:ue.length===0,children:[e.jsx(Bn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===ue.length&&ue.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[m.length," selected"]})]}),e.jsx(lo,{className:"h-[300px] border rounded-lg",children:M?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ue.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Bn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ue.map(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:()=>we(Ne.id),children:[e.jsx(wi,{checked:m.includes(Ne.id),onCheckedChange:()=>we(Ne.id),className:"flex-shrink-0"}),e.jsx(Ra,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Da,{className:"text-xs bg-primary/10 text-primary",children:fe(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(se,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(Ds,{id:"message",placeholder:"I thought you might find this useful...",value:C,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:xe,disabled:Ee===0||L,children:L?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function rq({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=j.useState(!1),{user:c}=Ns();return c?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(zd,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(q6s,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function V6s(){const{eventId:s}=$i(),t=Hn(),{user:n}=Ns(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(0),[d,u]=j.useState(!0),[h,m]=j.useState(!1);j.useEffect(()=>{s&&p()},[s,n]);const p=async()=>{try{const{data:k,error:C}=await U.from("events").select("*").eq("id",s).single();if(C)throw C;a(k);const{count:T}=await U.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(T||0),n){const{data:M}=await U.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",n.id).maybeSingle();l(M)}}catch(k){console.error("Error loading event:",k),re.error("Failed to load event"),t("/events")}finally{u(!1)}},x=async()=>{if(!(!n||!r)){m(!0);try{const{error:k}=await U.auth.refreshSession();if(k){console.error("Session refresh failed:",k),re.error("Your session has expired. Please log in again.");return}if(i){const{error:C}=await U.functions.invoke("zoom-unregister",{body:{event_id:r.id}});if(C)throw C;re.success("Successfully cancelled registration"),l(null),c(T=>T-1)}else{const{data:C,error:T}=await U.functions.invoke("zoom-register",{body:{event_id:r.id}});if(T)throw T;re.success("Successfully registered for event!"),l({id:C.registration_id,zoom_join_url:C.zoom_join_url}),c(M=>M+1)}}catch(k){console.error("Registration error:",k),re.error(i?"Failed to cancel registration":"Failed to register for event")}finally{m(!1)}}},y=k=>{var C,T,M;if(k.includes("iframe.mediadelivery.net")||k.includes("video.bunnycdn.com")){const P=k.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(P)return`https://iframe.mediadelivery.net/embed/${P[1]}/${P[2]}?autoplay=false&preload=true`}if(k.includes("youtube.com")||k.includes("youtu.be")){const P=k.includes("youtu.be")?(C=k.split("youtu.be/")[1])==null?void 0:C.split("?")[0]:(T=k.split("v=")[1])==null?void 0:T.split("&")[0];if(P)return`https://www.youtube.com/embed/${P}`}if(k.includes("vimeo.com")){const P=(M=k.split("vimeo.com/")[1])==null?void 0:M.split("?")[0];if(P)return`https://player.vimeo.com/video/${P}`}return k};if(d)return e.jsx(Vs,{title:"Event",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading event..."})]})})});if(!r)return e.jsx(Vs,{title:"Event Not Found",children:e.jsxs("div",{className:"text-center py-16",children:[e.jsx("p",{className:"text-muted-foreground",children:"Event not found"}),e.jsx(B,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const g=F5(new Date(r.event_date)),b=r.capacity&&o>=r.capacity,v=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx(Vs,{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(_a,{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"}),g&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(qe,{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(rq,{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(vh,{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(be,{children:e.jsxs(Re,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ra,{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:rZ(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Bn,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[o," / ",r.capacity]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Registered"})]})]}),i&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-500/10 rounded-lg",children:[e.jsx(To,{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:[!g&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"w-full gap-2",onClick:()=>window.open(v,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:x,disabled:h,children:[h?e.jsx(Wt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(B,{className:"w-full gap-2",onClick:x,disabled:h||(b??!1),children:h?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):b?"Event Full":"Register Now"})}),g&&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 H6s=[{to:"/apps",label:"Home",end:!0},{to:"/apps/my-apps",label:"My Apps"},{to:"/apps/browse",label:"Browse Apps"},{to:"/apps/workflows",label:"Workflows",adminOnly:!0},{to:"/apps/connected",label:"Connected Apps"}];function G6s(){const{isAdmin:s}=Ns(),t=H6s.filter(n=>!n.adminOnly||s);return e.jsx("div",{className:"-mx-4 px-4 sm:mx-0 sm:px-0 overflow-x-auto scrollbar-hide",children:e.jsx("nav",{className:"inline-flex gap-1 bg-muted/60 p-1 rounded-xl min-w-max",children:t.map(n=>e.jsx(KC,{to:n.to,end:n.end,className:({isActive:r})=>Et("px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-colors",r?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:n.label},n.to))})})}const $ke=[{id:"market-listing",title:"Market a Listing",blurb:"Presentations, copy, pages and video",icon:ia,color:"bg-violet-500/15 text-violet-600"},{id:"follow-up",title:"Follow Up With My Database",blurb:"Emails, cards, mail and check-ins",icon:on,color:"bg-emerald-500/15 text-emerald-600"},{id:"social-content",title:"Create Social Content",blurb:"Reels, posts and captions",icon:jh,color:"bg-rose-500/15 text-rose-600"},{id:"open-house",title:"Host an Open House",blurb:"Promote, sign in and follow up",icon:wj,color:"bg-sky-500/15 text-sky-600"},{id:"new-business",title:"Generate New Business",blurb:"Leads, expireds and by-owner sellers",icon:kl,color:"bg-amber-500/15 text-amber-600"},{id:"brand",title:"Build My Brand",blurb:"Your card, site, reviews and presence",icon:Ac,color:"bg-teal-500/15 text-teal-600"}];$ke.reduce((s,t)=>({...s,[t.id]:t}),{});const W6s=[{id:"listings",label:"Listings"},{id:"database",label:"Database & Follow-Up"},{id:"leads",label:"Leads & Conversion"},{id:"social",label:"Social & Content"},{id:"open-houses",label:"Open Houses"},{id:"brand",label:"Brand & Presence"},{id:"ai",label:"AI Assistants"}],yEt=[{id:"scheduler",name:"LevelUp Scheduler",description:"Share your booking link, sync Google Calendar and let clients book you",icon:ym,path:"/mission-control/scheduler",color:"bg-blue-500/15 text-blue-600",adminOnly:!0,isNew:!0,goals:["follow-up","new-business","brand"],categories:["database","leads","brand"],keywords:["scheduler","calendar","booking link","book a meeting","appointments","calendly","availability"]},{id:"quickvid",name:"QuickVid",description:"Record and share personalized video messages",icon:Zr,path:"/mission-control/video/record",color:"bg-rose-500/15 text-rose-600",popular:!0,goals:["follow-up","social-content","open-house"],categories:["database","social","open-houses"],keywords:["video","record a video","send a video","video email","screen record"]},{id:"smart-card",name:"Smart Card",description:"Your digital business card in one shareable link",icon:ty,path:"/mission-control/my-card",color:"bg-sky-500/15 text-sky-600",goals:["brand"],categories:["brand"],keywords:["business card","digital card","share my info","contact card"]},{id:"smart-presentations",name:"Smart Presentations",description:"Beautiful listing and buyer presentations",icon:yb,path:"/mission-control/presentations",color:"bg-amber-500/15 text-amber-600",goals:["market-listing","brand"],categories:["listings","brand"],keywords:["buyer presentation","listing presentation","pitch","slides"]},{id:"landing-pages",name:"Landing Pages",description:"Custom landing pages that capture leads",icon:$r,path:"/mission-control/landing-pages",color:"bg-emerald-500/15 text-emerald-600",goals:["market-listing","new-business","open-house"],categories:["listings","leads","open-houses"],keywords:["landing page","capture leads","promote an open house","single property site"]},{id:"guest-book",name:"Guest Book",description:"Digital open house sign-in that captures visitors",icon:Op,path:"/mission-control/guest-book",color:"bg-orange-500/15 text-orange-600",popular:!0,goals:["open-house","new-business"],categories:["open-houses","leads"],keywords:["open house sign in","sign-in sheet","visitors","host an open house"]},{id:"card-studio",name:"Card Studio",description:"Animated cards for birthdays and milestones",icon:yn,path:"/mission-control/card-studio",color:"bg-pink-500/15 text-pink-600",goals:["follow-up","social-content"],categories:["database","social"],keywords:["birthday card","anniversary","greeting","thank you card"]},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts",icon:on,path:"/mission-control/direct-mail",color:"bg-indigo-500/15 text-indigo-600",adminOnly:!0,beta:!0,goals:["follow-up","open-house"],categories:["database","open-houses"],keywords:["postcard","mailer","farming","direct mail"]},{id:"reelflow",name:"ReelFlow",description:"Turn property photos into cinematic reels with AI",icon:wh,path:"/admin/beta/homereel",color:"bg-violet-500/15 text-violet-600",beta:!0,isNew:!0,goals:["market-listing","social-content"],categories:["listings","social","ai"],keywords:["create a reel","video from photos","instagram","cinematic"]},{id:"mass-emails",name:"Mass Emails",description:"Send bulk email campaigns to your contacts",icon:Dr,path:"/admin/email-campaigns",color:"bg-teal-500/15 text-teal-600",beta:!0,goals:["follow-up","open-house"],categories:["database","open-houses"],keywords:["email my database","bulk email","campaign","blast","invite"]},{id:"listing-studio",name:"Listing Studio",description:"AI MLS descriptions, luxury copy and open house blurbs",icon:sN,path:"/mission-control/listing-studio",color:"bg-fuchsia-500/15 text-fuchsia-600",isNew:!0,goals:["market-listing","social-content"],categories:["listings","social","ai"],keywords:["mls description","write listing copy","captions","ai writing"]},{id:"website-apps",name:"Website Apps",description:"Drop-in conversion widgets for your website",icon:Q9,path:"/website-apps",color:"bg-cyan-500/15 text-cyan-600",isNew:!0,goals:["new-business","brand"],categories:["leads","brand"],keywords:["website widget","video greeter","lead magnet","pop up"]},{id:"newsletter-pro",name:"Newsletter Pro",description:"Branded newsletters for your database",icon:V_,path:"/newsletters",color:"bg-yellow-500/15 text-yellow-600",goals:["follow-up"],categories:["database"],keywords:["newsletter","monthly email","market update"]},{id:"weekly-reels",name:"Weekly Reels",description:"5 personalized Reel scripts every Monday morning",icon:wh,path:"/weekly-reels",color:"bg-orange-500/15 text-orange-600",isNew:!0,requiresWeeklyReels:!0,goals:["social-content"],categories:["social","ai"],keywords:["reel scripts","instagram","content ideas","social posts"]},{id:"cma",name:"CMA Reports",description:"Interactive CMAs with live comps you can share",icon:ol,path:"/mission-control/cma",color:"bg-blue-500/15 text-blue-600",isNew:!0,requiresLeadSiteMLS:!0,goals:["market-listing","new-business"],categories:["listings","leads"],keywords:["cma","comps","home value","pricing"]},{id:"listing-presentation-studio",name:"Listing Presentation Studio",description:"A branded 12-page seller presentation in minutes",icon:yb,path:"/apps/listing-presentation-studio",color:"bg-emerald-500/15 text-emerald-600",isNew:!0,popular:!0,goals:["market-listing"],categories:["listings"],keywords:["make a listing presentation","seller presentation","pdf","pre-listing"]},{id:"listing-revival",name:"Listing Revival",description:"Turn expired listings into appointments",icon:yn,path:"/apps/listing-revival",color:"bg-amber-500/15 text-amber-600",isNew:!0,goals:["new-business"],categories:["leads","listings","ai"],keywords:["expired listing","expired","withdrawn","revival letter"]},{id:"fsbo-breakthrough",name:"By-Owner Breakthrough",description:"Convert FSBO sellers with letters, guides and pages",icon:ia,path:"/apps/fsbo-breakthrough",color:"bg-[#5b8a5c]/15 text-[#5b8a5c]",isNew:!0,goals:["new-business"],categories:["leads","ai"],keywords:["fsbo","for sale by owner","by owner","convert fsbo"]}],Rot=yEt.reduce((s,t)=>({...s,[t.id]:t}),{}),K6s={agent_review:{goals:["brand","new-business"],categories:["brand","leads"],keywords:["reviews","get more reviews","testimonials","reputation"]},sigflow:{goals:["brand","follow-up"],categories:["brand","database"],keywords:["email signature","signature","branding"]},social_autopilot:{goals:["social-content","brand"],categories:["social","brand"],keywords:["social posts","schedule posts","autopilot","facebook","instagram"]},ai_agents:{goals:["new-business","follow-up"],categories:["ai","leads"],keywords:["ai assistant","chatbot","lead response","ai agent"]}};function Y6s(s){return K6s[s]??{goals:[],categories:[],keywords:[]}}const gHe=[{id:"new-listing-launch",title:"New Listing Launch",description:"Everything you need to take a new listing to market.",outcome:"A listing that is presented, promoted and seen",namePrompt:"What listing is this for?",namePlaceholder:"520 Harlan Drive",icon:ia,color:"bg-violet-500/15 text-violet-600",steps:[{key:"presentation",title:"Build the listing presentation",detail:"Create your branded seller presentation.",toolId:"listing-presentation-studio"},{key:"copy",title:"Write the listing copy",detail:"Generate the MLS description and marketing copy.",toolId:"listing-studio"},{key:"page",title:"Create the property page",detail:"Publish a landing page for the listing.",toolId:"landing-pages"},{key:"reel",title:"Make a reel",detail:"Turn the photos into a cinematic video.",toolId:"reelflow"},{key:"email",title:"Email your database",detail:"Announce the listing to your contacts.",toolId:"mass-emails"},{key:"video",title:"Send a personal video",detail:"Record a quick note for your top contacts.",toolId:"quickvid"}]},{id:"open-house-success",title:"Open House Success Kit",description:"Plan, promote, capture visitors, and follow up.",outcome:"A full open house with every visitor captured",namePrompt:"Which open house is this for?",namePlaceholder:"Sunday open house — 12 Oak St",icon:wj,color:"bg-sky-500/15 text-sky-600",steps:[{key:"page",title:"Build the open house page",detail:"Create a page with the date, time and details.",toolId:"landing-pages"},{key:"invite",title:"Invite your database",detail:"Send the invitation email.",toolId:"mass-emails"},{key:"signin",title:"Set up sign-in",detail:"Turn on the digital guest book for the event.",toolId:"guest-book"},{key:"followup",title:"Follow up with visitors",detail:"Send a personal video to everyone who came.",toolId:"quickvid"}]},{id:"database-touchpoint",title:"Database Touchpoint",description:"Get a valuable message in front of your whole database.",outcome:"Your sphere hears from you this month",namePrompt:"What month or theme is this for?",namePlaceholder:"August market update",icon:Bn,color:"bg-emerald-500/15 text-emerald-600",steps:[{key:"pick",title:"Pick your message",detail:"Start from a newsletter or market update.",toolId:"newsletter-pro"},{key:"personal",title:"Add a personal touch",detail:"Record a short video intro.",toolId:"quickvid"},{key:"send",title:"Send it out",detail:"Deliver it to your contacts.",toolId:"mass-emails"},{key:"cards",title:"Celebrate milestones",detail:"Send cards to anyone with a milestone this month.",toolId:"card-studio"}]}],zD=gHe.reduce((s,t)=>({...s,[t.id]:t}),{});function Z6s({goal:s,onSelect:t}){const n=s.icon;return e.jsxs("button",{type:"button",onClick:()=>t(s),className:"group text-left bg-card border border-border rounded-2xl p-5 transition-all hover:border-primary/40 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:[e.jsx("div",{className:Et("w-12 h-12 rounded-xl flex items-center justify-center mb-4",s.color),children:e.jsx(n,{className:"h-6 w-6"})}),e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.blurb})]})}function X6s({item:s,isFavorite:t,onOpen:n,onToggleFavorite:r}){const a=typeof s.icon=="string"?null:s.icon,i=s.isNew?{label:"New",className:"bg-primary/10 text-primary"}:s.beta?{label:"Beta",className:"bg-amber-500/15 text-amber-600"}:s.popular?{label:"Popular",className:"bg-emerald-500/15 text-emerald-600"}:s.kind==="app"?{label:"Connected",className:"bg-muted text-muted-foreground"}:null;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>n(s),onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),n(s))},className:"group h-full text-left bg-card border border-border rounded-2xl p-5 flex flex-col gap-3 cursor-pointer transition-all hover:border-primary/40 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Et("flex-shrink-0 w-12 h-12 rounded-xl flex items-center justify-center text-2xl",s.color),children:a?e.jsx(a,{className:"h-6 w-6"}):e.jsx("span",{children:s.icon})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors",children:s.name}),i&&e.jsx("span",{className:Et("text-[11px] font-medium px-2 py-0.5 rounded-full",i.className),children:i.label})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:s.description})]}),e.jsx("button",{type:"button","aria-label":t?`Remove ${s.name} from favorites`:`Add ${s.name} to favorites`,onClick:l=>{l.stopPropagation(),r(s)},className:Et("flex-shrink-0 p-2 -m-1 rounded-lg transition-colors",t?"text-primary":"text-muted-foreground/40 hover:text-primary"),children:e.jsx(s1,{className:Et("h-5 w-5",t&&"fill-current")})})]}),e.jsx("div",{className:"mt-auto pt-1",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:"Open →"})})]})}function rD({items:s,isFavorite:t,onOpen:n,onToggleFavorite:r}){return e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(a=>e.jsx(X6s,{item:a,isFavorite:t(a),onOpen:n,onToggleFavorite:r},a.key))})}const Q6s="bg-primary/10 text-primary";function MJ(){const{user:s,isAdmin:t}=Ns(),n=Hn(),{hasAccess:r}=nVe(),[a,i]=j.useState([]),[l,o]=j.useState(!0),[c,d]=j.useState(new Set),[u,h]=j.useState(new Set),[m,p]=j.useState(!1),[x,y]=j.useState([]),[g,b]=j.useState(""),v=j.useCallback(async()=>{if(s!=null&&s.id)try{const[{data:W},{data:G},{data:K},{data:ee},{data:J},{data:le},{data:ue}]=await Promise.all([U.from("user_tags").select("tag").eq("user_id",s.id),U.from("app_tiles").select("*").order("name"),U.from("user_favorites").select("app_id").eq("user_id",s.id),U.from("user_tool_favorites").select("tool_id").eq("user_id",s.id),U.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s.id),U.from("activity_logs").select("app_id, app_name, launched_at").eq("user_id",s.id).order("launched_at",{ascending:!1}).limit(40),U.from("profiles").select("name").eq("id",s.id).maybeSingle()]),oe=(W||[]).map(xe=>xe.tag);p((J||[]).some(xe=>xe.is_active&&xe.mls_provider_id&&!xe.no_mls_mode)),d(new Set((K||[]).map(xe=>xe.app_id))),h(new Set((ee||[]).map(xe=>xe.tool_id)));const ie=(G||[]).filter(xe=>xe.app_id==="newsletter_studio"?!1:!xe.required_tags||xe.required_tags.length===0?!0:xe.required_tags.some(fe=>oe.includes(fe)));i(ie.sort((xe,fe)=>xe.name==="LevelUp Members Portal"?-1:fe.name==="LevelUp Members Portal"?1:0));const de=new Set,we=[];for(const xe of le||[])if(!(!xe.app_id||de.has(xe.app_id))&&(de.add(xe.app_id),we.push({appId:xe.app_id,name:xe.app_name,at:xe.launched_at}),we.length>=8))break;y(we);const je=ue==null?void 0:ue.name;b(je?je.trim().split(" ")[0]:"")}catch(W){console.error("Error loading app catalog:",W),re.error("Failed to load apps")}finally{o(!1)}},[s==null?void 0:s.id]);j.useEffect(()=>{v()},[v]);const k=j.useMemo(()=>{const W=yEt.filter(K=>!(K.adminOnly&&!t||K.requiresLeadSiteMLS&&!m&&!t||K.requiresWeeklyReels&&!r)).map(K=>({key:`tool:${K.id}`,kind:"tool",id:K.id,name:K.name,description:K.description,icon:K.icon,color:K.color,isNew:K.isNew,beta:K.beta,popular:K.popular,goals:K.goals,categories:K.categories,keywords:K.keywords,tool:K})),G=a.map(K=>{const ee=Y6s(K.app_id);return{key:`app:${K.app_id}`,kind:"app",id:K.app_id,name:K.name,description:K.description,icon:K.icon,color:Q6s,goals:ee.goals,categories:ee.categories,keywords:ee.keywords,tile:K}});return[...W,...G]},[a,t,m,r]),C=j.useCallback(W=>{var G;return W.kind==="tool"?u.has(W.id):c.has(((G=W.tile)==null?void 0:G.id)??"")},[u,c]),T=j.useMemo(()=>k.filter(C),[k,C]),M=j.useMemo(()=>{const W=new Map(k.map(G=>[G.id,G]));return x.map(G=>W.get(G.appId)).filter(Boolean)},[k,x]),P=j.useMemo(()=>k.filter(W=>W.kind==="app"),[k]),L=j.useCallback(async(W,G)=>{try{await U.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:W,app_name:G,user_agent:navigator.userAgent})}catch{}},[s==null?void 0:s.id]),I=j.useCallback(async W=>{var K;try{const ee=new URL(W.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(ee.hostname)){await L(W.app_id,W.name),n(ee.pathname+ee.search+ee.hash);return}}catch{}const G=window.open("about:blank","_blank");try{const{data:ee,error:J}=await U.auth.getSession();if(J||!ee.session){G==null||G.close(),re.error("Session expired. Please refresh the page and try again.");return}await L(W.app_id,W.name);const{data:le,error:ue}=await U.functions.invoke("sso-launch",{body:{app_id:W.app_id},headers:{Authorization:`Bearer ${ee.session.access_token}`}});if(ue)throw ue;le!=null&&le.redirect_url?G&&!G.closed?(G.location.href=le.redirect_url,(K=G.focus)==null||K.call(G)):window.location.assign(le.redirect_url):(G==null||G.close(),re.error("Launch link unavailable"))}catch(ee){G==null||G.close(),console.error("Error launching app:",ee),re.error("Failed to launch app. Please try again.")}},[L,n]),O=j.useCallback(W=>{if(W.kind==="app"&&W.tile){I(W.tile);return}W.tool&&(L(W.tool.id,W.tool.name),n(W.tool.path))},[I,L,n]),$=j.useCallback(async W=>{var ue;if(!(s!=null&&s.id))return;const G=C(W),K=W.kind==="tool"?"user_tool_favorites":"user_favorites",ee=W.kind==="tool"?"tool_id":"app_id",J=W.kind==="tool"?W.id:(ue=W.tile)==null?void 0:ue.id;if(!J)return;const le=W.kind==="tool"?h:d;le(oe=>{const ie=new Set(oe);return G?ie.delete(J):ie.add(J),ie});try{if(G){const{error:oe}=await U.from(K).delete().eq("user_id",s.id).eq(ee,J);if(oe)throw oe}else{const{error:oe}=await U.from(K).insert({user_id:s.id,[ee]:J});if(oe)throw oe}}catch(oe){console.error("Error toggling favorite:",oe),re.error("Failed to update favorites"),le(ie=>{const de=new Set(ie);return G?de.add(J):de.delete(J),de})}},[C,s==null?void 0:s.id]),q=j.useCallback((W,G=k)=>{const K=W.trim().toLowerCase();if(!K)return G;const ee=K.split(/\s+/);return G.filter(J=>{const le=[J.name,J.description,...J.keywords,...J.categories,...J.goals].join(" ").toLowerCase();return ee.every(ue=>le.includes(ue))||le.includes(K)})},[k]);return{loading:l,items:k,favoriteItems:T,recentItems:M,connectedItems:P,recent:x,firstName:g,isFavorite:C,toggleFavorite:$,openItem:O,search:q,reload:v}}function zLe(s){return{id:s.id,workflow_id:s.workflow_id,run_name:s.run_name,status:s.status==="completed"?"completed":"in_progress",step_state:s.step_state??{},completed_at:s.completed_at,last_activity_at:s.last_activity_at,created_at:s.created_at}}function lCe(s){const t=zD[s.workflow_id],n=(t==null?void 0:t.steps.length)??0,r=t?t.steps.filter(a=>s.step_state[a.key]).length:Object.keys(s.step_state).length;return{touched:r,total:n,pct:n?Math.round(r/n*100):0}}function cCe(){const{user:s}=Ns(),[t,n]=j.useState([]),[r,a]=j.useState(!0),i=j.useCallback(async()=>{if(s!=null&&s.id)try{const{data:m,error:p}=await U.from("workflow_runs").select("*").eq("user_id",s.id).order("last_activity_at",{ascending:!1});if(p)throw p;n((m||[]).map(zLe))}catch(m){console.error("Error loading workflow runs:",m)}finally{a(!1)}},[s==null?void 0:s.id]);j.useEffect(()=>{i()},[i]);const l=j.useCallback(async(m,p)=>{var x;if(!(s!=null&&s.id))return null;try{const{data:y,error:g}=await U.from("workflow_runs").insert({user_id:s.id,workflow_id:m,run_name:p.trim()||((x=zD[m])==null?void 0:x.title)||"Untitled"}).select("*").single();if(g)throw g;const b=zLe(y);return n(v=>[b,...v]),b}catch(y){return console.error("Error starting workflow:",y),re.error("Could not start this workflow"),null}},[s==null?void 0:s.id]),o=j.useCallback(async(m,p)=>{const x={...p,last_activity_at:new Date().toISOString()};n(g=>g.map(b=>b.id===m?zLe({...b,...x}):b));const{error:y}=await U.from("workflow_runs").update(x).eq("id",m);y&&(console.error("Error updating workflow run:",y),re.error("Could not save your progress"))},[]),c=j.useCallback(async(m,p,x)=>{const y={...m.step_state};x?y[p]=x:delete y[p];const g=zD[m.workflow_id],b=g?g.steps.every(v=>y[v.key]):!1;await o(m.id,{step_state:y,status:b?"completed":"in_progress",completed_at:b?new Date().toISOString():null}),b&&m.status!=="completed"&&re.success("Workflow complete — nice work!")},[o]),d=j.useCallback((m,p)=>o(m.id,{run_name:p.trim()}),[o]),u=j.useCallback(m=>o(m.id,{status:"in_progress",completed_at:null}),[o]),h=j.useCallback(async m=>{n(x=>x.filter(y=>y.id!==m));const{error:p}=await U.from("workflow_runs").delete().eq("id",m);p&&(console.error("Error deleting workflow run:",p),re.error("Could not delete this workflow"))},[]);return{runs:t,loading:r,activeRuns:t.filter(m=>m.status==="in_progress"),completedRuns:t.filter(m=>m.status==="completed"),startRun:l,setStep:c,renameRun:d,reopenRun:u,deleteRun:h,reload:i}}function J6s(){const s=Number(new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",hour:"numeric",hour12:!1}).format(new Date));return s<12?"Good morning":s<18?"Good afternoon":"Good evening"}function eMs(){const s=Hn(),{items:t,firstName:n,recentItems:r,favoriteItems:a,isFavorite:i,toggleFavorite:l,openItem:o,search:c}=MJ(),{isAdmin:d}=Ns(),{activeRuns:u}=cCe(),h=d?u:[],[m,p]=j.useState(""),x=j.useMemo(()=>m.trim()?c(m).slice(0,8):[],[m,c]),y=j.useMemo(()=>{const b=new Set(r.map(C=>C.id)),v=[],k=C=>{for(const T of C){if(v.length>=4)break;v.some(M=>M.key===T.key)||v.push(T)}};return k(a.filter(C=>!b.has(C.id))),k(t.filter(C=>C.isNew&&!b.has(C.id))),k(t.filter(C=>C.popular&&!b.has(C.id))),v},[t,a,r]),g=b=>s(`/apps/browse?goal=${b.id}`);return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold text-foreground",children:[J6s(),n?`, ${n}`:""]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"What do you want to accomplish today?"}),e.jsxs("div",{className:"relative mt-5 max-w-2xl",children:[e.jsx(Fr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(ye,{value:m,onChange:b=>p(b.target.value),onKeyDown:b=>{b.key==="Enter"&&m.trim()&&s(`/apps/browse?q=${encodeURIComponent(m.trim())}`)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-14 text-base rounded-2xl"})]}),m.trim()&&e.jsx("div",{className:"mt-4 max-w-2xl bg-card border border-border rounded-2xl divide-y divide-border overflow-hidden",children:x.length===0?e.jsxs("p",{className:"p-4 text-sm text-muted-foreground",children:["Nothing matched “",m,"”. Try “open house”, “email my database” or “reel”."]}):x.map(b=>{const v=typeof b.icon=="string"?null:b.icon;return e.jsxs("button",{type:"button",onClick:()=>o(b),className:"w-full flex items-center gap-3 p-4 text-left hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:Et("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",b.color),children:v?e.jsx(v,{className:"h-5 w-5"}):b.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:b.name}),e.jsx("span",{className:"block text-sm text-muted-foreground truncate",children:b.description})]})]},b.key)})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-8",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Start with a goal"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:$ke.map(b=>e.jsx(Z6s,{goal:b,onSelect:g},b.id))})]}),(h.length>0||r.length>0)&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(Vr,{className:"h-4 w-4 text-muted-foreground"})," Continue working"]}),h.length>0&&e.jsx("div",{className:"space-y-3 mb-4",children:h.slice(0,2).map(b=>{const v=zD[b.workflow_id],k=lCe(b);return e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${b.id}`),className:"w-full text-left bg-card border border-border rounded-2xl p-4 hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:b.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[v==null?void 0:v.title," · Step ",Math.min(k.touched+1,k.total)," of ",k.total]})]}),e.jsx(Xa,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden mt-3",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${k.pct}%`}})})]},b.id)})}),r.length>0&&e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-2 -mx-4 px-4 sm:mx-0 sm:px-0 scrollbar-hide",children:r.slice(0,6).map(b=>{const v=typeof b.icon=="string"?null:b.icon;return e.jsxs("button",{type:"button",onClick:()=>o(b),className:"flex-shrink-0 w-44 bg-card border border-border rounded-2xl p-4 text-left hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:Et("w-10 h-10 rounded-lg flex items-center justify-center text-xl mb-3",b.color),children:v?e.jsx(v,{className:"h-5 w-5"}):b.icon}),e.jsx("span",{className:"block font-medium text-sm text-foreground truncate",children:b.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Open again"})]},b.key)})})]})]}),y.length>0&&e.jsxs("aside",{className:"space-y-4",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-primary"})," Recommended for you"]}),e.jsx("div",{className:"space-y-3",children:y.map(b=>{const v=typeof b.icon=="string"?null:b.icon;return e.jsxs("button",{type:"button",onClick:()=>o(b),className:"w-full flex items-start gap-3 bg-card border border-border rounded-2xl p-4 text-left hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:Et("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",b.color),children:v?e.jsx(v,{className:"h-5 w-5"}):b.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:b.name}),e.jsx("span",{className:"block text-sm text-muted-foreground line-clamp-2",children:b.description})]})]},b.key)})}),e.jsx(B,{variant:"outline",className:"w-full",onClick:()=>s("/apps/browse"),children:"Browse all apps"})]})]}),a.length>0&&e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Your favorites"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>s("/apps/my-apps"),children:"View all"})]}),e.jsx(rD,{items:a.slice(0,6),isFavorite:i,onOpen:o,onToggleFavorite:l})]})]})}function vEt({workflow:s,activeRun:t,onStart:n,onResume:r}){const a=s.icon,i=t?lCe(t):null;return e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-5 flex flex-col gap-4 h-full",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Et("w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0",s.color),children:e.jsx(a,{className:"h-6 w-6"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Rr,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[s.steps.length," steps · ",s.outcome]})]}),t&&i?e.jsxs("div",{className:"mt-auto space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground mb-1",children:[e.jsx("span",{className:"truncate pr-2",children:t.run_name}),e.jsxs("span",{className:"flex-shrink-0",children:["Step ",Math.min(i.touched+1,i.total)," of ",i.total]})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${i.pct}%`}})})]}),e.jsxs(B,{className:"w-full",onClick:()=>r(t),children:["Continue ",e.jsx(Xa,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"mt-auto",children:e.jsxs(B,{className:"w-full",onClick:()=>n(s),children:["Start Workflow ",e.jsx(Xa,{className:"h-4 w-4 ml-1"})]})})]})}function bEt({workflow:s,onClose:t,onStart:n}){const[r,a]=j.useState(""),[i,l]=j.useState(!1);j.useEffect(()=>{a(""),l(!1)},[s==null?void 0:s.id]);const o=async()=>{s&&(l(!0),await n(s,r.trim()||s.title),l(!1))};return e.jsx(Fs,{open:!!s,onOpenChange:c=>!c&&t(),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:s==null?void 0:s.title}),e.jsxs(kr,{children:[s==null?void 0:s.steps.length," steps · your progress saves automatically so you can come back any time."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"workflow-run-name",children:s==null?void 0:s.namePrompt}),e.jsx(ye,{id:"workflow-run-name",value:r,onChange:c=>a(c.target.value),placeholder:s==null?void 0:s.namePlaceholder,onKeyDown:c=>{c.key==="Enter"&&o()},autoFocus:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is just so you recognize it later. You can change it any time."})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:t,disabled:i,children:"Cancel"}),e.jsx(B,{onClick:o,disabled:i,children:i?"Starting…":"Start workflow"})]})]})})}function tMs(){const s=Hn(),[t,n]=dc(),{items:r,isFavorite:a,toggleFavorite:i,openItem:l,search:o}=MJ(),{isAdmin:c}=Ns(),{activeRuns:d,startRun:u}=cCe(),h=t.get("goal"),m=t.get("category")??null,[p,x]=j.useState(t.get("q")??""),[y,g]=j.useState(null);j.useEffect(()=>{x(t.get("q")??"")},[t]);const b=(M,P)=>{const L=new URLSearchParams(t);P?L.set(M,P):L.delete(M),n(L,{replace:!0})},v=()=>{const M=new URLSearchParams(t);M.delete("category"),M.delete("goal"),M.delete("q"),n(M,{replace:!0}),x("")},k=j.useMemo(()=>{let M=r;return h&&(M=M.filter(P=>P.goals.includes(h))),m&&(M=M.filter(P=>P.categories.includes(m))),p.trim()&&(M=o(p,M)),M},[r,h,m,p,o]),C=j.useMemo(()=>h||m||p.trim()?null:$ke.map(M=>({goal:M,apps:r.filter(P=>P.goals.includes(M.id))})).filter(M=>M.apps.length>0),[r,h,m,p]),T=h?$ke.find(M=>M.id===h):null;return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Browse apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Every LevelUp app in one place, grouped by what it helps you get done."})]}),e.jsxs("div",{className:"relative max-w-2xl",children:[e.jsx(Fr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(ye,{value:p,onChange:M=>{x(M.target.value),b("q",M.target.value||null)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-12 rounded-2xl"})]}),e.jsx("div",{className:"-mx-4 px-4 sm:mx-0 sm:px-0 overflow-x-auto scrollbar-hide",children:e.jsxs("div",{className:"inline-flex gap-2 min-w-max pb-1",children:[e.jsx("button",{type:"button",onClick:v,className:Et("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",!m&&!h&&!p.trim()?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:"All"}),W6s.map(M=>e.jsx("button",{type:"button",onClick:()=>b("category",m===M.id?null:M.id),className:Et("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",m===M.id?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:M.label},M.id))]})}),T&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Showing apps for"}),e.jsxs("button",{type:"button",onClick:()=>b("goal",null),className:"text-sm font-medium px-3 py-1.5 rounded-full bg-primary/10 text-primary",children:[T.title," ✕"]})]}),c&&!p.trim()&&!m&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Popular workflows"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:gHe.map(M=>e.jsx(vEt,{workflow:M,activeRun:d.find(P=>P.workflow_id===M.id),onStart:g,onResume:P=>s(`/apps/workflows/${P.id}`)},M.id))})]}),C?C.map(({goal:M,apps:P})=>e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:M.title}),e.jsx(rD,{items:P,isFavorite:a,onOpen:l,onToggleFavorite:i})]},M.id)):k.length>0?e.jsx(rD,{items:k,isFavorite:a,onOpen:l,onToggleFavorite:i}):e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(Fr,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"No apps matched that"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Try a simpler phrase, like “open house” or “email”."})]}),e.jsx(bEt,{workflow:y,onClose:()=>g(null),onStart:async(M,P)=>{const L=await u(M.id,P);g(null),L&&s(`/apps/workflows/${L.id}`)}})]})}function sMs(){const s=Hn(),{favoriteItems:t,recentItems:n,connectedItems:r,isFavorite:a,toggleFavorite:i,openItem:l}=MJ(),o=t.length===0&&n.length===0;return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"My apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Your favorites and what you've used recently."})]}),o&&e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(s1,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"Nothing saved yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-sm mx-auto",children:"Tap the bookmark on any app to pin it here for quick access."}),e.jsx(B,{className:"mt-4",onClick:()=>s("/apps/browse"),children:"Browse apps"})]}),t.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(s1,{className:"h-4 w-4 text-primary"})," Favorites"]}),e.jsx(rD,{items:t,isFavorite:a,onOpen:l,onToggleFavorite:i})]}),n.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(Vr,{className:"h-4 w-4 text-muted-foreground"})," Recently used"]}),e.jsx(rD,{items:n,isFavorite:a,onOpen:l,onToggleFavorite:i})]}),r.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(k_,{className:"h-4 w-4 text-muted-foreground"})," Activated for your account"]}),e.jsx(rD,{items:r,isFavorite:a,onOpen:l,onToggleFavorite:i})]})]})}function nMs(){const{connectedItems:s,isFavorite:t,toggleFavorite:n,openItem:r}=MJ();return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Connected apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Partner apps that are activated for your LevelUp account. Open one and you're signed in automatically."})]}),s.length===0?e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(Rc,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"No connected apps yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-sm mx-auto",children:"Connected apps appear here once they're activated for your account."})]}):e.jsx(rD,{items:s,isFavorite:t,onOpen:r,onToggleFavorite:n})]})}function rMs(){const s=Hn(),{activeRuns:t,completedRuns:n,startRun:r,reopenRun:a,deleteRun:i}=cCe(),[l,o]=j.useState(null);return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Workflows"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Step-by-step playbooks that walk you through the whole job. Your progress saves as you go."})]}),t.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"In progress"}),e.jsx("div",{className:"space-y-3",children:t.map(c=>{const d=zD[c.workflow_id],u=lCe(c);return e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-4 flex items-center gap-4",children:[e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${c.id}`),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:c.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[d==null?void 0:d.title," · Step ",Math.min(u.touched+1,u.total)," of ",u.total]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden mt-3",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${u.pct}%`}})})]}),e.jsx(B,{onClick:()=>s(`/apps/workflows/${c.id}`),children:"Continue"})]},c.id)})})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Start a workflow"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:gHe.map(c=>e.jsx(vEt,{workflow:c,onStart:o,onResume:d=>s(`/apps/workflows/${d.id}`)},c.id))})]}),n.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(Rr,{className:"h-4 w-4 text-emerald-600"})," Completed"]}),e.jsx("div",{className:"space-y-2",children:n.map(c=>{var d;return e.jsxs("div",{className:"bg-card border border-border rounded-xl p-4 flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${c.id}`),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:c.run_name}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:(d=zD[c.workflow_id])==null?void 0:d.title})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>a(c),children:[e.jsx(bm,{className:"h-4 w-4 mr-1"})," Reopen"]}),e.jsx(B,{variant:"ghost",size:"icon","aria-label":"Delete workflow",onClick:()=>i(c.id),children:e.jsx(Rn,{className:"h-4 w-4 text-muted-foreground"})})]},c.id)})})]}),e.jsx(bEt,{workflow:l,onClose:()=>o(null),onStart:async(c,d)=>{const u=await r(c.id,d);o(null),u&&s(`/apps/workflows/${u.id}`)}})]})}function aMs(){const{runId:s}=$i(),t=Hn(),{runs:n,loading:r,setStep:a,renameRun:i,reopenRun:l,deleteRun:o}=cCe(),{items:c,openItem:d}=MJ(),[u,h]=j.useState(!1),[m,p]=j.useState(""),x=j.useMemo(()=>n.find(k=>k.id===s),[n,s]),y=x?zD[x.workflow_id]:void 0;if(r)return e.jsx("p",{className:"text-muted-foreground",children:"Loading…"});if(!x||!y)return e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx("p",{className:"font-medium text-foreground",children:"This workflow isn't available"}),e.jsx(B,{className:"mt-4",onClick:()=>t("/apps/workflows"),children:"Back to workflows"})]});const g=lCe(x),b=y.icon,v=k=>{if(!k)return;const C=c.find(M=>M.kind==="tool"&&M.id===k);if(C){d(C);return}const T=Rot[k];T&&t(T.path)};return e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[e.jsxs("button",{type:"button",onClick:()=>t("/apps/workflows"),className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",children:[e.jsx(_a,{className:"h-4 w-4"})," All workflows"]}),e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-5",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:Et("w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0",y.color),children:e.jsx(b,{className:"h-6 w-6"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[u?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{value:m,onChange:k=>p(k.target.value),autoFocus:!0,onKeyDown:k=>{k.key==="Enter"&&(i(x,m),h(!1))}}),e.jsx(B,{size:"sm",onClick:()=>{i(x,m),h(!1)},children:"Save"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:x.run_name}),e.jsx("button",{type:"button","aria-label":"Rename workflow",onClick:()=>{p(x.run_name),h(!0)},className:"text-muted-foreground hover:text-foreground",children:e.jsx(Za,{className:"h-4 w-4"})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[y.title," · ",y.description]})]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground mb-2",children:[e.jsxs("span",{children:[g.touched," of ",g.total," steps done"]}),e.jsxs("span",{children:[g.pct,"%"]})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${g.pct}%`}})})]}),x.status==="completed"&&e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3 rounded-xl bg-emerald-500/10 p-3",children:[e.jsxs("p",{className:"text-sm font-medium text-emerald-700 flex items-center gap-2",children:[e.jsx(Rr,{className:"h-4 w-4"})," Workflow complete"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>l(x),children:"Reopen"})]})]}),e.jsx("ol",{className:"space-y-3",children:y.steps.map((k,C)=>{const T=x.step_state[k.key],M=k.toolId?Rot[k.toolId]:void 0,P=T==="done",L=T==="skipped";return e.jsx("li",{className:Et("bg-card border rounded-2xl p-4 sm:p-5 transition-colors",P?"border-emerald-500/40":L?"border-border opacity-70":"border-border"),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:Et("w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 text-sm font-semibold",P?"bg-emerald-500 text-white":L?"bg-muted text-muted-foreground":"bg-primary/10 text-primary"),children:P?e.jsx(da,{className:"h-4 w-4"}):C+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Et("font-medium text-foreground",(P||L)&&"line-through decoration-muted-foreground/40"),children:k.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:k.detail}),M&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Uses ",M.name]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-3",children:[M&&e.jsxs(B,{size:"sm",onClick:()=>v(k.toolId),children:["Open ",M.name," ",e.jsx(Tr,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs(B,{size:"sm",variant:P?"secondary":"outline",onClick:()=>a(x,k.key,P?null:"done"),children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),P?"Done":"Mark done"]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>a(x,k.key,L?null:"skipped"),children:[e.jsx(iK,{className:"h-3.5 w-3.5 mr-1"}),L?"Un-skip":"Skip"]})]})]})]})},k.key)})}),e.jsx("div",{className:"pt-2",children:e.jsxs(B,{variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>{o(x.id),t("/apps/workflows")},children:[e.jsx(Rn,{className:"h-4 w-4 mr-1"})," Delete this workflow"]})})]})}const iMs=()=>{const{isAdmin:s}=Ns();return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(G6s,{}),e.jsxs(GY,{children:[e.jsx(fs,{index:!0,element:e.jsx(eMs,{})}),e.jsx(fs,{path:"browse",element:e.jsx(tMs,{})}),e.jsx(fs,{path:"my-apps",element:e.jsx(sMs,{})}),e.jsx(fs,{path:"connected",element:e.jsx(nMs,{})}),s&&e.jsx(fs,{path:"workflows",element:e.jsx(rMs,{})}),s&&e.jsx(fs,{path:"workflows/:runId",element:e.jsx(aMs,{})}),e.jsx(fs,{path:"*",element:e.jsx(Tj,{to:"/apps",replace:!0})})]})]})})},oMs=()=>{var k;const s=Hn(),{isAdmin:t}=Ns(),[n,r]=j.useState(""),[a,i]=j.useState("all"),[l,o]=j.useState("all"),[c,d]=j.useState("grid"),{data:u=[]}=mt({queryKey:["template-categories"],queryFn:async()=>{const{data:C,error:T}=await U.from("template_categories").select("*").order("name");if(T)throw T;return C}}),{data:h=[]}=mt({queryKey:["template-types"],queryFn:async()=>{const{data:C,error:T}=await U.from("template_types").select("*").order("name");if(T)throw T;return C}}),{data:m=[],isLoading:p}=mt({queryKey:["canva-templates",t],queryFn:async()=>{const{data:C,error:T}=await U.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:M,error:P}=await U.from("template_links").select("*").order("sort_order");if(P)throw P;const L=async K=>{let J=0;const le=[];for(;;){const{data:ue,error:oe}=await K().range(J,J+1e3-1);if(oe)throw oe;if(!ue||ue.length===0||(le.push(...ue),ue.length<1e3))break;J+=1e3}return le},I=await L(()=>U.from("template_likes").select("template_id")),O=await L(()=>U.from("template_comments").select("template_id")),$=new Map;I.forEach(K=>{$.set(K.template_id,($.get(K.template_id)||0)+1)});const q=new Map;O.forEach(K=>{q.set(K.template_id,(q.get(K.template_id)||0)+1)});const W=new Map;return t&&(await L(()=>U.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(ee=>{W.set(ee.resource_id,(W.get(ee.resource_id)||0)+1)}),(C||[]).map(K=>({...K,links:(M||[]).filter(ee=>ee.template_id===K.id)||[],likesCount:$.get(K.id)||0,commentsCount:q.get(K.id)||0,viewsCount:W.get(K.id)||0}))}}),x=m.filter(C=>{var L;const T=C.name.toLowerCase().includes(n.toLowerCase())||((L=C.description)==null?void 0:L.toLowerCase().includes(n.toLowerCase())),M=a==="all"||C.category_id===a,P=l==="all"||C.type_id===l;return T&&M&&P}),y=()=>{r(""),i("all"),o("all")},g=n||a!=="all"||l!=="all",b=(k=[...m].sort((C,T)=>new Date(T.publish_date||T.created_at).getTime()-new Date(C.publish_date||C.created_at).getTime())[0])==null?void 0:k.id,v=C=>{s(`/templates/${C}`)};return e.jsx(Vs,{title:"Canva Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Canva Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse and use our collection of professionally designed templates"})]}),!p&&m.filter(C=>C.is_featured).length>0&&e.jsxs("div",{className:"rounded-xl p-5 space-y-3",style:{backgroundColor:"#9aa8b2"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(C=>C.is_featured).slice(0,4).map(C=>e.jsxs(be,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>v(C.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[C.id===b&&e.jsx(qe,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})]}),e.jsxs(Re,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:C.name}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:zY(C.description)})]})]},C.id))})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search templates...",value:n,onChange:C=>r(C.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:a,onValueChange:i,children:[e.jsx(gs,{className:"w-full sm:w-48",children:e.jsx(bs,{placeholder:"All Categories"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Categories"}),u.map(C=>e.jsx(Je,{value:C.id,children:C.name},C.id))]})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-full sm:w-48",children:e.jsx(bs,{placeholder:"All Types"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Types"}),h.map(C=>e.jsx(Je,{value:C.id,children:C.name},C.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[g&&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(r0,{className:"h-4 w-4"})}),e.jsx(B,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(ug,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[x.length," template",x.length!==1?"s":""," found"]}),p&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((C,T)=>e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsx(gn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(gn,{className:"h-5 w-3/4 mb-2"}),e.jsx(gn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(gn,{className:"h-5 w-16"}),e.jsx(gn,{className:"h-5 w-20"})]})]})},T))}),!p&&x.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:g?"No templates match your filters":"No templates available yet"}),g&&e.jsx(B,{variant:"outline",onClick:y,children:"Clear Filters"})]}),!p&&x.length>0&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:x.map(C=>e.jsxs(be,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>v(C.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[C.id===b&&e.jsx(qe,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),C.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(qe,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(vc,{className:"h-3 w-3"}),C.links.length]})})]}),e.jsxs(Re,{className:`p-4 flex flex-col ${c==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:C.name}),C.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:zY(C.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[C.category&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:C.category.name}),C.type&&e.jsx(qe,{variant:"outline",className:"text-xs",children:C.type.name})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mg,{className:"h-3.5 w-3.5"}),C.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yd,{className:"h-3.5 w-3.5"}),C.commentsCount]}),t&&e.jsxs("span",{className:"flex items-center gap-1",title:"Total views (admin only)",children:[e.jsx(ma,{className:"h-3.5 w-3.5"}),C.viewsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:T=>{T.stopPropagation(),v(C.id)},children:[e.jsx(Tr,{className:"h-4 w-4"}),"View Template"]})]})]},C.id))})]})})};var lMs="Separator",Dot="horizontal",cMs=["horizontal","vertical"],_Et=j.forwardRef((s,t)=>{const{decorative:n,orientation:r=Dot,...a}=s,i=dMs(r)?r:Dot,o=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(Ua.div,{"data-orientation":i,...o,...a,ref:t})});_Et.displayName=lMs;function dMs(s){return cMs.includes(s)}var wEt=_Et;const Xl=j.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(wEt,{ref:a,decorative:n,orientation:t,className:Et("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));Xl.displayName=wEt.displayName;const uMs=()=>{const{templateId:s}=$i(),t=Hn(),{user:n,isAdmin:r}=Ns(),{toast:a}=pi(),i=as(),{trackEngagement:l}=eq(),[o,c]=j.useState(""),{data:d,isLoading:u}=mt({queryKey:["template-detail",s],queryFn:async()=>{const{data:C,error:T}=await U.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(T)throw T;const{data:M}=await U.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:P}=await U.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...C,links:M||[],guides:P||[]}},enabled:!!s}),{data:h=[]}=mt({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:C,error:T}=await U.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(C||[]).map(M=>M.resource_kits).filter(Boolean)},enabled:!!s});j.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:m=[]}=mt({queryKey:["template-likes",s],queryFn:async()=>{const{data:C,error:T}=await U.from("template_likes").select("*").eq("template_id",s);if(T)throw T;return C},enabled:!!s}),{data:p=[]}=mt({queryKey:["template-comments",s],queryFn:async()=>{const{data:C,error:T}=await U.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(T)throw T;const M=[...new Set(C.map(I=>I.user_id))],{data:P}=await U.from("profiles").select("id, name").in("id",M),L=new Map((P==null?void 0:P.map(I=>[I.id,I.name]))||[]);return C.map(I=>({...I,user_name:L.get(I.user_id)||"Unknown User"}))},enabled:!!s}),x=vt({mutationFn:async C=>{const{error:T}=await U.from("template_comments").insert({template_id:s,user_id:n.id,content:C});if(T)throw T},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:C=>{a({title:"Error adding comment",description:C.message,variant:"destructive"})}}),y=vt({mutationFn:async C=>{const{error:T}=await U.from("template_comments").delete().eq("id",C);if(T)throw T},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),g=vt({mutationFn:async()=>{const C=m.find(T=>T.user_id===(n==null?void 0:n.id));if(C){const{error:T}=await U.from("template_likes").delete().eq("id",C.id);if(T)throw T}else{const{error:T}=await U.from("template_likes").insert({template_id:s,user_id:n.id});if(T)throw T}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),b=m.some(C=>C.user_id===(n==null?void 0:n.id)),v=C=>C.split(" ").map(T=>T[0]).join("").toUpperCase().slice(0,2),k=C=>{C.preventDefault(),!(!o.trim()||!n)&&x.mutate(o.trim())};return u?e.jsx(Vs,{title:"Templates",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):d?e.jsx(Vs,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/templates",children:[e.jsx(_a,{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(qe,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(qe,{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(Yn,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(Za,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(rq,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(B,{variant:b?"default":"outline",className:"gap-2 rounded-full",onClick:()=>g.mutate(),disabled:!n||g.isPending,children:[e.jsx(mg,{className:`h-4 w-4 ${b?"fill-current":""}`}),m.length," ",m.length===1?"Like":"Likes"]})]})]}),d.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&>p]:mb-4 [&>p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:d.description}})]}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(vc,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(C=>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(C.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:C.title}),e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground"})]},C.id))})]})}),d.video_url&&e.jsx(be,{children:e.jsx(Re,{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(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx($r,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(C=>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(C.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:C.name}),C.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(C.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(ii,{className:"h-4 w-4 text-muted-foreground"})]},C.id))})]})}),h.length>0&&e.jsx(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Eu,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:h.map(C=>e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${C.id}`),children:[C.featured_image_url?e.jsx("img",{src:C.featured_image_url,alt:"",className:"w-10 h-10 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(Eu,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:C.name})]},C.id))})]})}),e.jsx(Xl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Yd,{className:"h-5 w-5"}),"Comments (",p.length,")"]}),n?e.jsxs("form",{onSubmit:k,className:"flex gap-2",children:[e.jsx(Ds,{placeholder:"Add a comment...",value:o,onChange:C=>c(C.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()||x.isPending,children:e.jsx(Dr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:p.length===0?e.jsx(be,{children:e.jsx(Re,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):p.map(C=>e.jsx(be,{children:e.jsx(Re,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ra,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Da,{className:"text-sm",children:v(C.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:C.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:oc(new Date(C.created_at),{addSuffix:!0})}),C.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(C.id),children:e.jsx(Rn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:C.content})]})]})})},C.id))})]})]})}):e.jsx(Vs,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(vc,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Template not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This template may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(Yn,{to:"/templates",children:"Back to Templates"})})]})})},hMs=["reserved","scheduled_for_charge","paid","payment_failed","completed"],yZ=s=>!!s&&(s.access_override||hMs.includes(s.status)),Tp=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),vZ=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`},vFe=(s,t="usd",n)=>`One-time payment: ${Tp(s,t)} for the ${vZ(n)}`,yHe=[{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}],bZ=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:[]}},mMs=(s,t)=>!s.hidden.includes(t),Oot=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),Nd=(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,dCe=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 U.from("programs").select("*").eq("status","published").order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0});if(t)throw t;return s||[]}}),vHe=s=>mt({queryKey:["program",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("programs").select("*").eq("slug",s).maybeSingle();if(n)throw n;return t||null}}),jEt=s=>mt({queryKey:["program-seats",s],enabled:!!s,refetchInterval:6e4,queryFn:async()=>{const{data:t,error:n}=await U.rpc("program_seats_remaining",{_program_id:s});if(n)throw n;return t??0}}),NEt=()=>{const{user:s}=Ns();return mt({queryKey:["program-enrollments",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await U.from("program_enrollments").select("*").eq("user_id",s.id);if(n)throw n;return t||[]}})},bHe=s=>{const{data:t=[],...n}=NEt();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},fMs=()=>{const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{const{data:r,error:a}=await U.from("program_intake_responses").upsert({...n,user_id:s.id},{onConflict:"program_id,user_id"}).select("*").single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["program-intake"]}),onError:n=>re.error(n.message||"Could not save your answers")})},kEt=s=>{const{user:t}=Ns();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 U.from("program_intake_responses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n}})},xMs=()=>{const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.rpc("program_claim_seat",{_program_id:t});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["program-enrollments"]}),s.invalidateQueries({queryKey:["program-seats"]})}})},gMs=(s,t)=>{const{user:n}=Ns(),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,p,x,y]=await Promise.all([U.from("program_weeks").select("*").eq("program_id",s).order("week_number"),U.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),U.from("program_resources").select("*").eq("program_id",s).order("sort_order"),U.from("program_events").select("*").eq("program_id",s).order("starts_at"),U.from("program_announcements").select("*").eq("program_id",s).order("published_at",{ascending:!1}),U.from("program_lesson_completions").select("*").eq("program_id",s).eq("user_id",a),U.from("program_weekly_progress").select("*").eq("program_id",s).eq("user_id",a).order("week_number"),U.from("program_video_logs").select("*").eq("program_id",s).eq("user_id",a).order("posted_at",{ascending:!1}),U.from("program_badge_awards").select("*").eq("program_id",s).eq("user_id",a),U.from("program_profile_analyses").select("*").eq("program_id",s).eq("user_id",a).maybeSingle(),U.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",a).order("sort_order")]);return{weeks:i.data||[],lessons:l.data||[],resources:o.data||[],myResources:y.data||[],events:c.data||[],announcements:d.data||[],completions:u.data||[],progress:h.data||[],videoLogs:m.data||[],badges:p.data||[],analysis:x.data||null}}})},yMs=s=>{const{user:t}=Ns(),n=as();return vt({mutationFn:async({lessonId:r,done:a})=>{if(a){const{error:i}=await U.from("program_lesson_completions").insert({lesson_id:r,program_id:s,user_id:t.id});if(i&&!i.message.includes("duplicate"))throw i}else{const{error:i}=await U.from("program_lesson_completions").delete().eq("lesson_id",r).eq("user_id",t.id);if(i)throw i}},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>re.error(r.message||"Could not update progress")})},vMs=s=>{const{user:t}=Ns(),n=as();return vt({mutationFn:async r=>{const{error:a}=await U.from("program_video_logs").insert({...r,program_id:s,user_id:t.id});if(a)throw a},onSuccess:()=>{re.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>re.error(r.message||"Could not log the video")})},bMs=s=>{const{user:t}=Ns(),n=as();return vt({mutationFn:async r=>{const{error:a}=await U.from("program_weekly_progress").upsert({...r,program_id:s,user_id:t.id},{onConflict:"program_id,user_id,week_number"});if(a)throw a},onSuccess:()=>{re.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>re.error(r.message||"Could not save your check-in")})},_Ms=s=>{const{user:t}=Ns(),n=as();return vt({mutationFn:async({eventId:r,optIn:a})=>{const{error:i}=await U.from("program_event_attendance").upsert({event_id:r,program_id:s,user_id:t.id,reminder_opt_in:a},{onConflict:"event_id,user_id"});if(i)throw i},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>re.error(r.message||"Could not update your RSVP")})},wMs=s=>mt({queryKey:["program-discount-codes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("program_discount_codes").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}}),jMs=s=>{const t=as();return vt({mutationFn:async n=>{const r={program_id:s,code:(n.code||"").trim().toUpperCase(),label:n.label||null,percent_off:n.percent_off??null,amount_off_cents:n.amount_off_cents??null,max_redemptions:n.max_redemptions??null,starts_at:n.starts_at||null,expires_at:n.expires_at||null,is_active:n.is_active??!0};if(n.id){const{error:a}=await U.from("program_discount_codes").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_discount_codes").insert(r);if(a)throw a}},onSuccess:()=>{re.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return re.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},NMs=()=>{const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{re.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>re.error(t.message||"Could not delete the code")})},kMs=()=>vt({mutationFn:async({enrollmentId:s,code:t})=>{const{data:n,error:r}=await U.rpc("program_apply_discount",{_enrollment_id:s,_code:t});if(r)throw r;const a=n;if(!(a!=null&&a.ok))throw new Error((a==null?void 0:a.error)||"That code could not be applied");return a}}),SMs=()=>vt({mutationFn:async s=>{const{error:t}=await U.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),CMs=s=>mt({queryKey:["admin-program-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("program_events").select("*").eq("program_id",s).order("starts_at",{ascending:!0});if(n)throw n;return t||[]}}),AMs=s=>{const t=as();return vt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,event_kind:n.event_kind||"mastermind",starts_at:n.starts_at,duration_minutes:n.duration_minutes??60,speaker:n.speaker||null,meeting_link:n.meeting_link||null,replay_url:n.replay_url||null,is_published:n.is_published??!0};if(n.id){const{error:a}=await U.from("program_events").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_events").insert(r);if(a)throw a}},onSuccess:()=>{re.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>re.error(n.message||"Could not save the session")})},TMs=()=>{const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{re.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the session")})},EMs=s=>mt({queryKey:["admin-program-lessons",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([U.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),U.from("program_weeks").select("id, week_number, title").eq("program_id",s).order("week_number")]);if(t.error)throw t.error;return{lessons:t.data||[],weeks:n.data||[]}}}),MMs=s=>{const t=as();return vt({mutationFn:async n=>{const r={program_id:s,week_id:n.week_id||null,title:(n.title||"").trim(),summary:n.summary||null,duration_minutes:n.duration_minutes??null,video_url:n.video_url||null,worksheet_url:n.worksheet_url||null,action_assignment:n.action_assignment||null,status:n.status||"published",publish_at:n.publish_at||null,sort_order:n.sort_order??0};if(n.id){const{error:a}=await U.from("program_lessons").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_lessons").insert(r);if(a)throw a}},onSuccess:()=>{re.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>re.error(n.message||"Could not save the video")})},LMs=()=>{const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{re.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the video")})},SEt=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},CEt=[{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"}],aq="event-images",uCe=s=>{if(s.file_path){const{data:t}=U.storage.from(aq).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},HK=async(s,t="open")=>{if(!s.file_path){const c=s.url;c&&window.open(c,"_blank","noopener,noreferrer");return}const{data:n,error:r}=await U.storage.from(aq).download(s.file_path);if(r||!n){const c=uCe(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)},PMs=s=>mt({queryKey:["admin-program-resources",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("program_resources").select("*").eq("program_id",s).order("sort_order");if(n)throw n;return t||[]}}),IMs=s=>{const t=as();return vt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,category:(n.category||"Resources").trim()||"Resources",resource_kind:n.resource_kind||"pdf",url:n.url||null,file_path:n.file_path||null,status:n.status||"published",sort_order:n.sort_order??0};if(n.id){const{error:a}=await U.from("program_resources").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await U.from("program_resources").insert(r);if(a)throw a}},onSuccess:()=>{re.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>re.error(n.message||"Could not save the resource")})},RMs=()=>{const s=as();return vt({mutationFn:async t=>{t.file_path&&await U.storage.from(aq).remove([t.file_path]);const{error:n}=await U.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{re.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the resource")})},DMs=(s,t)=>mt({queryKey:["admin-program-member-resources",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await U.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",t).order("sort_order");if(r)throw r;return n||[]}}),OMs=(s,t)=>{const n=as(),{user:r}=Ns();return vt({mutationFn:async a=>{const i={program_id:s,user_id:t,uploaded_by:(r==null?void 0:r.id)??null,title:(a.title||"").trim(),description:a.description||null,category:(a.category||"Personal").trim()||"Personal",resource_kind:a.resource_kind||"pdf",url:a.url||null,file_path:a.file_path||null,status:a.status||"published",sort_order:a.sort_order??0};if(a.id){const{error:l}=await U.from("program_member_resources").update(i).eq("id",a.id);if(l)throw l}else{const{error:l}=await U.from("program_member_resources").insert(i);if(l)throw l}},onSuccess:()=>{re.success("Personal resource saved"),n.invalidateQueries({queryKey:["admin-program-member-resources"]}),n.invalidateQueries({queryKey:["program-workspace"]})},onError:a=>re.error(a.message||"Could not save the resource")})},FMs=()=>{const s=as();return vt({mutationFn:async t=>{t.file_path&&await U.storage.from(aq).remove([t.file_path]);const{error:n}=await U.from("program_member_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{re.success("Personal resource removed"),s.invalidateQueries({queryKey:["admin-program-member-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the resource")})},zMs=s=>{const{user:t}=Ns();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 U.from("program_interest").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})},BMs=s=>{const t=as(),{user:n}=Ns();return vt({mutationFn:async r=>{if(!(n!=null&&n.id)||!s)throw new Error("You need to be signed in.");if(r){const{error:a}=await U.from("program_interest").upsert({program_id:s,user_id:n.id,source:"program_detail"},{onConflict:"program_id,user_id"});if(a)throw a}else{const{error:a}=await U.from("program_interest").delete().eq("program_id",s).eq("user_id",n.id);if(a)throw a}return r},onSuccess:r=>{re.success(r?"You're on the list — we'll email you when enrollment opens.":"Removed from the notify list"),t.invalidateQueries({queryKey:["program-interest"]}),t.invalidateQueries({queryKey:["admin-program-interest"]})},onError:r=>re.error(r.message||"Could not update your notify preference")})},$Ms=s=>mt({queryKey:["admin-program-interest",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("program_interest").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;const r=t||[];if(!r.length)return[];const a=Array.from(new Set(r.map(o=>o.user_id))),{data:i}=await U.from("profiles").select("id, name, email, phone, brokerage_name").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>{const c=l.get(o.user_id)||{};return{...o,full_name:c.name??null,email:c.email??null,phone:c.phone??null,brokerage:c.brokerage_name??null}})}}),Fot=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=dCe(s);return e.jsxs(be,{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(yn,{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(qe,{className:"shadow-sm",children:"Featured"}),t&&e.jsxs(qe,{variant:"secondary",className:"shadow-sm",children:[e.jsx(Rr,{className:"mr-1 h-3 w-3"})," Enrolled"]})]})]}),e.jsxs(Re,{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(Vr,{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(Vc,{className:"h-3.5 w-3.5"}),"Starts ",Nd(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),s.capacity," seats"]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:s.payment_mode==="free"?"Included":Tp(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 ",vZ(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${Nd(s.charge_at)}`:""]}):null]}),e.jsx(B,{asChild:!0,size:"sm",children:e.jsxs(Yn,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(Xa,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},UMs=()=>{const{data:s=[],isLoading:t}=pMs(),{data:n=[]}=NEt(),r=new Set(n.filter(l=>yZ(l)).map(l=>l.program_id)),a=s.filter(l=>r.has(l.id)),i=s.filter(l=>!r.has(l.id));return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-10 p-4 md:p-8",children:[e.jsxs("header",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.2em] text-primary",children:"LevelUp Programs"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight md:text-4xl",children:"Go deeper than the membership"}),e.jsx("p",{className:"max-w-2xl text-muted-foreground",children:"Time-bound coaching programs, masterminds and challenges built to move one specific part of your business forward — with a real cohort, a real roadmap and real accountability."})]}),t?e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(l=>e.jsx(gn,{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(Fot,{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(be,{className:"border-dashed",children:e.jsxs(Re,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(yn,{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(Fot,{program:l,enrolled:!1},l.id))})]})]})]})})},qMs=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},VMs=({url:s,headline:t,posterUrl:n})=>{const[r,a]=j.useState(!1),i=(s||"").trim();if(!i)return null;const l=qMs(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(vh,{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 ON="Accordion",HMs=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[_He,GMs,WMs]=MU(ON),[hCe,MBn]=Zm(ON,[WMs,O3t]),wHe=O3t(),AEt=Lt.forwardRef((s,t)=>{const{type:n,...r}=s,a=r,i=r;return e.jsx(_He.Provider,{scope:s.__scopeAccordion,children:n==="multiple"?e.jsx(XMs,{...i,ref:t}):e.jsx(ZMs,{...a,ref:t})})});AEt.displayName=ON;var[TEt,KMs]=hCe(ON),[EEt,YMs]=hCe(ON,{collapsible:!1}),ZMs=Lt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},collapsible:i=!1,...l}=s,[o,c]=Mx({prop:n,defaultProp:r??"",onChange:a,caller:ON});return e.jsx(TEt,{scope:s.__scopeAccordion,value:Lt.useMemo(()=>o?[o]:[],[o]),onItemOpen:c,onItemClose:Lt.useCallback(()=>i&&c(""),[i,c]),children:e.jsx(EEt,{scope:s.__scopeAccordion,collapsible:i,children:e.jsx(MEt,{...l,ref:t})})})}),XMs=Lt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Mx({prop:n,defaultProp:r??[],onChange:a,caller:ON}),c=Lt.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Lt.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(TEt,{scope:s.__scopeAccordion,value:l,onItemOpen:c,onItemClose:d,children:e.jsx(EEt,{scope:s.__scopeAccordion,collapsible:!0,children:e.jsx(MEt,{...i,ref:t})})})}),[QMs,mCe]=hCe(ON),MEt=Lt.forwardRef((s,t)=>{const{__scopeAccordion:n,disabled:r,dir:a,orientation:i="vertical",...l}=s,o=Lt.useRef(null),c=ko(o,t),d=GMs(n),h=J3(a)==="ltr",m=ua(s.onKeyDown,p=>{var L;if(!HMs.includes(p.key))return;const x=p.target,y=d().filter(I=>{var O;return!((O=I.ref.current)!=null&&O.disabled)}),g=y.findIndex(I=>I.ref.current===x),b=y.length;if(g===-1)return;p.preventDefault();let v=g;const k=0,C=b-1,T=()=>{v=g+1,v>C&&(v=k)},M=()=>{v=g-1,v{const{__scopeAccordion:n,value:r,...a}=s,i=mCe(Uke,n),l=KMs(Uke,n),o=wHe(n),c=Cx(),d=r&&l.value.includes(r)||!1,u=i.disabled||s.disabled;return e.jsx(JMs,{scope:n,open:d,disabled:u,triggerId:c,children:e.jsx(B3t,{"data-orientation":i.orientation,"data-state":FEt(d),...o,...a,ref:t,disabled:u,open:d,onOpenChange:h=>{h?l.onItemOpen(r):l.onItemClose(r)}})})});LEt.displayName=Uke;var PEt="AccordionHeader",IEt=Lt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=mCe(ON,n),i=jHe(PEt,n);return e.jsx(Ua.h3,{"data-orientation":a.orientation,"data-state":FEt(i.open),"data-disabled":i.disabled?"":void 0,...r,ref:t})});IEt.displayName=PEt;var bFe="AccordionTrigger",REt=Lt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=mCe(ON,n),i=jHe(bFe,n),l=YMs(bFe,n),o=wHe(n);return e.jsx(_He.ItemSlot,{scope:n,children:e.jsx(wws,{"aria-disabled":i.open&&!l.collapsible||void 0,"data-orientation":a.orientation,id:i.triggerId,...o,...r,ref:t})})});REt.displayName=bFe;var DEt="AccordionContent",OEt=Lt.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=mCe(ON,n),i=jHe(DEt,n),l=wHe(n);return e.jsx(jws,{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}})});OEt.displayName=DEt;function FEt(s){return s?"open":"closed"}var eLs=AEt,tLs=LEt,sLs=IEt,zEt=REt,BEt=OEt;const vO=eLs,l6=j.forwardRef(({className:s,...t},n)=>e.jsx(tLs,{ref:n,className:Et("border-b",s),...t}));l6.displayName="AccordionItem";const c6=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(sLs,{className:"flex",children:e.jsxs(zEt,{ref:r,className:Et("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(Po,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));c6.displayName=zEt.displayName;const d6=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(BEt,{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:Et("pb-4 pt-0",s),children:t})}));d6.displayName=BEt.displayName;const nLs=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=zMs(s),a=BMs(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(f3,{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(Wt,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(da,{className:"mr-2 h-4 w-4"}):e.jsx(f3,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},rLs=()=>{const{slug:s}=$i(),{data:t,isLoading:n}=vHe(s),{data:r}=jEt(t==null?void 0:t.id),{data:a}=bHe(t==null?void 0:t.id),i=yZ(a),l=(t==null?void 0:t.sales_copy)||{},o=l.outcomes||[],c=l.included||[],d=l.for_who||[],u=l.not_for||[],h=l.faqs||[],m=l.phases||[];if(n)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-8",children:[e.jsx(gn,{className:"h-64 w-full rounded-xl"}),e.jsx(gn,{className:"h-40 w-full rounded-xl"})]})});if(!t)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:"This program may have been closed or unpublished."}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(Yn,{to:"/programs",children:"Back to Programs"})})]})});const p=typeof r=="number"&&r<=0&&!i,{notOpenYet:x,closed:y,opensLabel:g}=dCe(t),b=!i&&(p||y||x),v=i?"Open your program":x?`Enrollment opens ${Nd(t.enrollment_open_at)}`:p?"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(Vs,{children:[e.jsxs(ql,{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(VMs,{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(qe,{variant:"secondary",children:[t.duration_weeks,"-week program"]}),typeof r=="number"&&!i&&e.jsx(qe,{variant:r<=10?"destructive":"outline",children:r>0?`${r} of ${t.capacity} seats left`:"Full"}),i&&e.jsxs(qe,{children:[e.jsx(Rr,{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":Tp(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 ",vZ(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:Nd(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(ty,{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:[vFe(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:Nd(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:!b,size:"lg",disabled:b,children:b?e.jsx("span",{children:v}):e.jsxs(Yn,{to:k,children:[v,e.jsx(Xa,{className:"ml-2 h-4 w-4"})]})}),e.jsx(B,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(Yn,{to:"/programs",children:"All programs"})})]}),x&&!i&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Vc,{className:"h-3.5 w-3.5"}),"Enrollment opens ",g]}),e.jsx(nLs,{programId:t.id,opensLabel:g})]})]})]}),t.description&&e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What this program is"}),e.jsx("div",{className:"whitespace-pre-line text-muted-foreground",children:t.description})]}),o.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What you'll walk away with"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.map((C,T)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(Rr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{className:"text-sm",children:C})]},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((C,T)=>e.jsx(be,{className:"border-border/60",children:e.jsxs(Re,{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:C.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:C.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((C,T)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-sm",children:[e.jsx(yn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),C]},T))})]}),(d.length>0||u.length>0)&&e.jsxs("section",{className:"grid gap-6 md:grid-cols-2",children:[d.length>0&&e.jsx(be,{className:"border-border/60",children:e.jsxs(Re,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This is for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:d.map((C,T)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Rr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),C]},T))})]})}),u.length>0&&e.jsx(be,{className:"border-border/60",children:e.jsxs(Re,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This isn't for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:u.map((C,T)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Vr,{className:"mt-0.5 h-4 w-4 shrink-0"}),C]},T))})]})})]}),h.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Questions"}),e.jsx(vO,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((C,T)=>e.jsxs(l6,{value:`faq-${T}`,children:[e.jsx(c6,{className:"text-left text-sm font-medium",children:C.q}),e.jsx(d6,{className:"text-sm text-muted-foreground",children:C.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(Zr,{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:!b,size:"lg",disabled:b,children:b?e.jsx("span",{children:v}):e.jsxs(Yn,{to:k,children:[v,e.jsx(Xa,{className:"ml-2 h-4 w-4"})]})}),typeof r=="number"&&r>0&&!i&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Bn,{className:"h-4 w-4"}),r," seats remaining"]})]}),!i&&(x?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Vc,{className:"h-3.5 w-3.5"}),"Enrollment opens ",g]}):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(Vc,{className:"h-3.5 w-3.5"}),"Enrollment closes ",Nd(t.enrollment_close_at)]}):null)]})]})]})},Xse=["Your business","Your content","Your goals","Reserve your seat"],aLs=()=>{const{slug:s}=$i(),t=Hn(),[n,r]=dc(),{user:a}=Ns(),{data:i,isLoading:l}=vHe(s),{data:o}=jEt(i==null?void 0:i.id),{data:c,refetch:d}=bHe(i==null?void 0:i.id),{data:u}=kEt(i==null?void 0:i.id),h=fMs(),m=xMs(),p=kMs(),x=SMs(),[y,g]=j.useState(0),[b,v]=j.useState(!1),[k,C]=j.useState(!1),[T,M]=j.useState(!1),[P,L]=j.useState(!1),[I,O]=j.useState(""),[$,q]=j.useState(null),W=j.useRef({}),[G,K]=j.useState({}),ee=j.useRef(!1),J=(Ue,Ze)=>{W.current={...W.current,[Ue]:Ze},K(W.current)};j.useEffect(()=>{ee.current||(u?(W.current={...u},K(W.current),ee.current=!0):a&&(W.current={email:a.email,...W.current},K(W.current)))},[u,a]),j.useEffect(()=>{const Ue=c;!i||!(Ue!=null&&Ue.discount_code)||$||q({code:Ue.discount_code,discount_cents:Ue.discount_cents||0,amount_cents:Ue.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,$]);const le=$?$.amount_cents:(i==null?void 0:i.price_cents)??0,ue=j.useMemo(()=>bZ(i),[i]),oe=Ue=>mMs(ue,Ue),ie=Ue=>Oot(ue,Ue)?e.jsx("span",{className:"text-destructive",children:" *"}):null,de=(Ue,Ze)=>{const Qe={...W.current.extra||{},[Ue]:Ze};J("extra",Qe)},we=Ue=>ue.custom.filter((Ze,Qe)=>Qe%3===Ue),je=Ue=>{const Ze=we(Ue);if(!Ze.length)return null;const Qe=G.extra||{};return e.jsx("div",{className:"space-y-4",children:Ze.map(Ye=>e.jsxs("div",{className:"space-y-2",children:[Ye.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(wi,{id:Ye.id,checked:!!Qe[Ye.id],onCheckedChange:nt=>de(Ye.id,!!nt)}),e.jsxs(se,{htmlFor:Ye.id,className:"text-sm font-normal leading-relaxed",children:[Ye.label,Ye.required&&e.jsx("span",{className:"text-destructive",children:" *"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(se,{htmlFor:Ye.id,children:[Ye.label,Ye.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),Ye.type==="long_text"?e.jsx(Ds,{id:Ye.id,rows:3,value:Qe[Ye.id]||"",onChange:nt=>de(Ye.id,nt.target.value)}):Ye.type==="select"?e.jsxs(vs,{value:Qe[Ye.id]||"",onValueChange:nt=>de(Ye.id,nt),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:(Ye.options||[]).map(nt=>e.jsx(Je,{value:nt,children:nt},nt))})]}):e.jsx(ye,{id:Ye.id,value:Qe[Ye.id]||"",onChange:nt=>de(Ye.id,nt.target.value)})]}),Ye.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Ye.help})]},Ye.id))})},xe=Ue=>{const Ze=W.current,Qe=Fe=>Fe==null||Fe===""||Fe===!1,Ye=yHe.find(Fe=>Fe.step===Ue&&Oot(ue,Fe.key)&&Qe(Fe.key==="timezone"?Ze.timezone||(i==null?void 0:i.timezone):Ze[Fe.key]));if(Ye)return Ye.label;const nt=Ze.extra||{},rt=we(Ue).find(Fe=>Fe.required&&Qe(nt[Fe.id]));return rt?rt.label:null},fe=()=>{if(y<=2){const Ue=xe(y);if(Ue)return re.error(`Please answer: ${Ue}`)}g(Ue=>Ue+1)},Se=async()=>{if(!(!i||!I.trim()))try{let Ue=c==null?void 0:c.id;(!Ue||(c==null?void 0:c.status)==="canceled")&&(Ue=await m.mutateAsync(i.id));const Ze=await p.mutateAsync({enrollmentId:Ue,code:I});q(Ze),O(""),await d(),re.success(`Code applied — you save ${Tp(Ze.discount_cents,i.currency)}`)}catch(Ue){re.error(Ue.message||"That code could not be applied")}},Ee=async()=>{if(!(c!=null&&c.id))return q(null);try{await x.mutateAsync(c.id),q(null),await d()}catch(Ue){re.error(Ue.message||"Could not remove the code")}},Le=n.get("setup"),De=n.get("session_id"),Be=j.useRef(!1);j.useEffect(()=>{Le!=="success"||!De||!(c!=null&&c.id)||Be.current||(Be.current=!0,C(!0),(async()=>{const{data:Ue,error:Ze}=await U.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:De}});if(C(!1),Ze||Ue!=null&&Ue.error||(Ue==null?void 0:Ue.success)===!1){re.error((Ue==null?void 0:Ue.error)||(Ze==null?void 0:Ze.message)||"We could not confirm your card");return}await d(),n.delete("setup"),n.delete("session_id"),r(n,{replace:!0}),re.success("Your seat is confirmed")})())},[Le,De,c==null?void 0:c.id]),j.useEffect(()=>{Le==="cancelled"&&re.info("Checkout cancelled — your seat is held for a short while.")},[Le]);const Ne=j.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Ge=async()=>{if(i){if(!T||i.payment_mode!=="free"&&!P){re.error("Please confirm the checkboxes to continue");return}v(!0);try{let Ue=c==null?void 0:c.id;(!Ue||(c==null?void 0:c.status)==="canceled")&&(Ue=await m.mutateAsync(i.id)),await h.mutateAsync({...W.current,id:void 0,program_id:i.id,enrollment_id:Ue,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:Ze,error:Qe}=await U.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:Ue}});if(Qe||Ze!=null&&Ze.error)throw new Error((Ze==null?void 0:Ze.error)||(Qe==null?void 0:Qe.message));if(Ze!=null&&Ze.free){await d(),re.success("You're in"),t(`/programs/${i.slug}/workspace`);return}Ze!=null&&Ze.url&&(window.location.href=Ze.url)}catch(Ue){re.error(Ue.message||"Could not start enrollment")}finally{v(!1)}}};if(l)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-8",children:[e.jsx(gn,{className:"h-10 w-1/2"}),e.jsx(gn,{className:"h-64 w-full rounded-xl"})]})});if(!i)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(Yn,{to:"/programs",children:"Back to Programs"})})]})});if(yZ(c)&&Ne&&Le!=="success")return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(Rr,{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 ${Nd(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx(B,{asChild:!0,size:"lg",children:e.jsx(Yn,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const _e=typeof o=="number"&&o<=0,{notOpenYet:Oe,closed:Ae,opensLabel:Xe}=dCe(i);return Oe||Ae?e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-xl space-y-4 p-8 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:Oe?"Enrollment is not open yet":"Enrollment is closed"}),e.jsx("p",{className:"text-muted-foreground",children:Oe?`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(Yn,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 p-4 md:p-8",children:[e.jsx(B,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2",children:e.jsxs(Yn,{to:`/programs/${i.slug}`,children:[e.jsx(_a,{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?`${vFe(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${Nd(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:Xse[y]}),e.jsxs("span",{children:["Step ",y+1," of ",Xse.length]})]}),e.jsx(qi,{value:(y+1)/Xse.length*100})]}),k&&e.jsx(be,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Re,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(be,{children:e.jsxs(Re,{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:[oe("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"full_name",children:["Full name",ie("full_name")]}),e.jsx(ye,{id:"full_name",value:G.full_name||"",onChange:Ue=>J("full_name",Ue.target.value)})]}),oe("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"phone",children:["Mobile number",ie("phone")]}),e.jsx(ye,{id:"phone",value:G.phone||"",onChange:Ue=>J("phone",Ue.target.value)})]}),oe("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"instagram_handle",children:["Instagram handle",ie("instagram_handle")]}),e.jsx(ye,{id:"instagram_handle",placeholder:"@yourhandle",value:G.instagram_handle||"",onChange:Ue=>J("instagram_handle",Ue.target.value)})]}),oe("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"city",children:["Primary city / market",ie("city")]}),e.jsx(ye,{id:"city",value:G.city||"",onChange:Ue=>J("city",Ue.target.value)})]})]}),oe("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",ie("service_areas")]}),e.jsx(Ds,{id:"service_areas",rows:2,value:G.service_areas||"",onChange:Ue=>J("service_areas",Ue.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[oe("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["Years in real estate",ie("years_experience")]}),e.jsxs(vs,{value:G.years_experience||"",onValueChange:Ue=>J("years_experience",Ue),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:["Less than 1","1-3","4-7","8-15","15+"].map(Ue=>e.jsx(Je,{value:Ue,children:Ue},Ue))})]})]}),oe("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"specialty",children:["Specialty or niche",ie("specialty")]}),e.jsx(ye,{id:"specialty",value:G.specialty||"",onChange:Ue=>J("specialty",Ue.target.value)})]})]}),je(0)]}),y===1&&e.jsxs(e.Fragment,{children:[oe("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"target_audience",children:["Who are you trying to reach?",ie("target_audience")]}),e.jsx(Ds,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:G.target_audience||"",onChange:Ue=>J("target_audience",Ue.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[oe("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["How comfortable are you on camera?",ie("video_comfort")]}),e.jsxs(vs,{value:G.video_comfort||"",onValueChange:Ue=>J("video_comfort",Ue),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map(Ue=>e.jsx(Je,{value:Ue,children:Ue},Ue))})]})]}),oe("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["How often do you post today?",ie("posting_frequency")]}),e.jsxs(vs,{value:G.posting_frequency||"",onValueChange:Ue=>J("posting_frequency",Ue),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map(Ue=>e.jsx(Je,{value:Ue,children:Ue},Ue))})]})]})]}),oe("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"content_style",children:["What content style feels like you?",ie("content_style")]}),e.jsx(Ds,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:G.content_style||"",onChange:Ue=>J("content_style",Ue.target.value)})]}),oe("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",ie("personal_interests")]}),e.jsx(Ds,{id:"personal_interests",rows:2,value:G.personal_interests||"",onChange:Ue=>J("personal_interests",Ue.target.value)})]}),je(1)]}),y===2&&e.jsxs(e.Fragment,{children:[oe("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"primary_goal",children:["Your #1 goal for this program",ie("primary_goal")]}),e.jsx(Ds,{id:"primary_goal",rows:3,value:G.primary_goal||"",onChange:Ue=>J("primary_goal",Ue.target.value)})]}),oe("topics_to_avoid")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"topics_to_avoid",children:["Anything you don't want to talk about",ie("topics_to_avoid")]}),e.jsx(Ds,{id:"topics_to_avoid",rows:2,value:G.topics_to_avoid||"",onChange:Ue=>J("topics_to_avoid",Ue.target.value)})]}),oe("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["Your time zone",ie("timezone")]}),e.jsxs(vs,{value:G.timezone||i.timezone,onValueChange:Ue=>J("timezone",Ue),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map(Ue=>e.jsx(Je,{value:Ue,children:Ue.replace("America/","").replace("_"," ")},Ue))})]})]}),je(2),oe("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(wi,{id:"consent_public_profile",checked:!!G.consent_public_profile,onCheckedChange:Ue=>J("consent_public_profile",!!Ue)}),e.jsx(se,{htmlFor:"consent_public_profile",className:"text-sm font-normal leading-relaxed",children:"I'm okay with my content being reviewed and shared as an example inside the cohort."})]})]}),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:Tp($.original_cents,i.currency)}),Tp(le,i.currency)]}):Tp(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:vFe(le,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(wf,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:$.code})," applied — you save ",Tp($.discount_cents,i.currency)]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:Ee,disabled:x.isPending,children:[e.jsx(dr,{className:"mr-1 h-3.5 w-3.5"})," Remove"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"discount_code",className:"text-xs text-muted-foreground",children:"Have a discount code?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{id:"discount_code",placeholder:"Enter code",className:"font-mono uppercase",value:I,onChange:Ue=>O(Ue.target.value.toUpperCase()),onKeyDown:Ue=>{Ue.key==="Enter"&&(Ue.preventDefault(),Se())}}),e.jsx(B,{variant:"outline",onClick:Se,disabled:!I.trim()||p.isPending||m.isPending,children:p.isPending||m.isPending?e.jsx(Wt,{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(ty,{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:Nd(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(wi,{id:"terms",checked:T,onCheckedChange:Ue=>M(!!Ue)}),e.jsx(se,{htmlFor:"terms",className:"text-sm font-normal leading-relaxed",children:"I agree to the program terms, including the attendance and participation expectations, and understand seats are limited."})]}),i.payment_mode!=="free"&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(wi,{id:"charge",checked:P,onCheckedChange:Ue=>L(!!Ue)}),e.jsx(se,{htmlFor:"charge",className:"text-sm font-normal leading-relaxed",children:i.payment_mode==="delayed"?`I authorize LevelUp to charge my saved card one time — ${Tp(le,i.currency)} for the ${vZ(i.duration_weeks)} — on ${Nd(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 — ${Tp(le,i.currency)} for the ${vZ(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(a0,{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:()=>g(Ue=>Math.max(0,Ue-1)),disabled:y===0||b,children:[e.jsx(_a,{className:"mr-1.5 h-4 w-4"})," Back"]}),yString(s).padStart(2,"0"),$Le=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",iLs=({program:s,intakeComplete:t})=>{const n=s!=null&&s.kickoff_at?new Date(s.kickoff_at).getTime():null,[r,a]=j.useState(()=>Date.now());j.useEffect(()=>{const d=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(d)},[]);const i=j.useMemo(()=>{if(!n)return null;const d=Math.max(n-r,0);return{days:Math.floor(d/864e5),hours:Math.floor(d%864e5/36e5),minutes:Math.floor(d%36e5/6e4),seconds:Math.floor(d%6e4/1e3),done:d===0}},[n,r]);if(!n||!i)return null;const l=new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short",timeZone:"America/New_York"}).format(new Date(n)),o=()=>{const d=new Date(n),u=new Date(n+90*6e4),h=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp//Programs//EN","BEGIN:VEVENT",`UID:kickoff-${s.id}@levelup`,`DTSTAMP:${$Le(new Date)}`,`DTSTART:${$Le(d)}`,`DTEND:${$Le(u)}`,`SUMMARY:${s.name} — Kickoff Call`,`DESCRIPTION:The official kickoff for ${s.name}. Bring a phone and a story.`,"END:VEVENT","END:VCALENDAR"].join(`\r `),m=URL.createObjectURL(new Blob([h],{type:"text/calendar"})),p=document.createElement("a");p.href=m,p.download="program-kickoff.ics",p.click(),URL.revokeObjectURL(m)},c=[{label:"Days",value:i.days},{label:"Hours",value:BLe(i.hours)},{label:"Minutes",value:BLe(i.minutes)},{label:"Seconds",value:BLe(i.seconds)}];return e.jsxs(be,{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(Re,{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(qe,{className:"gap-1.5",children:[e.jsx(yn,{className:"h-3.5 w-3.5"})," Your seat is confirmed"]}),e.jsxs(qe,{variant:"outline",className:"gap-1.5",children:[e.jsx(Vr,{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(Wy,{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(Rr,{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))})]})]})},ULe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",oLs=(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:${ULe(new Date)}`,`DTSTART:${ULe(n)}`,`DTEND:${ULe(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)},lLs={pdf:$r,document:pN,checklist:zp,template_link:q_,video:wh,external:Rc},cLs=()=>{var we;const{slug:s}=$i(),[t]=dc(),{isAdmin:n}=Ns(),r=n?t.get("as"):null,a=t.get("name")||"this member",i=n&&(t.get("preview")==="1"||!!r),{data:l,isLoading:o}=vHe(s),{data:c}=bHe(l==null?void 0:l.id),{data:d,isLoading:u}=gMs(l==null?void 0:l.id,r),h=yMs(l==null?void 0:l.id),m=vMs(l==null?void 0:l.id),p=bMs(l==null?void 0:l.id),x=_Ms(l==null?void 0:l.id),{data:y}=kEt(l==null?void 0:l.id),g=!!(l!=null&&l.kickoff_at)&&new Date(l.kickoff_at).getTime()>Date.now(),[b,v]=j.useState(!1),[k,C]=j.useState({title:"",instagram_url:""}),[T,M]=j.useState({}),[P,L]=j.useState(null),I=j.useMemo(()=>{if(!(l!=null&&l.kickoff_at))return 1;const je=Math.floor((Date.now()-new Date(l.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(je/7)+1,1),l.duration_weeks)},[l]),O=new Set(((d==null?void 0:d.completions)||[]).map(je=>je.lesson_id)),$=(d==null?void 0:d.lessons)||[],q=$.length?Math.round(O.size/$.length*100):0,W=((d==null?void 0:d.videoLogs)||[]).filter(je=>je.week_number===I).length,G=((d==null?void 0:d.videoLogs)||[]).length,K=(l==null?void 0:l.weekly_video_goal)||3,ee=j.useMemo(()=>{const je=new Map;((d==null?void 0:d.videoLogs)||[]).forEach(fe=>je.set(fe.week_number,(je.get(fe.week_number)||0)+1));let xe=0;for(let fe=I;fe>=1;fe--)if((je.get(fe)||0)>=K)xe++;else if(fe!==I)break;return xe},[d==null?void 0:d.videoLogs,I,K]);if(o||u)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6 p-8",children:[e.jsx(gn,{className:"h-28 w-full rounded-xl"}),e.jsx(gn,{className:"h-64 w-full rounded-xl"})]})});if(!l)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(Yn,{to:"/programs",children:"Back to Programs"})})]})});if(!yZ(c)&&!i)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"You're not enrolled yet"}),e.jsxs("p",{className:"text-muted-foreground",children:["Reserve your seat in ",l.name," to unlock the roadmap, lessons and mastermind sessions."]}),e.jsx(B,{asChild:!0,size:"lg",children:e.jsx(Yn,{to:`/programs/${l.slug}`,children:"View the program"})})]})});const J=((d==null?void 0:d.events)||[]).filter(je=>new Date(je.starts_at)>=new Date),le=((d==null?void 0:d.events)||[]).filter(je=>new Date(je.starts_at)je.is_pinned),ie=[...(d==null?void 0:d.myResources)||[],...(d==null?void 0:d.resources)||[]].reduce((je,xe)=>{const fe=xe.user_id?`Just for you · ${xe.category}`:xe.category;return(je[fe]||(je[fe]=[])).push(xe),je},{}),de=((d==null?void 0:d.progress)||[]).find(je=>je.week_number===I)||{};return e.jsx(Vs,{children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-6xl space-y-8 p-4 md:p-8",children:[i&&(r||!yZ(c))&&e.jsx(be,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Re,{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(Yn,{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(qe,{variant:"secondary",children:["Week ",I," of ",l.duration_weeks]}),(c==null?void 0:c.status)==="scheduled_for_charge"&&c.charge_scheduled_at&&e.jsxs(qe,{variant:"outline",children:["Billing ",Nd(c.charge_scheduled_at)]}),(c==null?void 0:c.status)==="payment_failed"&&e.jsx(qe,{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})]}),g&&e.jsx(iLs,{program:l,intakeComplete:!!y}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(be,{className:"neon-topline",children:e.jsxs(Re,{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(uu,{className:"h-3.5 w-3.5 text-primary"})," This week"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[W,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",K]})]}),e.jsx(qi,{value:Math.min(W/K*100,100),className:"h-1.5"})]})}),e.jsx(be,{className:"neon-topline",children:e.jsxs(Re,{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(wh,{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(be,{className:"neon-topline",children:e.jsxs(Re,{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(Fd,{className:"h-3.5 w-3.5 text-primary"})," Streak"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[ee," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(be,{className:"neon-topline",children:e.jsxs(Re,{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(kl,{className:"h-3.5 w-3.5 text-primary"})," Curriculum"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[q,"%"]}),e.jsx(qi,{value:q,className:"h-1.5"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(Fs,{open:b,onOpenChange:v,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Js,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Log a posted video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(ye,{id:"v-title",value:k.title,onChange:je=>C(xe=>({...xe,title:je.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"v-url",children:"Instagram link (optional)"}),e.jsx(ye,{id:"v-url",placeholder:"https://instagram.com/reel/…",value:k.instagram_url,onChange:je=>C(xe=>({...xe,instagram_url:je.target.value}))})]})]}),e.jsx(Nr,{children:e.jsx(B,{onClick:async()=>{await m.mutateAsync({week_number:I,...k}),C({title:"",instagram_url:""}),v(!1)},children:"Log video"})})]})]}),((we=J[0])==null?void 0:we.meeting_link)&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:J[0].meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(vh,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),ue.length>0&&e.jsx(be,{className:"border-primary/30 bg-primary/5",children:e.jsx(Re,{className:"space-y-3 p-5",children:ue.map(je=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(jh,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:je.title}),je.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:je.body})]})]},je.id))})}),e.jsxs(fa,{defaultValue:"roadmap",children:[e.jsxs(xa,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(ss,{value:"roadmap",children:"Roadmap"}),e.jsx(ss,{value:"lessons",children:"Lessons"}),e.jsx(ss,{value:"checkin",children:"Weekly check-in"}),e.jsx(ss,{value:"events",children:"Sessions"}),e.jsx(ss,{value:"resources",children:"Resources"}),e.jsx(ss,{value:"profile",children:"Profile review"})]}),e.jsxs(ns,{value:"roadmap",className:"mt-6 space-y-4",children:[((d==null?void 0:d.weeks)||[]).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"The roadmap will appear here before kickoff."}),((d==null?void 0:d.weeks)||[]).map(je=>{const xe=je.release_at&&new Date(je.release_at)>new Date;return e.jsx(be,{className:xe?"opacity-60":je.week_number===I?"border-primary/50":"",children:e.jsxs(Re,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(qe,{variant:"outline",children:["Week ",je.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:je.phase}),je.week_number===I&&e.jsx(qe,{children:"Current"}),xe&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Vr,{className:"h-3 w-3"})," Unlocks ",Nd(je.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:je.title}),je.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:je.learning_goal}),!xe&&Array.isArray(je.tasks)&&je.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:je.tasks.map((fe,Se)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Rr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof fe=="string"?fe:fe.label]},Se))})]})},je.id)})]}),e.jsxs(ns,{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(je=>{const xe=SEt(je.video_url),fe=P===je.id;return e.jsx(be,{children:e.jsxs(Re,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(wi,{checked:O.has(je.id),onCheckedChange:Se=>h.mutate({lessonId:je.id,done:!!Se}),"aria-label":`Mark ${je.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:je.title}),je.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:je.summary}),je.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",je.action_assignment]})]}),je.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Vr,{className:"h-3 w-3"})," ",je.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[je.video_url&&xe&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>L(fe?null:je.id),children:[e.jsx(vh,{className:"mr-1.5 h-3.5 w-3.5"})," ",fe?"Close":"Watch"]}),je.video_url&&!xe&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:je.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(vh,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),je.worksheet_url&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:je.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(ii,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),fe&&xe&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:xe,title:je.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})})]})},je.id)})]}),e.jsx(ns,{value:"checkin",className:"mt-6",children:e.jsx(be,{children:e.jsxs(Re,{className:"space-y-5 p-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold",children:["Week ",I," check-in"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Two minutes of honesty here is what makes the next week better."})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["videos_planned","Videos planned"],["videos_recorded","Videos recorded"],["videos_posted","Videos posted"]].map(([je,xe])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:je,children:xe}),e.jsx(ye,{id:je,type:"number",min:0,defaultValue:de[je]??"",onChange:fe=>M(Se=>({...Se,[je]:Number(fe.target.value)}))})]},je))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([je,xe])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:je,children:xe}),e.jsx(Ds,{id:je,rows:2,defaultValue:de[je]??"",onChange:fe=>M(Se=>({...Se,[je]:fe.target.value}))})]},je)),e.jsx(B,{onClick:()=>p.mutate({week_number:I,goal_videos:K,...T}),children:"Save check-in"})]})})}),e.jsxs(ns,{value:"events",className:"mt-6 space-y-4",children:[J.length===0&&le.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),J.map(je=>e.jsx(be,{className:"border-primary/30",children:e.jsxs(Re,{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(qe,{variant:"secondary",className:"capitalize",children:String(je.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Vc,{className:"h-3 w-3"})," ",Nd(je.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:je.title}),je.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",je.speaker]}),je.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:je.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>x.mutate({eventId:je.id,optIn:!0}),children:"Remind me"}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>oLs(je,l.name),children:[e.jsx(Vc,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),je.meeting_link&&e.jsx(B,{size:"sm",asChild:!0,children:e.jsxs("a",{href:je.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(Tr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},je.id)),le.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"pt-2 text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Replays"}),le.map(je=>e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:je.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Nd(je.starts_at,!0)})]}),je.replay_url?e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:je.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(vh,{className:"mr-1.5 h-3.5 w-3.5"})," Watch replay"]})}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Replay coming soon"})]})},je.id))]})]}),e.jsxs(ns,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(ie).length===0&&e.jsx(be,{className:"border-dashed",children:e.jsxs(Re,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx($r,{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(ie).map(([je,xe])=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:je}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[xe.length," item",xe.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:xe.map(fe=>{const Se=uCe(fe),Ee=lLs[fe.resource_kind]||$r;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>Se&&HK(fe),onKeyDown:Le=>{Se&&(Le.key==="Enter"||Le.key===" ")&&(Le.preventDefault(),HK(fe))},className:"group relative flex cursor-pointer flex-col gap-3 overflow-hidden rounded-2xl border border-border/60 bg-card p-5 transition-all hover:-translate-y-0.5 hover:border-primary/50 hover:shadow-lg",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary",children:e.jsx(Ee,{className:"h-5 w-5"})}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:String(fe.resource_kind).replace("_"," ")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold leading-snug",children:fe.title}),fe.description&&e.jsx("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:fe.description})]}),e.jsxs("div",{className:"mt-auto flex items-center gap-4",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm font-medium text-primary",children:[e.jsx(Tr,{className:"h-3.5 w-3.5"})," Open"]}),fe.file_path&&e.jsxs("button",{type:"button",onClick:Le=>{Le.stopPropagation(),HK(fe,"download")},className:"inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-primary",children:[e.jsx(ii,{className:"h-3.5 w-3.5"})," Download"]})]})]},fe.id)})})]},je))]}),e.jsx(ns,{value:"profile",className:"mt-6",children:e.jsx(be,{children:e.jsxs(Re,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vm,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"Your profile review"})]}),!(d!=null&&d.analysis)||d.analysis.status==="not_submitted"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Instagram review hasn't been submitted yet. Your coach will request screenshots during onboarding week."}):d.analysis.status==="in_review"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your profile is in review — you'll get a notification when the report is ready."}):e.jsxs("div",{className:"space-y-4",children:[d.analysis.scores&&Object.keys(d.analysis.scores).length>0&&e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:Object.entries(d.analysis.scores).map(([je,xe])=>e.jsxs("div",{className:"space-y-1 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"capitalize",children:je.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[xe,"/10"]})]}),e.jsx(qi,{value:Number(xe)*10,className:"h-1.5"})]},je))}),Array.isArray(d.analysis.top_priorities)&&d.analysis.top_priorities.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Top priorities"}),e.jsx("ul",{className:"space-y-1.5",children:d.analysis.top_priorities.map((je,xe)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(cu,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof je=="string"?je:je.label]},xe))})]}),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(ii,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})})},Oa=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:n,className:Et("w-full caption-bottom text-sm",s),...t})}));Oa.displayName="Table";const Fa=j.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:Et("[&_tr]:border-b",s),...t}));Fa.displayName="TableHeader";const za=j.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:Et("[&_tr:last-child]:border-0",s),...t}));za.displayName="TableBody";const dLs=j.forwardRef(({className:s,...t},n)=>e.jsx("tfoot",{ref:n,className:Et("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));dLs.displayName="TableFooter";const un=j.forwardRef(({className:s,...t},n)=>e.jsx("tr",{ref:n,className:Et("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));un.displayName="TableRow";const Tt=j.forwardRef(({className:s,...t},n)=>e.jsx("th",{ref:n,className:Et("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Tt.displayName="TableHead";const xt=j.forwardRef(({className:s,...t},n)=>e.jsx("td",{ref:n,className:Et("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));xt.displayName="TableCell";const uLs=j.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Et("mt-4 text-sm text-muted-foreground",s),...t}));uLs.displayName="TableCaption";const Qse=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())}`},Jse=s=>s?new Date(s).toISOString():null,qLe=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:Qse(s.enrollment_open_at),enrollment_close_at:Qse(s.enrollment_close_at),kickoff_at:Qse(s.kickoff_at),charge_at:Qse(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),hLs=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>qLe(s)),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=j.useRef(null),h=j.useRef(null);j.useEffect(()=>{r(qLe(s)),i(!1)},[s.id,s.updated_at]);const m=(g,b)=>{r(v=>({...v,[g]:b})),i(!0)},p=async(g,b)=>{if(!g.type.startsWith("image/")){re.error("Please choose an image file");return}if(g.size>8*1024*1024){re.error("Image must be under 8MB");return}d(b);try{const v=g.name.split(".").pop()||"jpg",k=`programs/${s.id}/${b}-${Date.now()}.${v}`,{error:C}=await U.storage.from("event-images").upload(k,g,{cacheControl:"31536000",upsert:!0});if(C)throw C;const{data:T}=U.storage.from("event-images").getPublicUrl(k);m(b==="cover"?"cover_image_url":"hero_image_url",T.publicUrl),re.success(`${b==="cover"?"Cover":"Hero"} image uploaded — remember to save`)}catch(v){re.error(v.message||"Upload failed")}finally{d(null)}},x=async()=>{if(!n.name.trim())return re.error("Program name is required");if(!n.slug.trim())return re.error("Slug is required");o(!0);try{const g={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:Jse(n.enrollment_open_at),enrollment_close_at:Jse(n.enrollment_close_at),kickoff_at:Jse(n.kickoff_at),charge_at:Jse(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:b}=await U.from("programs").update(g).eq("id",s.id);if(b)throw b;re.success("Program saved"),i(!1),t()}catch(g){re.error(g.message||"Could not save the program")}finally{o(!1)}},y=({kind:g,label:b,hint:v})=>{const k=g==="cover"?n.cover_image_url:n.hero_image_url,C=g==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:b}),e.jsxs("div",{className:"flex flex-wrap items-start gap-4",children:[e.jsx("div",{className:"relative h-28 w-48 shrink-0 overflow-hidden rounded-lg border border-border bg-muted/40",children:k?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:k,alt:`${b} preview`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>m(g==="cover"?"cover_image_url":"hero_image_url",""),className:"absolute right-1.5 top-1.5 rounded-full bg-background/90 p-1 text-foreground shadow","aria-label":`Remove ${b}`,children:e.jsx(dr,{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(a1,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"No image"})]})}),e.jsxs("div",{className:"min-w-[220px] flex-1 space-y-2",children:[e.jsx("input",{ref:C,type:"file",accept:"image/*",className:"hidden",onChange:T=>{var P;const M=(P=T.target.files)==null?void 0:P[0];M&&p(M,g),T.target.value=""}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var T;return(T=C.current)==null?void 0:T.click()},disabled:c===g,children:[c===g?e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ja,{className:"mr-1.5 h-4 w-4"}),"Upload image"]}),e.jsx(ye,{placeholder:"…or paste an image URL",value:k,onChange:T=>m(g==="cover"?"cover_image_url":"hero_image_url",T.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v})]})]})]})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"sticky top-0 z-10 -mx-1 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-background/95 px-4 py-3 backdrop-blur",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:a?"You have unsaved changes.":"All changes saved."}),e.jsxs("div",{className:"flex gap-2",children:[a&&e.jsx(B,{variant:"ghost",onClick:()=>{r(qLe(s)),i(!1)},children:"Discard"}),e.jsxs(B,{onClick:x,disabled:l||!a,children:[l?e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})]})]}),e.jsx(be,{children:e.jsxs(Re,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Basics"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Program name"}),e.jsx(ye,{value:n.name,onChange:g=>m("name",g.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Slug (public URL)"}),e.jsx(ye,{value:n.slug,onChange:g=>m("slug",g.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["/programs/",n.slug||"slug"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subtitle"}),e.jsx(ye,{value:n.subtitle,onChange:g=>m("subtitle",g.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Tagline"}),e.jsx(ye,{value:n.tagline,onChange:g=>m("tagline",g.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Short description (cards & previews)"}),e.jsx(Ds,{rows:2,value:n.short_description,onChange:g=>m("short_description",g.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Full program description (sales page)"}),e.jsx(Ds,{rows:8,value:n.description,onChange:g=>m("description",g.target.value)})]})]})}),e.jsx(be,{children:e.jsxs(Re,{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(se,{children:"Promo video URL (optional)"}),e.jsx(ye,{placeholder:"https://youtu.be/… , Vimeo, or a direct .mp4 link",value:n.promo_video_url,onChange:g=>m("promo_video_url",g.target.value)}),e.jsx(ye,{placeholder:"Video headline (e.g. Watch: what 90 days inside Reel Estate looks like)",value:n.promo_video_headline,onChange:g=>m("promo_video_headline",g.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Plays in a cinematic player near the top of the program signup page."})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Accent color"}),e.jsx(ye,{placeholder:"#406E71",value:n.accent_color,onChange:g=>m("accent_color",g.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Sort order"}),e.jsx(ye,{type:"number",value:n.sort_order,onChange:g=>m("sort_order",Number(g.target.value))})]})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Pricing & seats"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"One-time price (USD)"}),e.jsx(ye,{type:"number",min:0,step:"1",value:n.price_cents/100,onChange:g=>m("price_cents",Math.round(Number(g.target.value)*100))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Seats (capacity)"}),e.jsx(ye,{type:"number",min:0,value:n.capacity,onChange:g=>m("capacity",Number(g.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Billing mode"}),e.jsxs(vs,{value:n.payment_mode,onValueChange:g=>m("payment_mode",g),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"delayed",children:"Save card, charge once later"}),e.jsx(Je,{value:"immediate",children:"Charge once at checkout"}),e.jsx(Je,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Charge date (one-time)"}),e.jsx(ye,{type:"datetime-local",value:n.charge_at,onChange:g=>m("charge_at",g.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Payment grace days"}),e.jsx(ye,{type:"number",min:0,value:n.payment_grace_days,onChange:g=>m("payment_grace_days",Number(g.target.value))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Days of access kept after a failed charge before access is paused."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Currency"}),e.jsx(ye,{value:n.currency,onChange:g=>m("currency",g.target.value)})]})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Schedule & structure"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Enrollment opens"}),e.jsx(ye,{type:"datetime-local",value:n.enrollment_open_at,onChange:g=>m("enrollment_open_at",g.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Enrollment closes"}),e.jsx(ye,{type:"datetime-local",value:n.enrollment_close_at,onChange:g=>m("enrollment_close_at",g.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Kickoff"}),e.jsx(ye,{type:"datetime-local",value:n.kickoff_at,onChange:g=>m("kickoff_at",g.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Length (weeks)"}),e.jsx(ye,{type:"number",min:1,value:n.duration_weeks,onChange:g=>m("duration_weeks",Number(g.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Videos per week goal"}),e.jsx(ye,{type:"number",min:0,value:n.weekly_video_goal,onChange:g=>m("weekly_video_goal",Number(g.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Timezone"}),e.jsx(ye,{value:n.timezone,onChange:g=>m("timezone",g.target.value)})]})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Visibility"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:n.status,onValueChange:g=>m("status",g),children:[e.jsx(gs,{className:"sm:max-w-xs",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"draft",children:"Draft (hidden)"}),e.jsx(Je,{value:"published",children:"Published (members can enroll)"}),e.jsx(Je,{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(Mn,{checked:n.is_featured,onCheckedChange:g=>m("is_featured",g)})]}),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(Mn,{checked:n.is_public,onCheckedChange:g=>m("is_public",g)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs(B,{onClick:x,disabled:l||!a,size:"lg",children:[l?e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},zot={title:"",description:"",category:"Personal",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},mLs=({programId:s,userId:t,memberName:n})=>{const{data:r=[],isLoading:a}=DMs(s,t),i=OMs(s,t),l=FMs(),[o,c]=j.useState(!1),[d,u]=j.useState({...zot}),[h,m]=j.useState(!1),p=j.useRef(null),x=()=>{u({...zot,sort_order:r.length}),c(!0)},y=v=>{u({id:v.id,title:v.title,description:v.description||"",category:v.category||"Personal",resource_kind:v.resource_kind,url:v.url||"",file_path:v.file_path||"",status:v.status,sort_order:v.sort_order}),c(!0)},g=async v=>{if(!(!v||!s||!t)){if(v.size>50*1024*1024)return re.error("File must be under 50MB");m(!0);try{const k=v.name.split(".").pop()||"pdf",C=`programs/${s}/members/${t}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${k}`,{error:T}=await U.storage.from(aq).upload(C,v,{contentType:v.type||"application/pdf",upsert:!1});if(T)throw T;u(M=>({...M,file_path:C,url:"",title:M.title||v.name.replace(/\.[^.]+$/,""),resource_kind:v.type==="application/pdf"?"pdf":M.resource_kind})),re.success("File uploaded")}catch(k){re.error(k.message||"Upload failed")}finally{m(!1),p.current&&(p.current.value="")}}},b=async()=>{if(!d.title.trim())return re.error("Give the resource a title");if(!d.file_path&&!d.url.trim())return re.error("Upload a file or paste a link");await i.mutateAsync({...d,sort_order:Number(d.sort_order)||0}),c(!1)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"flex items-center gap-1.5 font-medium",children:[e.jsx(du,{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:x,disabled:!t,children:[e.jsx(Js,{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(be,{className:"border-dashed",children:e.jsx(Re,{className:"p-6 text-center text-sm text-muted-foreground",children:"No personal resources yet. Upload their custom plan, feedback doc or scripts."})}):e.jsx("div",{className:"space-y-2",children:r.map(v=>e.jsx(be,{className:"border-border/60",children:e.jsxs(Re,{className:"flex flex-wrap items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:v.title}),e.jsx(qe,{variant:"secondary",children:v.category}),e.jsx(qe,{variant:"outline",className:"capitalize",children:v.resource_kind.replace("_"," ")}),v.status!=="published"&&e.jsx(qe,{variant:"outline",className:"capitalize",children:v.status})]}),v.description&&e.jsx("p",{className:"max-w-xl text-sm text-muted-foreground",children:v.description}),uCe(v)&&e.jsxs("button",{type:"button",onClick:()=>HK(v),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Tr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>y(v),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Bi(`Remove "${v.title}"?`)&&l.mutate(v)},children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})]})},v.id))}),e.jsx(Fs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx($s,{children:e.jsx(zs,{children:d.id?"Edit personal resource":"New personal resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:d.title,onChange:v=>u({...d,title:v.target.value}),placeholder:"Your 90-day content plan"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{rows:2,value:d.description,onChange:v=>u({...d,description:v.target.value})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Category"}),e.jsx(ye,{value:d.category,onChange:v=>u({...d,category:v.target.value}),placeholder:"Personal"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Type"}),e.jsxs(vs,{value:d.resource_kind,onValueChange:v=>u({...d,resource_kind:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:CEt.map(v=>e.jsx(Je,{value:v.value,children:v.label},v.value))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"File"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:h,onClick:()=>{var v;return(v=p.current)==null?void 0:v.click()},children:[h?e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ja,{className:"mr-1.5 h-4 w-4"}),d.file_path?"Replace file":"Upload file"]}),d.file_path&&e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:d.file_path.split("/").pop()})]}),e.jsx("input",{ref:p,type:"file",hidden:!0,onChange:v=>{var k;return g((k=v.target.files)==null?void 0:k[0])}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"…or link"}),e.jsx(ye,{value:d.url,onChange:v=>u({...d,url:v.target.value,file_path:""}),placeholder:"https://…"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:d.status,onValueChange:v=>u({...d,status:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"published",children:"Published"}),e.jsx(Je,{value:"draft",children:"Draft"}),e.jsx(Je,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Sort order"}),e.jsx(ye,{type:"number",value:d.sort_order,onChange:v=>u({...d,sort_order:v.target.value})})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:b,disabled:i.isPending||h,children:[i.isPending&&e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save"]})]})]})})]})},pLs=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var K,ee,J,le,ue,oe,ie,de,we,je;const i=t==null?void 0:t.user_id,[l,o]=j.useState((t==null?void 0:t.admin_notes)||""),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState(!1),[x,y]=j.useState(!1),g=j.useRef(null),{data:b,isLoading:v,refetch:k}=mt({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[xe,fe,Se,Ee,Le,De,Be,Ne]=await Promise.all([U.from("program_weekly_progress").select("*").eq("program_id",s.id).eq("user_id",i).order("week_number"),U.from("program_video_logs").select("*").eq("program_id",s.id).eq("user_id",i).order("posted_at",{ascending:!1}),U.from("program_lesson_completions").select("*").eq("program_id",s.id).eq("user_id",i),U.from("program_badge_awards").select("*").eq("program_id",s.id).eq("user_id",i),U.from("program_intake_responses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle(),U.from("program_event_attendance").select("*").eq("program_id",s.id).eq("user_id",i),U.from("program_lessons").select("id").eq("program_id",s.id),U.from("program_profile_analyses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle()]);return{weekly:xe.data||[],videos:fe.data||[],completions:Se.data||[],badges:Ee.data||[],intake:Le.data,attendance:De.data||[],lessonCount:(Be.data||[]).length,analysis:Ne.data}}});j.useEffect(()=>{var xe;h(((xe=b==null?void 0:b.analysis)==null?void 0:xe.member_notes)||"")},[(K=b==null?void 0:b.analysis)==null?void 0:K.id]);const C=j.useMemo(()=>{var Se;const xe=bZ(s),fe=((Se=b==null?void 0:b.intake)==null?void 0:Se.extra)||{};return xe.custom.map(Ee=>({label:Ee.label,value:typeof fe[Ee.id]=="boolean"?fe[Ee.id]?"Yes":"No":fe[Ee.id]||""})).filter(Ee=>!!Ee.value)},[s,b==null?void 0:b.intake]),T=async xe=>i?U.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...xe},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},M=async xe=>{if(xe.type!=="application/pdf")return re.error("Please choose a PDF file");if(xe.size>25*1024*1024)return re.error("PDF must be under 25MB");y(!0);try{const fe=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:Se}=await U.storage.from("event-images").upload(fe,xe,{contentType:"application/pdf",upsert:!0});if(Se)throw Se;const{data:Ee}=U.storage.from("event-images").getPublicUrl(fe),{error:Le}=await T({report_url:Ee.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Le)throw Le;re.success("Profile review uploaded"),await k()}catch(fe){re.error(fe.message||"Upload failed")}finally{y(!1)}},P=async()=>{const{error:xe}=await T({report_url:null,status:"in_review"});if(xe)return re.error(xe.message);re.success("Review removed"),await k()},L=async()=>{p(!0);const{error:xe}=await T({member_notes:u});if(p(!1),xe)return re.error(xe.message);re.success("Review notes saved"),await k()},I=async()=>{if(!t)return;d(!0);const{error:xe}=await U.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),xe)return re.error(xe.message);re.success("Notes saved"),a()},O=((b==null?void 0:b.videos)||[]).filter(xe=>xe.posted).length,$=(s.weekly_video_goal||0)*(s.duration_weeks||0),q=b!=null&&b.lessonCount?Math.round(((b==null?void 0:b.completions.length)||0)/b.lessonCount*100):0,W=$?Math.min(100,Math.round(O/$*100)):0,G=((b==null?void 0:b.attendance)||[]).filter(xe=>xe.attended).length;return e.jsx(v1,{open:n,onOpenChange:r,children:e.jsxs(rv,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(Lb,{className:"mb-4",children:[e.jsxs(Pb,{children:[((ee=t==null?void 0:t.profile)==null?void 0:ee.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(J=t==null?void 0:t.profile)==null?void 0:J.email}),i&&e.jsx(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(((le=t==null?void 0:t.profile)==null?void 0:le.name)||((ue=t==null?void 0:t.profile)==null?void 0:ue.email)||"this member")}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"mr-2 h-4 w-4"}),"Open their dashboard"]})})]}),t?v?e.jsx(gn,{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(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx(qe,{className:"mt-1 capitalize",children:String(t.status).replace(/_/g," ")}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[Tp(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${Nd(t.charged_at)}`:`Charge ${Nd(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(be,{children:e.jsxs(Re,{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:Nd(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",Nd(t.created_at)]})]})})]}),e.jsx(be,{children:e.jsxs(Re,{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:[O," / ",$||"—"]})]}),e.jsx(qi,{value:W})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Curriculum completed"}),e.jsxs("span",{className:"text-muted-foreground",children:[(b==null?void 0:b.completions.length)||0," / ",(b==null?void 0:b.lessonCount)||0]})]}),e.jsx(qi,{value:q})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 border-t border-border/60 pt-4 text-sm",children:[e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Live sessions attended: "}),G]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Badges: "}),(b==null?void 0:b.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(b==null?void 0:b.weekly.length)||0]})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((b==null?void 0:b.weekly.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No weekly check-ins yet."}):e.jsx("div",{className:"space-y-3",children:b.weekly.map(xe=>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 ",xe.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[xe.videos_posted,"/",xe.goal_videos||s.weekly_video_goal," posted ·"," ",xe.stories_posted," stories"]})]}),xe.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",xe.biggest_win]}),xe.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",xe.biggest_challenge]})]},xe.id))})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((b==null?void 0:b.videos.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No videos logged yet."}):e.jsx("div",{className:"space-y-2",children:b.videos.slice(0,25).map(xe=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Zr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:xe.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",xe.week_number," · ",Nd(xe.posted_at)]}),xe.instagram_url&&e.jsx("a",{href:xe.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"})})]},xe.id))})]})}),(b==null?void 0:b.intake)&&e.jsx(be,{children:e.jsxs(Re,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",b.intake.full_name],["Email",b.intake.email],["Phone",b.intake.phone],["Instagram",b.intake.instagram_handle],["City / market",b.intake.city],["Areas served",b.intake.service_areas],["Years in real estate",b.intake.years_experience],["Specialty",b.intake.specialty],["Target audience",b.intake.target_audience],["On camera",b.intake.video_comfort],["Posts today",b.intake.posting_frequency],["Content style",b.intake.content_style],["Interests",b.intake.personal_interests],["#1 goal",b.intake.primary_goal],["Topics to avoid",b.intake.topics_to_avoid],["Time zone",b.intake.timezone]].filter(([,xe])=>!!xe).map(([xe,fe])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[xe,": "]}),fe]},xe)),C.map(({label:xe,value:fe})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[xe,": "]}),fe]},xe)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",b.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(be,{children:e.jsx(Re,{className:"p-5",children:e.jsx(mLs,{programId:s.id,userId:i,memberName:(oe=t==null?void 0:t.profile)==null?void 0:oe.name})})}),e.jsx(be,{children:e.jsxs(Re,{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."})]}),((ie=b==null?void 0:b.analysis)==null?void 0:ie.status)&&e.jsx(qe,{variant:"secondary",className:"capitalize",children:String(b.analysis.status).replace(/_/g," ")})]}),(de=b==null?void 0:b.analysis)!=null&&de.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($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:b.analysis.report_url,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex items-center gap-1 text-primary hover:underline",children:["View ",e.jsx(Tr,{className:"h-3.5 w-3.5"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No review uploaded yet."}),e.jsx("input",{ref:g,type:"file",accept:"application/pdf",className:"hidden",onChange:xe=>{var Se;const fe=(Se=xe.target.files)==null?void 0:Se[0];fe&&M(fe),xe.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{var xe;return(xe=g.current)==null?void 0:xe.click()},disabled:x,children:[e.jsx(Ja,{className:"mr-1.5 h-3.5 w-3.5"}),x?"Uploading…":(we=b==null?void 0:b.analysis)!=null&&we.report_url?"Replace PDF":"Upload PDF"]}),((je=b==null?void 0:b.analysis)==null?void 0:je.report_url)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:P,children:"Remove"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(se,{children:"Review summary shown to the agent (optional)"}),e.jsx(Ds,{rows:3,value:u,onChange:xe=>h(xe.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:L,disabled:m,children:"Save review notes"})})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"space-y-3 p-5",children:[e.jsx(se,{children:"Coach notes (internal)"}),e.jsx(Ds,{rows:4,value:l,onChange:xe=>o(xe.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{size:"sm",onClick:I,disabled:c,children:"Save notes"})})]})})]}):null]})})},Bot={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},$ot=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},fLs=({program:s})=>{const{data:t=[],isLoading:n}=wMs(s.id),r=jMs(s.id),a=NMs(),[i,l]=j.useState(!1),[o,c]=j.useState({...Bot}),d=()=>{c({...Bot}),l(!0)},u=x=>{c({id:x.id,code:x.code,label:x.label||"",kind:x.percent_off!=null?"percent":"amount",percent_off:x.percent_off!=null?String(x.percent_off):"",amount_off:x.amount_off_cents!=null?String(x.amount_off_cents/100):"",max_redemptions:x.max_redemptions!=null?String(x.max_redemptions):"",starts_at:$ot(x.starts_at),expires_at:$ot(x.expires_at),is_active:x.is_active}),l(!0)},h=j.useMemo(()=>{const x=o.kind==="percent"?Math.floor(s.price_cents*Number(o.percent_off||0)/100):Math.round(Number(o.amount_off||0)*100),y=Math.min(Math.max(x,0),s.price_cents);return{discount:y,final:s.price_cents-y}},[o,s.price_cents]),m=async()=>{if(!o.code.trim())return re.error("Give the code a name, e.g. FOUNDER50");await r.mutateAsync({id:o.id,code:o.code,label:o.label||null,percent_off:o.kind==="percent"?Number(o.percent_off)||0:null,amount_off_cents:o.kind==="amount"?Math.round(Number(o.amount_off||0)*100):null,max_redemptions:o.max_redemptions?Number(o.max_redemptions):null,starts_at:o.starts_at?new Date(o.starts_at).toISOString():null,expires_at:o.expires_at?new Date(o.expires_at).toISOString():null,is_active:o.is_active}),l(!1)},p=x=>{const y=x.percent_off!=null?Math.floor(s.price_cents*Number(x.percent_off)/100):x.amount_off_cents||0,g=Math.max(s.price_cents-Math.min(y,s.price_cents),0);return{off:x.percent_off!=null?`${Number(x.percent_off)}% off`:`${Tp(x.amount_off_cents||0,s.currency)} off`,final:Tp(g,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{children:e.jsxs(Re,{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 ",Tp(s.price_cents,s.currency)," charge."]})]}),e.jsxs(Fs,{open:i,onOpenChange:l,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{onClick:d,children:[e.jsx(Js,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(Os,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:o.id?"Edit discount code":"Create a discount code"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Code"}),e.jsx(ye,{placeholder:"FOUNDER50",value:o.code,onChange:x=>c({...o,code:x.target.value.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Internal label (optional)"}),e.jsx(ye,{placeholder:"Founding cohort",value:o.label,onChange:x=>c({...o,label:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Discount type"}),e.jsxs(vs,{value:o.kind,onValueChange:x=>c({...o,kind:x}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"percent",children:"Percent off"}),e.jsx(Je,{value:"amount",children:"Dollar amount off"})]})]})]}),o.kind==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Percent off"}),e.jsx(ye,{type:"number",min:1,max:100,value:o.percent_off,onChange:x=>c({...o,percent_off:x.target.value})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Amount off (USD)"}),e.jsx(ye,{type:"number",min:0,value:o.amount_off,onChange:x=>c({...o,amount_off:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Max redemptions (blank = unlimited)"}),e.jsx(ye,{type:"number",min:1,value:o.max_redemptions,onChange:x=>c({...o,max_redemptions:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Active from (optional)"}),e.jsx(ye,{type:"datetime-local",value:o.starts_at,onChange:x=>c({...o,starts_at:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Expires (optional)"}),e.jsx(ye,{type:"datetime-local",value:o.expires_at,onChange:x=>c({...o,expires_at:x.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Code is active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to stop new redemptions instantly."})]}),e.jsx(Mn,{checked:o.is_active,onCheckedChange:x=>c({...o,is_active:x})})]}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 text-sm",children:[e.jsx("p",{className:"font-medium",children:"Enrollee sees"}),e.jsxs("p",{className:"mt-1 text-muted-foreground",children:[Tp(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Tp(h.final,s.currency)})," ","(",Tp(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(Nr,{children:e.jsxs(B,{onClick:m,disabled:r.isPending,children:[r.isPending&&e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save changes":"Create code"]})})]})]})]})}),n?e.jsx(gn,{className:"h-40 w-full rounded-xl"}):t.length===0?e.jsx(be,{className:"border-dashed",children:e.jsxs(Re,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(wf,{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(be,{children:e.jsx(Re,{className:"overflow-x-auto p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Code"}),e.jsx(Tt,{children:"Discount"}),e.jsx(Tt,{children:"Price after"}),e.jsx(Tt,{children:"Used"}),e.jsx(Tt,{children:"Window"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:t.map(x=>{const y=p(x);return e.jsxs(un,{children:[e.jsxs(xt,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:x.code}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(x.code),re.success("Code copied")},children:e.jsx(ja,{className:"h-3.5 w-3.5"})})]}),x.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:x.label})]}),e.jsx(xt,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(QT,{className:"h-3.5 w-3.5 text-muted-foreground"}),y.off]})}),e.jsx(xt,{className:"font-medium",children:y.final}),e.jsxs(xt,{children:[x.times_redeemed,x.max_redemptions?` / ${x.max_redemptions}`:""]}),e.jsxs(xt,{className:"text-xs text-muted-foreground",children:[x.starts_at?`From ${Nd(x.starts_at)}`:"Anytime",x.expires_at?` · until ${Nd(x.expires_at)}`:""]}),e.jsx(xt,{children:e.jsx(qe,{variant:x.is_active?"default":"secondary",children:x.is_active?"Active":"Paused"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>u(x),children:"Edit"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Bi(`Delete ${x.code}?`)&&a.mutate(x.id)},children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})})]},x.id)})})]})})})]})},vk=({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(Rr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx(hd,{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})]})]}),xLs=({program:s})=>{var c,d;const{data:t,isLoading:n}=mt({queryKey:["admin-program-content-counts",s.id],queryFn:async()=>{const[u,h,m,p,x]=await Promise.all([U.from("program_weeks").select("id, week_number, title").eq("program_id",s.id),U.from("program_lessons").select("id, title").eq("program_id",s.id),U.from("program_resources").select("id, title").eq("program_id",s.id),U.from("program_events").select("id, title, starts_at").eq("program_id",s.id),U.from("program_announcements").select("id, title").eq("program_id",s.id)]);return{weeks:u.data||[],lessons:h.data||[],resources:m.data||[],events:p.data||[],announcements:x.data||[]}}}),{notOpenYet:r,closed:a,opensLabel:i}=dCe(s),l=`/programs/${s.slug}`,o=[{icon:yn,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:rz,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:ty,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 ${Tp(s.price_cents,s.currency)} charge runs on ${Nd(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${Tp(s.price_cents,s.currency)} once at checkout.`},{icon:on,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:Q9,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(be,{children:e.jsxs(Re,{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(be,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Re,{className:"flex items-start gap-3 p-5 text-sm",children:[e.jsx(hd,{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(be,{children:e.jsxs(Re,{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(be,{children:e.jsxs(Re,{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(gn,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(vk,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(vk,{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(vk,{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(vk,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":Tp(s.price_cents,s.currency)}),e.jsx(vk,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${Nd(s.kickoff_at)||"not set"} · charge ${Nd(s.charge_at)||"not set"}`}),e.jsx(vk,{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(vk,{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(vk,{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(vk,{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 ${Nd(t.events[0].starts_at)}`:""}`}),e.jsx(vk,{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(be,{children:e.jsx(Re,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:Vc,label:"Weeks",value:t.weeks.length},{icon:$r,label:"Lessons",value:t.lessons.length},{icon:$r,label:"Resources",value:t.resources.length},{icon:Vc,label:"Events",value:t.events.length},{icon:jh,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(qe,{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."})]})},gLs=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],yLs={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},vLs=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>bZ(s)),[a,i]=j.useState(!1),[l,o]=j.useState(!1);j.useEffect(()=>{r(bZ(s)),i(!1)},[s.id,s.updated_at]);const c=g=>{r(b=>({...b,...g})),i(!0)},d=(g,b)=>{const v=b?n.hidden.filter(C=>C!==g):[...new Set([...n.hidden,g])],k=b?n.required:n.required.filter(C=>C!==g);c({hidden:v,required:k})},u=(g,b)=>{c({required:b?[...new Set([...n.required,g])]:n.required.filter(v=>v!==g)})},h=()=>{const g={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,g]})},m=(g,b)=>c({custom:n.custom.map(v=>v.id===g?{...v,...b}:v)}),p=g=>c({custom:n.custom.filter(b=>b.id!==g)}),x=(g,b)=>{const v=[...n.custom],k=g+b;k<0||k>=v.length||([v[g],v[k]]=[v[k],v[g]],c({custom:v}))},y=async()=>{if(n.custom.find(k=>!k.label.trim()))return re.error("Every custom question needs a label");o(!0);const b={...s.sales_copy||{},intake:n},{error:v}=await U.from("programs").update({sales_copy:b}).eq("id",s.id);if(o(!1),v)return re.error(v.message);i(!1),re.success("Intake form saved"),t==null||t()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake form"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls the questions each agent answers during enrollment."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(Jo,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Saving…":"Save intake form"]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsx(Ut,{className:"text-sm",children:"Intro message"})}),e.jsx(Re,{children:e.jsx(Ds,{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:g=>c({intro:g.target.value})})})]}),[0,1,2].map(g=>e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsx(Ut,{className:"text-sm",children:gLs[g]})}),e.jsxs(Re,{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"})]}),yHe.filter(b=>b.step===g).map(b=>{const v=!n.hidden.includes(b.key);return e.jsxs("div",{className:"grid grid-cols-[1fr,auto,auto] items-center gap-4 rounded-lg border border-border/60 px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:b.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(Mn,{checked:v,onCheckedChange:k=>d(b.key,k),"aria-label":`Show ${b.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(Mn,{checked:n.required.includes(b.key),disabled:!v,onCheckedChange:k=>u(b.key,k),"aria-label":`Require ${b.label}`})})]},b.key)})]})]},g)),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Ut,{className:"text-sm",children:["Custom questions"," ",e.jsx(qe,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(Js,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(Re,{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((g,b)=>e.jsxs("div",{className:"space-y-3 rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"flex flex-col pt-1.5",children:e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>x(b,-1),"aria-label":"Move up",children:e.jsx(Fp,{className:"h-4 w-4"})})}),e.jsxs("div",{className:"grid flex-1 gap-3 sm:grid-cols-[2fr,1fr]",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Question"}),e.jsx(ye,{value:g.label,placeholder:"What is your biggest content roadblock?",onChange:v=>m(g.id,{label:v.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Answer type"}),e.jsxs(vs,{value:g.type,onValueChange:v=>m(g.id,{type:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Object.entries(yLs).map(([v,k])=>e.jsx(Je,{value:v,children:k},v))})]})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p(g.id),"aria-label":"Delete question",children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]}),g.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Ds,{rows:3,value:(g.options||[]).join(` `),onChange:v=>m(g.id,{options:v.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(se,{className:"text-xs",children:"Helper text (optional)"}),e.jsx(ye,{value:g.help||"",onChange:v=>m(g.id,{help:v.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(Mn,{checked:!!g.required,onCheckedChange:v=>m(g.id,{required:v}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},g.id))]})]})]})},bLs=[kx,$r,uu],_Ls=["Business profile","Content style","Goals & consent"],wLs=({fieldKey:s})=>s.includes("phone")?e.jsx(pa,{className:"h-3.5 w-3.5"}):s.includes("email")?e.jsx(on,{className:"h-3.5 w-3.5"}):s.includes("instagram")?e.jsx(vm,{className:"h-3.5 w-3.5"}):s.includes("city")||s.includes("area")?e.jsx(oi,{className:"h-3.5 w-3.5"}):s.includes("timezone")?e.jsx(Vr,{className:"h-3.5 w-3.5"}):s.includes("consent")?s.includes("true")?e.jsx(Rr,{className:"h-3.5 w-3.5"}):e.jsx(Rd,{className:"h-3.5 w-3.5"}):e.jsx(Eo,{className:"h-3.5 w-3.5"}),Uot=(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(Rr,{className:"h-3.5 w-3.5"})," Yes"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[e.jsx(Rd,{className:"h-3.5 w-3.5"})," No"]}):String(s),jLs=({program:s})=>{const[t,n]=j.useState(""),[r,a]=j.useState(new Set),{data:i=[],isLoading:l}=mt({queryKey:["admin-program-intakes",s.id],queryFn:async()=>{const{data:h,error:m}=await U.from("program_intake_responses").select("*").eq("program_id",s.id).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=bZ(s),c=yHe.filter(h=>!o.hidden.includes(h.key)),d=i.filter(h=>{const m=t.toLowerCase();return m?String(h.full_name||"").toLowerCase().includes(m)||String(h.email||"").toLowerCase().includes(m)||String(h.city||"").toLowerCase().includes(m)||Object.values(h).some(p=>String(p).toLowerCase().includes(m)):!0}),u=h=>{const m=new Set(r);m.has(h)?m.delete(h):m.add(h),a(m)};return l?e.jsx(gn,{className:"h-96 w-full rounded-xl"}):i.length===0?e.jsx(be,{className:"border-dashed",children:e.jsxs(Re,{className:"p-12 text-center text-sm text-muted-foreground",children:[e.jsx($r,{className:"mx-auto mb-3 h-6 w-6"}),e.jsx("p",{children:"No intake responses yet."}),e.jsx("p",{className:"mt-1 text-xs",children:"Responses appear here once members complete the enrollment intake form."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake responses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[d.length," of ",i.length," response",i.length===1?"":"s"," · every field from the enrollment intake form"]})]}),e.jsxs("div",{className:"relative w-full sm:w-64",children:[e.jsx(Fr,{className:"absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search responses…",value:t,onChange:h=>n(h.target.value),className:"pl-9"})]})]}),d.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No responses match your search."}),e.jsx("div",{className:"space-y-3",children:d.map(h=>{const m=r.has(h.id),p=Nd(h.created_at,!0);return e.jsx(be,{className:"overflow-hidden",children:e.jsxs(i0,{open:m,onOpenChange:()=>u(h.id),children:[e.jsx(o0,{asChild:!0,children:e.jsxs(Ft,{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(Eo,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-sm font-semibold",children:[h.full_name||"Unnamed member",h.city&&e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["· ",h.city]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.email,h.email&&h.phone&&" · ",h.phone]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"hidden text-right sm:block",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Submitted"}),e.jsx("p",{className:"text-xs font-medium",children:p})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(Po,{className:`h-4 w-4 transition-transform ${m?"rotate-180":""}`})})]})]})}),e.jsx(l0,{children:e.jsxs(Re,{className:"space-y-5 p-5",children:[[0,1,2].map(x=>{const y=c.filter(b=>b.step===x),g=bLs[x];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(g,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:_Ls[x]})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:y.map(b=>{const v=h[b.key];return v==null||v===""?null:e.jsxs("div",{className:"rounded-lg border border-border/50 p-3",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(wLs,{fieldKey:b.key}),b.label]}),e.jsx("p",{className:"text-sm font-medium",children:Uot(v,b.key)})]},b.key)})})]},x)}),o.custom&&o.custom.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx($r,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom questions"})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.custom.map(x=>{var g;const y=(g=h.extra)==null?void 0:g[x.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:x.label}),e.jsx("p",{className:"text-sm font-medium",children:Uot(y,x.id)})]},x.id)})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2 text-xs text-muted-foreground",children:[e.jsx(ra,{className:"h-3.5 w-3.5"}),"Submitted ",p,h.timezone&&e.jsxs("span",{className:"ml-2",children:["· Timezone: ",h.timezone]})]})]})})]})},h.id)})})]})},NLs=[{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"}],kLs=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},qot={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},SLs=({programId:s})=>{const{data:t=[],isLoading:n}=CMs(s),r=AMs(s),a=TMs(),[i,l]=j.useState(!1),[o,c]=j.useState({...qot}),d=()=>{c({...qot}),l(!0)},u=g=>{c({id:g.id,title:g.title,description:g.description||"",event_kind:g.event_kind,starts_at:kLs(g.starts_at),duration_minutes:g.duration_minutes,speaker:g.speaker||"",meeting_link:g.meeting_link||"",replay_url:g.replay_url||"",is_published:g.is_published}),l(!0)},h=async()=>{if(!o.title.trim())return re.error("Give the session a title");if(!o.starts_at)return re.error("Pick a date and time");await r.mutateAsync({...o,starts_at:new Date(o.starts_at).toISOString(),duration_minutes:Number(o.duration_minutes)||60}),l(!1)},m=Date.now(),p=t.filter(g=>new Date(g.starts_at).getTime()>=m),x=t.filter(g=>new Date(g.starts_at).getTime()e.jsx(be,{className:"border-border/60",children:e.jsxs(Re,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:g.title}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:g.event_kind.replace("_"," ")}),!g.is_published&&e.jsx(qe,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Nd(g.starts_at,!0)," · ",g.duration_minutes," min",g.speaker?` · ${g.speaker}`:""]}),g.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:g.description}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[g.meeting_link?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:g.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(g.meeting_link),re.success("Join link copied")},children:[e.jsx(ja,{className:"h-3 w-3"})," Copy"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"No meeting link yet"}),g.replay_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:g.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Zr,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>u(g),children:e.jsx(Za,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:async()=>{await Bi(`Remove "${g.title}"?`)&&a.mutate(g.id)},children:e.jsx(Rn,{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(Js,{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(be,{className:"border-dashed",children:e.jsxs(Re,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(ym,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No live sessions scheduled"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Paste your recurring Zoom link once for each call — kickoff, weekly masterminds, workshops and office hours."})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Upcoming (",p.length,")"]}),p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing upcoming."}):p.map(g=>e.jsx(y,{e:g},g.id))]}),x.length>0&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Past (",x.length,") — add replay links so members can catch up"]}),x.map(g=>e.jsx(y,{e:g},g.id))]})]}),e.jsx(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:o.id?"Edit session":"Add a live session"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{placeholder:"Week 1 Mastermind — Content that converts",value:o.title,onChange:g=>c({...o,title:g.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Type"}),e.jsxs(vs,{value:o.event_kind,onValueChange:g=>c({...o,event_kind:g}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:NLs.map(g=>e.jsx(Je,{value:g.value,children:g.label},g.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Host / speaker"}),e.jsx(ye,{value:o.speaker,onChange:g=>c({...o,speaker:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Starts (your local time)"}),e.jsx(ye,{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(se,{children:"Length (minutes)"}),e.jsx(ye,{type:"number",value:o.duration_minutes,onChange:g=>c({...o,duration_minutes:g.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Zoom / meeting link"}),e.jsx(ye,{placeholder:"https://us02web.zoom.us/j/1234567890?pwd=…",value:o.meeting_link,onChange:g=>c({...o,meeting_link:g.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Members only see this after they're enrolled. A recurring Zoom link can be reused on every session."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Replay link (after the call)"}),e.jsx(ye,{placeholder:"YouTube, Vimeo, Loom or Zoom cloud recording URL",value:o.replay_url,onChange:g=>c({...o,replay_url:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"What we'll cover"}),e.jsx(Ds,{rows:3,value:o.description,onChange:g=>c({...o,description: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:"Visible to members"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to draft a session privately."})]}),e.jsx(Mn,{checked:o.is_published,onCheckedChange:g=>c({...o,is_published:g})})]})]}),e.jsx(Nr,{children:e.jsxs(B,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},Vot={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},CLs=({programId:s})=>{const{data:t,isLoading:n}=EMs(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],i=MMs(s),l=LMs(),[o,c]=j.useState(!1),[d,u]=j.useState({...Vot}),h=()=>{u({...Vot,sort_order:r.length}),c(!0)},m=g=>{u({id:g.id,title:g.title,summary:g.summary||"",week_id:g.week_id||"none",duration_minutes:g.duration_minutes??"",video_url:g.video_url||"",worksheet_url:g.worksheet_url||"",action_assignment:g.action_assignment||"",status:g.status,sort_order:g.sort_order}),c(!0)},p=async()=>{if(!d.title.trim())return re.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)},x=g=>{const b=a.find(v=>v.id===g);return b?`Week ${b.week_number}`:"Unassigned"},y=SEt(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(Js,{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(be,{className:"border-dashed",children:e.jsxs(Re,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(wh,{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(g=>e.jsx(be,{className:"border-border/60",children:e.jsxs(Re,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:g.title}),e.jsx(qe,{variant:"secondary",children:x(g.week_id)}),g.status!=="published"&&e.jsx(qe,{variant:"outline",className:"capitalize",children:g.status}),g.duration_minutes?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[g.duration_minutes," min"]}):null]}),g.summary&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:g.summary}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[g.video_url?e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:g.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"}),g.worksheet_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:g.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(g),children:e.jsx(Za,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:async()=>{await Bi(`Remove "${g.title}"?`)&&l.mutate(g.id)},children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]})},g.id))}),e.jsx(Fs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{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(se,{children:"Title"}),e.jsx(ye,{placeholder:"How to script a 30-second listing reel",value:d.title,onChange:g=>u({...d,title:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Video link"}),e.jsx(ye,{placeholder:"https://youtu.be/… , Vimeo or Loom URL",value:d.video_url,onChange:g=>u({...d,video_url:g.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(se,{children:"Week"}),e.jsxs(vs,{value:d.week_id,onValueChange:g=>u({...d,week_id:g}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"Unassigned (library)"}),a.map(g=>e.jsxs(Je,{value:g.id,children:["Week ",g.week_number," — ",g.title]},g.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Length (minutes)"}),e.jsx(ye,{type:"number",value:d.duration_minutes,onChange:g=>u({...d,duration_minutes:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:d.status,onValueChange:g=>u({...d,status:g}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"published",children:"Published (visible)"}),e.jsx(Je,{value:"draft",children:"Draft (hidden)"}),e.jsx(Je,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Order"}),e.jsx(ye,{type:"number",value:d.sort_order,onChange:g=>u({...d,sort_order:g.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Summary"}),e.jsx(Ds,{rows:3,value:d.summary,onChange:g=>u({...d,summary:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Worksheet / download link"}),e.jsx(ye,{value:d.worksheet_url,onChange:g=>u({...d,worksheet_url:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Action assignment"}),e.jsx(Ds,{rows:2,placeholder:"Post one reel using this hook before your next mastermind.",value:d.action_assignment,onChange:g=>u({...d,action_assignment:g.target.value})})]})]}),e.jsx(Nr,{children:e.jsxs(B,{onClick:p,disabled:i.isPending,children:[i.isPending&&e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"}),d.id?"Save video":"Add video"]})})]})})]})},Hot={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},ALs=({programId:s})=>{const{data:t=[],isLoading:n}=PMs(s),r=IMs(s),a=RMs(),[i,l]=j.useState(!1),[o,c]=j.useState({...Hot}),[d,u]=j.useState(!1),h=j.useRef(null),m=Array.from(new Set(t.map(b=>b.category))).filter(Boolean),p=()=>{c({...Hot,sort_order:t.length}),l(!0)},x=b=>{c({id:b.id,title:b.title,description:b.description||"",category:b.category||"Resources",resource_kind:b.resource_kind,url:b.url||"",file_path:b.file_path||"",status:b.status,sort_order:b.sort_order}),l(!0)},y=async b=>{if(!(!b||!s)){if(b.size>50*1024*1024)return re.error("File must be under 50MB");u(!0);try{const v=b.name.split(".").pop()||"pdf",k=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${v}`,{error:C}=await U.storage.from(aq).upload(k,b,{contentType:b.type||"application/pdf",upsert:!1});if(C)throw C;c(T=>({...T,file_path:k,url:"",title:T.title||b.name.replace(/\.[^.]+$/,""),resource_kind:b.type==="application/pdf"?"pdf":T.resource_kind})),re.success("File uploaded")}catch(v){re.error(v.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},g=async()=>{if(!o.title.trim())return re.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return re.error("Upload a file or paste a link");await r.mutateAsync({...o,sort_order:Number(o.sort_order)||0}),l(!1)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Resources"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload PDFs, worksheets and checklists — or link to Canva/Google templates. Enrollees see them grouped by category in their program dashboard."})]}),e.jsxs(B,{onClick:p,children:[e.jsx(Js,{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(be,{className:"border-dashed",children:e.jsxs(Re,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx($r,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No resources yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add the swipe files, scripts and worksheets that make this program feel premium."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(b=>{const v=uCe(b);return e.jsx(be,{className:"border-border/60",children:e.jsxs(Re,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:b.title}),e.jsx(qe,{variant:"secondary",children:b.category}),e.jsx(qe,{variant:"outline",className:"capitalize",children:b.resource_kind.replace("_"," ")}),b.status!=="published"&&e.jsx(qe,{variant:"outline",className:"capitalize",children:b.status})]}),b.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:b.description}),v&&e.jsxs("button",{type:"button",onClick:()=>HK(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:()=>x(b),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Bi(`Remove "${b.title}"?`)&&a.mutate(b)},children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})]})},b.id)})}),e.jsx(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx($s,{children:e.jsx(zs,{children:o.id?"Edit resource":"Add resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:o.title,onChange:b=>c({...o,title:b.target.value}),placeholder:"90-Day Content Calendar"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{rows:2,value:o.description,onChange:b=>c({...o,description:b.target.value}),placeholder:"What this is and how to use it"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Category"}),e.jsx(ye,{value:o.category,onChange:b=>c({...o,category:b.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:m.map(b=>e.jsx("option",{value:b},b))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Type"}),e.jsxs(vs,{value:o.resource_kind,onValueChange:b=>c({...o,resource_kind:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:CEt.map(b=>e.jsx(Je,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(se,{children:"File"}),e.jsx("input",{ref:h,type:"file",className:"hidden",accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.csv,.zip,image/*",onChange:b=>{var v;return y((v=b.target.files)==null?void 0:v[0])}}),o.file_path?e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate",children:o.file_path.split("/").pop()}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c({...o,file_path:""}),children:"Remove"})]}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{var b;return(b=h.current)==null?void 0:b.click()},disabled:d,children:[d?e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ja,{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(ye,{value:o.url,onChange:b=>c({...o,url:b.target.value,file_path:""}),placeholder:"https://…",disabled:!!o.file_path})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:o.status,onValueChange:b=>c({...o,status:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"published",children:"Published (visible)"}),e.jsx(Je,{value:"draft",children:"Draft (hidden)"}),e.jsx(Je,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Sort order"}),e.jsx(ye,{type:"number",value:o.sort_order,onChange:b=>c({...o,sort_order:b.target.value})})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:g,disabled:r.isPending||d,children:[r.isPending&&e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},TLs=({programId:s})=>{const{data:t=[],isLoading:n}=$Ms(s),r=j.useMemo(()=>{const l=Date.now()-6048e5;return t.filter(o=>new Date(o.created_at).getTime()>=l).length},[t]),a=t.map(l=>l.email).filter(Boolean).join(", "),i=()=>{const l=`Name,Email,Phone,Brokerage,Joined `,o=t.map(u=>[u.full_name,u.email,u.phone,u.brokerage,u.created_at].map(h=>`"${(h??"").toString().replace(/"/g,'""')}"`).join(",")).join(` `),c=URL.createObjectURL(new Blob([l+o],{type:"text/csv"})),d=document.createElement("a");d.href=c,d.download="program-interest.csv",d.click(),URL.revokeObjectURL(c)};return n?e.jsx(gn,{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(be,{children:e.jsxs(Re,{className:"flex items-center gap-3 p-4",children:[e.jsx(f3,{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(be,{children:e.jsxs(Re,{className:"flex items-center gap-3 p-4",children:[e.jsx(Bn,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:r}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signed up in last 7 days"})]})]})}),e.jsx(be,{children:e.jsx(Re,{className:"flex items-center gap-3 p-4",children:e.jsxs(qe,{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),re.success("Emails copied")},children:[e.jsx(ja,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs(B,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(ii,{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(Tt,{children:"Member"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"Joined"})]})}),e.jsx(za,{children:t.map(l=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:l.full_name||"—"}),e.jsx(xt,{children:l.email||"—"}),e.jsx(xt,{children:l.phone||"—"}),e.jsx(xt,{children:l.brokerage||"—"}),e.jsx(xt,{className:"text-muted-foreground",children:Nd(l.created_at)})]},l.id))})]})})]})},Got={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:""},ELs=()=>{const s=as(),[t,n]=j.useState(null),[r,a]=j.useState(!1),[i,l]=j.useState({...Got}),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(null),{data:p=[],isLoading:x}=mt({queryKey:["admin-programs"],queryFn:async()=>{const{data:L,error:I}=await U.from("programs").select("*").order("created_at",{ascending:!1});if(I)throw I;return L||[]}}),y=p.find(L=>L.id===t)||p[0]||null,{data:g=[]}=mt({queryKey:["admin-program-enrollments",y==null?void 0:y.id],enabled:!!(y!=null&&y.id),queryFn:async()=>{const{data:L,error:I}=await U.from("program_enrollments").select("*").eq("program_id",y.id).order("created_at",{ascending:!1});if(I)throw I;const O=(L||[]).map(W=>W.user_id),{data:$}=O.length?await U.from("profiles").select("id, name, email").in("id",O):{data:[]},q=new Map(($||[]).map(W=>[W.id,W]));return(L||[]).map(W=>({...W,profile:q.get(W.user_id)}))}}),{data:b=[]}=mt({queryKey:["admin-program-intakes",y==null?void 0:y.id],enabled:!!(y!=null&&y.id),queryFn:async()=>{const{data:L,error:I}=await U.from("program_intake_responses").select("*").eq("program_id",y.id);if(I)throw I;return L||[]}}),{data:v=[]}=mt({queryKey:["admin-program-audit",y==null?void 0:y.id],enabled:!!(y!=null&&y.id),queryFn:async()=>{const{data:L,error:I}=await U.from("program_audit_logs").select("*").eq("program_id",y.id).order("created_at",{ascending:!1}).limit(100);if(I)throw I;return L||[]}}),k=async()=>{c(!0);try{const L={...i,slug:i.slug||i.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),kickoff_at:i.kickoff_at||null,charge_at:i.charge_at||null,enrollment_close_at:i.enrollment_close_at||null},{error:I}=await U.from("programs").insert(L);if(I)throw I;re.success("Program created"),a(!1),l({...Got}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(L){re.error(L.message||"Could not create the program")}finally{c(!1)}},C=async L=>{if(!y)return;const{error:I}=await U.from("programs").update(L).eq("id",y.id);if(I)return re.error(I.message);s.invalidateQueries({queryKey:["admin-programs"]})},T=async(L,I)=>{const{error:O}=await U.from("program_enrollments").update(I).eq("id",L);if(O)return re.error(O.message);re.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},M=async L=>{u(!0);const{data:I,error:O}=await U.functions.invoke("program-charge-due",{body:L?{enrollment_id:L}:{}});if(u(!1),O||I!=null&&I.error)return re.error((I==null?void 0:I.error)||(O==null?void 0:O.message));re.success(`Processed ${(I==null?void 0:I.processed)??0} charge(s)`),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},P=L=>L==="paid"||L==="completed"?"default":L==="payment_failed"?"destructive":"secondary";return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-7xl space-y-6 p-4 md:p-8",children:[e.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Programs"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage cohorts, enrollments, delayed billing and program content."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>M(),disabled:d,children:[d?e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(ty,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(Fs,{open:r,onOpenChange:a,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Js,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(Os,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Create a program"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Name"}),e.jsx(ye,{value:i.name,onChange:L=>l({...i,name:L.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Slug (URL)"}),e.jsx(ye,{placeholder:"reel-estate-90",value:i.slug,onChange:L=>l({...i,slug:L.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subtitle"}),e.jsx(ye,{value:i.subtitle,onChange:L=>l({...i,subtitle:L.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{rows:4,value:i.description,onChange:L=>l({...i,description:L.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"One-time price (USD)"}),e.jsx(ye,{type:"number",value:i.price_cents/100,onChange:L=>l({...i,price_cents:Math.round(Number(L.target.value)*100)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Seats"}),e.jsx(ye,{type:"number",value:i.capacity,onChange:L=>l({...i,capacity:Number(L.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Weeks"}),e.jsx(ye,{type:"number",value:i.duration_weeks,onChange:L=>l({...i,duration_weeks:Number(L.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Videos per week"}),e.jsx(ye,{type:"number",value:i.weekly_video_goal,onChange:L=>l({...i,weekly_video_goal:Number(L.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Billing"}),e.jsxs(vs,{value:i.payment_mode,onValueChange:L=>l({...i,payment_mode:L}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"delayed",children:"Save card, charge later"}),e.jsx(Je,{value:"immediate",children:"Charge at checkout"}),e.jsx(Je,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Kickoff"}),e.jsx(ye,{type:"datetime-local",value:i.kickoff_at,onChange:L=>l({...i,kickoff_at:L.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Charge date"}),e.jsx(ye,{type:"datetime-local",value:i.charge_at,onChange:L=>l({...i,charge_at:L.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Enrollment closes"}),e.jsx(ye,{type:"datetime-local",value:i.enrollment_close_at,onChange:L=>l({...i,enrollment_close_at:L.target.value})})]})]})]}),e.jsx(Nr,{children:e.jsxs(B,{onClick:k,disabled:o||!i.name,children:[o&&e.jsx(Wt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),x?e.jsx(gn,{className:"h-40 w-full rounded-xl"}):p.length===0?e.jsx(be,{className:"border-dashed",children:e.jsx(Re,{className:"p-12 text-center text-sm text-muted-foreground",children:"No programs yet. Create your first cohort to get started."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:p.map(L=>e.jsxs(B,{variant:(y==null?void 0:y.id)===L.id?"default":"outline",size:"sm",onClick:()=>n(L.id),children:[L.name,e.jsx(qe,{variant:"secondary",className:"ml-2 capitalize",children:L.status})]},L.id))}),y&&e.jsxs(fa,{defaultValue:"overview",children:[e.jsxs(xa,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(ss,{value:"overview",children:"Overview"}),e.jsx(ss,{value:"details",children:"Details & pricing"}),e.jsx(ss,{value:"sessions",children:"Live sessions"}),e.jsx(ss,{value:"videos",children:"On-demand videos"}),e.jsx(ss,{value:"resources",children:"Resources"}),e.jsx(ss,{value:"intake-form",children:"Intake form"}),e.jsx(ss,{value:"discounts",children:"Discount codes"}),e.jsx(ss,{value:"experience",children:"Enrollee experience"}),e.jsx(ss,{value:"interest",children:"Interest list"}),e.jsxs(ss,{value:"enrollments",children:["Enrollments (",g.length,")"]}),e.jsxs(ss,{value:"intake",children:["Intake (",b.length,")"]}),e.jsx(ss,{value:"audit",children:"Audit"})]}),e.jsxs(ns,{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(be,{children:e.jsxs(Re,{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:[g.filter(L=>["reserved","scheduled_for_charge","paid","completed"].includes(L.status)).length,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",y.capacity]})]})]})}),e.jsx(be,{children:e.jsxs(Re,{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:g.filter(L=>L.status==="paid").length})]})}),e.jsx(be,{children:e.jsxs(Re,{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:g.filter(L=>L.status==="payment_failed").length})]})}),e.jsx(be,{children:e.jsxs(Re,{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:Tp(g.filter(L=>["scheduled_for_charge","paid","completed"].includes(L.status)).reduce((L,I)=>L+(I.amount_cents||0),0),y.currency)})]})})]}),e.jsx(be,{children:e.jsxs(Re,{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(Mn,{checked:y.status==="published",onCheckedChange:L=>C({status:L?"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(Mn,{checked:y.is_featured,onCheckedChange:L=>C({is_featured:L})})]}),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:Tp(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:Nd(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:Nd(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(ns,{value:"details",className:"mt-6",children:e.jsx(hLs,{program:y,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(ns,{value:"sessions",className:"mt-6",children:e.jsx(SLs,{programId:y.id})}),e.jsx(ns,{value:"videos",className:"mt-6",children:e.jsx(CLs,{programId:y.id})}),e.jsx(ns,{value:"resources",className:"mt-6",children:e.jsx(ALs,{programId:y.id})}),e.jsx(ns,{value:"discounts",className:"mt-6",children:e.jsx(fLs,{program:y})}),e.jsx(ns,{value:"intake-form",className:"mt-6",children:e.jsx(vLs,{program:y,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(ns,{value:"experience",className:"mt-6",children:e.jsx(xLs,{program:y})}),e.jsx(ns,{value:"interest",className:"mt-6",children:e.jsx(TLs,{programId:y.id})}),e.jsx(ns,{value:"enrollments",className:"mt-6",children:e.jsx(be,{children:e.jsx(Re,{className:"overflow-x-auto p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Member"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Charge date"}),e.jsx(Tt,{children:"Amount"}),e.jsx(Tt,{children:"Access"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsxs(za,{children:[g.length===0&&e.jsx(un,{children:e.jsxs(xt,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(Bn,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),g.map(L=>{var I,O;return e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs("button",{type:"button",className:"text-left hover:underline",onClick:()=>m(L),children:[e.jsx("p",{className:"font-medium",children:((I=L.profile)==null?void 0:I.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(O=L.profile)==null?void 0:O.email})]})}),e.jsxs(xt,{children:[e.jsx(qe,{variant:P(L.status),className:"capitalize",children:String(L.status).replace(/_/g," ")}),L.last_payment_error&&e.jsx("p",{className:"mt-1 max-w-[200px] truncate text-xs text-destructive",children:L.last_payment_error})]}),e.jsx(xt,{className:"text-sm",children:Nd(L.charge_scheduled_at)||"—"}),e.jsx(xt,{className:"text-sm",children:Tp(L.amount_cents,L.currency)}),e.jsx(xt,{children:e.jsx(Mn,{checked:L.access_override,onCheckedChange:$=>T(L.id,{access_override:$})})}),e.jsxs(xt,{className:"space-x-2 text-right",children:[["scheduled_for_charge","payment_failed"].includes(L.status)&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>M(L.id),disabled:d,children:[e.jsx(Ki,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(L.status)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>T(L.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},L.id)})]})]})})})}),e.jsx(ns,{value:"intake",className:"mt-6",children:e.jsx(jLs,{program:y})}),e.jsx(ns,{value:"audit",className:"mt-6",children:e.jsx(be,{children:e.jsxs(Re,{className:"space-y-2 p-5 text-sm",children:[v.length===0&&e.jsx("p",{className:"text-muted-foreground",children:"No activity yet."}),v.map(L=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 py-2 last:border-0",children:[e.jsx(qe,{variant:"outline",className:"capitalize",children:String(L.action).replace(/_/g," ")}),e.jsx("span",{className:"text-muted-foreground",children:L.actor_label||"system"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:Nd(L.created_at,!0)})]},L.id))]})})})]}),y&&e.jsx(pLs,{program:y,enrollment:h,open:!!h,onOpenChange:L=>!L&&m(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},MLs=()=>{const{user:s}=Ns(),[t,n]=j.useState(""),[r,a]=j.useState("all"),{data:i=[]}=mt({queryKey:["academy-categories"],queryFn:async()=>{const{data:m,error:p}=await U.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(p)throw p;return m}}),{data:l=[],isLoading:o}=mt({queryKey:["academy-videos"],queryFn:async()=>{const{data:m,error:p}=await U.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(p)throw p;const{data:x,error:y}=await U.from("academy_resources").select("*").order("sort_order");if(y)throw y;return m.map(b=>({...b,resources:(x==null?void 0:x.filter(v=>v.video_id===b.id))||[]}))}}),{data:c=[]}=mt({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:m,error:p}=await U.from("academy_video_likes").select("video_id, user_id");if(p)throw p;return m}}),d=l.filter(m=>{var y;const p=t===""||m.title.toLowerCase().includes(t.toLowerCase())||((y=m.description)==null?void 0:y.toLowerCase().includes(t.toLowerCase())),x=r==="all"||m.category_id===r;return p&&x}),u=m=>c.filter(p=>p.video_id===m).length,h=m=>c.some(p=>p.video_id===m&&p.user_id===(s==null?void 0:s.id));return e.jsx(Vs,{title:"Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Academy"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"On-demand training videos and resources"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search videos...",value:t,onChange:m=>n(m.target.value),className:"pl-10"})]})}),e.jsx(fa,{value:r,onValueChange:a,children:e.jsxs(xa,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(ss,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(m=>e.jsx(ss,{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(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Zr,{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(Yn,{to:`/academy/${m.id}`,children:e.jsxs(be,{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(Zr,{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(fd,{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(Vr,{className:"h-3 w-3"}),m.duration]})]}),e.jsxs(Ft,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(Ut,{className:"text-lg line-clamp-2",children:m.title})}),m.category&&e.jsx(qe,{variant:"secondary",className:"w-fit",children:m.category.name})]}),e.jsxs(Re,{className:"pt-0",children:[m.description&&e.jsx(fr,{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(mg,{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($r,{className:"h-4 w-4"}),m.resources.length]})]})]})]})},m.id))})]})})};function $Et({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 U.from("academy_video_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("video_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}else{const{data:r,error:a}=await U.from("resource_kit_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("kit_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}},enabled:!!t});return n.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-sm",children:[e.jsx(Ac,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(Yn,{to:`/templates/${r.id}`,children:e.jsxs(qe,{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(Ac,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const LLs=(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},PLs=()=>{const{videoId:s}=$i();Hn();const{user:t,isAdmin:n}=Ns(),{toast:r}=pi(),a=as(),{trackEngagement:i}=eq(),[l,o]=j.useState(""),{data:c,isLoading:d}=mt({queryKey:["academy-video",s],queryFn:async()=>{const{data:k,error:C}=await U.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(C)throw C;const{data:T}=await U.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...k,resources:T||[]}},enabled:!!s});j.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:C}=await U.from("academy_video_likes").select("*").eq("video_id",s);if(C)throw C;return k},enabled:!!s}),{data:h=[]}=mt({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:k,error:C}=await U.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(C)throw C;const T=[...new Set(k.map(L=>L.user_id))],{data:M}=await U.from("profiles").select("id, name").in("id",T),P=new Map((M==null?void 0:M.map(L=>[L.id,L.name]))||[]);return k.map(L=>({...L,user_name:P.get(L.user_id)||"Unknown User"}))},enabled:!!s}),m=vt({mutationFn:async k=>{const{error:C}=await U.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:k});if(C)throw C},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"})}}),p=vt({mutationFn:async k=>{const{error:C}=await U.from("academy_video_comments").delete().eq("id",k);if(C)throw C},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),r({title:"Comment deleted"})}}),x=vt({mutationFn:async()=>{const k=u.find(C=>C.user_id===(t==null?void 0:t.id));if(k){const{error:C}=await U.from("academy_video_likes").delete().eq("id",k.id);if(C)throw C}else{const{error:C}=await U.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(C)throw C}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),y=u.some(k=>k.user_id===(t==null?void 0:t.id)),g=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"📁"}},b=k=>k.split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),v=k=>{k.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Vs,{title:"Academy",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(Vs,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/academy",children:[e.jsx(_a,{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:LLs(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(Zr,{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(qe,{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(Yn,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(Za,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(rq,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(B,{variant:y?"default":"outline",className:"gap-2 w-fit",onClick:()=>x.mutate(),disabled:!t||x.isPending,children:[e.jsx(mg,{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(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx($r,{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:g(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(ii,{className:"h-4 w-4 text-muted-foreground"})]},k.id))})]})}),e.jsx($Et,{resourceType:"academy_video",resourceId:c.id}),e.jsx(Xl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Yd,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:v,className:"flex gap-2",children:[e.jsx(Ds,{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(Dr,{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(be,{children:e.jsx(Re,{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(be,{children:e.jsx(Re,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ra,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Da,{className:"text-sm",children:b(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:oc(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:()=>p.mutate(k.id),children:e.jsx(Rn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:k.content})]})]})})},k.id))})]})]})}):e.jsx(Vs,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Zr,{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(Yn,{to:"/academy",children:"Back to Academy"})})]})})},HF="https://dashboard.relevelup.com",ILs=(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},RLs=[{icon:vh,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:jf,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:Bn,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:ll,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function DLs(){var i;const{slug:s}=$i(),{data:t,isLoading:n,error:r}=mt({queryKey:["public-academy-video",s],queryFn:async()=>{if(!s)return null;const{data:l,error:o}=await U.from("academy_videos").select("id, title, description, video_url, video_type, thumbnail_url, duration, category:academy_categories(name)").eq("public_slug",s).eq("is_public",!0).maybeSingle();if(o)throw o;return l},enabled:!!s});j.useEffect(()=>{if(t&&s){U.rpc("increment_academy_public_view",{_slug:s}),document.title=`${t.title} | LevelUp Academy`;const l=(t.description||"").replace(/<[^>]+>/g,"").slice(0,155),o=document.querySelector('meta[name="description"]');if(o&&o.setAttribute("content",l||"Free training preview from LevelUp Academy."),t.thumbnail_url){let c=document.querySelector('meta[property="og:image"]');c||(c=document.createElement("meta"),c.setAttribute("property","og:image"),document.head.appendChild(c)),c.setAttribute("content",t.thumbnail_url)}}},[t,s]);const a=j.useMemo(()=>t?ILs(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:HF,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(yn,{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:HF,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(qe,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx(vh,{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(oy,{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:HF,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(Xa,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:HF,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:RLs.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(Rr,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:HF,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(Xa,{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:HF,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function OLs(){const s=Hn(),[t,n]=j.useState(""),{data:r,isLoading:a}=mt({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:p,error:x}=await U.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(x)throw x;return p}}),{data:i}=mt({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:p,error:x}=await U.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(x)throw x;return p}}),{data:l}=mt({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:p,error:x}=await U.from("resource_kit_likes").select("kit_id");if(x)throw x;return p}}),{data:o}=mt({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:p,error:x}=await U.from("resource_kit_comments").select("kit_id");if(x)throw x;return p}}),c=r==null?void 0:r.filter(p=>{var x;return p.name.toLowerCase().includes(t.toLowerCase())||((x=p.description)==null?void 0:x.toLowerCase().includes(t.toLowerCase()))}),d=p=>(i==null?void 0:i.filter(x=>x.kit_id===p))||[],u=p=>(l==null?void 0:l.filter(x=>x.kit_id===p).length)||0,h=p=>(o==null?void 0:o.filter(x=>x.kit_id===p).length)||0,m=p=>{s(`/toolbox/${p}`)};return e.jsx(Vs,{title:"Toolbox",description:"Download resource kits and tools to help grow your business",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Toolbox"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Download resource kits and tools to help grow your business"})]}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search resource kits...",value:t,onChange:p=>n(p.target.value),className:"pl-10"})]}),!a&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(c==null?void 0:c.length)||0," resource kit",(c==null?void 0:c.length)!==1?"s":""," available"]}),a?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((p,x)=>e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsx(gn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(gn,{className:"h-5 w-3/4 mb-2"}),e.jsx(gn,{className:"h-4 w-full mb-4"}),e.jsx(gn,{className:"h-4 w-2/3"})]})},x))}):(c==null?void 0:c.length)===0?e.jsxs(be,{className:"p-12 text-center",children:[e.jsx(Eu,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resource kits found"}),e.jsx("p",{className:"text-muted-foreground",children:t?"Try adjusting your search terms":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:c==null?void 0:c.map(p=>{const x=d(p.id).length,y=u(p.id),g=h(p.id);return e.jsxs(be,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>m(p.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:p.featured_image_url?e.jsx("img",{src:p.featured_image_url,alt:p.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Eu,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Re,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:p.name}),p.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:zY(p.description)}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($r,{className:"h-4 w-4"}),x," file",x!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mg,{className:"h-3.5 w-3.5"}),y]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yd,{className:"h-3.5 w-3.5"}),g]})]})]})]})]},p.id)})})]})})}const FLs=()=>{const{kitId:s}=$i(),{user:t,isAdmin:n}=Ns(),{toast:r}=pi(),a=as(),{trackEngagement:i}=eq(),[l,o]=j.useState(""),{data:c,isLoading:d}=mt({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:k,error:C}=await U.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(C)throw C;const{data:T}=await U.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:M}=await U.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...k,files:T||[],links:M||[]}},enabled:!!s});j.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:C}=await U.from("resource_kit_likes").select("*").eq("kit_id",s);if(C)throw C;return k},enabled:!!s}),{data:h=[]}=mt({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:k,error:C}=await U.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(C)throw C;const T=[...new Set(k.map(L=>L.user_id))],{data:M}=await U.from("profiles").select("id, name").in("id",T),P=new Map((M==null?void 0:M.map(L=>[L.id,L.name]))||[]);return k.map(L=>({...L,user_name:P.get(L.user_id)||"Unknown User"}))},enabled:!!s}),m=vt({mutationFn:async k=>{const{error:C}=await U.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:k});if(C)throw C},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"})}}),p=vt({mutationFn:async k=>{const{error:C}=await U.from("resource_kit_comments").delete().eq("id",k);if(C)throw C},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),r({title:"Comment deleted"})}}),x=vt({mutationFn:async()=>{const k=u.find(C=>C.user_id===(t==null?void 0:t.id));if(k){const{error:C}=await U.from("resource_kit_likes").delete().eq("id",k.id);if(C)throw C}else{const{error:C}=await U.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(C)throw C}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),y=u.some(k=>k.user_id===(t==null?void 0:t.id)),g=k=>k.split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),b=k=>k?k<1024?k+" B":k<1024*1024?(k/1024).toFixed(1)+" KB":(k/(1024*1024)).toFixed(1)+" MB":"",v=k=>{k.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Vs,{title:"Toolbox",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(Vs,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/toolbox",children:[e.jsx(_a,{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(Yn,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(Za,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(rq,{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:()=>x.mutate(),disabled:!t||x.isPending,children:[e.jsx(mg,{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(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx($r,{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($r,{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:b(k.file_size)})]})]}),e.jsx(ii,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},k.id))})]})}),c.links&&c.links.length>0&&e.jsx(be,{children:e.jsxs(Re,{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($Et,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(Xl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Yd,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:v,className:"flex gap-2",children:[e.jsx(Ds,{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(Dr,{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(be,{children:e.jsx(Re,{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(be,{children:e.jsx(Re,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ra,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Da,{className:"text-sm",children:g(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:oc(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:()=>p.mutate(k.id),children:e.jsx(Rn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:k.content})]})]})})},k.id))})]})]})}):e.jsx(Vs,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Eu,{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(Yn,{to:"/toolbox",children:"Back to Toolbox"})})]})})},zLs=()=>{const s=Hn(),[t,n]=j.useState(""),[r,a]=j.useState("grid"),{data:i=[],isLoading:l}=mt({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:u}=await U.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(u)throw u;const{data:h,error:m}=await U.from("social_swag_links").select("*").order("sort_order");if(m)throw m;const{data:p}=await U.from("social_swag_likes").select("swag_id"),{data:x}=await U.from("social_swag_comments").select("swag_id"),y=new Map;p==null||p.forEach(v=>{y.set(v.swag_id,(y.get(v.swag_id)||0)+1)});const g=new Map;return x==null||x.forEach(v=>{g.set(v.swag_id,(g.get(v.swag_id)||0)+1)}),(d||[]).map(v=>({...v,links:(h||[]).filter(k=>k.swag_id===v.id)||[],likesCount:y.get(v.id)||0,commentsCount:g.get(v.id)||0}))}}),o=i.filter(d=>{var h;return d.title.toLowerCase().includes(t.toLowerCase())||((h=d.description)==null?void 0:h.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(Vs,{title:"Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Social Swag"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse our collection of social media content and graphics"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{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(r0,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(ug,{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(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsx(gn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(gn,{className:"h-5 w-3/4 mb-2"}),e.jsx(gn,{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(be,{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(qe,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(vc,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Re,{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(mg,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yd,{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 ul=function(){return ul=Object.assign||function(t){for(var n,r=1,a=arguments.length;r1&&(c||!d),h=t>1&&(d||!c),m=function(){r&&i(r)},p=function(){a&&i(a)};return e.jsx(yPs,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:m,onNextClick:p})}function vPs(s){var t,n=Gh(),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:VEt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(Wot,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Wot,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(Kot,{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(Kot,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function bPs(s){var t=Gh(),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 _Ps(s,t,n){for(var r=n?B3(new Date):xg(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=jd(r,i);a.push(l)}return a}function wPs(){var s=Gh(),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=_Ps(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 jPs(){var s,t=Gh(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:wPs;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function NPs(s){var t=Gh(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var NHe=j.createContext(void 0);function kPs(s){if(!LJ(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(NHe.Provider,{value:t,children:s.children})}return e.jsx(SPs,{initialProps:s.initialProps,children:s.children})}function SPs(s){var t=s.initialProps,n=s.children,r=t.selected,a=t.min,i=t.max,l=function(d,u,h){var m,p;(m=t.onDayClick)===null||m===void 0||m.call(t,d,u,h);var x=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!x){var y=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!y){var g=r?UEt([],r):[];if(u.selected){var b=g.findIndex(function(v){return pd(d,v)});g.splice(b,1)}else g.push(d);(p=t.onSelect)===null||p===void 0||p.call(t,g,d,u,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var u=i&&r.length>i-1,h=r.some(function(m){return pd(m,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(NHe.Provider,{value:c,children:n})}function kHe(){var s=j.useContext(NHe);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function CPs(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?pd(a,s)&&pd(r,s)?void 0:pd(a,s)?{from:a,to:void 0}:pd(r,s)?void 0:vb(r,s)?{from:s,to:a}:{from:r,to:s}:a?vb(s,a)?{from:a,to:s}:{from:s,to:a}:r?W_(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var SHe=j.createContext(void 0);function APs(s){if(!PJ(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(SHe.Provider,{value:t,children:s.children})}return e.jsx(TPs,{initialProps:s.initialProps,children:s.children})}function TPs(s){var t=s.initialProps,n=s.children,r=t.selected,a=r||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(p,x,y){var g,b;(g=t.onDayClick)===null||g===void 0||g.call(t,p,x,y);var v=CPs(p,r);(b=t.onSelect)===null||b===void 0||b.call(t,v,p,x,y)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],pd(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:kK(i,o-1),before:jd(i,o-1)}),i&&l&&u.disabled.push({after:i,before:jd(i,o-1)}),!i&&l&&u.disabled.push({after:kK(l,o-1),before:jd(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:jd(i,-c+1)}),u.disabled.push({after:jd(i,c-1)})),i&&l){var h=Ky(l,i)+1,m=c-h;u.disabled.push({before:kK(i,m)}),u.disabled.push({after:jd(l,m)})}!i&&l&&(u.disabled.push({before:jd(l,-c+1)}),u.disabled.push({after:jd(l,c-1)}))}return e.jsx(SHe.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function CHe(){var s=j.useContext(SHe);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function Ije(s){return Array.isArray(s)?UEt([],s):s!==void 0?[s]:[]}function EPs(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=Ije(a)}),t}var TN;(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"})(TN||(TN={}));var MPs=TN.Selected,XS=TN.Disabled,LPs=TN.Hidden,PPs=TN.Today,VLe=TN.RangeEnd,HLe=TN.RangeMiddle,GLe=TN.RangeStart,IPs=TN.Outside;function RPs(s,t,n){var r,a=(r={},r[MPs]=Ije(s.selected),r[XS]=Ije(s.disabled),r[LPs]=Ije(s.hidden),r[PPs]=[s.today],r[VLe]=[],r[HLe]=[],r[GLe]=[],r[IPs]=[],r);return s.fromDate&&a[XS].push({before:s.fromDate}),s.toDate&&a[XS].push({after:s.toDate}),LJ(s)?a[XS]=a[XS].concat(t.modifiers[XS]):PJ(s)&&(a[XS]=a[XS].concat(n.modifiers[XS]),a[GLe]=n.modifiers[GLe],a[HLe]=n.modifiers[HLe],a[VLe]=n.modifiers[VLe]),a}var WEt=j.createContext(void 0);function DPs(s){var t=Gh(),n=kHe(),r=CHe(),a=RPs(t,n,r),i=EPs(t.modifiers),l=ul(ul({},a),i);return e.jsx(WEt.Provider,{value:l,children:s.children})}function KEt(){var s=j.useContext(WEt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function OPs(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function FPs(s){return!!(s&&typeof s=="object"&&"from"in s)}function zPs(s){return!!(s&&typeof s=="object"&&"after"in s)}function BPs(s){return!!(s&&typeof s=="object"&&"before"in s)}function $Ps(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function UPs(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=Ky(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=Ky(s,r)>=0&&Ky(a,s)>=0;return l}return a?pd(a,s):r?pd(r,s):!1}function qPs(s){return iqe(s)}function VPs(s){return Array.isArray(s)&&s.every(iqe)}function HPs(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(qPs(n))return pd(s,n);if(VPs(n))return n.includes(s);if(FPs(n))return UPs(s,n);if($Ps(n))return n.dayOfWeek.includes(s.getDay());if(OPs(n)){var r=Ky(n.before,s),a=Ky(n.after,s),i=r>0,l=a<0,o=vb(n.before,n.after);return o?l&&i:i||l}return zPs(n)?Ky(s,n.after)>0:BPs(n)?Ky(n.before,s)>0:typeof n=="function"?n(s):!1})}function AHe(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return HPs(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!GU(s,n)&&(a.outside=!0),a}function GPs(s,t){for(var n=Vu(s[0]),r=Uv(s[s.length-1]),a,i,l=n;l<=r;){var o=AHe(l,t),c=!o.disabled&&!o.hidden;if(!c){l=jd(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=jd(l,1)}return i||a}var WPs=365;function YEt(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:jd,week:i3,month:Ax,year:Pds,startOfWeek:function(g){return a.ISOWeek?B3(g):xg(g,{locale:h,weekStartsOn:c})},endOfWeek:function(g){return a.ISOWeek?b5t(g):v$(g,{locale:h,weekStartsOn:c})}},p=m[n](s,r==="after"?1:-1);r==="before"&&d?p=Ids([d,p]):r==="after"&&u&&(p=Rds([u,p]));var x=!0;if(i){var y=AHe(p,i);x=!y.disabled&&!y.hidden}return x?p:o.count>WPs?o.lastFocused:YEt(p,{moveBy:n,direction:r,context:a,modifiers:i,retry:ul(ul({},o),{count:o.count+1})})}var ZEt=j.createContext(void 0);function KPs(s){var t=IJ(),n=KEt(),r=j.useState(),a=r[0],i=r[1],l=j.useState(),o=l[0],c=l[1],d=GPs(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},m=function(g){i(g)},p=Gh(),x=function(g,b){if(a){var v=YEt(a,{moveBy:g,direction:b,context:p,modifiers:n});pd(a,v)||(t.goToDate(v,a),m(v))}},y={focusedDay:a,focusTarget:u,blur:h,focus:m,focusDayAfter:function(){return x("day","after")},focusDayBefore:function(){return x("day","before")},focusWeekAfter:function(){return x("week","after")},focusWeekBefore:function(){return x("week","before")},focusMonthBefore:function(){return x("month","before")},focusMonthAfter:function(){return x("month","after")},focusYearBefore:function(){return x("year","before")},focusYearAfter:function(){return x("year","after")},focusStartOfWeek:function(){return x("startOfWeek","before")},focusEndOfWeek:function(){return x("endOfWeek","after")}};return e.jsx(ZEt.Provider,{value:y,children:s.children})}function THe(){var s=j.useContext(ZEt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function YPs(s,t){var n=KEt(),r=AHe(s,n,t);return r}var EHe=j.createContext(void 0);function ZPs(s){if(!pCe(s.initialProps)){var t={selected:void 0};return e.jsx(EHe.Provider,{value:t,children:s.children})}return e.jsx(XPs,{initialProps:s.initialProps,children:s.children})}function XPs(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(EHe.Provider,{value:a,children:n})}function XEt(){var s=j.useContext(EHe);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function QPs(s,t){var n=Gh(),r=XEt(),a=kHe(),i=CHe(),l=THe(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,m=l.focus,p=l.focusMonthBefore,x=l.focusMonthAfter,y=l.focusYearBefore,g=l.focusYearAfter,b=l.focusStartOfWeek,v=l.focusEndOfWeek,k=function(J){var le,ue,oe,ie;pCe(n)?(le=r.onDayClick)===null||le===void 0||le.call(r,s,t,J):LJ(n)?(ue=a.onDayClick)===null||ue===void 0||ue.call(a,s,t,J):PJ(n)?(oe=i.onDayClick)===null||oe===void 0||oe.call(i,s,t,J):(ie=n.onDayClick)===null||ie===void 0||ie.call(n,s,t,J)},C=function(J){var le;m(s),(le=n.onDayFocus)===null||le===void 0||le.call(n,s,t,J)},T=function(J){var le;h(),(le=n.onDayBlur)===null||le===void 0||le.call(n,s,t,J)},M=function(J){var le;(le=n.onDayMouseEnter)===null||le===void 0||le.call(n,s,t,J)},P=function(J){var le;(le=n.onDayMouseLeave)===null||le===void 0||le.call(n,s,t,J)},L=function(J){var le;(le=n.onDayPointerEnter)===null||le===void 0||le.call(n,s,t,J)},I=function(J){var le;(le=n.onDayPointerLeave)===null||le===void 0||le.call(n,s,t,J)},O=function(J){var le;(le=n.onDayTouchCancel)===null||le===void 0||le.call(n,s,t,J)},$=function(J){var le;(le=n.onDayTouchEnd)===null||le===void 0||le.call(n,s,t,J)},q=function(J){var le;(le=n.onDayTouchMove)===null||le===void 0||le.call(n,s,t,J)},W=function(J){var le;(le=n.onDayTouchStart)===null||le===void 0||le.call(n,s,t,J)},G=function(J){var le;(le=n.onDayKeyUp)===null||le===void 0||le.call(n,s,t,J)},K=function(J){var le;switch(J.key){case"ArrowLeft":J.preventDefault(),J.stopPropagation(),n.dir==="rtl"?o():c();break;case"ArrowRight":J.preventDefault(),J.stopPropagation(),n.dir==="rtl"?c():o();break;case"ArrowDown":J.preventDefault(),J.stopPropagation(),d();break;case"ArrowUp":J.preventDefault(),J.stopPropagation(),u();break;case"PageUp":J.preventDefault(),J.stopPropagation(),J.shiftKey?y():p();break;case"PageDown":J.preventDefault(),J.stopPropagation(),J.shiftKey?g():x();break;case"Home":J.preventDefault(),J.stopPropagation(),b();break;case"End":J.preventDefault(),J.stopPropagation(),v();break}(le=n.onDayKeyDown)===null||le===void 0||le.call(n,s,t,J)},ee={onClick:k,onFocus:C,onBlur:T,onKeyDown:K,onKeyUp:G,onMouseEnter:M,onMouseLeave:P,onPointerEnter:L,onPointerLeave:I,onTouchCancel:O,onTouchEnd:$,onTouchMove:q,onTouchStart:W};return ee}function JPs(){var s=Gh(),t=XEt(),n=kHe(),r=CHe(),a=pCe(s)?t.selected:LJ(s)?n.selected:PJ(s)?r.selected:void 0;return a}function eIs(s){return Object.values(TN).includes(s)}function tIs(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(eIs(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function sIs(s,t){var n=ul({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=ul(ul({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function nIs(s,t,n){var r,a,i,l=Gh(),o=THe(),c=YPs(s,t),d=QPs(s,c),u=JPs(),h=!!(l.onDayClick||l.mode!=="default");j.useEffect(function(){var M;c.outside||o.focusedDay&&h&&pd(o.focusedDay,s)&&((M=n.current)===null||M===void 0||M.focus())},[o.focusedDay,s,n,h,c.outside]);var m=tIs(l,c).join(" "),p=sIs(l,c),x=!!(c.outside&&!l.showOutsideDays||c.hidden),y=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:NPs,g=e.jsx(y,{date:s,displayMonth:t,activeModifiers:c}),b={style:p,className:m,children:g,role:"gridcell"},v=o.focusTarget&&pd(o.focusTarget,s)&&!c.outside,k=o.focusedDay&&pd(o.focusedDay,s),C=ul(ul(ul({},b),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=k||v?0:-1,r)),d),T={isButton:h,isHidden:x,activeModifiers:c,selectedDays:u,buttonProps:C,divProps:b};return T}function rIs(s){var t=j.useRef(null),n=nIs(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(qke,ul({name:"day",ref:t},n.buttonProps)):e.jsx("div",ul({},n.divProps))}function aIs(s){var t=s.number,n=s.dates,r=Gh(),a=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,u=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:u});var h=c(Number(t),{locale:o}),m=function(p){a(t,n,p)};return e.jsx(qke,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:m,children:u})}function iIs(s){var t,n,r=Gh(),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:rIs,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:aIs,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})},Fus(h))})]})}function Yot(s,t,n){for(var r=n!=null&&n.ISOWeek?b5t(t):v$(t,n),a=n!=null&&n.ISOWeek?B3(s):xg(s,n),i=Ky(r,a),l=[],o=0;o<=i;o++)l.push(jd(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?oqe(u):cqe(u,n),m=d.find(function(p){return p.weekNumber===h});return m?(m.dates.push(u),d):(d.push({weekNumber:h,dates:[u]}),d)},[]);return c}function oIs(s,t){var n=Yot(Vu(s),Uv(s),t);if(t!=null&&t.useFixedWeeks){var r=Bus(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=i3(i,6-r),o=Yot(i3(i,1),l,t);n.push.apply(n,o)}}return n}function lIs(s){var t,n,r,a=Gh(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,h=a.weekStartsOn,m=a.firstWeekContainsDate,p=a.ISOWeek,x=oIs(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:p,locale:i,weekStartsOn:h,firstWeekContainsDate:m}),y=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:jPs,g=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:iIs,b=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:bPs;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:x.map(function(v){return e.jsx(g,{displayMonth:s.displayMonth,dates:v.dates,weekNumber:v.weekNumber},v.weekNumber)})}),e.jsx(b,{displayMonth:s.displayMonth})]})}function cIs(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var dIs=cIs()?j.useLayoutEffect:j.useEffect,WLe=!1,uIs=0;function Zot(){return"react-day-picker-".concat(++uIs)}function hIs(s){var t,n=s??(WLe?Zot():null),r=j.useState(n),a=r[0],i=r[1];return dIs(function(){a===null&&i(Zot())},[]),j.useEffect(function(){WLe===!1&&(WLe=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function mIs(s){var t,n,r=Gh(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=IJ().displayMonths,d=hIs(r.id?"".concat(r.id,"-").concat(s.displayIndex):void 0),u=r.id?"".concat(r.id,"-grid-").concat(s.displayIndex):void 0,h=[i.month],m=l.month,p=s.displayIndex===0,x=s.displayIndex===c.length-1,y=!p&&!x;a==="rtl"&&(t=[p,x],x=t[0],p=t[1]),p&&(h.push(i.caption_start),m=ul(ul({},m),l.caption_start)),x&&(h.push(i.caption_end),m=ul(ul({},m),l.caption_end)),y&&(h.push(i.caption_between),m=ul(ul({},m),l.caption_between));var g=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:vPs;return e.jsxs("div",{className:h.join(" "),style:m,children:[e.jsx(g,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(lIs,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function pIs(s){var t=Gh(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function fIs(s){var t,n,r=s.initialProps,a=Gh(),i=THe(),l=IJ(),o=j.useState(!1),c=o[0],d=o[1];j.useEffect(function(){a.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[a.initialFocus,c,i.focus,i.focusTarget,i]);var u=[a.classNames.root,a.className];a.numberOfMonths>1&&u.push(a.classNames.multiple_months),a.showWeekNumber&&u.push(a.classNames.with_weeknumber);var h=ul(ul({},a.styles.root),a.style),m=Object.keys(r).filter(function(x){return x.startsWith("data-")}).reduce(function(x,y){var g;return ul(ul({},x),(g={},g[y]=r[y],g))},{}),p=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:pIs;return e.jsx("div",ul({className:u.join(" "),style:h,dir:a.dir,id:a.id,nonce:r.nonce,title:r.title,lang:r.lang},m,{children:e.jsx(p,{children:l.displayMonths.map(function(x,y){return e.jsx(mIs,{displayIndex:y,displayMonth:x},y)})})}))}function xIs(s){var t=s.children,n=BLs(s,["children"]);return e.jsx(aPs,{initialProps:n,children:e.jsx(fPs,{children:e.jsx(ZPs,{initialProps:n,children:e.jsx(kPs,{initialProps:n,children:e.jsx(APs,{initialProps:n,children:e.jsx(DPs,{children:e.jsx(KPs,{children:t})})})})})})})}function gIs(s){return e.jsx(xIs,ul({},s,{children:e.jsx(fIs,{initialProps:s})}))}function o1({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(gIs,{showOutsideDays:n,className:Et("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:Et(h$({variant:"outline"}),"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),nav_button_previous:"absolute left-1",nav_button_next:"absolute right-1",table:"w-full border-collapse space-y-1",head_row:"flex",head_cell:"text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",row:"flex w-full mt-2",cell:"h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",day:Et(h$({variant:"ghost"}),"h-9 w-9 p-0 font-normal aria-selected:opacity-100"),day_range_end:"day-range-end",day_selected:"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",day_today:"bg-accent text-accent-foreground",day_outside:"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",day_disabled:"text-muted-foreground opacity-50",day_range_middle:"aria-selected:bg-accent aria-selected:text-accent-foreground",day_hidden:"invisible",...t},components:{IconLeft:({...a})=>e.jsx(Cc,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(Qa,{className:"h-4 w-4"})},...r})}o1.displayName="Calendar";var fCe="Popover",[QEt,LBn]=Zm(fCe,[rS]),RJ=rS(),[yIs,u6]=QEt(fCe),JEt=s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=RJ(t),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=Mx({prop:r,defaultProp:a??!1,onChange:i,caller:fCe});return e.jsx(oJ,{...o,children:e.jsx(yIs,{scope:t,contentId:Cx(),triggerRef:c,open:h,onOpenChange:m,onOpenToggle:j.useCallback(()=>m(p=>!p),[m]),hasCustomAnchor:d,onCustomAnchorAdd:j.useCallback(()=>u(!0),[]),onCustomAnchorRemove:j.useCallback(()=>u(!1),[]),modal:l,children:n})})};JEt.displayName=fCe;var e6t="PopoverAnchor",vIs=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=u6(e6t,n),i=RJ(n),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return j.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(FU,{...i,...r,ref:t})});vIs.displayName=e6t;var t6t="PopoverTrigger",s6t=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=u6(t6t,n),i=RJ(n),l=ko(t,a.triggerRef),o=e.jsx(Ua.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":o6t(a.open),...r,ref:l,onClick:ua(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(FU,{asChild:!0,...i,children:o})});s6t.displayName=t6t;var MHe="PopoverPortal",[bIs,_Is]=QEt(MHe,{forceMount:void 0}),n6t=s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=u6(MHe,t);return e.jsx(bIs,{scope:t,forceMount:n,children:e.jsx(ax,{present:n||i.open,children:e.jsx(LU,{asChild:!0,container:a,children:r})})})};n6t.displayName=MHe;var E$="PopoverContent",r6t=j.forwardRef((s,t)=>{const n=_Is(E$,s.__scopePopover),{forceMount:r=n.forceMount,...a}=s,i=u6(E$,s.__scopePopover);return e.jsx(ax,{present:r||i.open,children:i.modal?e.jsx(jIs,{...a,ref:t}):e.jsx(NIs,{...a,ref:t})})});r6t.displayName=E$;var wIs=NE("PopoverContent.RemoveScroll"),jIs=j.forwardRef((s,t)=>{const n=u6(E$,s.__scopePopover),r=j.useRef(null),a=ko(t,r),i=j.useRef(!1);return j.useEffect(()=>{const l=r.current;if(l)return L4e(l)},[]),e.jsx(tJ,{as:wIs,allowPinchZoom:!0,children:e.jsx(a6t,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ua(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=n.triggerRef.current)==null||o.focus()}),onPointerDownOutside:ua(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:ua(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),NIs=j.forwardRef((s,t)=>{const n=u6(E$,s.__scopePopover),r=j.useRef(!1),a=j.useRef(!1);return e.jsx(a6t,{...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()}})}),a6t=j.forwardRef((s,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:u,...h}=s,m=u6(E$,n),p=RJ(n);return E4e(),e.jsx(eJ,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(ZE,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:e.jsx(lJ,{"data-state":o6t(m.open),role:"dialog",id:m.contentId,...p,...h,ref:t,style:{...h.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),i6t="PopoverClose",kIs=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=u6(i6t,n);return e.jsx(Ua.button,{type:"button",...r,ref:t,onClick:ua(s.onClick,()=>a.onOpenChange(!1))})});kIs.displayName=i6t;var SIs="PopoverArrow",CIs=j.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=RJ(n);return e.jsx(cJ,{...a,...r,ref:t})});CIs.displayName=SIs;function o6t(s){return s?"open":"closed"}var AIs=JEt,TIs=s6t,EIs=n6t,l6t=r6t;const lc=AIs,cc=TIs,Jl=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(EIs,{children:e.jsx(l6t,{ref:a,align:t,sideOffset:n,className:Et("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})}));Jl.displayName=l6t.displayName;const MIs=hO("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"}}),LHe=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Et(MIs({variant:t}),s),...n}));LHe.displayName="Alert";const LIs=j.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Et("mb-1 font-medium leading-none tracking-tight",s),...t}));LIs.displayName="AlertTitle";const PHe=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Et("text-sm [&_p]:leading-relaxed",s),...t}));PHe.displayName="AlertDescription";function PIs({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=as(),{user:c}=Ns(),d=(c==null?void 0:c.id)??null,[u,h]=j.useState(a),[m,p]=j.useState([]),[x,y]=j.useState(null),[g,b]=j.useState("now"),[v,k]=j.useState(rnt(unt(new Date),1)),[C,T]=j.useState("12"),[M,P]=j.useState("00"),[L,I]=j.useState("PM");j.useEffect(()=>{if(s){h(a),b("now"),p([]);const xe=rnt(unt(new Date),1);k(xe);const fe=xe.getHours();T(String(fe>12?fe-12:fe===0?12:fe)),P("00"),I(fe>=12?"PM":"AM")}},[s,a]);const O=()=>{if(!v)return null;let xe=parseInt(C);const fe=parseInt(M);return L==="PM"&&xe!==12&&(xe+=12),L==="AM"&&xe===12&&(xe=0),E5t(T5t(v,xe),fe)},{data:$,isLoading:q}=mt({queryKey:["social-accounts-for-post",d],queryFn:async()=>{const{data:{user:xe}}=await U.auth.getUser();if(!xe)return[];const{data:fe,error:Se}=await U.from("social_accounts").select("*").eq("user_id",xe.id).eq("is_active",!0).order("platform",{ascending:!0});if(Se)throw Se;return console.log("Fetched social accounts for posting:",fe),fe},enabled:s,staleTime:0}),W=vt({mutationFn:async({accountId:xe,platform:fe})=>{y(xe);const{data:Se,error:Ee}=await U.functions.invoke("social-post",{body:{platform:fe,accountId:xe,imageUrl:n,caption:u}});if(Ee)throw Ee;if(Se!=null&&Se.error)throw new Error(Se.error);return Se},onSuccess:xe=>{const fe=xe.platform==="facebook"?"Facebook":xe.platform==="instagram"?"Instagram":xe.platform==="linkedin"?"LinkedIn":"Google Business";re.success(`Posted to ${fe}!`)},onError:xe=>{re.error(`Failed to post: ${xe.message}`)},onSettled:()=>{y(null)}}),G=vt({mutationFn:async({accountId:xe,platform:fe,scheduledFor:Se})=>{const{data:{user:Ee}}=await U.auth.getUser();if(!Ee)throw new Error("Not authenticated");const{error:Le}=await U.from("scheduled_posts").insert({user_id:Ee.id,social_account_id:xe,platform:fe,image_url:n,caption:u,swag_item_id:i||null,reel_id:l||null,scheduled_for:Se.toISOString(),status:"scheduled"});if(Le)throw Le;return{platform:fe}},onSuccess:xe=>{const fe=xe.platform==="facebook"?"Facebook":xe.platform==="instagram"?"Instagram":"LinkedIn";re.success(`Post scheduled for ${fe}!`)},onError:xe=>{re.error(`Failed to schedule: ${xe.message}`)}}),K=async()=>{if(m.length===0){re.error("Please select at least one account");return}if(g==="schedule"){const xe=O();if(!xe||xe<=new Date){re.error("Please select a future date and time");return}for(const fe of m){const Se=$==null?void 0:$.find(Ee=>Ee.id===fe);Se&&await G.mutateAsync({accountId:fe,platform:Se.platform,scheduledFor:xe})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),re.success(`${m.length} post(s) scheduled for ${Bs(xe,"PPp")}`)}else for(const xe of m){const fe=$==null?void 0:$.find(Se=>Se.id===xe);fe&&await W.mutateAsync({accountId:xe,platform:fe.platform})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),h(""),p([]),t(!1)},ee=xe=>{p(fe=>fe.includes(xe)?fe.filter(Se=>Se!==xe):[...fe,xe])},J=($==null?void 0:$.filter(xe=>xe.platform==="facebook"))||[],le=($==null?void 0:$.filter(xe=>xe.platform==="instagram"))||[],ue=($==null?void 0:$.filter(xe=>xe.platform==="linkedin"))||[],oe=($==null?void 0:$.filter(xe=>xe.platform==="google_business"))||[],ie=(($==null?void 0:$.length)||0)>0,de=W.isPending||G.isPending,we=Array.from({length:12},(xe,fe)=>String(fe+1)),je=["00","15","30","45"];return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Create Social Post"}),e.jsx(kr,{children:"Share this image to your connected social accounts"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"aspect-square w-full max-w-[200px] mx-auto overflow-hidden rounded-lg border",children:e.jsx("img",{src:n,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"caption",children:"Caption"}),e.jsx(Ds,{id:"caption",placeholder:"Write a caption for your post...",value:u,onChange:xe=>h(xe.target.value),rows:3}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[u.length,"/2200 characters"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Publish Time"}),e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsx("button",{type:"button",onClick:()=>b("now"),className:Et("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",g==="now"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Post Now"}),e.jsx("button",{type:"button",onClick:()=>b("schedule"),className:Et("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",g==="schedule"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Schedule"})]})]}),g==="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(Vr,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("justify-start text-left font-normal flex-1",!v&&"text-muted-foreground"),children:[e.jsx(ra,{className:"mr-2 h-4 w-4"}),v?Bs(v,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Jl,{className:"w-auto p-0",align:"start",children:e.jsx(o1,{mode:"single",selected:v,onSelect:k,disabled:xe=>xee.jsx(Je,{value:xe,children:xe},xe))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(vs,{value:M,onValueChange:P,children:[e.jsx(gs,{className:"w-[70px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:je.map(xe=>e.jsx(Je,{value:xe,children:xe},xe))})]}),e.jsxs(vs,{value:L,onValueChange:xe=>I(xe),children:[e.jsx(gs,{className:"w-[70px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"AM",children:"AM"}),e.jsx(Je,{value:"PM",children:"PM"})]})]})]})]}),v&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",Bs(O()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Post to"}),q&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin"})}),!q&&!ie&&e.jsxs(LHe,{children:[e.jsx(po,{className:"h-4 w-4"}),e.jsxs(PHe,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(Yn,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(ic,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),J.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(sx,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),J.map(xe=>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(wi,{checked:m.includes(xe.id),onCheckedChange:()=>ee(xe.id),disabled:x===xe.id}),e.jsxs(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:xe.profile_picture_url||""}),e.jsx(Da,{children:e.jsx(sx,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:xe.page_name||xe.platform_username}),x===xe.id&&e.jsx(Wt,{className:"h-4 w-4 animate-spin"})]},xe.id))]}),le.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(vm,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),le.map(xe=>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(wi,{checked:m.includes(xe.id),onCheckedChange:()=>ee(xe.id),disabled:x===xe.id}),e.jsxs(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:xe.profile_picture_url||""}),e.jsx(Da,{children:e.jsx(vm,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",xe.platform_username]}),x===xe.id&&e.jsx(Wt,{className:"h-4 w-4 animate-spin"})]},xe.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(ry,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),ue.map(xe=>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(wi,{checked:m.includes(xe.id),onCheckedChange:()=>ee(xe.id),disabled:x===xe.id}),e.jsxs(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:xe.profile_picture_url||""}),e.jsx(Da,{children:e.jsx(ry,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:xe.platform_username}),x===xe.id&&e.jsx(Wt,{className:"h-4 w-4 animate-spin"})]},xe.id))]}),oe.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(oi,{className:"h-4 w-4 text-red-600"})," Google Business"]}),oe.map(xe=>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(wi,{checked:m.includes(xe.id),onCheckedChange:()=>ee(xe.id),disabled:x===xe.id}),e.jsxs(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:xe.profile_picture_url||""}),e.jsx(Da,{children:e.jsx(oi,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:xe.page_name||xe.platform_username}),x===xe.id&&e.jsx(Wt,{className:"h-4 w-4 animate-spin"})]},xe.id))]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:K,disabled:m.length===0||de,className:"gap-2",children:[de?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):g==="schedule"?e.jsx(ra,{className:"h-4 w-4"}):e.jsx(Dr,{className:"h-4 w-4"}),g==="schedule"?`Schedule ${m.length} post${m.length!==1?"s":""}`:`Post to ${m.length} account${m.length!==1?"s":""}`]})]})]})})}function IIs(){const{user:s}=Ns(),t=(s==null?void 0:s.id)??null,n=as(),[r,a]=j.useState(void 0),[i,l]=j.useState("all"),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState(void 0),[p,x]=j.useState("12"),[y,g]=j.useState("00"),[b,v]=j.useState("PM"),{data:k=[],isLoading:C}=mt({queryKey:["scheduled-posts",t],enabled:!!t,queryFn:async()=>{const{data:oe,error:ie}=await U.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).eq("user_id",t).order("scheduled_for",{ascending:!1});if(ie)throw ie;return oe}}),T=k.filter(oe=>{if(i!=="all"&&oe.status!==i)return!1;if(r&&oe.scheduled_for){const ie=new Date(oe.scheduled_for);if(!pd(ie,r))return!1}return!0}),M=k.filter(oe=>oe.scheduled_for).map(oe=>xm(new Date(oe.scheduled_for))),P=vt({mutationFn:async oe=>{const{error:ie}=await U.from("scheduled_posts").update({caption:oe.caption,scheduled_for:oe.scheduled_for}).eq("id",oe.id);if(ie)throw ie},onSuccess:()=>{re.success("Post updated!"),n.invalidateQueries({queryKey:["scheduled-posts",t]}),c(null)},onError:oe=>{re.error(`Failed to update: ${oe.message}`)}}),L=vt({mutationFn:async oe=>{const{error:ie}=await U.from("scheduled_posts").update({status:"cancelled"}).eq("id",oe);if(ie)throw ie},onSuccess:()=>{re.success("Post cancelled"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:oe=>{re.error(`Failed to cancel: ${oe.message}`)}}),I=vt({mutationFn:async oe=>{const{error:ie}=await U.from("scheduled_posts").delete().eq("id",oe);if(ie)throw ie},onSuccess:()=>{re.success("Post deleted"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:oe=>{re.error(`Failed to delete: ${oe.message}`)}}),O=vt({mutationFn:async oe=>{const{data:ie,error:de}=await U.functions.invoke("social-post",{body:{platform:oe.platform,accountId:oe.social_account_id,imageUrl:oe.image_url,caption:oe.caption}});if(de)throw de;if(ie!=null&&ie.error)throw new Error(ie.error);return await U.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:ie.postId}).eq("id",oe.id),ie},onSuccess:oe=>{const ie=oe.platform==="facebook"?"Facebook":oe.platform==="instagram"?"Instagram":"LinkedIn";re.success(`Posted to ${ie}!`),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:oe=>{re.error(`Failed to post: ${oe.message}`)}}),$=oe=>{if(c(oe),u(oe.caption||""),oe.scheduled_for){const ie=new Date(oe.scheduled_for);m(ie);const de=ie.getHours();x(String(de>12?de-12:de===0?12:de)),g(String(ie.getMinutes()).padStart(2,"0")),v(de>=12?"PM":"AM")}},q=()=>{if(!o||!h)return;let oe=parseInt(p);const ie=parseInt(y);b==="PM"&&oe!==12&&(oe+=12),b==="AM"&&oe===12&&(oe=0);const de=E5t(T5t(h,oe),ie);P.mutate({id:o.id,caption:d,scheduled_for:de.toISOString()})},W=oe=>{switch(oe){case"facebook":return e.jsx(sx,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(vm,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(ry,{className:"h-4 w-4 text-blue-700"});default:return null}},G=oe=>{switch(oe){case"scheduled":return e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(qe,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(To,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(qe,{variant:"destructive",className:"gap-1",children:[e.jsx(Rd,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(qe,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(po,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(qe,{variant:"outline",children:oe})}},K=Array.from({length:12},(oe,ie)=>String(ie+1)),ee=["00","15","30","45"],J=k.filter(oe=>oe.status==="scheduled").length,le=k.filter(oe=>oe.status==="posted").length,ue=k.filter(oe=>oe.status==="scheduled"&&oe.scheduled_for&&$us(new Date(oe.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(be,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:J}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(be,{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(be,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:le}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(be,{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(be,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Vc,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(o1,{mode:"single",selected:r,onSelect:a,className:Et("pointer-events-auto"),modifiers:{hasPost:M},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(Nj,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(oe=>e.jsx(B,{variant:i===oe?"default":"outline",size:"sm",onClick:()=>l(oe),className:"capitalize",children:oe},oe))})]}),C&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!C&&T.length===0&&e.jsxs(be,{className:"p-8 text-center",children:[e.jsx(ra,{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 ${Bs(r,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:T.map(oe=>{var ie,de;return e.jsx(be,{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:oe.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Re,{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(oe.platform),e.jsx("span",{className:"font-medium",children:((ie=oe.social_accounts)==null?void 0:ie.page_name)||((de=oe.social_accounts)==null?void 0:de.platform_username)||"Unknown"}),G(oe.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[oe.status==="scheduled"&&e.jsxs(RN,{children:[e.jsxs(Cu,{children:[e.jsx(Au,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>$(oe),children:e.jsx(Za,{className:"h-4 w-4"})})}),e.jsx(ou,{children:"Edit post"})]}),e.jsxs(Cu,{children:[e.jsx(Au,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>O.mutate(oe),disabled:O.isPending,children:O.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"})})}),e.jsx(ou,{children:"Post now"})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Cancel this scheduled post?"}),e.jsx(xl,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Keep"}),e.jsx(cl,{onClick:()=>L.mutate(oe.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(cl,{onClick:()=>I.mutate(oe.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(oe.status==="posted"||oe.status==="cancelled"||oe.status==="failed")&&e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete this post?"}),e.jsx(xl,{children:"This will permanently remove this post from your history."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>I.mutate(oe.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),oe.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:oe.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),oe.status==="posted"&&oe.posted_at?`Posted ${Bs(new Date(oe.posted_at),"PPp")}`:oe.scheduled_for?`Scheduled for ${Bs(new Date(oe.scheduled_for),"PPp")}`:"Not scheduled"]}),oe.status==="failed"&&oe.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",oe.error_message]})]})]})},oe.id)})})]})]}),e.jsx(Fs,{open:!!o,onOpenChange:oe=>!oe&&c(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Edit Scheduled Post"}),e.jsx(kr,{children:"Update the caption or reschedule this post"})]}),o&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"aspect-square w-32 mx-auto overflow-hidden rounded-lg border",children:e.jsx("img",{src:o.image_url,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Caption"}),e.jsx(Ds,{value:d,onChange:oe=>u(oe.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(se,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("justify-start text-left font-normal flex-1",!h&&"text-muted-foreground"),children:[e.jsx(ra,{className:"mr-2 h-4 w-4"}),h?Bs(h,"PPP"):"Pick a date"]})}),e.jsx(Jl,{className:"w-auto p-0",align:"start",children:e.jsx(o1,{mode:"single",selected:h,onSelect:m,disabled:oe=>oee.jsx(Je,{value:oe,children:oe},oe))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(vs,{value:y,onValueChange:g,children:[e.jsx(gs,{className:"w-[70px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:ee.map(oe=>e.jsx(Je,{value:oe,children:oe},oe))})]}),e.jsxs(vs,{value:b,onValueChange:oe=>v(oe),children:[e.jsx(gs,{className:"w-[70px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"AM",children:"AM"}),e.jsx(Je,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(null),children:"Cancel"}),e.jsxs(B,{onClick:q,disabled:P.isPending,children:[P.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function ene(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 c6t={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 ene=="function"&&ene;if(!u&&h)return h(d,!0);if(o)return o(d,!0);var m=new Error("Cannot find module '"+d+"'");throw m.code="MODULE_NOT_FOUND",m}var p=a[d]={exports:{}};r[d][0].call(p.exports,function(x){var y=r[d][1][x];return l(y||x)},p,p.exports,n,r,a,i)}return a[d].exports}for(var o=typeof ene=="function"&&ene,c=0;c>2,p=(3&d)<<4|u>>4,x=1>6:64,y=2>4,u=(15&m)<<4|(p=o.indexOf(c.charAt(y++)))>>2,h=(3&p)<<6|(x=o.indexOf(c.charAt(y++))),v[g++]=d,p!==64&&(v[g++]=u),x!==64&&(v[g++]=h);return v}},{"./support":30,"./utils":32}],2:[function(n,r,a){var i=n("./external"),l=n("./stream/DataWorker"),o=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,h,m,p,x){this.compressedSize=u,this.uncompressedSize=h,this.crc32=m,this.compression=p,this.compressedContent=x}d.prototype={getContentWorker:function(){var u=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new l(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(u,h,m){return u.pipe(new o).pipe(new c("uncompressedSize")).pipe(h.compressWorker(m)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,a){var i=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,a){var i=n("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var u=0;u<8;u++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();r.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,u,h,m){var p=l,x=m+h;d^=-1;for(var y=m;y>>8^p[255&(d^u[y])];return-1^d}(0|c,o,o.length,0):function(d,u,h,m){var p=l,x=m+h;d^=-1;for(var y=m;y>>8^p[255&(d^u.charCodeAt(y))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(n,r,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(n,r,a){var i=null;i=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:i}},{lie:37}],7:[function(n,r,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=n("pako"),o=n("./utils"),c=n("./stream/GenericWorker"),d=i?"uint8array":"array";function u(h,m){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=m,this.meta={}}a.magic="\b\0",o.inherits(u,c),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,h.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(m){h.push({data:m,meta:h.meta})}},a.compressWorker=function(h){return new u("Deflate",h)},a.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,a){function i(p,x){var y,g="";for(y=0;y>>=8;return g}function l(p,x,y,g,b,v){var k,C,T=p.file,M=p.compression,P=v!==d.utf8encode,L=o.transformTo("string",v(T.name)),I=o.transformTo("string",d.utf8encode(T.name)),O=T.comment,$=o.transformTo("string",v(O)),q=o.transformTo("string",d.utf8encode(O)),W=I.length!==T.name.length,G=q.length!==O.length,K="",ee="",J="",le=T.dir,ue=T.date,oe={crc32:0,compressedSize:0,uncompressedSize:0};x&&!y||(oe.crc32=p.crc32,oe.compressedSize=p.compressedSize,oe.uncompressedSize=p.uncompressedSize);var ie=0;x&&(ie|=8),P||!W&&!G||(ie|=2048);var de=0,we=0;le&&(de|=16),b==="UNIX"?(we=798,de|=function(xe,fe){var Se=xe;return xe||(Se=fe?16893:33204),(65535&Se)<<16}(T.unixPermissions,le)):(we=20,de|=function(xe){return 63&(xe||0)}(T.dosPermissions)),k=ue.getUTCHours(),k<<=6,k|=ue.getUTCMinutes(),k<<=5,k|=ue.getUTCSeconds()/2,C=ue.getUTCFullYear()-1980,C<<=4,C|=ue.getUTCMonth()+1,C<<=5,C|=ue.getUTCDate(),W&&(ee=i(1,1)+i(u(L),4)+I,K+="up"+i(ee.length,2)+ee),G&&(J=i(1,1)+i(u($),4)+q,K+="uc"+i(J.length,2)+J);var je="";return je+=` \0`,je+=i(ie,2),je+=M.magic,je+=i(k,2),je+=i(C,2),je+=i(oe.crc32,4),je+=i(oe.compressedSize,4),je+=i(oe.uncompressedSize,4),je+=i(L.length,2),je+=i(K.length,2),{fileRecord:h.LOCAL_FILE_HEADER+je+L+K,dirRecord:h.CENTRAL_FILE_HEADER+i(we,2)+je+i($.length,2)+"\0\0\0\0"+i(de,4)+i(g,4)+L+K+$}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function m(p,x,y,g){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=x,this.zipPlatform=y,this.encodeFileName=g,this.streamFiles=p,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(m,c),m.prototype.push=function(p){var x=p.meta.percent||0,y=this.entriesCount,g=this._sources.length;this.accumulate?this.contentBuffer.push(p):(this.bytesWritten+=p.data.length,c.prototype.push.call(this,{data:p.data,meta:{currentFile:this.currentFile,percent:y?(x+100*(y-g-1))/y:100}}))},m.prototype.openedSource=function(p){this.currentSourceOffset=this.bytesWritten,this.currentFile=p.file.name;var x=this.streamFiles&&!p.file.dir;if(x){var y=l(p,x,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:y.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(p){this.accumulate=!1;var x=this.streamFiles&&!p.file.dir,y=l(p,x,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(y.dirRecord),x)this.push({data:function(g){return h.DATA_DESCRIPTOR+i(g.crc32,4)+i(g.compressedSize,4)+i(g.uncompressedSize,4)}(p),meta:{percent:100}});else for(this.push({data:y.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},m.prototype.flush=function(){for(var p=this.bytesWritten,x=0;x=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=o,d},readString:function(o){return i.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},r.exports=l},{"../utils":32}],19:[function(n,r,a){var i=n("./Uint8ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,a){var i=n("./DataReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},l.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},l.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./DataReader":18}],21:[function(n,r,a){var i=n("./ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,a){var i=n("../utils"),l=n("../support"),o=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(h){var m=i.getTypeOf(h);return i.checkSupport(m),m!=="string"||l.uint8array?m==="nodebuffer"?new d(h):l.uint8array?new u(i.transformTo("uint8array",h)):new o(i.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,a){var i=n("./GenericWorker"),l=n("../utils");function o(c){i.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(o,i),o.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},r.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,a){var i=n("./GenericWorker"),l=n("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}i.inherits(o,l),o.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}l.prototype.processChunk.call(this,c)},r.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){d.dataIsReady=!0,d.data=u,d.max=u&&u.length||0,d.type=i.getTypeOf(u),d.isPaused||d._tickAndRepeat()},function(u){d.error(u)})}i.inherits(o,l),o.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,a){function i(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,o){return this._listeners[l].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,o){if(this._listeners[l])for(var c=0;c "+l:l}},r.exports=i},{}],29:[function(n,r,a){var i=n("../utils"),l=n("./ConvertWorker"),o=n("./GenericWorker"),c=n("../base64"),d=n("../support"),u=n("../external"),h=null;if(d.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function m(x,y){return new u.Promise(function(g,b){var v=[],k=x._internalType,C=x._outputType,T=x._mimeType;x.on("data",function(M,P){v.push(M),y&&y(P)}).on("error",function(M){v=[],b(M)}).on("end",function(){try{var M=function(P,L,I){switch(P){case"blob":return i.newBlob(i.transformTo("arraybuffer",L),I);case"base64":return c.encode(L);default:return i.transformTo(P,L)}}(C,function(P,L){var I,O=0,$=null,q=0;for(I=0;I"u")a.blob=!1;else{var i=new ArrayBuffer(0);try{a.blob=new Blob([i],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(i),a.blob=l.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,a){for(var i=n("./utils"),l=n("./support"),o=n("./nodejsUtils"),c=n("./stream/GenericWorker"),d=new Array(256),u=0;u<256;u++)d[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;d[254]=d[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function m(){c.call(this,"utf-8 encode")}a.utf8encode=function(p){return l.nodebuffer?o.newBufferFrom(p,"utf-8"):function(x){var y,g,b,v,k,C=x.length,T=0;for(v=0;v>>6:(g<65536?y[k++]=224|g>>>12:(y[k++]=240|g>>>18,y[k++]=128|g>>>12&63),y[k++]=128|g>>>6&63),y[k++]=128|63&g);return y}(p)},a.utf8decode=function(p){return l.nodebuffer?i.transformTo("nodebuffer",p).toString("utf-8"):function(x){var y,g,b,v,k=x.length,C=new Array(2*k);for(y=g=0;y>10&1023,C[g++]=56320|1023&b)}return C.length!==g&&(C.subarray?C=C.subarray(0,g):C.length=g),i.applyFromCharCode(C)}(p=i.transformTo(l.uint8array?"uint8array":"array",p))},i.inherits(h,c),h.prototype.processChunk=function(p){var x=i.transformTo(l.uint8array?"uint8array":"array",p.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var y=x;(x=new Uint8Array(y.length+this.leftOver.length)).set(this.leftOver,0),x.set(y,this.leftOver.length)}else x=this.leftOver.concat(x);this.leftOver=null}var g=function(v,k){var C;for((k=k||v.length)>v.length&&(k=v.length),C=k-1;0<=C&&(192&v[C])==128;)C--;return C<0||C===0?k:C+d[v[C]]>k?C:k}(x),b=x;g!==x.length&&(l.uint8array?(b=x.subarray(0,g),this.leftOver=x.subarray(g,x.length)):(b=x.slice(0,g),this.leftOver=x.slice(g,x.length))),this.push({data:a.utf8decode(b),meta:p.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=h,i.inherits(m,c),m.prototype.processChunk=function(p){this.push({data:a.utf8encode(p.data),meta:p.meta})},a.Utf8EncodeWorker=m},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,a){var i=n("./support"),l=n("./base64"),o=n("./nodejsUtils"),c=n("./external");function d(y){return y}function u(y,g){for(var b=0;b>8;this.dir=!!(16&this.externalFileAttributes),p==0&&(this.dosPermissions=63&this.externalFileAttributes),p==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var p=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=p.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=p.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=p.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=p.readInt(4))}},readExtraFields:function(p){var x,y,g,b=p.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});p.index+4>>6:(p<65536?m[g++]=224|p>>>12:(m[g++]=240|p>>>18,m[g++]=128|p>>>12&63),m[g++]=128|p>>>6&63),m[g++]=128|63&p);return m},a.buf2binstring=function(h){return u(h,h.length)},a.binstring2buf=function(h){for(var m=new i.Buf8(h.length),p=0,x=m.length;p>10&1023,v[x++]=56320|1023&y)}return u(v,x)},a.utf8border=function(h,m){var p;for((m=m||h.length)>h.length&&(m=h.length),p=m-1;0<=p&&(192&h[p])==128;)p--;return p<0||p===0?m:p+c[h[p]]>m?p:m}},{"./common":41}],43:[function(n,r,a){r.exports=function(i,l,o,c){for(var d=65535&i|0,u=i>>>16&65535|0,h=0;o!==0;){for(o-=h=2e3>>1:l>>>1;o[c]=l}return o}();r.exports=function(l,o,c,d){var u=i,h=d+c;l^=-1;for(var m=d;m>>8^u[255&(l^o[m])];return-1^l}},{}],46:[function(n,r,a){var i,l=n("../utils/common"),o=n("./trees"),c=n("./adler32"),d=n("./crc32"),u=n("./messages"),h=0,m=4,p=0,x=-2,y=-1,g=4,b=2,v=8,k=9,C=286,T=30,M=19,P=2*C+1,L=15,I=3,O=258,$=O+I+1,q=42,W=113,G=1,K=2,ee=3,J=4;function le(_e,Oe){return _e.msg=u[Oe],Oe}function ue(_e){return(_e<<1)-(4<_e?9:0)}function oe(_e){for(var Oe=_e.length;0<=--Oe;)_e[Oe]=0}function ie(_e){var Oe=_e.state,Ae=Oe.pending;Ae>_e.avail_out&&(Ae=_e.avail_out),Ae!==0&&(l.arraySet(_e.output,Oe.pending_buf,Oe.pending_out,Ae,_e.next_out),_e.next_out+=Ae,Oe.pending_out+=Ae,_e.total_out+=Ae,_e.avail_out-=Ae,Oe.pending-=Ae,Oe.pending===0&&(Oe.pending_out=0))}function de(_e,Oe){o._tr_flush_block(_e,0<=_e.block_start?_e.block_start:-1,_e.strstart-_e.block_start,Oe),_e.block_start=_e.strstart,ie(_e.strm)}function we(_e,Oe){_e.pending_buf[_e.pending++]=Oe}function je(_e,Oe){_e.pending_buf[_e.pending++]=Oe>>>8&255,_e.pending_buf[_e.pending++]=255&Oe}function xe(_e,Oe){var Ae,Xe,Ue=_e.max_chain_length,Ze=_e.strstart,Qe=_e.prev_length,Ye=_e.nice_match,nt=_e.strstart>_e.w_size-$?_e.strstart-(_e.w_size-$):0,rt=_e.window,Fe=_e.w_mask,dt=_e.prev,Dt=_e.strstart+O,pt=rt[Ze+Qe-1],zt=rt[Ze+Qe];_e.prev_length>=_e.good_match&&(Ue>>=2),Ye>_e.lookahead&&(Ye=_e.lookahead);do if(rt[(Ae=Oe)+Qe]===zt&&rt[Ae+Qe-1]===pt&&rt[Ae]===rt[Ze]&&rt[++Ae]===rt[Ze+1]){Ze+=2,Ae++;do;while(rt[++Ze]===rt[++Ae]&&rt[++Ze]===rt[++Ae]&&rt[++Ze]===rt[++Ae]&&rt[++Ze]===rt[++Ae]&&rt[++Ze]===rt[++Ae]&&rt[++Ze]===rt[++Ae]&&rt[++Ze]===rt[++Ae]&&rt[++Ze]===rt[++Ae]&&Zent&&--Ue!=0);return Qe<=_e.lookahead?Qe:_e.lookahead}function fe(_e){var Oe,Ae,Xe,Ue,Ze,Qe,Ye,nt,rt,Fe,dt=_e.w_size;do{if(Ue=_e.window_size-_e.lookahead-_e.strstart,_e.strstart>=dt+(dt-$)){for(l.arraySet(_e.window,_e.window,dt,dt,0),_e.match_start-=dt,_e.strstart-=dt,_e.block_start-=dt,Oe=Ae=_e.hash_size;Xe=_e.head[--Oe],_e.head[Oe]=dt<=Xe?Xe-dt:0,--Ae;);for(Oe=Ae=dt;Xe=_e.prev[--Oe],_e.prev[Oe]=dt<=Xe?Xe-dt:0,--Ae;);Ue+=dt}if(_e.strm.avail_in===0)break;if(Qe=_e.strm,Ye=_e.window,nt=_e.strstart+_e.lookahead,rt=Ue,Fe=void 0,Fe=Qe.avail_in,rt=I)for(Ze=_e.strstart-_e.insert,_e.ins_h=_e.window[Ze],_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[Ze+1])&_e.hash_mask;_e.insert&&(_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[Ze+I-1])&_e.hash_mask,_e.prev[Ze&_e.w_mask]=_e.head[_e.ins_h],_e.head[_e.ins_h]=Ze,Ze++,_e.insert--,!(_e.lookahead+_e.insert=I&&(_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[_e.strstart+I-1])&_e.hash_mask,Ae=_e.prev[_e.strstart&_e.w_mask]=_e.head[_e.ins_h],_e.head[_e.ins_h]=_e.strstart),Ae!==0&&_e.strstart-Ae<=_e.w_size-$&&(_e.match_length=xe(_e,Ae)),_e.match_length>=I)if(Xe=o._tr_tally(_e,_e.strstart-_e.match_start,_e.match_length-I),_e.lookahead-=_e.match_length,_e.match_length<=_e.max_lazy_match&&_e.lookahead>=I){for(_e.match_length--;_e.strstart++,_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[_e.strstart+I-1])&_e.hash_mask,Ae=_e.prev[_e.strstart&_e.w_mask]=_e.head[_e.ins_h],_e.head[_e.ins_h]=_e.strstart,--_e.match_length!=0;);_e.strstart++}else _e.strstart+=_e.match_length,_e.match_length=0,_e.ins_h=_e.window[_e.strstart],_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[_e.strstart+1])&_e.hash_mask;else Xe=o._tr_tally(_e,0,_e.window[_e.strstart]),_e.lookahead--,_e.strstart++;if(Xe&&(de(_e,!1),_e.strm.avail_out===0))return G}return _e.insert=_e.strstart=I&&(_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[_e.strstart+I-1])&_e.hash_mask,Ae=_e.prev[_e.strstart&_e.w_mask]=_e.head[_e.ins_h],_e.head[_e.ins_h]=_e.strstart),_e.prev_length=_e.match_length,_e.prev_match=_e.match_start,_e.match_length=I-1,Ae!==0&&_e.prev_length<_e.max_lazy_match&&_e.strstart-Ae<=_e.w_size-$&&(_e.match_length=xe(_e,Ae),_e.match_length<=5&&(_e.strategy===1||_e.match_length===I&&4096<_e.strstart-_e.match_start)&&(_e.match_length=I-1)),_e.prev_length>=I&&_e.match_length<=_e.prev_length){for(Ue=_e.strstart+_e.lookahead-I,Xe=o._tr_tally(_e,_e.strstart-1-_e.prev_match,_e.prev_length-I),_e.lookahead-=_e.prev_length-1,_e.prev_length-=2;++_e.strstart<=Ue&&(_e.ins_h=(_e.ins_h<<_e.hash_shift^_e.window[_e.strstart+I-1])&_e.hash_mask,Ae=_e.prev[_e.strstart&_e.w_mask]=_e.head[_e.ins_h],_e.head[_e.ins_h]=_e.strstart),--_e.prev_length!=0;);if(_e.match_available=0,_e.match_length=I-1,_e.strstart++,Xe&&(de(_e,!1),_e.strm.avail_out===0))return G}else if(_e.match_available){if((Xe=o._tr_tally(_e,0,_e.window[_e.strstart-1]))&&de(_e,!1),_e.strstart++,_e.lookahead--,_e.strm.avail_out===0)return G}else _e.match_available=1,_e.strstart++,_e.lookahead--}return _e.match_available&&(Xe=o._tr_tally(_e,0,_e.window[_e.strstart-1]),_e.match_available=0),_e.insert=_e.strstart_e.pending_buf_size-5&&(Ae=_e.pending_buf_size-5);;){if(_e.lookahead<=1){if(fe(_e),_e.lookahead===0&&Oe===h)return G;if(_e.lookahead===0)break}_e.strstart+=_e.lookahead,_e.lookahead=0;var Xe=_e.block_start+Ae;if((_e.strstart===0||_e.strstart>=Xe)&&(_e.lookahead=_e.strstart-Xe,_e.strstart=Xe,de(_e,!1),_e.strm.avail_out===0)||_e.strstart-_e.block_start>=_e.w_size-$&&(de(_e,!1),_e.strm.avail_out===0))return G}return _e.insert=0,Oe===m?(de(_e,!0),_e.strm.avail_out===0?ee:J):(_e.strstart>_e.block_start&&(de(_e,!1),_e.strm.avail_out),G)}),new Le(4,4,8,4,Se),new Le(4,5,16,8,Se),new Le(4,6,32,32,Se),new Le(4,4,16,16,Ee),new Le(8,16,32,32,Ee),new Le(8,16,128,128,Ee),new Le(8,32,128,256,Ee),new Le(32,128,258,1024,Ee),new Le(32,258,258,4096,Ee)],a.deflateInit=function(_e,Oe){return Ge(_e,Oe,v,15,8,0)},a.deflateInit2=Ge,a.deflateReset=Ne,a.deflateResetKeep=Be,a.deflateSetHeader=function(_e,Oe){return _e&&_e.state?_e.state.wrap!==2?x:(_e.state.gzhead=Oe,p):x},a.deflate=function(_e,Oe){var Ae,Xe,Ue,Ze;if(!_e||!_e.state||5>8&255),we(Xe,Xe.gzhead.time>>16&255),we(Xe,Xe.gzhead.time>>24&255),we(Xe,Xe.level===9?2:2<=Xe.strategy||Xe.level<2?4:0),we(Xe,255&Xe.gzhead.os),Xe.gzhead.extra&&Xe.gzhead.extra.length&&(we(Xe,255&Xe.gzhead.extra.length),we(Xe,Xe.gzhead.extra.length>>8&255)),Xe.gzhead.hcrc&&(_e.adler=d(_e.adler,Xe.pending_buf,Xe.pending,0)),Xe.gzindex=0,Xe.status=69):(we(Xe,0),we(Xe,0),we(Xe,0),we(Xe,0),we(Xe,0),we(Xe,Xe.level===9?2:2<=Xe.strategy||Xe.level<2?4:0),we(Xe,3),Xe.status=W);else{var Qe=v+(Xe.w_bits-8<<4)<<8;Qe|=(2<=Xe.strategy||Xe.level<2?0:Xe.level<6?1:Xe.level===6?2:3)<<6,Xe.strstart!==0&&(Qe|=32),Qe+=31-Qe%31,Xe.status=W,je(Xe,Qe),Xe.strstart!==0&&(je(Xe,_e.adler>>>16),je(Xe,65535&_e.adler)),_e.adler=1}if(Xe.status===69)if(Xe.gzhead.extra){for(Ue=Xe.pending;Xe.gzindex<(65535&Xe.gzhead.extra.length)&&(Xe.pending!==Xe.pending_buf_size||(Xe.gzhead.hcrc&&Xe.pending>Ue&&(_e.adler=d(_e.adler,Xe.pending_buf,Xe.pending-Ue,Ue)),ie(_e),Ue=Xe.pending,Xe.pending!==Xe.pending_buf_size));)we(Xe,255&Xe.gzhead.extra[Xe.gzindex]),Xe.gzindex++;Xe.gzhead.hcrc&&Xe.pending>Ue&&(_e.adler=d(_e.adler,Xe.pending_buf,Xe.pending-Ue,Ue)),Xe.gzindex===Xe.gzhead.extra.length&&(Xe.gzindex=0,Xe.status=73)}else Xe.status=73;if(Xe.status===73)if(Xe.gzhead.name){Ue=Xe.pending;do{if(Xe.pending===Xe.pending_buf_size&&(Xe.gzhead.hcrc&&Xe.pending>Ue&&(_e.adler=d(_e.adler,Xe.pending_buf,Xe.pending-Ue,Ue)),ie(_e),Ue=Xe.pending,Xe.pending===Xe.pending_buf_size)){Ze=1;break}Ze=Xe.gzindexUe&&(_e.adler=d(_e.adler,Xe.pending_buf,Xe.pending-Ue,Ue)),Ze===0&&(Xe.gzindex=0,Xe.status=91)}else Xe.status=91;if(Xe.status===91)if(Xe.gzhead.comment){Ue=Xe.pending;do{if(Xe.pending===Xe.pending_buf_size&&(Xe.gzhead.hcrc&&Xe.pending>Ue&&(_e.adler=d(_e.adler,Xe.pending_buf,Xe.pending-Ue,Ue)),ie(_e),Ue=Xe.pending,Xe.pending===Xe.pending_buf_size)){Ze=1;break}Ze=Xe.gzindexUe&&(_e.adler=d(_e.adler,Xe.pending_buf,Xe.pending-Ue,Ue)),Ze===0&&(Xe.status=103)}else Xe.status=103;if(Xe.status===103&&(Xe.gzhead.hcrc?(Xe.pending+2>Xe.pending_buf_size&&ie(_e),Xe.pending+2<=Xe.pending_buf_size&&(we(Xe,255&_e.adler),we(Xe,_e.adler>>8&255),_e.adler=0,Xe.status=W)):Xe.status=W),Xe.pending!==0){if(ie(_e),_e.avail_out===0)return Xe.last_flush=-1,p}else if(_e.avail_in===0&&ue(Oe)<=ue(Ae)&&Oe!==m)return le(_e,-5);if(Xe.status===666&&_e.avail_in!==0)return le(_e,-5);if(_e.avail_in!==0||Xe.lookahead!==0||Oe!==h&&Xe.status!==666){var Ye=Xe.strategy===2?function(nt,rt){for(var Fe;;){if(nt.lookahead===0&&(fe(nt),nt.lookahead===0)){if(rt===h)return G;break}if(nt.match_length=0,Fe=o._tr_tally(nt,0,nt.window[nt.strstart]),nt.lookahead--,nt.strstart++,Fe&&(de(nt,!1),nt.strm.avail_out===0))return G}return nt.insert=0,rt===m?(de(nt,!0),nt.strm.avail_out===0?ee:J):nt.last_lit&&(de(nt,!1),nt.strm.avail_out===0)?G:K}(Xe,Oe):Xe.strategy===3?function(nt,rt){for(var Fe,dt,Dt,pt,zt=nt.window;;){if(nt.lookahead<=O){if(fe(nt),nt.lookahead<=O&&rt===h)return G;if(nt.lookahead===0)break}if(nt.match_length=0,nt.lookahead>=I&&0nt.lookahead&&(nt.match_length=nt.lookahead)}if(nt.match_length>=I?(Fe=o._tr_tally(nt,1,nt.match_length-I),nt.lookahead-=nt.match_length,nt.strstart+=nt.match_length,nt.match_length=0):(Fe=o._tr_tally(nt,0,nt.window[nt.strstart]),nt.lookahead--,nt.strstart++),Fe&&(de(nt,!1),nt.strm.avail_out===0))return G}return nt.insert=0,rt===m?(de(nt,!0),nt.strm.avail_out===0?ee:J):nt.last_lit&&(de(nt,!1),nt.strm.avail_out===0)?G:K}(Xe,Oe):i[Xe.level].func(Xe,Oe);if(Ye!==ee&&Ye!==J||(Xe.status=666),Ye===G||Ye===ee)return _e.avail_out===0&&(Xe.last_flush=-1),p;if(Ye===K&&(Oe===1?o._tr_align(Xe):Oe!==5&&(o._tr_stored_block(Xe,0,0,!1),Oe===3&&(oe(Xe.head),Xe.lookahead===0&&(Xe.strstart=0,Xe.block_start=0,Xe.insert=0))),ie(_e),_e.avail_out===0))return Xe.last_flush=-1,p}return Oe!==m?p:Xe.wrap<=0?1:(Xe.wrap===2?(we(Xe,255&_e.adler),we(Xe,_e.adler>>8&255),we(Xe,_e.adler>>16&255),we(Xe,_e.adler>>24&255),we(Xe,255&_e.total_in),we(Xe,_e.total_in>>8&255),we(Xe,_e.total_in>>16&255),we(Xe,_e.total_in>>24&255)):(je(Xe,_e.adler>>>16),je(Xe,65535&_e.adler)),ie(_e),0=Ae.w_size&&(Ze===0&&(oe(Ae.head),Ae.strstart=0,Ae.block_start=0,Ae.insert=0),rt=new l.Buf8(Ae.w_size),l.arraySet(rt,Oe,Fe-Ae.w_size,Ae.w_size,0),Oe=rt,Fe=Ae.w_size),Qe=_e.avail_in,Ye=_e.next_in,nt=_e.input,_e.avail_in=Fe,_e.next_in=0,_e.input=Oe,fe(Ae);Ae.lookahead>=I;){for(Xe=Ae.strstart,Ue=Ae.lookahead-(I-1);Ae.ins_h=(Ae.ins_h<>>=I=L>>>24,k-=I,(I=L>>>16&255)===0)K[u++]=65535&L;else{if(!(16&I)){if(!(64&I)){L=C[(65535&L)+(v&(1<>>=I,k-=I),k<15&&(v+=G[c++]<>>=I=L>>>24,k-=I,!(16&(I=L>>>16&255))){if(!(64&I)){L=T[(65535&L)+(v&(1<>>=I,k-=I,(I=u-h)<$){if(y<(I=$-I)&&o.sane){i.msg="invalid distance too far back",o.mode=30;break e}if(W=b,(q=0)===g){if(q+=x-I,I>3,v&=(1<<(k-=O<<3))-1,i.next_in=c,i.next_out=u,i.avail_in=c>>24&255)+(q>>>8&65280)+((65280&q)<<8)+((255&q)<<24)}function v(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function k(q){var W;return q&&q.state?(W=q.state,q.total_in=q.total_out=W.total=0,q.msg="",W.wrap&&(q.adler=1&W.wrap),W.mode=x,W.last=0,W.havedict=0,W.dmax=32768,W.head=null,W.hold=0,W.bits=0,W.lencode=W.lendyn=new i.Buf32(y),W.distcode=W.distdyn=new i.Buf32(g),W.sane=1,W.back=-1,m):p}function C(q){var W;return q&&q.state?((W=q.state).wsize=0,W.whave=0,W.wnext=0,k(q)):p}function T(q,W){var G,K;return q&&q.state?(K=q.state,W<0?(G=0,W=-W):(G=1+(W>>4),W<48&&(W&=15)),W&&(W<8||15=J.wsize?(i.arraySet(J.window,W,G-J.wsize,J.wsize,0),J.wnext=0,J.whave=J.wsize):(K<(ee=J.wsize-J.wnext)&&(ee=K),i.arraySet(J.window,W,G-K,ee,J.wnext),(K-=ee)?(i.arraySet(J.window,W,G-K,K,0),J.wnext=K,J.whave=J.wsize):(J.wnext+=ee,J.wnext===J.wsize&&(J.wnext=0),J.whave>>8&255,G.check=o(G.check,Ze,2,0),de=ie=0,G.mode=2;break}if(G.flags=0,G.head&&(G.head.done=!1),!(1&G.wrap)||(((255&ie)<<8)+(ie>>8))%31){q.msg="incorrect header check",G.mode=30;break}if((15&ie)!=8){q.msg="unknown compression method",G.mode=30;break}if(de-=4,_e=8+(15&(ie>>>=4)),G.wbits===0)G.wbits=_e;else if(_e>G.wbits){q.msg="invalid window size",G.mode=30;break}G.dmax=1<<_e,q.adler=G.check=1,G.mode=512&ie?10:12,de=ie=0;break;case 2:for(;de<16;){if(ue===0)break e;ue--,ie+=K[J++]<>8&1),512&G.flags&&(Ze[0]=255&ie,Ze[1]=ie>>>8&255,G.check=o(G.check,Ze,2,0)),de=ie=0,G.mode=3;case 3:for(;de<32;){if(ue===0)break e;ue--,ie+=K[J++]<>>8&255,Ze[2]=ie>>>16&255,Ze[3]=ie>>>24&255,G.check=o(G.check,Ze,4,0)),de=ie=0,G.mode=4;case 4:for(;de<16;){if(ue===0)break e;ue--,ie+=K[J++]<>8),512&G.flags&&(Ze[0]=255&ie,Ze[1]=ie>>>8&255,G.check=o(G.check,Ze,2,0)),de=ie=0,G.mode=5;case 5:if(1024&G.flags){for(;de<16;){if(ue===0)break e;ue--,ie+=K[J++]<>>8&255,G.check=o(G.check,Ze,2,0)),de=ie=0}else G.head&&(G.head.extra=null);G.mode=6;case 6:if(1024&G.flags&&(ue<(xe=G.length)&&(xe=ue),xe&&(G.head&&(_e=G.head.extra_len-G.length,G.head.extra||(G.head.extra=new Array(G.head.extra_len)),i.arraySet(G.head.extra,K,J,xe,_e)),512&G.flags&&(G.check=o(G.check,K,xe,J)),ue-=xe,J+=xe,G.length-=xe),G.length))break e;G.length=0,G.mode=7;case 7:if(2048&G.flags){if(ue===0)break e;for(xe=0;_e=K[J+xe++],G.head&&_e&&G.length<65536&&(G.head.name+=String.fromCharCode(_e)),_e&&xe>9&1,G.head.done=!0),q.adler=G.check=0,G.mode=12;break;case 10:for(;de<32;){if(ue===0)break e;ue--,ie+=K[J++]<>>=7&de,de-=7&de,G.mode=27;break}for(;de<3;){if(ue===0)break e;ue--,ie+=K[J++]<>>=1)){case 0:G.mode=14;break;case 1:if(O(G),G.mode=20,W!==6)break;ie>>>=2,de-=2;break e;case 2:G.mode=17;break;case 3:q.msg="invalid block type",G.mode=30}ie>>>=2,de-=2;break;case 14:for(ie>>>=7&de,de-=7&de;de<32;){if(ue===0)break e;ue--,ie+=K[J++]<>>16^65535)){q.msg="invalid stored block lengths",G.mode=30;break}if(G.length=65535&ie,de=ie=0,G.mode=15,W===6)break e;case 15:G.mode=16;case 16:if(xe=G.length){if(ue>>=5,de-=5,G.ndist=1+(31&ie),ie>>>=5,de-=5,G.ncode=4+(15&ie),ie>>>=4,de-=4,286>>=3,de-=3}for(;G.have<19;)G.lens[Qe[G.have++]]=0;if(G.lencode=G.lendyn,G.lenbits=7,Ae={bits:G.lenbits},Oe=d(0,G.lens,0,19,G.lencode,0,G.work,Ae),G.lenbits=Ae.bits,Oe){q.msg="invalid code lengths set",G.mode=30;break}G.have=0,G.mode=19;case 19:for(;G.have>>16&255,De=65535&Ue,!((Ee=Ue>>>24)<=de);){if(ue===0)break e;ue--,ie+=K[J++]<>>=Ee,de-=Ee,G.lens[G.have++]=De;else{if(De===16){for(Xe=Ee+2;de>>=Ee,de-=Ee,G.have===0){q.msg="invalid bit length repeat",G.mode=30;break}_e=G.lens[G.have-1],xe=3+(3&ie),ie>>>=2,de-=2}else if(De===17){for(Xe=Ee+3;de>>=Ee)),ie>>>=3,de-=3}else{for(Xe=Ee+7;de>>=Ee)),ie>>>=7,de-=7}if(G.have+xe>G.nlen+G.ndist){q.msg="invalid bit length repeat",G.mode=30;break}for(;xe--;)G.lens[G.have++]=_e}}if(G.mode===30)break;if(G.lens[256]===0){q.msg="invalid code -- missing end-of-block",G.mode=30;break}if(G.lenbits=9,Ae={bits:G.lenbits},Oe=d(u,G.lens,0,G.nlen,G.lencode,0,G.work,Ae),G.lenbits=Ae.bits,Oe){q.msg="invalid literal/lengths set",G.mode=30;break}if(G.distbits=6,G.distcode=G.distdyn,Ae={bits:G.distbits},Oe=d(h,G.lens,G.nlen,G.ndist,G.distcode,0,G.work,Ae),G.distbits=Ae.bits,Oe){q.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<=oe){q.next_out=le,q.avail_out=oe,q.next_in=J,q.avail_in=ue,G.hold=ie,G.bits=de,c(q,je),le=q.next_out,ee=q.output,oe=q.avail_out,J=q.next_in,K=q.input,ue=q.avail_in,ie=G.hold,de=G.bits,G.mode===12&&(G.back=-1);break}for(G.back=0;Le=(Ue=G.lencode[ie&(1<>>16&255,De=65535&Ue,!((Ee=Ue>>>24)<=de);){if(ue===0)break e;ue--,ie+=K[J++]<>Be)])>>>16&255,De=65535&Ue,!(Be+(Ee=Ue>>>24)<=de);){if(ue===0)break e;ue--,ie+=K[J++]<>>=Be,de-=Be,G.back+=Be}if(ie>>>=Ee,de-=Ee,G.back+=Ee,G.length=De,Le===0){G.mode=26;break}if(32&Le){G.back=-1,G.mode=12;break}if(64&Le){q.msg="invalid literal/length code",G.mode=30;break}G.extra=15&Le,G.mode=22;case 22:if(G.extra){for(Xe=G.extra;de>>=G.extra,de-=G.extra,G.back+=G.extra}G.was=G.length,G.mode=23;case 23:for(;Le=(Ue=G.distcode[ie&(1<>>16&255,De=65535&Ue,!((Ee=Ue>>>24)<=de);){if(ue===0)break e;ue--,ie+=K[J++]<>Be)])>>>16&255,De=65535&Ue,!(Be+(Ee=Ue>>>24)<=de);){if(ue===0)break e;ue--,ie+=K[J++]<>>=Be,de-=Be,G.back+=Be}if(ie>>>=Ee,de-=Ee,G.back+=Ee,64&Le){q.msg="invalid distance code",G.mode=30;break}G.offset=De,G.extra=15&Le,G.mode=24;case 24:if(G.extra){for(Xe=G.extra;de>>=G.extra,de-=G.extra,G.back+=G.extra}if(G.offset>G.dmax){q.msg="invalid distance too far back",G.mode=30;break}G.mode=25;case 25:if(oe===0)break e;if(xe=je-oe,G.offset>xe){if((xe=G.offset-xe)>G.whave&&G.sane){q.msg="invalid distance too far back",G.mode=30;break}fe=xe>G.wnext?(xe-=G.wnext,G.wsize-xe):G.wnext-xe,xe>G.length&&(xe=G.length),Se=G.window}else Se=ee,fe=le-G.offset,xe=G.length;for(oeP?(I=fe[Se+g[W]],de[we+g[W]]):(I=96,0),v=1<>le)+(k-=v)]=L<<24|I<<16|O|0,k!==0;);for(v=1<>=1;if(v!==0?(ie&=v-1,ie+=v):ie=0,W++,--je[q]==0){if(q===K)break;q=h[m+g[W]]}if(ee>>7)]}function we(Ue,Ze){Ue.pending_buf[Ue.pending++]=255&Ze,Ue.pending_buf[Ue.pending++]=Ze>>>8&255}function je(Ue,Ze,Qe){Ue.bi_valid>b-Qe?(Ue.bi_buf|=Ze<>b-Ue.bi_valid,Ue.bi_valid+=Qe-b):(Ue.bi_buf|=Ze<>>=1,Qe<<=1,0<--Ze;);return Qe>>>1}function Se(Ue,Ze,Qe){var Ye,nt,rt=new Array(g+1),Fe=0;for(Ye=1;Ye<=g;Ye++)rt[Ye]=Fe=Fe+Qe[Ye-1]<<1;for(nt=0;nt<=Ze;nt++){var dt=Ue[2*nt+1];dt!==0&&(Ue[2*nt]=fe(rt[dt]++,dt))}}function Ee(Ue){var Ze;for(Ze=0;Ze>1;1<=Qe;Qe--)Be(Ue,rt,Qe);for(nt=Dt;Qe=Ue.heap[1],Ue.heap[1]=Ue.heap[Ue.heap_len--],Be(Ue,rt,1),Ye=Ue.heap[1],Ue.heap[--Ue.heap_max]=Qe,Ue.heap[--Ue.heap_max]=Ye,rt[2*nt]=rt[2*Qe]+rt[2*Ye],Ue.depth[nt]=(Ue.depth[Qe]>=Ue.depth[Ye]?Ue.depth[Qe]:Ue.depth[Ye])+1,rt[2*Qe+1]=rt[2*Ye+1]=nt,Ue.heap[1]=nt++,Be(Ue,rt,1),2<=Ue.heap_len;);Ue.heap[--Ue.heap_max]=Ue.heap[1],function(zt,Gt){var qs,As,Bt,At,Is,jt,Qs=Gt.dyn_tree,cn=Gt.max_code,qt=Gt.stat_desc.static_tree,Gs=Gt.stat_desc.has_stree,Ls=Gt.stat_desc.extra_bits,sn=Gt.stat_desc.extra_base,Hs=Gt.stat_desc.max_length,nn=0;for(At=0;At<=g;At++)zt.bl_count[At]=0;for(Qs[2*zt.heap[zt.heap_max]+1]=0,qs=zt.heap_max+1;qs>=7;nt>>=1)if(1&pt&&dt.dyn_ltree[2*Dt]!==0)return l;if(dt.dyn_ltree[18]!==0||dt.dyn_ltree[20]!==0||dt.dyn_ltree[26]!==0)return o;for(Dt=32;Dt>>3,(rt=Ue.static_len+3+7>>>3)<=nt&&(nt=rt)):nt=rt=Qe+5,Qe+4<=nt&&Ze!==-1?Xe(Ue,Ze,Qe,Ye):Ue.strategy===4||rt===nt?(je(Ue,2+(Ye?1:0),3),Ne(Ue,$,q)):(je(Ue,4+(Ye?1:0),3),function(dt,Dt,pt,zt){var Gt;for(je(dt,Dt-257,5),je(dt,pt-1,5),je(dt,zt-4,4),Gt=0;Gt>>8&255,Ue.pending_buf[Ue.d_buf+2*Ue.last_lit+1]=255&Ze,Ue.pending_buf[Ue.l_buf+Ue.last_lit]=255&Qe,Ue.last_lit++,Ze===0?Ue.dyn_ltree[2*Qe]++:(Ue.matches++,Ze--,Ue.dyn_ltree[2*(G[Qe]+h+1)]++,Ue.dyn_dtree[2*de(Ze)]++),Ue.last_lit===Ue.lit_bufsize-1},a._tr_align=function(Ue){je(Ue,2,3),xe(Ue,k,$),function(Ze){Ze.bi_valid===16?(we(Ze,Ze.bi_buf),Ze.bi_buf=0,Ze.bi_valid=0):8<=Ze.bi_valid&&(Ze.pending_buf[Ze.pending++]=255&Ze.bi_buf,Ze.bi_buf>>=8,Ze.bi_valid-=8)}(Ue)}},{"../utils/common":41}],53:[function(n,r,a){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,u,h,m=1,p={},x=!1,y=l.document,g=Object.getPrototypeOf&&Object.getPrototypeOf(l);g=g&&g.setTimeout?g:l,c={}.toString.call(l.process)==="[object process]"?function(C){process.nextTick(function(){v(C)})}:function(){if(l.postMessage&&!l.importScripts){var C=!0,T=l.onmessage;return l.onmessage=function(){C=!1},l.postMessage("","*"),l.onmessage=T,C}}()?(h="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",k,!1):l.attachEvent("onmessage",k),function(C){l.postMessage(h+C,"*")}):l.MessageChannel?((u=new MessageChannel).port1.onmessage=function(C){v(C.data)},function(C){u.port2.postMessage(C)}):y&&"onreadystatechange"in y.createElement("script")?(d=y.documentElement,function(C){var T=y.createElement("script");T.onreadystatechange=function(){v(C),T.onreadystatechange=null,d.removeChild(T),T=null},d.appendChild(T)}):function(C){setTimeout(v,0,C)},g.setImmediate=function(C){typeof C!="function"&&(C=new Function(""+C));for(var T=new Array(arguments.length-1),M=0;M"u"?i===void 0?this:i:self)}).call(this,typeof Xf<"u"?Xf:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(c6t);var RIs=c6t.exports;const d6t=sd(RIs);function KLe(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 DIs=()=>{Ns();const[s,t]=j.useState(null),[n,r]=j.useState(null),[a,i]=j.useState("all"),[l,o]=j.useState(new Set),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState("images"),[x,y]=j.useState(null),{data:g=[],isLoading:b}=mt({queryKey:["social-swag-2"],queryFn:async()=>{const{data:le,error:ue}=await U.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(ue)throw ue;return le}}),{data:v=[]}=mt({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:le,error:ue}=await U.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(ue)throw ue;return le}}),{data:k=[]}=mt({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:le,error:ue}=await U.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(ue)throw ue;return le}}),{data:C=[]}=mt({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:le,error:ue}=await U.from("social_accounts").select("id, platform").eq("is_active",!0);if(ue)throw ue;return le||[]}}),T=C.length>0,M=j.useMemo(()=>a==="all"?null:k.find(le=>le.month===a)||null,[a,k]),P=j.useMemo(()=>[...new Set(g.map(ue=>ue.month))].sort((ue,oe)=>oe.localeCompare(ue)),[g]);j.useEffect(()=>{P.length>0&&a==="all"&&i(P[0])},[P,a]);const L=le=>{try{const ue=hqe(le,"yyyy-MM",new Date);return Bs(ue,"MMMM yyyy")}catch{return le}},I=j.useMemo(()=>a==="all"?g:g.filter(le=>le.month===a),[a,g]),O=j.useMemo(()=>{var le;return a==="all"?null:((le=v.find(ue=>ue.month===a))==null?void 0:le.canva_link)||null},[a,v]),$=async le=>{try{await navigator.clipboard.writeText(le),re.success("Caption copied to clipboard!")}catch{re.error("Failed to copy caption")}},q=async(le,ue)=>{try{const ie=await(await fetch(le)).blob(),de=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),we=navigator.canShare&&navigator.canShare({files:[new File([ie],"test.jpg",{type:"image/jpeg"})]});if(de&&we){const je=new File([ie],`social-swag-${ue}.jpg`,{type:"image/jpeg"});await navigator.share({files:[je],title:"Social Swag Image"}),re.success("Image ready to save!")}else{const je=window.URL.createObjectURL(ie),xe=document.createElement("a");xe.href=je,xe.download=`social-swag-${ue}.jpg`,document.body.appendChild(xe),xe.click(),document.body.removeChild(xe),window.URL.revokeObjectURL(je),re.success("Image downloaded!")}}catch(oe){oe.name!=="AbortError"&&re.error("Failed to download image")}},W=le=>{o(ue=>{const oe=new Set(ue);return oe.has(le)?oe.delete(le):oe.add(le),oe})},G=()=>{o(new Set(I.map(le=>le.id)))},K=()=>{o(new Set),d(!1)},ee=async()=>{const le=I.filter(ue=>l.has(ue.id));if(le.length===0){re.error("No images selected");return}h(!0),re.info(`Preparing ${le.length} images for download...`);try{const ue=new d6t,oe=[...le].sort((xe,fe)=>xe.sort_order-fe.sort_order);for(let xe=0;xe{c?W(le.id):t(le)};return e.jsx(Vs,{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(qe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(yn,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(qe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(ac,{className:"h-3 w-3 mr-1"}),g.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(fa,{defaultValue:"gallery",className:"space-y-6",children:[e.jsxs(xa,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(ss,{value:"gallery",className:"gap-2",children:[e.jsx(ac,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(ss,{value:"scheduled",className:"gap-2",children:[e.jsx(Vc,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(ns,{value:"gallery",className:"space-y-6",children:[T?e.jsx(be,{className:"border rounded-xl",children:e.jsx(Re,{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(Yn,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(be,{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(Re,{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(sx,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(vm,{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(Yn,{to:"/social-connections",children:[e.jsx(Rc,{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:P.map(le=>e.jsx("button",{onClick:()=>i(le),className:Et("px-4 py-2 rounded-full text-sm font-medium transition-all",a===le?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:L(le)},le))}),a!=="all"&&(O?e.jsxs("a",{href:O,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 ",L(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 ",L(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:()=>{p("images"),K()},className:Et("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(ac,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{p("reels"),K()},className:Et("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(wh,{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 (",I.length,")"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:K,className:"gap-2",children:[e.jsx(dr,{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:ee,disabled:u,className:"gap-2",children:[e.jsx(ii,{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(da,{className:"h-4 w-4"}),"Select Images"]})})]}),b&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!b&&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:I.map(le=>{const ue=l.has(le.id);return e.jsx(be,{className:Et("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:()=>J(le),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:KLe(le.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"}),le.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:Bs(new Date(le.post_date+"T00:00:00"),"MMM d")})}),c&&e.jsx("div",{className:Et("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(da,{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"})})]})},le.id)})}),I.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ac,{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."})]})]}),!b&&m==="reels"&&e.jsx(e.Fragment,{children:M?e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4",children:e.jsx(be,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>r(M),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:KLe(M.image_url,400,75),alt:"Reel preview",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-105",loading:"lazy",decoding:"async"}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsxs(qe,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(wh,{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(wh,{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(Fs,{open:!!s,onOpenChange:()=>t(null),children:e.jsx(Os,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children: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:KLe(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(ra,{className:"h-4 w-4"}),Bs(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(ra,{className:"h-3.5 w-3.5"}),"Post on ",Bs(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(Dr,{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(ja,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(B,{variant:"outline",onClick:()=>q(s.image_url,s.id),className:"flex-1 gap-2",children:[e.jsx(ii,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(Fs,{open:!!n,onOpenChange:()=>r(null),children:e.jsx(Os,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children: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(wh,{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(ja,{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(PIs,{open:!!x,onOpenChange:le=>!le&&y(null),imageUrl:(x==null?void 0:x.imageUrl)||"",imageId:(x==null?void 0:x.imageId)||"",defaultCaption:(x==null?void 0:x.caption)||"",swagItemId:x==null?void 0:x.imageId})]}),e.jsx(ns,{value:"scheduled",children:e.jsx(IIs,{})})]})]})})},OIs=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:ac,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:ia,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:Eo,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:ol,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:Wm,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:gj,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:w3,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function FIs(){return e.jsx(Vs,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(ql,{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(qe,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(yn,{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(Yn,{to:"/marketing-studio/brand-kit",children:[e.jsx(Ac,{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:OIs.map(s=>{const t=s.icon,n=e.jsxs(be,{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(Re,{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(qe,{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(Yn,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function DJ(){const s=ei();return mt({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("marketing_brand_presets").select("*").eq("user_id",s).order("is_default",{ascending:!1}).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function zIs(){const{data:s,...t}=DJ();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function BIs(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");if(n.is_default&&await U.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),n.id){const{id:r,...a}=n,{data:i,error:l}=await U.from("marketing_brand_presets").update(a).eq("id",r).eq("user_id",s).select().single();if(l)throw l;return i}else{const{data:r,error:a}=await U.from("marketing_brand_presets").insert({...n,user_id:s}).select().single();if(a)throw a;return r}},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}function $Is(){const s=ei(),t=as();return vt({mutationFn:async n=>{const{error:r}=await U.from("marketing_brand_presets").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function UIs(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await U.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await U.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function qIs({preset:s,onSaved:t,onCancel:n}){var y;const r=ei(),a=BIs(),i=$Is(),l=j.useRef(null),o=j.useRef(null),[c,d]=j.useState(null),[u,h]=j.useState({name:(s==null?void 0:s.name)??"My Brand",is_default:(s==null?void 0:s.is_default)??!0,display_name:(s==null?void 0:s.display_name)??"",phone:(s==null?void 0:s.phone)??"",email:(s==null?void 0:s.email)??"",license_number:(s==null?void 0:s.license_number)??"",tagline:(s==null?void 0:s.tagline)??"",website_url:(s==null?void 0:s.website_url)??"",headshot_url:(s==null?void 0:s.headshot_url)??"",brokerage_logo_url:(s==null?void 0:s.brokerage_logo_url)??"",brand_color:(s==null?void 0:s.brand_color)??"#0f172a",accent_color:(s==null?void 0:s.accent_color)??"#3b82f6"});j.useEffect(()=>{s||(async()=>{if(!r)return;const{supabase:g}=await Mi(async()=>{const{supabase:v}=await Promise.resolve().then(()=>nis);return{supabase:v}},void 0),{data:b}=await g.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();b&&h(v=>({...v,display_name:v.display_name||(b.name??""),email:v.email||(b.email??""),phone:v.phone||(b.phone??""),headshot_url:v.headshot_url||(b.avatar_url??""),website_url:v.website_url||(b.website_url??""),tagline:v.tagline||(b.title??"")}))})()},[r]);const m=async(g,b)=>{if(r){d(g);try{const v=await UIs(r,b,g);h(k=>({...k,[g==="headshot"?"headshot_url":"brokerage_logo_url"]:v}))}catch(v){re.error(v.message||"Upload failed")}finally{d(null)}}},p=async()=>{try{const g=await a.mutateAsync({id:s==null?void 0:s.id,...u});re.success("Brand preset saved"),t==null||t(g)}catch(g){re.error(g.message||"Save failed")}},x=async()=>{s!=null&&s.id&&await Bi("Delete this brand preset?")&&(await i.mutateAsync(s.id),re.success("Preset deleted"),n==null||n())};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Preset name"}),e.jsx(ye,{value:u.name,onChange:g=>h({...u,name:g.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(Mn,{checked:u.is_default,onCheckedChange:g=>h({...u,is_default:g})}),e.jsx(se,{children:"Use as default"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Display name"}),e.jsx(ye,{value:u.display_name,onChange:g=>h({...u,display_name:g.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:u.phone,onChange:g=>h({...u,phone:g.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{value:u.email,onChange:g=>h({...u,email:g.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"License #"}),e.jsx(ye,{value:u.license_number,onChange:g=>h({...u,license_number:g.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Tagline"}),e.jsx(ye,{value:u.tagline,onChange:g=>h({...u,tagline:g.target.value}),placeholder:"Helping families find home"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Website"}),e.jsx(ye,{value:u.website_url,onChange:g=>h({...u,website_url:g.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ra,{className:"h-16 w-16",children:[e.jsx(Fi,{src:u.headshot_url||void 0}),e.jsx(Da,{children:((y=u.display_name)==null?void 0:y[0])??"A"})]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var g;return(g=l.current)==null?void 0:g.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ja,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:g=>{var b;return((b=g.target.files)==null?void 0:b[0])&&m("headshot",g.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Brokerage logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-16 w-24 bg-muted rounded flex items-center justify-center overflow-hidden border",children:u.brokerage_logo_url?e.jsx("img",{src:u.brokerage_logo_url,alt:"logo",className:"max-h-full max-w-full object-contain"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"No logo"})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var g;return(g=o.current)==null?void 0:g.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ja,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:g=>{var b;return((b=g.target.files)==null?void 0:b[0])&&m("logo",g.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Brand color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.brand_color,onChange:g=>h({...u,brand_color:g.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(ye,{value:u.brand_color,onChange:g=>h({...u,brand_color:g.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.accent_color,onChange:g=>h({...u,accent_color:g.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(ye,{value:u.accent_color,onChange:g=>h({...u,accent_color:g.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:x,className:"text-destructive",children:[e.jsx(Rn,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsxs(B,{onClick:p,disabled:a.isPending,children:[a.isPending&&e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function VIs(){const{data:s,isLoading:t}=DJ(),[n,r]=j.useState(null);return e.jsx(Vs,{title:"Brand Kit",children:e.jsxs("div",{className:"container max-w-5xl py-6 md:py-8 space-y-6 px-4",children:[e.jsx(ql,{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(Yn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(_a,{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(Js,{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(be,{className:"border-dashed",children:e.jsxs(Re,{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(Js,{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(be,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(Ft,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs(qe,{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(Za,{className:"h-4 w-4"})})]}),e.jsx(fr,{children:a.display_name})]}),e.jsxs(Re,{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(Fs,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx($s,{children:e.jsx(zs,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(qIs,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const _Fe=[{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"}],HIs=s=>_Fe.find(t=>t.id===s)??_Fe[0];function GIs(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 WIs({value:s,onChange:t,mediaType:n}){const r=_Fe.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:Et("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(KIs,{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 KIs({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 YIs=Math.PI/180;function ZIs(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const l8=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},si={_global:l8,version:"10.2.5",isBrowser:ZIs(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return si.angleDeg?s*YIs: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 si.DD.isDragging},isTransforming(){var s,t;return(t=(s=si.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!si.DD.node},releaseCanvasOnDestroy:!0,document:l8.document,_injectGlobal(s){typeof l8.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),l8.Konva=s}},Vp=s=>{si[s.prototype.getClassName()]=s};si._injectGlobal(si);const XIs=`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"; `,Xot=()=>{if(typeof document>"u")throw new Error(XIs)};class D_{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 D_(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=Kn._getRotation(c.rotation),c}}const QIs="[object Array]",JIs="[object Number]",e8s="[object String]",t8s="[object Boolean]",s8s=Math.PI/180,n8s=180/Math.PI,CH="#",r8s="",a8s="0",i8s="Konva warning: ",Qot="Konva error: ",o8s="rgb(",YLe={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]},l8s=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let tne=[],AH=null;const c8s=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},Kn={_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)===QIs},_isNumber(s){return Object.prototype.toString.call(s)===JIs&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===e8s},_isBoolean(s){return Object.prototype.toString.call(s)===t8s},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){tne.push(s),tne.length===1&&c8s(function(){const t=tne;tne=[],t.forEach(function(n){n()})})},createCanvasElement(){Xot();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return Xot(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const n=Kn.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(CH,r8s);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=a8s+s;return CH+s},isCanvasFarblingActive(){if(AH!==null)return AH;if(typeof document>"u")return AH=!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 AH=r,this.releaseCanvas(s),AH},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),CH+this._rgbToHex(s,t,n)},getSnappedHexColor(s){const t=this._hexToRgb(s);return CH+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 YLe?(t=YLe[s],{r:t[0],g:t[1],b:t[2]}):s[0]===CH?this._hexToRgb(s.substring(1)):s.substr(0,4)===o8s?(t=l8s.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",Kn._namedColorToRBA(s)||Kn._hex3ColorToRGBA(s)||Kn._hex4ColorToRGBA(s)||Kn._hex6ColorToRGBA(s)||Kn._hex8ColorToRGBA(s)||Kn._rgbColorToRGBA(s)||Kn._rgbaColorToRGBA(s)||Kn._hslColorToRGBA(s)},_namedColorToRBA(s){const t=YLe[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=Kn.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=Kn._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+=u8s+d.join(Jot)+h8s)):(i+=o.property,t||(i+=g8s+o.val)),i+=f8s;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=v8s&&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=elt.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=d8s(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 Id._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];Id._dragElements.forEach((n,r)=>{const{node:a}=n,i=a.getStage();i.setPointersPositions(s),n.pointerId===void 0&&(n.pointerId=Kn._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=[];Id._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")&&(Id.justDragged=!0,si._mouseListenClick=!1,si._touchListenClick=!1,si._pointerListenClick=!1,n.dragStatus="stopped");const l=n.node.getLayer()||n.node instanceof si.Stage&&n.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(n=>{n.draw()})},_endDragAfter(s){Id._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&Id._dragElements.delete(n)})}};si.isBrowser&&(window.addEventListener("mouseup",Id._endDragBefore,!0),window.addEventListener("touchend",Id._endDragBefore,!0),window.addEventListener("touchcancel",Id._endDragBefore,!0),window.addEventListener("mousemove",Id._drag),window.addEventListener("touchmove",Id._drag),window.addEventListener("mouseup",Id._endDragAfter,!1),window.addEventListener("touchend",Id._endDragAfter,!1),window.addEventListener("touchcancel",Id._endDragAfter,!1));function h6(s){return Kn._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||Kn._isBoolean(s)?s:Object.prototype.toString.call(s)}function u6t(s){return s>255?255:s<0?0:Math.round(s)}function Ka(){if(si.isUnminified)return function(s,t){return Kn._isNumber(s)||Kn.warn(h6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function gCe(s){if(si.isUnminified)return function(t,n){let r=Kn._isNumber(t),a=Kn._isArray(t)&&t.length==s;return!r&&!a&&Kn.warn(h6(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function DHe(){if(si.isUnminified)return function(s,t){return Kn._isNumber(s)||s==="auto"||Kn.warn(h6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function bO(){if(si.isUnminified)return function(s,t){return Kn._isString(s)||Kn.warn(h6(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function h6t(){if(si.isUnminified)return function(s,t){const n=Kn._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||Kn.warn(h6(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function j8s(){if(si.isUnminified)return function(s,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&s instanceof n||(Kn._isArray(s)?s.forEach(function(r){Kn._isNumber(r)||Kn.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):Kn.warn(h6(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function FN(){if(si.isUnminified)return function(s,t){return s===!0||s===!1||Kn.warn(h6(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function N8s(s){if(si.isUnminified)return function(t,n){return t==null||Kn.isObject(t)||Kn.warn(h6(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const TH="get",EH="set",ln={addGetterSetter(s,t,n,r,a){ln.addGetter(s,t,n),ln.addSetter(s,t,r,a),ln.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=TH+Kn._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=EH+Kn._capitalize(t);s.prototype[a]||ln.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=EH+Kn._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=Kn._capitalize,o=TH+l(t),c=EH+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},ln.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=Kn._capitalize(t),r=EH+n,a=TH+n;s.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,n,r){Kn.error("Adding deprecated "+t);const a=TH+Kn._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){Kn.error(i);const l=this.attrs[t];return l===void 0?n:l},ln.addSetter(s,t,r,function(){Kn.error(i)}),ln.addOverloadedGetterSetter(s,t)},backCompat(s,t){Kn.each(t,function(n,r){const a=s.prototype[r],i=TH+Kn._capitalize(n),l=EH+Kn._capitalize(n);function o(){a.apply(this,arguments),Kn.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 k8s(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=si.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=si.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=si.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=si.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=si.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=si.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:Kn.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const Rje="absoluteOpacity",slt="allEventListeners",u4="absoluteTransform",nlt="absoluteScale",dM="canvas",S8s="Change",C8s="children",A8s="konva",wFe="listening",T8s="mouseenter",E8s="mouseleave",M8s="pointerenter",L8s="pointerleave",P8s="touchenter",I8s="touchleave",rlt="set",alt="Shape",Dje=" ",ilt="stage",tA="transform",R8s="Stage",jFe="visible",D8s=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Dje);let O8s=1,ai=class OG{constructor(t){this._id=O8s++,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===tA||t===u4)&&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===tA||t===u4)&&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(Dje);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(dM)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===u4&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(dM)){const{scene:t,filter:n,hit:r}=this._cache.get(dM);Kn.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(dM)}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){Kn.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const m=Math.abs(Math.round(r.x)-o)>.5?1:0,p=Math.abs(Math.round(r.y)-c)>.5?1:0;a+=d*2+m,i+=d*2+p,o-=d,c-=d;const x=new TA({pixelRatio:l,width:a,height:i}),y=new TA({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),g=new RHe({pixelRatio:h,width:a,height:i}),b=x.getContext(),v=g.getContext(),k=new TA({width:x.width/x.pixelRatio+Math.abs(o),height:x.height/x.pixelRatio+Math.abs(c),pixelRatio:x.pixelRatio}),C=k.getContext();return g.isCache=!0,x.isCache=!0,this._cache.delete(dM),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(x.getContext()._context.imageSmoothingEnabled=!1,y.getContext()._context.imageSmoothingEnabled=!1),b.save(),v.save(),C.save(),b.translate(-o,-c),v.translate(-o,-c),C.translate(-o,-c),k.x=o,k.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Rje),this._clearSelfAndDescendantCache(nlt),this.drawScene(x,this,k),this.drawHit(g,this),this._isUnderCache=!1,b.restore(),v.restore(),u&&(b.save(),b.beginPath(),b.rect(0,0,a,i),b.closePath(),b.setAttr("strokeStyle","red"),b.setAttr("lineWidth",5),b.stroke(),b.restore()),Kn.releaseCanvas(k._canvas),this._cache.set(dM,{scene:x,filter:y,hit:g,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(dM)}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)&&Id._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(u4),this._clearSelfAndDescendantCache(Rje),this._clearSelfAndDescendantCache(nlt),this._clearSelfAndDescendantCache(ilt),this._clearSelfAndDescendantCache(jFe),this._clearSelfAndDescendantCache(wFe)}_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"+Kn._capitalize(t);return Kn._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!==C8s&&(r=rlt+Kn._capitalize(n),Kn._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(wFe,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(jFe,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;Id._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===r)&&(a=!0)});const i=!n&&!si.hitOnDragEnabled&&(a||si.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!==R8s&&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(tA),this._clearSelfAndDescendantCache(u4)),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 D_,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(tA);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(tA),this._clearSelfAndDescendantCache(u4),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 Kn.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 Kn.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&Kn.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(Rje,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=Kn.isObject(r)&&!Kn._isPlainObject(r)&&!Kn._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 Kn._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,Kn._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():si.dragDistance}_off(t,n,r){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;Id._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=Id._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&Id._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 Kn.haveIntersection(r,this.getClientRect())}static create(t,n){return Kn._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=OG.prototype.getClassName.call(t),a=t.children,i,l,o;n&&(t.attrs.container=n),si[r]||(Kn.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const c=si[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=ai.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=ai.prototype.clone.call(this,t);return this.getChildren().forEach(function(r){n.add(r.clone())}),n}getAllIntersections(t){const n=[];return this.find("Shape").forEach(r=>{r.isVisible()&&r.intersects(t)&&n.push(r)}),n}_clearSelfAndDescendantCache(t){var n;super._clearSelfAndDescendantCache(t),!this.isCached()&&((n=this.children)===null||n===void 0||n.forEach(function(r){r._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;(t=this.children)===null||t===void 0||t.forEach(function(n,r){n.index=r}),this._requestDraw()}drawScene(t,n,r){const a=this.getLayer(),i=t||a&&a.getCanvas(),l=i&&i.getContext(),o=this._getCanvasCache(),c=o&&o.scene,d=i&&i.isCache;if(!this.isVisible()&&!d)return this;if(c){l.save();const u=this.getAbsoluteTransform(n).getMatrix();l.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(l),l.restore()}else this._drawChildren("drawScene",i,n,r);return this}drawHit(t,n){if(!this.shouldDrawHit(n))return this;const r=this.getLayer(),a=t||r&&r.hitCanvas,i=a&&a.getContext(),l=this._getCanvasCache();if(l&&l.hit){i.save();const c=this.getAbsoluteTransform(n).getMatrix();i.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedHitCanvas(i),i.restore()}else this._drawChildren("drawHit",a,n);return this}_drawChildren(t,n,r,a){var i;const l=n&&n.getContext(),o=this.clipWidth(),c=this.clipHeight(),d=this.clipFunc(),u=typeof o=="number"&&typeof c=="number"||d,h=r===this;if(u){l.save();const p=this.getAbsoluteTransform(r);let x=p.getMatrix();l.transform(x[0],x[1],x[2],x[3],x[4],x[5]),l.beginPath();let y;if(d)y=d.call(this,l,this);else{const g=this.clipX(),b=this.clipY();l.rect(g||0,b||0,o,c)}l.clip.apply(l,y),x=p.copy().invert().getMatrix(),l.transform(x[0],x[1],x[2],x[3],x[4],x[5])}const m=!h&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";m&&(l.save(),l._applyGlobalCompositeOperation(this)),(i=this.children)===null||i===void 0||i.forEach(function(p){p[t](n,r,a)}),m&&l.restore(),u&&l.restore()}getClientRect(t={}){var n;const r=t.skipTransform,a=t.relativeTo;let i,l,o,c,d={x:1/0,y:1/0,width:0,height:0};const u=this;(n=this.children)===null||n===void 0||n.forEach(function(p){if(!p.visible())return;const x=p.getClientRect({relativeTo:u,skipShadow:t.skipShadow,skipStroke:t.skipStroke});x.width===0&&x.height===0||(i===void 0?(i=x.x,l=x.y,o=x.x+x.width,c=x.y+x.height):(i=Math.min(i,x.x),l=Math.min(l,x.y),o=Math.max(o,x.x+x.width),c=Math.max(c,x.y+x.height)))});const h=this.find("Shape");let m=!1;for(let p=0;ps.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",GF=s=>{const t=UG(s);if(t==="pointer")return si.pointerEventsEnabled&&XLe.pointer;if(t==="touch")return XLe.touch;if(t==="mouse")return XLe.mouse};function llt(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&Kn.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const V8s="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);",WK=[];let yCe=class extends K_{constructor(t){super(llt(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),WK.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{llt(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||Kn.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===z8s){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&&WK.splice(n,1),Kn.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}:(Kn.warn(V8s),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 TA({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+olt,this.content.style.height=n+olt),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;aU8s&&Kn.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(),si.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return p6t(t,this)}setPointerCapture(t){f6t(t,this)}releaseCapture(t){GK(t)}getLayers(){return this.children}_bindContentEvents(){si.isBrowser&&q8s.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this[n](r)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const n=GF(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=GF(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=GF(t.type),r=UG(t.type);if(!n)return;this.setPointersPositions(t);const a=this._getTargetShape(r),i=!(si.isDragging()||si.isTransforming())||si.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=GF(t.type),r=UG(t.type);if(!n)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if(Id.justDragged=!1,si["_"+r+"ListenClick"]=!0,!l||!l.isListening()){this[r+"ClickStartShape"]=void 0;return}si.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=GF(t.type),r=UG(t.type);if(!n)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(si.isDragging()&&Id.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(si.isDragging()||si.isTransforming())||si.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(r);this._changedPointerPositions.forEach(d=>{const u=ZLe(d.id)||this.getIntersection(d),h=d.id,m={evt:t,pointerId:h},p=c!==u;if(p&&c&&(c._fireAndBubble(n.pointerout,{...m},u),c._fireAndBubble(n.pointerleave,{...m},u)),u){if(l[u._id])return;l[u._id]=!0}u&&u.isListening()?(o=!0,p&&(u._fireAndBubble(n.pointerover,{...m},c),u._fireAndBubble(n.pointerenter,{...m},c),this[r+"targetShape"]=u),u._fireAndBubble(n.pointermove,{...m})):c&&(this._fire(n.pointerover,{evt:t,target:this,currentTarget:this,pointerId:h}),this[r+"targetShape"]=null)}),o||this._fire(n.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const n=GF(t.type),r=UG(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=ZLe(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;si["_"+r+"InDblClickWindow"]?(m=!0,clearTimeout(this[r+"DblTimeout"])):Id.justDragged||(si["_"+r+"InDblClickWindow"]=!0,clearTimeout(this[r+"DblTimeout"])),this[r+"DblTimeout"]=setTimeout(function(){si["_"+r+"InDblClickWindow"]=!1},si.dblClickWindow),d&&d.isListening()?(o=!0,this[r+"ClickEndShape"]=d,d._fireAndBubble(n.pointerup,{...h}),si["_"+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),si["_"+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}),si["_"+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(NFe,{evt:t}):this._fire(NFe,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(kFe,{evt:t}):this._fire(kFe,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const n=ZLe(t.pointerId)||this.getIntersection(this.getPointerPosition());n&&n._fireAndBubble(m9,OHe(t)),GK(t.pointerId)}_lostpointercapture(t){GK(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:Kn._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:Kn._getFirstPointerId(t)}])}_setPointerPosition(t){Kn.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 TA({width:this.width(),height:this.height()}),this.bufferHitCanvas=new RHe({pixelRatio:1,width:this.width(),height:this.height()}),!si.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 Kn.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}};yCe.prototype.nodeType=F8s;Vp(yCe);ln.addGetterSetter(yCe,"container");si.isBrowser&&document.addEventListener("visibilitychange",()=>{WK.forEach(s=>{s.batchDraw()})});const S6t="hasShadow",C6t="shadowRGBA",A6t="patternImage",T6t="linearGradient",E6t="radialGradient";let one;function QLe(){return one||(one=Kn.createCanvasElement().getContext("2d"),one)}const KK={};function H8s(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function G8s(s){s.stroke()}function W8s(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function K8s(s){s.stroke()}function Y8s(){this._clearCache(S6t)}function Z8s(){this._clearCache(C6t)}function X8s(){this._clearCache(A6t)}function Q8s(){this._clearCache(T6t)}function J8s(){this._clearCache(E6t)}let Ia=class extends ai{constructor(t){super(t);let n,r=0;for(;n=Kn.getHitColor(),!(n&&!(n in KK));)if(r++,r>=1e4){Kn.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=Kn.getRandomColor();break}this.colorKey=n,KK[n]=this}getContext(){return Kn.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return Kn.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(S6t,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(A6t,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=QLe().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new D_;r.translate(this.fillPatternX(),this.fillPatternY()),r.rotate(si.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(T6t,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=QLe(),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 ai.prototype.destroy.call(this),delete KK[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){Kn.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){let n=!1,r=this.getParent();for(;r;){if(r.isCached()){n=!0;break}r=r.getParent()}const a=t.skipTransform,i=t.relativeTo||n&&this.getStage()||void 0,l=this.getSelfRect(),c=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,d=l.width+c,u=l.height+c,h=!t.skipShadow&&this.hasShadow(),m=h?this.shadowOffsetX():0,p=h?this.shadowOffsetY():0,x=d+Math.abs(m),y=u+Math.abs(p),g=h&&this.shadowBlur()||0,b=x+g*2,v=y+g*2,k={width:b,height:v,x:-(c/2+g)+Math.min(m,0)+l.x,y:-(c/2+g)+Math.min(p,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 p=this.getAbsoluteTransform(n).getMatrix();return l.transform(p[0],p[1],p[2],p[3],p[4],p[5]),this._drawCachedSceneCanvas(l),l.restore(),this}if(!c)return this;if(l.save(),this._useBufferCanvas()&&!h){u=this.getStage();const p=r||u.bufferCanvas,x=p.getContext();r?(x.save(),x.setTransform(1,0,0,1,0,0),x.clearRect(0,0,p.width,p.height),x.restore()):x.clear(),x.save(),x._applyLineJoin(this),x._applyMiterLimit(this);const y=this.getAbsoluteTransform(n).getMatrix();x.transform(y[0],y[1],y[2],y[3],y[4],y[5]),c.call(this,x,this),x.restore();const g=p.pixelRatio;d&&l._applyShadow(this),m||(l._applyOpacity(this),l._applyGlobalCompositeOperation(this)),l.drawImage(p._canvas,p.x||0,p.y||0,p.width/g,p.height/g)}else{if(l._applyLineJoin(this),l._applyMiterLimit(this),!m){const p=this.getAbsoluteTransform(n).getMatrix();l.transform(p[0],p[1],p[2],p[3],p[4],p[5]),l._applyOpacity(this),l._applyGlobalCompositeOperation(this)}d&&l._applyShadow(this),c.call(this,l,this)}return l.restore(),this}drawHit(t,n,r=!1){if(!this.shouldDrawHit(n,r))return this;const a=this.getLayer(),i=t||a.hitCanvas,l=i&&i.getContext(),o=this.hitFunc()||this.sceneFunc(),c=this._getCanvasCache(),d=c&&c.hit;if(this.colorKey||Kn.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=Kn._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){Kn.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return p6t(t,this)}setPointerCapture(t){f6t(t,this)}releaseCapture(t){GK(t)}};Ia.prototype._fillFunc=H8s;Ia.prototype._strokeFunc=G8s;Ia.prototype._fillFuncHit=W8s;Ia.prototype._strokeFuncHit=K8s;Ia.prototype._centroid=!1;Ia.prototype.nodeType="Shape";Vp(Ia);Ia.prototype.eventListeners={};Ia.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Y8s);Ia.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Z8s);Ia.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",X8s);Ia.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Q8s);Ia.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",J8s);ln.addGetterSetter(Ia,"stroke",void 0,h6t());ln.addGetterSetter(Ia,"strokeWidth",2,Ka());ln.addGetterSetter(Ia,"fillAfterStrokeEnabled",!1);ln.addGetterSetter(Ia,"hitStrokeWidth","auto",DHe());ln.addGetterSetter(Ia,"strokeHitEnabled",!0,FN());ln.addGetterSetter(Ia,"perfectDrawEnabled",!0,FN());ln.addGetterSetter(Ia,"shadowForStrokeEnabled",!0,FN());ln.addGetterSetter(Ia,"lineJoin");ln.addGetterSetter(Ia,"lineCap");ln.addGetterSetter(Ia,"miterLimit");ln.addGetterSetter(Ia,"sceneFunc");ln.addGetterSetter(Ia,"hitFunc");ln.addGetterSetter(Ia,"dash");ln.addGetterSetter(Ia,"dashOffset",0,Ka());ln.addGetterSetter(Ia,"shadowColor",void 0,bO());ln.addGetterSetter(Ia,"shadowBlur",0,Ka());ln.addGetterSetter(Ia,"shadowOpacity",1,Ka());ln.addComponentsGetterSetter(Ia,"shadowOffset",["x","y"]);ln.addGetterSetter(Ia,"shadowOffsetX",0,Ka());ln.addGetterSetter(Ia,"shadowOffsetY",0,Ka());ln.addGetterSetter(Ia,"fillPatternImage");ln.addGetterSetter(Ia,"fill",void 0,h6t());ln.addGetterSetter(Ia,"fillPatternX",0,Ka());ln.addGetterSetter(Ia,"fillPatternY",0,Ka());ln.addGetterSetter(Ia,"fillLinearGradientColorStops");ln.addGetterSetter(Ia,"strokeLinearGradientColorStops");ln.addGetterSetter(Ia,"fillRadialGradientStartRadius",0);ln.addGetterSetter(Ia,"fillRadialGradientEndRadius",0);ln.addGetterSetter(Ia,"fillRadialGradientColorStops");ln.addGetterSetter(Ia,"fillPatternRepeat","repeat");ln.addGetterSetter(Ia,"fillEnabled",!0);ln.addGetterSetter(Ia,"strokeEnabled",!0);ln.addGetterSetter(Ia,"shadowEnabled",!0);ln.addGetterSetter(Ia,"dashEnabled",!0);ln.addGetterSetter(Ia,"strokeScaleEnabled",!0);ln.addGetterSetter(Ia,"fillPriority","color");ln.addComponentsGetterSetter(Ia,"fillPatternOffset",["x","y"]);ln.addGetterSetter(Ia,"fillPatternOffsetX",0,Ka());ln.addGetterSetter(Ia,"fillPatternOffsetY",0,Ka());ln.addComponentsGetterSetter(Ia,"fillPatternScale",["x","y"]);ln.addGetterSetter(Ia,"fillPatternScaleX",1,Ka());ln.addGetterSetter(Ia,"fillPatternScaleY",1,Ka());ln.addComponentsGetterSetter(Ia,"fillLinearGradientStartPoint",["x","y"]);ln.addComponentsGetterSetter(Ia,"strokeLinearGradientStartPoint",["x","y"]);ln.addGetterSetter(Ia,"fillLinearGradientStartPointX",0);ln.addGetterSetter(Ia,"strokeLinearGradientStartPointX",0);ln.addGetterSetter(Ia,"fillLinearGradientStartPointY",0);ln.addGetterSetter(Ia,"strokeLinearGradientStartPointY",0);ln.addComponentsGetterSetter(Ia,"fillLinearGradientEndPoint",["x","y"]);ln.addComponentsGetterSetter(Ia,"strokeLinearGradientEndPoint",["x","y"]);ln.addGetterSetter(Ia,"fillLinearGradientEndPointX",0);ln.addGetterSetter(Ia,"strokeLinearGradientEndPointX",0);ln.addGetterSetter(Ia,"fillLinearGradientEndPointY",0);ln.addGetterSetter(Ia,"strokeLinearGradientEndPointY",0);ln.addComponentsGetterSetter(Ia,"fillRadialGradientStartPoint",["x","y"]);ln.addGetterSetter(Ia,"fillRadialGradientStartPointX",0);ln.addGetterSetter(Ia,"fillRadialGradientStartPointY",0);ln.addComponentsGetterSetter(Ia,"fillRadialGradientEndPoint",["x","y"]);ln.addGetterSetter(Ia,"fillRadialGradientEndPointX",0);ln.addGetterSetter(Ia,"fillRadialGradientEndPointY",0);ln.addGetterSetter(Ia,"fillPatternRotation",0);ln.addGetterSetter(Ia,"fillRule",void 0,bO());ln.backCompat(Ia,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const eRs="beforeDraw",tRs="draw",M6t=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],sRs=M6t.length;let _O=class extends K_{constructor(t){super(t),this.canvas=new TA,this.hitCanvas=new RHe({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(eRs,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),K_.prototype.drawScene.call(this,i,n,r),this._fire(tRs,{node:this}),this}drawHit(t,n){const r=this.getLayer(),a=t||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),K_.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){Kn.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return Kn.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 Kn.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};_O.prototype.nodeType="Layer";Vp(_O);ln.addGetterSetter(_O,"imageSmoothingEnabled",!0);ln.addGetterSetter(_O,"clearBeforeDraw",!0);ln.addGetterSetter(_O,"hitGraphEnabled",!0,FN());class FHe extends _O{constructor(t){super(t),this.listening(!1),Kn.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}FHe.prototype.nodeType="FastLayer";Vp(FHe);let M$=class extends K_{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&Kn.throw("You may only add groups and shapes to groups.")}};M$.prototype.nodeType="Group";Vp(M$);const JLe=function(){return l8.performance&&l8.performance.now?function(){return l8.performance.now()}:function(){return new Date().getTime()}}();class cj{constructor(t,n){this.id=cj.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:JLe(),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=clt,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=dlt,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===clt?this.setTime(t):this.state===dlt&&this.setTime(this.duration-t)}pause(){this.state=rRs,this.fire("onPause")}getTimer(){return new Date().getTime()}}class Oh{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||YK.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=aRs++;const d=r.getLayer()||(r instanceof si.Stage?r.getLayers():null);d||Kn.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new cj(function(){n.tween.onEnterFrame()},d),this.tween=new iRs(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),Oh.attrs[a]||(Oh.attrs[a]={}),Oh.attrs[a][this._id]||(Oh.attrs[a][this._id]={}),Oh.tweens[a]||(Oh.tweens[a]={});for(c in t)nRs[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=Oh.tweens[a][t];u&&delete Oh.attrs[a][u][t];let h=r.getAttr(t);if(Kn._isArray(n))if(i=[],l=Math.max(n.length,h.length),t==="points"&&n.length!==h.length&&(n.length>h.length?(c=h,h=Kn._prepareArrayForTween(h,n,r.closed())):(o=n,n=Kn._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=Oh.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=Oh.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=Oh.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in r)delete Oh.tweens[t][a];delete Oh.attrs[t][n],Oh.tweens[t]&&(Object.keys(Oh.tweens[t]).length===0&&delete Oh.tweens[t],Object.keys(Oh.attrs[t]).length===0&&delete Oh.attrs[t])}}Oh.attrs={};Oh.tweens={};ai.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new Oh(s).play()};const YK={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}}}eC.prototype._centroid=!0;eC.prototype.className="Arc";eC.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Vp(eC);ln.addGetterSetter(eC,"innerRadius",0,Ka());ln.addGetterSetter(eC,"outerRadius",0,Ka());ln.addGetterSetter(eC,"angle",0,Ka());ln.addGetterSetter(eC,"clockwise",!1,FN());function SFe(s,t,n,r,a,i,l){const o=Math.sqrt(Math.pow(n-s,2)+Math.pow(r-t,2)),c=Math.sqrt(Math.pow(a-n,2)+Math.pow(i-r,2)),d=l*o/(o+c),u=l*c/(o+c),h=n-d*(a-s),m=r-d*(i-t),p=n+u*(a-s),x=r+u*(i-t);return[h,m,p,x]}function hlt(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 tC=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*lRs[20][o]+l,r+=cRs[20][o]*uRs(s,t,a);return l*r},plt=(s,t,n)=>{n===void 0&&(n=1);const r=s[0]-2*s[1]+s[2],a=t[0]-2*t[1]+t[2],i=2*s[1]-2*s[0],l=2*t[1]-2*t[0],o=4*(r*r+a*a),c=4*(r*i+a*l),d=i*i+l*l;if(o===0)return n*Math.sqrt(Math.pow(s[2]-s[0],2)+Math.pow(t[2]-t[0],2));const u=c/(2*o),h=d/o,m=n+u,p=h-u*u,x=m*m+p>0?Math.sqrt(m*m+p):0,y=u*u+p>0?Math.sqrt(u*u+p):0,g=u+Math.sqrt(u*u+p)!==0?p*Math.log(Math.abs((m+x)/(u+y))):0;return Math.sqrt(o)/2*(m*x-u*y+g)};function uRs(s,t,n){const r=CFe(1,n,s),a=CFe(1,n,t),i=r*r+a*a;return Math.sqrt(i)}const CFe=(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+=dRs[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 dj=class H1 extends Ia{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=H1.parsePathData(this.data()),this.pathLength=H1.getPathLength(this.dataArray)}_sceneFunc(t){const n=this.dataArray;t.beginPath();let r=!1;for(let a=0;au?d:u,g=d>u?1:d/u,b=d>u?u/d:1;t.translate(o,c),t.rotate(p),t.scale(g,b),t.arc(0,0,y,h,h+m,1-x),t.scale(1/g,1/b),t.rotate(-p),t.translate(-o,-c);break;case"z":r=!0,t.closePath();break}}!r&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(c){if(c.command==="A"){const d=c.points[4],u=c.points[5],h=c.points[4]+u;let m=Math.PI/180;if(Math.abs(d-h)h;p-=m){const x=H1.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],p,0);t.push(x.x,x.y)}else for(let p=d+m;pn[a].pathLength;)t-=n[a].pathLength,++a;if(a===i)return r=n[a-1].points.slice(-2),{x:r[0],y:r[1]};if(t<.01)return n[a].command==="M"?(r=n[a].points.slice(0,2),{x:r[0],y:r[1]}):{x:n[a].start.x,y:n[a].start.y};const l=n[a],o=l.points;switch(l.command){case"L":return H1.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return H1.getPointOnCubicBezier(flt(t,H1.getPathLength(n),y=>mlt([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 H1.getPointOnQuadraticBezier(flt(t,H1.getPathLength(n),y=>plt([l.start.x,o[0],o[2]],[l.start.y,o[1],o[3]],y)),l.start.x,l.start.y,o[0],o[1],o[2],o[3]);case"A":const c=o[0],d=o[1],u=o[2],h=o[3],m=o[5],p=o[6];let x=o[4];return x+=m*t/l.pathLength,H1.getPointOnEllipticalArc(c,d,u,h,x,p)}return null}static getPointOnLine(t,n,r,a,i,l,o){l=l??n,o=o??r;const c=this.getLineLength(n,r,a,i);if(c<1e-10)return{x:n,y:r};if(a===n)return{x:l,y:o+(i>r?t:-t)};const d=(i-r)/(a-n),u=Math.sqrt(t*t/(1+d*d))*(a=0&&(y+=2,y>=7&&(y-=7));continue}if(y>=0){if(y===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(v)){x.push(parseInt(v[0],10)),x.push(parseInt(v[1],10)),x.push(parseFloat(v.slice(2))),y+=3,y>=7&&(y-=7);continue}if(v==="11"||v==="10"||v==="01"){x.push(parseInt(v[0],10)),x.push(parseInt(v[1],10)),y+=2,y>=7&&(y-=7);continue}if(v==="0"||v==="1"){x.push(parseInt(v,10)),y+=1,y>=7&&(y-=7);continue}}else if(y===4){if(/^[01]\d+(?:\.\d+)?$/.test(v)){x.push(parseInt(v[0],10)),x.push(parseFloat(v.slice(1))),y+=2,y>=7&&(y-=7);continue}if(v==="0"||v==="1"){x.push(parseInt(v,10)),y+=1,y>=7&&(y-=7);continue}}const k=parseFloat(v);isNaN(k)?x.push(0):x.push(k),y+=1,y>=7&&(y-=7)}else{const k=parseFloat(v);isNaN(k)?x.push(0):x.push(k)}}for(;x.length>0&&!isNaN(x[0]);){let g="",b=[];const v=o,k=c;let C,T,M,P,L,I,O,$,q,W;switch(p){case"l":o+=x.shift(),c+=x.shift(),g="L",b.push(o,c);break;case"L":o=x.shift(),c=x.shift(),b.push(o,c);break;case"m":const G=x.shift(),K=x.shift();if(o+=G,c+=K,g="M",i.length>2&&i[i.length-1].command==="z"){for(let ee=i.length-2;ee>=0;ee--)if(i[ee].command==="M"){o=i[ee].points[0]+G,c=i[ee].points[1]+K;break}}b.push(o,c),p="l";break;case"M":o=x.shift(),c=x.shift(),g="M",b.push(o,c),p="L";break;case"h":o+=x.shift(),g="L",b.push(o,c);break;case"H":o=x.shift(),g="L",b.push(o,c);break;case"v":c+=x.shift(),g="L",b.push(o,c);break;case"V":c=x.shift(),g="L",b.push(o,c);break;case"C":b.push(x.shift(),x.shift(),x.shift(),x.shift()),o=x.shift(),c=x.shift(),b.push(o,c);break;case"c":b.push(o+x.shift(),c+x.shift(),o+x.shift(),c+x.shift()),o+=x.shift(),c+=x.shift(),g="C",b.push(o,c);break;case"S":T=o,M=c,C=i[i.length-1],C.command==="C"&&(T=o+(o-C.points[2]),M=c+(c-C.points[3])),b.push(T,M,x.shift(),x.shift()),o=x.shift(),c=x.shift(),g="C",b.push(o,c);break;case"s":T=o,M=c,C=i[i.length-1],C.command==="C"&&(T=o+(o-C.points[2]),M=c+(c-C.points[3])),b.push(T,M,o+x.shift(),c+x.shift()),o+=x.shift(),c+=x.shift(),g="C",b.push(o,c);break;case"Q":b.push(x.shift(),x.shift()),o=x.shift(),c=x.shift(),b.push(o,c);break;case"q":b.push(o+x.shift(),c+x.shift()),o+=x.shift(),c+=x.shift(),g="Q",b.push(o,c);break;case"T":T=o,M=c,C=i[i.length-1],C.command==="Q"&&(T=o+(o-C.points[0]),M=c+(c-C.points[1])),o=x.shift(),c=x.shift(),g="Q",b.push(T,M,o,c);break;case"t":T=o,M=c,C=i[i.length-1],C.command==="Q"&&(T=o+(o-C.points[0]),M=c+(c-C.points[1])),o+=x.shift(),c+=x.shift(),g="Q",b.push(T,M,o,c);break;case"A":P=x.shift(),L=x.shift(),I=x.shift(),O=x.shift(),$=x.shift(),q=o,W=c,o=x.shift(),c=x.shift(),g="A",b=this.convertEndpointToCenterParameterization(q,W,o,c,O,$,P,L,I);break;case"a":P=x.shift(),L=x.shift(),I=x.shift(),O=x.shift(),$=x.shift(),q=o,W=c,o+=x.shift(),c+=x.shift(),g="A",b=this.convertEndpointToCenterParameterization(q,W,o,c,O,$,P,L,I);break}i.push({command:g||p,points:b,start:{x:v,y:k},pathLength:this.calcLength(v,k,g||p,b)})}(p==="z"||p==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(t,n,r,a){let i,l,o,c;const d=H1;switch(r){case"L":return d.getLineLength(t,n,a[0],a[1]);case"C":return mlt([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return plt([t,a[0],a[2]],[n,a[1],a[3]],1);case"A":i=0;const u=a[4],h=a[5],m=a[4]+h;let p=Math.PI/180;if(Math.abs(u-m)m;c-=p)o=d.getPointOnEllipticalArc(a[0],a[1],a[2],a[3],c,0),i+=d.getLineLength(l.x,l.y,o.x,o.y),l=o;else for(c=u+p;c1&&(o*=Math.sqrt(p),c*=Math.sqrt(p));let x=Math.sqrt((o*o*(c*c)-o*o*(m*m)-c*c*(h*h))/(o*o*(m*m)+c*c*(h*h)));i===l&&(x*=-1),isNaN(x)&&(x=0);const y=x*o*m/c,g=x*-c*h/o,b=(t+r)/2+Math.cos(u)*y-Math.sin(u)*g,v=(n+a)/2+Math.sin(u)*y+Math.cos(u)*g,k=function(O){return Math.sqrt(O[0]*O[0]+O[1]*O[1])},C=function(O,$){return(O[0]*$[0]+O[1]*$[1])/(k(O)*k($))},T=function(O,$){return(O[0]*$[1]=1&&(I=0),l===0&&I>0&&(I=I-2*Math.PI),l===1&&I<0&&(I=I+2*Math.PI),[b,v,o,c,M,I,u,l]}};dj.prototype.className="Path";dj.prototype._attrsAffectingSize=["data"];Vp(dj);ln.addGetterSetter(dj,"data");class wO extends tC{_sceneFunc(t){super._sceneFunc(t);const n=Math.PI*2,r=this.points();let a=r;const i=this.tension()!==0&&r.length>4;i&&(a=this.getTensionPoints());const l=this.pointerLength(),o=r.length;let c,d;if(i){const m=[a[a.length-4],a[a.length-3],a[a.length-2],a[a.length-1],r[o-2],r[o-1]],p=dj.calcLength(a[a.length-4],a[a.length-3],"C",m),x=dj.getPointOnQuadraticBezier(Math.min(1,1-l/p),m[0],m[1],m[2],m[3],m[4],m[5]);c=r[o-2]-x.x,d=r[o-1]-x.y}else c=r[o-2]-r[o-4],d=r[o-1]-r[o-3];const u=(Math.atan2(d,c)+n)%n,h=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(r[o-2],r[o-1]),t.rotate(u),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.translate(r[0],r[1]),i?(c=(a[0]+a[2])/2-r[0],d=(a[1]+a[3])/2-r[1]):(c=r[2]-r[0],d=r[3]-r[1]),t.rotate((Math.atan2(-d,-c)+n)%n),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t))}__fillStroke(t){const n=this.dashEnabled();n&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),n&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),n=this.pointerWidth()/2;return{x:t.x,y:t.y-n,width:t.width,height:t.height+n*2}}}wO.prototype.className="Arrow";Vp(wO);ln.addGetterSetter(wO,"pointerLength",10,Ka());ln.addGetterSetter(wO,"pointerWidth",10,Ka());ln.addGetterSetter(wO,"pointerAtBeginning",!1);ln.addGetterSetter(wO,"pointerAtEnding",!0);class iq 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)}}iq.prototype._centroid=!0;iq.prototype.className="Circle";iq.prototype._attrsAffectingSize=["radius"];Vp(iq);ln.addGetterSetter(iq,"radius",0,Ka());class m6 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)}}m6.prototype.className="Ellipse";m6.prototype._centroid=!0;m6.prototype._attrsAffectingSize=["radiusX","radiusY"];Vp(m6);ln.addComponentsGetterSetter(m6,"radius",["x","y"]);ln.addGetterSetter(m6,"radiusX",0,Ka());ln.addGetterSetter(m6,"radiusY",0,Ka());let zN=class L6t 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?Kn.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?Kn.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=Kn.createImageElement();a.onload=function(){const i=new L6t({image:a});n(i)},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};zN.prototype.className="Image";zN.prototype._attrsAffectingSize=["image"];Vp(zN);ln.addGetterSetter(zN,"cornerRadius",0,gCe(4));ln.addGetterSetter(zN,"image");ln.addComponentsGetterSetter(zN,"crop",["x","y","width","height"]);ln.addGetterSetter(zN,"cropX",0,Ka());ln.addGetterSetter(zN,"cropY",0,Ka());ln.addGetterSetter(zN,"cropWidth",0,Ka());ln.addGetterSetter(zN,"cropHeight",0,Ka());const P6t=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],hRs="Change.konva",mRs="none",AFe="up",TFe="right",EFe="down",MFe="left",pRs=P6t.length;let zHe=class extends M${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)}}p6.prototype.className="RegularPolygon";p6.prototype._centroid=!0;p6.prototype._attrsAffectingSize=["radius"];Vp(p6);ln.addGetterSetter(p6,"radius",0,Ka());ln.addGetterSetter(p6,"sides",0,Ka());ln.addGetterSetter(p6,"cornerRadius",0,gCe(4));const xlt=Math.PI*2;let NO=class extends Ia{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,xlt,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),xlt,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)}};NO.prototype.className="Ring";NO.prototype._centroid=!0;NO.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Vp(NO);ln.addGetterSetter(NO,"innerRadius",0,Ka());ln.addGetterSetter(NO,"outerRadius",0,Ka());class cS extends Ia{constructor(t){super(t),this._updated=!0,this.anim=new cj(()=>{const n=this._updated;return this._updated=!1,n}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+0],c=i[a+1],d=i[a+2],u=i[a+3],h=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,d,u),t.closePath(),t.fillStrokeShape(this)),h)if(l){const m=l[n],p=r*2;t.drawImage(h,o,c,d,u,m[p+0],m[p+1],d,u)}else t.drawImage(h,o,c,d,u,0,0,d,u)}_hitFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+2],c=i[a+3];if(t.beginPath(),l){const d=l[n],u=r*2;t.rect(d[u+0],d[u+1],o,c)}else t.rect(0,0,o,c);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const t=this;this.interval=setInterval(function(){t._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const t=this.frameIndex(),n=this.animation(),r=this.animations(),a=r[n],i=a.length/4;t{if(new RegExp("\\p{Emoji}","u").test(n)){const i=a[r+1];i&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(i)?(t.push(n+i),a[r+1]=""):t.push(n)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(n+(a[r+1]||""))?t.push(n+a[r+1]):r>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(n)?t[t.length-1]+=n:n&&t.push(n);return t},[])}const WF="auto",fRs="center",I6t="inherit",MH="justify",xRs="Change.konva",R6t="2d",glt="-",D6t="left",gRs="text",yRs="Text",vRs="top",bRs="bottom",ylt="middle",O6t="normal",_Rs="px ",lne=" ",wRs="right",vlt="rtl",jRs="word",NRs="char",blt="none",ePe="…",F6t=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],kRs=F6t.length;let LH=null;function SRs(){if(LH!==null)return LH;LH=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(R6t);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){LH=!0;break}}}catch{}return LH}function CRs(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 cne;function tPe(){return cne||(cne=Kn.createCanvasElement().getContext(R6t),cne)}function ARs(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function TRs(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function ERs(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let Hh=class extends Ia{constructor(t){super(ERs(t)),this._partialTextX=0,this._partialTextY=0;for(let n=0;nde+sA(we.text).length,0),ie=J+oe;y({char:le,index:ie,x:L,y:M+I,lineIndex:T,column:J,isLastInLine:W,width:this.measureSize(le).width,context:t})}t.fillStrokeShape(this),y&&t.restore(),L+=this.measureSize(le).width+x}}else x!==0&&t.setAttr("letterSpacing",`${x}px`),this._partialTextX=L,this._partialTextY=M+I,this._partialText=$,t.fillStrokeShape(this);if(C){t.save(),t.beginPath();const K=si.legacyTextRendering?0:-Math.round(o/4),ee=G;t.moveTo(ee,M+I+K);const J=m===MH&&!W?p-l*2:q;t.lineTo(ee+Math.round(J),M+I+K),t.lineWidth=o/15;const le=this._getLinearGradient();t.strokeStyle=le||g,t.stroke(),t.restore()}t.restore(),i>1&&(M+=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=Kn._isString(t)?t:t==null?"":t+"";return this._setAttr(gRs,n),this}getWidth(){return this.attrs.width===WF||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===WF||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return Kn.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var n,r,a,i,l,o,c,d,u,h,m;let p=tPe(),x=this.fontSize(),y;p.save(),p.font=this._getContextFont(),y=p.measureText(t),p.restore();const g=x/100;return{actualBoundingBoxAscent:(n=y.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*g,actualBoundingBoxDescent:(r=y.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=y.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*g,actualBoundingBoxRight:(i=y.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*g,alphabeticBaseline:(l=y.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=y.emHeightAscent)!==null&&o!==void 0?o:100*g,emHeightDescent:(c=y.emHeightDescent)!==null&&c!==void 0?c:-20*g,fontBoundingBoxAscent:(d=y.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*g,fontBoundingBoxDescent:(u=y.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*g,hangingBaseline:(h=y.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*g,ideographicBaseline:(m=y.ideographicBaseline)!==null&&m!==void 0?m:-21*g,width:y.width,height:x}}_getContextFont(){return this.fontStyle()+lne+this.fontVariant()+lne+(this.fontSize()+_Rs)+CRs(this.fontFamily())}_addTextLine(t){this.align()===MH&&(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 tPe().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!==WF&&i!==void 0,c=l!==WF&&l!==void 0,d=this.padding(),u=i-d*2,h=l-d*2,m=0,p=this.wrap(),x=p!==blt,y=p!==NRs&&x,g=this.ellipsis();this.textArr=[],tPe().font=this._getContextFont();const b=g?this._getTextWidth(ePe):0;for(let v=0,k=t.length;vu)for(;C.length>0;){let M=0,P=sA(C).length,L="",I=0;for(;M>>1,$=sA(C),q=$.slice(0,O+1).join(""),W=this._getTextWidth(q);(g&&c&&m+a>h?W+b:W)<=u?(M=O+1,L=q,I=W):P=O}if(L){if(y){const q=sA(C),W=sA(L),G=q[W.length],K=G===lne||G===glt;let ee;if(K&&I<=u)ee=W.length;else{const J=W.lastIndexOf(lne),le=W.lastIndexOf(glt);ee=Math.max(J,le)+1}ee>0&&(M=ee,L=q.slice(0,M).join(""),I=this._getTextWidth(L))}if(L=L.trimRight(),this._addTextLine(L),r=Math.max(r,I),m+=a,this._shouldHandleEllipsis(m)){this._tryToAddEllipsisToLastLine();break}if(C=sA(C).slice(M).join("").trimLeft(),C.length>0&&(T=this._getTextWidth(C),T<=u)){this._addTextLine(C),m+=a,r=Math.max(r,T);break}}else break}else this._addTextLine(C),m+=a,r=Math.max(r,T),this._shouldHandleEllipsis(m)&&vh)break}this.textHeight=n,this.textWidth=r}_shouldHandleEllipsis(t){const n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.height,i=a!==WF&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==blt)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==WF&&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+ePe)n?null:dj.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=dj.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();const n=this.textDecoration(),r=this.fill(),a=this.fontSize(),i=this.glyphInfo,l=n.indexOf("underline")!==-1,o=n.indexOf("line-through")!==-1;l&&t.beginPath();for(let c=0;c=1){const r=n[0].p0;t.moveTo(r.x,r.y)}for(let r=0;rthis.pathLength&&b-this.pathLength<=d?this.pathLength:b);if(!v)return;const k=dj.getLineLength(x.x,x.y,v.x,v.y);let C=0;if(c)try{C=c(n[p-1].char,y)*this.fontSize()}catch{C=0}x.x+=C,v.x+=C,this.textWidth+=C;const T=dj.getPointOnLine(C+k/2,x.x,x.y,v.x,v.y),M=Math.atan2(v.y-x.y,v.x-x.x);this.glyphInfo.push({transposeX:T.x,transposeY:T.y,text:t[p],rotation:M,p0:x,p1:v,width:k}),m+=g}}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+`.${U6t}`).join(" "),_lt="nodesRect",PRs=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],IRs={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},RRs="ontouchstart"in si._global;function DRs(s,t,n){if(s==="rotater")return n;t+=Kn.degToRad(IRs[s]||0);const r=(Kn.radToDeg(t)%360+360)%360;return Kn._inRange(r,315+22.5,360)||Kn._inRange(r,0,22.5)?"ns-resize":Kn._inRange(r,45-22.5,45+22.5)?"nesw-resize":Kn._inRange(r,90-22.5,90+22.5)?"ew-resize":Kn._inRange(r,135-22.5,135+22.5)?"nwse-resize":Kn._inRange(r,180-22.5,180+22.5)?"ns-resize":Kn._inRange(r,225-22.5,225+22.5)?"nesw-resize":Kn._inRange(r,270-22.5,270+22.5)?"ew-resize":Kn._inRange(r,315-22.5,315+22.5)?"nwse-resize":(Kn.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const Vke=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],wlt=1e8;function ORs(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 q6t(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 FRs(s,t){const n=ORs(s);return q6t(s,t,n)}function zRs(s,t,n){let r=t;for(let a=0;aa.isAncestorOf(this)?(Kn.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(PRs.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(_lt),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(_lt,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=(si.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 q6t(u,-si.getAngle(n),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-wlt,y:-wlt,width:0,height:0,rotation:0};const n=[];this.nodes().map(d=>{const u=d.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),h=[{x:u.x,y:u.y},{x:u.x+u.width,y:u.y},{x:u.x+u.width,y:u.y+u.height},{x:u.x,y:u.y+u.height}],m=d.getAbsoluteTransform();h.forEach(function(p){const x=m.point(p);n.push(x)})});const r=new D_;r.rotate(-si.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:si.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(),Vke.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new OJ({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:RRs?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=si.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=DRs(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=Kn.degToRad(c),h=Math.sin(u),m=-Math.cos(u),p=l/2,x=o/2;let y=1/0;m<0?y=Math.min(y,-x/m):m>0&&(y=Math.min(y,(o-x)/m)),h<0?y=Math.min(y,-p/h):h>0&&(y=Math.min(y,(l-p)/h));const g=p+h*y,b=x+m*y,v=Kn._sign(o),k=g+h*d*v,C=b+m*d*v;n.moveTo(g,b),n.lineTo(k,C)}n.fillStrokeShape(r)},hitFunc:(n,r)=>{if(!this.shouldOverdrawWholeArea())return;const a=this.padding();n.beginPath(),n.rect(-a,-a,r.width()+a*2,r.height()+a*2),n.fillStrokeShape(r)}});this.add(t),this._proxyDrag(t),t.on("dragstart",n=>{n.cancelBubble=!0}),t.on("dragmove",n=>{n.cancelBubble=!0}),t.on("dragend",n=>{n.cancelBubble=!0}),this.on("dragmove",n=>{this.update()})}_handleMouseDown(t){if(this._transforming)return;this._movingAnchorName=t.target.name().split(" ")[0];const n=this._getNodeRect(),r=n.width,a=n.height,i=Math.sqrt(Math.pow(r,2)+Math.pow(a,2));this.sin=Math.abs(a/i),this.cos=Math.abs(r/i),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const l=t.target.getAbsolutePosition(),o=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-l.x,y:o.y-l.y},LFe++,this._fire("transformstart",{evt:t.evt,target:this.getNode()}),this._nodes.forEach(c=>{c._fire("transformstart",{evt:t.evt,target:c})})}_handleMouseMove(t){let n,r,a;const i=this.findOne("."+this._movingAnchorName),l=i.getStage();l.setPointersPositions(t);const o=l.getPointerPosition();let c={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const d=i.getAbsolutePosition();this.anchorDragBoundFunc()&&(c=this.anchorDragBoundFunc()(d,c,t)),i.setAbsolutePosition(c);const u=i.getAbsolutePosition();if(d.x===u.x&&d.y===u.y)return;if(this._movingAnchorName==="rotater"){const v=this._getNodeRect();n=i.x()-v.width/2,r=-i.y()+v.height/2;const k=si.getAngle(this.rotateAnchorAngle());let C=Math.atan2(-r,n)+Math.PI/2-k;v.height<0&&(C-=Math.PI);const M=si.getAngle(this.rotation())+C,P=si.getAngle(this.rotationSnapTolerance()),I=zRs(this.rotationSnaps(),M,P)-v.rotation,O=FRs(v,I);this._fitNodesInto(O,t);return}const h=this.shiftBehavior();let m;h==="inverted"?m=this.keepRatio()&&!t.shiftKey:h==="none"?m=this.keepRatio():m=this.keepRatio()||t.shiftKey;let p=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(m){const v=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};a=Math.sqrt(Math.pow(v.x-i.x(),2)+Math.pow(v.y-i.y(),2));const k=this.findOne(".top-left").x()>v.x?-1:1,C=this.findOne(".top-left").y()>v.y?-1:1;n=a*this.cos*k,r=a*this.sin*C,this.findOne(".top-left").x(v.x-n),this.findOne(".top-left").y(v.y-r)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(i.y());else if(this._movingAnchorName==="top-right"){if(m){const v=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};a=Math.sqrt(Math.pow(i.x()-v.x,2)+Math.pow(v.y-i.y(),2));const k=this.findOne(".top-right").x()v.y?-1:1;n=a*this.cos*k,r=a*this.sin*C,this.findOne(".top-right").x(v.x+n),this.findOne(".top-right").y(v.y-r)}var x=i.position();this.findOne(".top-left").y(x.y),this.findOne(".bottom-right").x(x.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(i.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(i.x());else if(this._movingAnchorName==="bottom-left"){if(m){const v=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};a=Math.sqrt(Math.pow(v.x-i.x(),2)+Math.pow(i.y()-v.y,2));const k=v.x{var i;a._fire("transformend",{evt:t,target:a}),(i=a.getLayer())===null||i===void 0||i.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,n){const r=this._getNodeRect(),a=1;if(Kn._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(Kn._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new D_;if(i.rotate(si.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:Kn.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new D_;o.translate(r.x,r.y),o.rotate(r.rotation),o.scale(r.width/l,r.height/l);const c=new D_,d=t.width/l,u=t.height/l;this.flipEnabled()===!1?(c.translate(t.x,t.y),c.rotate(t.rotation),c.translate(t.width<0?t.width:0,t.height<0?t.height:0),c.scale(Math.abs(d),Math.abs(u))):(c.translate(t.x,t.y),c.rotate(t.rotation),c.scale(d,u));const h=c.multiply(o.invert());this._nodes.forEach(m=>{var p;if(!m.getStage())return;const x=m.getParent().getAbsoluteTransform(),y=m.getTransform().copy();y.translate(m.offsetX(),m.offsetY());const g=new D_;g.multiply(x.copy().invert()).multiply(h).multiply(x).multiply(y);const b=g.decompose();m.setAttrs(b),(p=m.getLayer())===null||p===void 0||p.batchDraw()}),this.rotation(Kn._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(Kn._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(M=>{M.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=Kn.degToRad(u),p=Math.sin(m),x=-Math.cos(m),y=r/2,g=a/2;let b=1/0;x<0?b=Math.min(b,-g/x):x>0&&(b=Math.min(b,(a-g)/x)),p<0?b=Math.min(b,-y/p):p>0&&(b=Math.min(b,(r-y)/p));const v=y+p*b,k=g+x*b,C=Kn._sign(a);this._batchChangeChild(".rotater",{x:v+p*h*C,y:k+x*h*C-o*x,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:r,height:a,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(M=>M.draggable()),x:0,y:0});const T=this.anchorStyleFunc();T&&d.forEach(M=>{T(M)}),(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=""),M$.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(Kn.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return ai.prototype.toObject.call(this)}clone(t){return ai.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};nd.isTransforming=()=>LFe>0;function BRs(s){return s instanceof Array||Kn.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){Vke.indexOf(t)===-1&&Kn.warn("Unknown anchor name: "+t+". Available names are: "+Vke.join(", "))}),s||[]}nd.prototype.className="Transformer";Vp(nd);ln.addGetterSetter(nd,"enabledAnchors",Vke,BRs);ln.addGetterSetter(nd,"flipEnabled",!0,FN());ln.addGetterSetter(nd,"resizeEnabled",!0);ln.addGetterSetter(nd,"anchorSize",10,Ka());ln.addGetterSetter(nd,"rotateEnabled",!0);ln.addGetterSetter(nd,"rotateLineVisible",!0);ln.addGetterSetter(nd,"rotationSnaps",[]);ln.addGetterSetter(nd,"rotateAnchorOffset",50,Ka());ln.addGetterSetter(nd,"rotateAnchorAngle",0,Ka());ln.addGetterSetter(nd,"rotateAnchorCursor","crosshair");ln.addGetterSetter(nd,"rotationSnapTolerance",5,Ka());ln.addGetterSetter(nd,"borderEnabled",!0);ln.addGetterSetter(nd,"anchorStroke","rgb(0, 161, 255)");ln.addGetterSetter(nd,"anchorStrokeWidth",1,Ka());ln.addGetterSetter(nd,"anchorFill","white");ln.addGetterSetter(nd,"anchorCornerRadius",0,Ka());ln.addGetterSetter(nd,"borderStroke","rgb(0, 161, 255)");ln.addGetterSetter(nd,"borderStrokeWidth",1,Ka());ln.addGetterSetter(nd,"borderDash");ln.addGetterSetter(nd,"keepRatio",!0);ln.addGetterSetter(nd,"shiftBehavior","default");ln.addGetterSetter(nd,"centeredScaling",!1);ln.addGetterSetter(nd,"ignoreStroke",!1);ln.addGetterSetter(nd,"padding",0,Ka());ln.addGetterSetter(nd,"nodes");ln.addGetterSetter(nd,"node");ln.addGetterSetter(nd,"boundBoxFunc");ln.addGetterSetter(nd,"anchorDragBoundFunc");ln.addGetterSetter(nd,"anchorStyleFunc");ln.addGetterSetter(nd,"shouldOverdrawWholeArea",!1);ln.addGetterSetter(nd,"useSingleNodeRotation",!0);ln.backCompat(nd,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class sC extends Ia{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,si.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}sC.prototype.className="Wedge";sC.prototype._centroid=!0;sC.prototype._attrsAffectingSize=["radius"];Vp(sC);ln.addGetterSetter(sC,"radius",0,Ka());ln.addGetterSetter(sC,"angle",0,Ka());ln.addGetterSetter(sC,"clockwise",!1);ln.backCompat(sC,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function jlt(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const $Rs=[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],URs=[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 qRs(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,m,p,x,y,g,b,v,k,C,T,M,P,L;const I=t+t+1,O=r-1,$=a-1,q=t+1,W=q*(q+1)/2,G=new jlt,K=$Rs[t],ee=URs[t];let J=null,le=G,ue=null,oe=null;for(let ie=1;ie>ee,P!==0?(P=255/P,n[l]=(c*K>>ee)*P,n[l+1]=(d*K>>ee)*P,n[l+2]=(u*K>>ee)*P):n[l]=n[l+1]=n[l+2]=0,c-=m,d-=p,u-=x,h-=y,m-=ue.r,p-=ue.g,x-=ue.b,y-=ue.a,i=o+((i=de+t+1)>ee,P>0?(P=255/P,n[i]=(c*K>>ee)*P,n[i+1]=(d*K>>ee)*P,n[i+2]=(u*K>>ee)*P):n[i]=n[i+1]=n[i+2]=0,c-=m,d-=p,u-=x,h-=y,m-=ue.r,p-=ue.g,x-=ue.b,y-=ue.a,i=ie+((i=we+q)<$?i:$)*r<<2,c+=g+=ue.r=n[i],d+=b+=ue.g=n[i+1],u+=v+=ue.b=n[i+2],h+=k+=ue.a=n[i+3],ue=ue.next,m+=C=oe.r,p+=T=oe.g,x+=M=oe.b,y+=P=oe.a,g-=C,b-=T,v-=M,k-=P,oe=oe.next,l+=r}}const VRs=function(t){const n=Math.round(this.blurRadius());n>0&&qRs(t,n)};ln.addGetterSetter(ai,"blurRadius",0,Ka(),ln.afterSetFilter);const HRs=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};ln.addGetterSetter(ai,"contrast",0,Ka(),ln.afterSetFilter);const KRs=function(s){var t,n,r,a,i,l,o,c,d;const u=s.data,h=s.width,m=s.height,p=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),x=Math.min(1,Math.max(0,(a=(r=this.embossWhiteLevel)===null||r===void 0?void 0:r.call(this))!==null&&a!==void 0?a:.5)),g=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(l=(i=this.embossDirection)===null||i===void 0?void 0:i.call(this))!==null&&l!==void 0?l:"top-left"])!==null&&o!==void 0?o:315,b=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),v=p*10,k=x*255,C=g*Math.PI/180,T=Math.cos(C),M=Math.sin(C),P=128/1020*v,L=new Uint8ClampedArray(u),I=new Float32Array(h*m);for(let G=0,K=0;KG<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 p,x,y,g,b,v;if(m>0)p=a+m*(255-a),x=r-m*(r-0),y=o+m*(255-o),g=l-m*(l-0),b=u+m*(255-u),v=d-m*(d-0);else{const k=(a+r)*.5;p=a+m*(a-k),x=r+m*(r-k);const C=(o+l)*.5;y=o+m*(o-C),g=l+m*(l-C);const T=(u+d)*.5;b=u+m*(u-T),v=d+m*(d-T)}for(let k=0;kd?m:d;const p=l,x=i,y=360/x*Math.PI/180;for(let g=0;gd?m:d;const p=l,x=i,y=0;let g,b;for(u=0;ut&&(C=k,T=0,M=-1),a=0;a=0&&p=0&&x=0&&p=0&&x=255*4?255:0}return l}function lDs(s,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(r.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&p=0&&x=n))for(let k=y;k=r)continue;const C=(n*k+v)*4;d+=l[C+0],u+=l[C+1],h+=l[C+2],m+=l[C+3],b+=1}d=d/b,u=u/b,h=h/b,m=m/b;for(let v=p;v=n))for(let k=y;k=r)continue;const C=(n*k+v)*4;l[C+0]=d,l[C+1]=u,l[C+2]=h,l[C+3]=m}}};ln.addGetterSetter(ai,"pixelSize",8,Ka(),ln.afterSetFilter);const hDs=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)});ln.addGetterSetter(ai,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});ln.addGetterSetter(ai,"blue",0,u6t,ln.afterSetFilter);const pDs=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)});ln.addGetterSetter(ai,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});ln.addGetterSetter(ai,"blue",0,u6t,ln.afterSetFilter);ln.addGetterSetter(ai,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const fDs=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},gDs=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;aqn||lt[Ps]!==Ct[qn]){var Er=` `+lt[Ps].replace(" at new "," at ");return Q.displayName&&Er.includes("")&&(Er=Er.replace("",Q.displayName)),Er}while(1<=Ps&&0<=qn);break}}}finally{Xr=!1,Error.prepareStackTrace=Pe}return(Q=Q?Q.displayName||Q.name:"")?Mr(Q):""}var Zn=Object.prototype.hasOwnProperty,aa=[],zr=-1;function Na(Q){return{current:Q}}function oa(Q){0>zr||(Q.current=aa[zr],aa[zr]=null,zr--)}function ur(Q,ne){zr++,aa[zr]=Q.current,Q.current=ne}var ao={},fo=Na(ao),Va=Na(!1),So=ao;function $a(Q,ne){var Pe=Q.type.contextTypes;if(!Pe)return ao;var st=Q.stateNode;if(st&&st.__reactInternalMemoizedUnmaskedChildContext===ne)return st.__reactInternalMemoizedMaskedChildContext;var lt={},Ct;for(Ct in Pe)lt[Ct]=ne[Ct];return st&&(Q=Q.stateNode,Q.__reactInternalMemoizedUnmaskedChildContext=ne,Q.__reactInternalMemoizedMaskedChildContext=lt),lt}function Gr(Q){return Q=Q.childContextTypes,Q!=null}function Qn(){oa(Va),oa(fo)}function qa(Q,ne,Pe){if(fo.current!==ao)throw Error(l(168));ur(fo,ne),ur(Va,Pe)}function xo(Q,ne,Pe){var st=Q.stateNode;if(ne=ne.childContextTypes,typeof st.getChildContext!="function")return Pe;st=st.getChildContext();for(var lt in st)if(!(lt in ne))throw Error(l(108,L(Q)||"Unknown",lt));return i({},Pe,st)}function Wo(Q){return Q=(Q=Q.stateNode)&&Q.__reactInternalMemoizedMergedChildContext||ao,So=fo.current,ur(fo,Q),ur(Va,Va.current),!0}function Co(Q,ne,Pe){var st=Q.stateNode;if(!st)throw Error(l(169));Pe?(Q=xo(Q,ne,So),st.__reactInternalMemoizedMergedChildContext=Q,oa(Va),oa(fo),ur(fo,Q)):oa(Va),ur(Va,Pe)}var Ko=Math.clz32?Math.clz32:Qm,Ud=Math.log,Mu=Math.LN2;function Qm(Q){return Q>>>=0,Q===0?32:31-(Ud(Q)/Mu|0)|0}var Gc=64,lh=4194304;function qd(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 Wc(Q,ne){var Pe=Q.pendingLanes;if(Pe===0)return 0;var st=0,lt=Q.suspendedLanes,Ct=Q.pingedLanes,Ps=Pe&268435455;if(Ps!==0){var qn=Ps&~lt;qn!==0?st=qd(qn):(Ct&=Ps,Ct!==0&&(st=qd(Ct)))}else Ps=Pe&~lt,Ps!==0?st=qd(Ps):Ct!==0&&(st=qd(Ct));if(st===0)return 0;if(ne!==0&&ne!==st&&!(ne<)&&(lt=st&-st,Ct=ne&-ne,lt>=Ct||lt===16&&(Ct&4194240)!==0))return ne;if(st&4&&(st|=Pe&16),ne=Q.entangledLanes,ne!==0)for(Q=Q.entanglements,ne&=st;0Pe;Pe++)ne.push(Q);return ne}function Mf(Q,ne,Pe){Q.pendingLanes|=ne,ne!==536870912&&(Q.suspendedLanes=0,Q.pingedLanes=0),Q=Q.eventTimes,ne=31-Ko(ne),Q[ne]=Pe}function pu(Q,ne){var Pe=Q.pendingLanes&~ne;Q.pendingLanes=ne,Q.suspendedLanes=0,Q.pingedLanes=0,Q.expiredLanes&=ne,Q.mutableReadLanes&=ne,Q.entangledLanes&=ne,ne=Q.entanglements;var st=Q.eventTimes;for(Q=Q.expirationTimes;0>=Ps,lt-=Ps,Vd=1<<32-Ko(ne)+lt|Pe<dl?(Em=Xi,Xi=null):Em=Xi.sibling;var Mc=hi(Sr,Xi,Fn[dl],_i);if(Mc===null){Xi===null&&(Xi=Em);break}Q&&Xi&&Mc.alternate===null&&ne(Sr,Xi),wn=Ct(Mc,wn,dl),Uo===null?Pi=Mc:Uo.sibling=Mc,Uo=Mc,Xi=Em}if(dl===Fn.length)return Pe(Sr,Xi),en&&Xh(Sr,dl),Pi;if(Xi===null){for(;dldl?(Em=Xi,Xi=null):Em=Xi.sibling;var I1=hi(Sr,Xi,Mc.value,_i);if(I1===null){Xi===null&&(Xi=Em);break}Q&&Xi&&I1.alternate===null&&ne(Sr,Xi),wn=Ct(I1,wn,dl),Uo===null?Pi=I1:Uo.sibling=I1,Uo=I1,Xi=Em}if(Mc.done)return Pe(Sr,Xi),en&&Xh(Sr,dl),Pi;if(Xi===null){for(;!Mc.done;dl++,Mc=Fn.next())Mc=vl(Sr,Mc.value,_i),Mc!==null&&(wn=Ct(Mc,wn,dl),Uo===null?Pi=Mc:Uo.sibling=Mc,Uo=Mc);return en&&Xh(Sr,dl),Pi}for(Xi=st(Sr,Xi);!Mc.done;dl++,Mc=Fn.next())Mc=Du(Xi,Sr,dl,Mc.value,_i),Mc!==null&&(Q&&Mc.alternate!==null&&Xi.delete(Mc.key===null?dl:Mc.key),wn=Ct(Mc,wn,dl),Uo===null?Pi=Mc:Uo.sibling=Mc,Uo=Mc);return Q&&Xi.forEach(function(D6){return ne(Sr,D6)}),en&&Xh(Sr,dl),Pi}function M0(Sr,wn,Fn,_i){if(typeof Fn=="object"&&Fn!==null&&Fn.type===u&&Fn.key===null&&(Fn=Fn.props.children),typeof Fn=="object"&&Fn!==null){switch(Fn.$$typeof){case c:e:{for(var Pi=Fn.key,Uo=wn;Uo!==null;){if(Uo.key===Pi){if(Pi=Fn.type,Pi===u){if(Uo.tag===7){Pe(Sr,Uo.sibling),wn=lt(Uo,Fn.props.children),wn.return=Sr,Sr=wn;break e}}else if(Uo.elementType===Pi||typeof Pi=="object"&&Pi!==null&&Pi.$$typeof===k&&jg(Pi)===Uo.type){Pe(Sr,Uo.sibling),wn=lt(Uo,Fn.props),wn.ref=Qh(Sr,Uo,Fn),wn.return=Sr,Sr=wn;break e}Pe(Sr,Uo);break}else ne(Sr,Uo);Uo=Uo.sibling}Fn.type===u?(wn=Rs(Fn.props.children,Sr.mode,_i,Fn.key),wn.return=Sr,Sr=wn):(_i=pc(Fn.type,Fn.key,Fn.props,null,Sr.mode,_i),_i.ref=Qh(Sr,wn,Fn),_i.return=Sr,Sr=_i)}return Ps(Sr);case d:e:{for(Uo=Fn.key;wn!==null;){if(wn.key===Uo)if(wn.tag===4&&wn.stateNode.containerInfo===Fn.containerInfo&&wn.stateNode.implementation===Fn.implementation){Pe(Sr,wn.sibling),wn=lt(wn,Fn.children||[]),wn.return=Sr,Sr=wn;break e}else{Pe(Sr,wn);break}else ne(Sr,wn);wn=wn.sibling}wn=LS(Fn,Sr.mode,_i),wn.return=Sr,Sr=wn}return Ps(Sr);case k:return Uo=Fn._init,M0(Sr,wn,Uo(Fn._payload),_i)}if(K(Fn))return bl(Sr,wn,Fn,_i);if(M(Fn))return Of(Sr,wn,Fn,_i);wg(Sr,Fn)}return typeof Fn=="string"&&Fn!==""||typeof Fn=="number"?(Fn=""+Fn,wn!==null&&wn.tag===6?(Pe(Sr,wn.sibling),wn=lt(wn,Fn),wn.return=Sr,Sr=wn):(Pe(Sr,wn),wn=ik(Fn,Sr.mode,_i),wn.return=Sr,Sr=wn),Ps(Sr)):Pe(Sr,wn)}return M0}var Hl=fu(!0),b1=fu(!1),Dx=Na(null),y0=null,Hd=null,lp=null;function v0(){lp=Hd=y0=null}function yy(Q,ne,Pe){De?(ur(Dx,ne._currentValue),ne._currentValue=Pe):(ur(Dx,ne._currentValue2),ne._currentValue2=Pe)}function ad(Q){var ne=Dx.current;oa(Dx),De?Q._currentValue=ne:Q._currentValue2=ne}function gd(Q,ne,Pe){for(;Q!==null;){var st=Q.alternate;if((Q.childLanes&ne)!==ne?(Q.childLanes|=ne,st!==null&&(st.childLanes|=ne)):st!==null&&(st.childLanes&ne)!==ne&&(st.childLanes|=ne),Q===Pe)break;Q=Q.return}}function Lu(Q,ne){y0=Q,lp=Hd=null,Q=Q.dependencies,Q!==null&&Q.firstContext!==null&&(Q.lanes&ne&&(Yp=!0),Q.firstContext=null)}function jm(Q){var ne=De?Q._currentValue:Q._currentValue2;if(lp!==Q)if(Q={context:Q,memoizedValue:ne,next:null},Hd===null){if(y0===null)throw Error(l(308));Hd=Q,y0.dependencies={lanes:0,firstContext:Q}}else Hd=Hd.next=Q;return ne}var Lf=null;function yl(Q){Lf===null?Lf=[Q]:Lf.push(Q)}function ka(Q,ne,Pe,st){var lt=ne.interleaved;return lt===null?(Pe.next=Pe,yl(ne)):(Pe.next=lt.next,lt.next=Pe),ne.interleaved=Pe,Ir(Q,st)}function Ir(Q,ne){Q.lanes|=ne;var Pe=Q.alternate;for(Pe!==null&&(Pe.lanes|=ne),Pe=Q,Q=Q.return;Q!==null;)Q.childLanes|=ne,Pe=Q.alternate,Pe!==null&&(Pe.childLanes|=ne),Pe=Q,Q=Q.return;return Pe.tag===3?Pe.stateNode:null}var Fl=!1;function Sa(Q){Q.updateQueue={baseState:Q.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Nm(Q,ne){Q=Q.updateQueue,ne.updateQueue===Q&&(ne.updateQueue={baseState:Q.baseState,firstBaseUpdate:Q.firstBaseUpdate,lastBaseUpdate:Q.lastBaseUpdate,shared:Q.shared,effects:Q.effects})}function id(Q,ne){return{eventTime:Q,lane:ne,tag:0,payload:null,callback:null,next:null}}function la(Q,ne,Pe){var st=Q.updateQueue;if(st===null)return null;if(st=st.shared,yo&2){var lt=st.pending;return lt===null?ne.next=ne:(ne.next=lt.next,lt.next=ne),st.pending=ne,Ir(Q,Pe)}return lt=st.interleaved,lt===null?(ne.next=ne,yl(st)):(ne.next=lt.next,lt.next=ne),st.interleaved=ne,Ir(Q,Pe)}function Ox(Q,ne,Pe){if(ne=ne.updateQueue,ne!==null&&(ne=ne.shared,(Pe&4194240)!==0)){var st=ne.lanes;st&=Q.pendingLanes,Pe|=st,ne.lanes=Pe,Px(Q,Pe)}}function Ng(Q,ne){var Pe=Q.updateQueue,st=Q.alternate;if(st!==null&&(st=st.updateQueue,Pe===st)){var lt=null,Ct=null;if(Pe=Pe.firstBaseUpdate,Pe!==null){do{var Ps={eventTime:Pe.eventTime,lane:Pe.lane,tag:Pe.tag,payload:Pe.payload,callback:Pe.callback,next:null};Ct===null?lt=Ct=Ps:Ct=Ct.next=Ps,Pe=Pe.next}while(Pe!==null);Ct===null?lt=Ct=ne:Ct=Ct.next=ne}else lt=Ct=ne;Pe={baseState:st.baseState,firstBaseUpdate:lt,lastBaseUpdate:Ct,shared:st.shared,effects:st.effects},Q.updateQueue=Pe;return}Q=Pe.lastBaseUpdate,Q===null?Pe.firstBaseUpdate=ne:Q.next=ne,Pe.lastBaseUpdate=ne}function ox(Q,ne,Pe,st){var lt=Q.updateQueue;Fl=!1;var Ct=lt.firstBaseUpdate,Ps=lt.lastBaseUpdate,qn=lt.shared.pending;if(qn!==null){lt.shared.pending=null;var Er=qn,Ca=Er.next;Er.next=null,Ps===null?Ct=Ca:Ps.next=Ca,Ps=Er;var Ei=Q.alternate;Ei!==null&&(Ei=Ei.updateQueue,qn=Ei.lastBaseUpdate,qn!==Ps&&(qn===null?Ei.firstBaseUpdate=Ca:qn.next=Ca,Ei.lastBaseUpdate=Er))}if(Ct!==null){var vl=lt.baseState;Ps=0,Ei=Ca=Er=null,qn=Ct;do{var hi=qn.lane,Du=qn.eventTime;if((st&hi)===hi){Ei!==null&&(Ei=Ei.next={eventTime:Du,lane:0,tag:qn.tag,payload:qn.payload,callback:qn.callback,next:null});e:{var bl=Q,Of=qn;switch(hi=ne,Du=Pe,Of.tag){case 1:if(bl=Of.payload,typeof bl=="function"){vl=bl.call(Du,vl,hi);break e}vl=bl;break e;case 3:bl.flags=bl.flags&-65537|128;case 0:if(bl=Of.payload,hi=typeof bl=="function"?bl.call(Du,vl,hi):bl,hi==null)break e;vl=i({},vl,hi);break e;case 2:Fl=!0}}qn.callback!==null&&qn.lane!==0&&(Q.flags|=64,hi=lt.effects,hi===null?lt.effects=[qn]:hi.push(qn))}else Du={eventTime:Du,lane:hi,tag:qn.tag,payload:qn.payload,callback:qn.callback,next:null},Ei===null?(Ca=Ei=Du,Er=vl):Ei=Ei.next=Du,Ps|=hi;if(qn=qn.next,qn===null){if(qn=lt.shared.pending,qn===null)break;hi=qn,qn=hi.next,hi.next=null,lt.lastBaseUpdate=hi,lt.shared.pending=null}}while(!0);if(Ei===null&&(Er=vl),lt.baseState=Er,lt.firstBaseUpdate=Ca,lt.lastBaseUpdate=Ei,ne=lt.shared.interleaved,ne!==null){lt=ne;do Ps|=lt.lane,lt=lt.next;while(lt!==ne)}else Ct===null&&(lt.shared.lanes=0);xv|=Ps,Q.lanes=Ps,Q.memoizedState=vl}}function b0(Q,ne,Pe){if(Q=ne.effects,ne.effects=null,Q!==null)for(ne=0;nePe?Pe:4,Q(!0);var st=_1.transition;_1.transition={};try{Q(!1),ne()}finally{Do=Pe,_1.transition=st}}function WN(){return yu().memoizedState}function wS(Q,ne,Pe){var st=A0(Q);if(Pe={lane:st,action:Pe,hasEagerState:!1,eagerState:null,next:null},jS(Q))iC(ne,Pe);else if(Pe=ka(Q,ne,Pe,st),Pe!==null){var lt=bu();Df(Pe,Q,st,lt),wc(Pe,ne,st)}}function E6(Q,ne,Pe){var st=A0(Q),lt={lane:st,action:Pe,hasEagerState:!1,eagerState:null,next:null};if(jS(Q))iC(ne,lt);else{var Ct=Q.alternate;if(Q.lanes===0&&(Ct===null||Ct.lanes===0)&&(Ct=ne.lastRenderedReducer,Ct!==null))try{var Ps=ne.lastRenderedState,qn=Ct(Ps,Pe);if(lt.hasEagerState=!0,lt.eagerState=qn,Yh(qn,Ps)){var Er=ne.interleaved;Er===null?(lt.next=lt,yl(ne)):(lt.next=Er.next,Er.next=lt),ne.interleaved=lt;return}}catch{}finally{}Pe=ka(Q,ne,lt,st),Pe!==null&&(lt=bu(),Df(Pe,Q,st,lt),wc(Pe,ne,st))}}function jS(Q){var ne=Q.alternate;return Q===zl||ne!==null&&ne===zl}function iC(Q,ne){Yc=Gd=!0;var Pe=Q.pending;Pe===null?ne.next=ne:(ne.next=Pe.next,Pe.next=ne),Q.pending=ne}function wc(Q,ne,Pe){if(Pe&4194240){var st=ne.lanes;st&=Q.pendingLanes,Pe|=st,ne.lanes=Pe,Px(Q,Pe)}}var Gb={readContext:jm,useCallback:uh,useContext:uh,useEffect:uh,useImperativeHandle:uh,useInsertionEffect:uh,useLayoutEffect:uh,useMemo:uh,useReducer:uh,useRef:uh,useState:uh,useDebugValue:uh,useDeferredValue:uh,useTransition:uh,useMutableSource:uh,useSyncExternalStore:uh,useId:uh,unstable_isNewReconciler:!1},NS={readContext:jm,useCallback:function(Q,ne){return Bx().memoizedState=[Q,ne===void 0?null:ne],Q},useContext:jm,useEffect:pv,useImperativeHandle:function(Q,ne,Pe){return Pe=Pe!=null?Pe.concat([Q]):null,N1(4194308,4,Hb.bind(null,ne,Q),Pe)},useLayoutEffect:function(Q,ne){return N1(4194308,4,Q,ne)},useInsertionEffect:function(Q,ne){return N1(4,2,Q,ne)},useMemo:function(Q,ne){var Pe=Bx();return ne=ne===void 0?null:ne,Q=Q(),Pe.memoizedState=[Q,ne],Q},useReducer:function(Q,ne,Pe){var st=Bx();return ne=Pe!==void 0?Pe(ne):ne,st.memoizedState=st.baseState=ne,Q={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Q,lastRenderedState:ne},st.queue=Q,Q=Q.dispatch=wS.bind(null,zl,Q),[st.memoizedState,Q]},useRef:function(Q){var ne=Bx();return Q={current:Q},ne.memoizedState=Q},useState:up,useDebugValue:n2,useDeferredValue:function(Q){return Bx().memoizedState=Q},useTransition:function(){var Q=up(!1),ne=Q[0];return Q=oo.bind(null,Q[1]),Bx().memoizedState=Q,[ne,Q]},useMutableSource:function(){},useSyncExternalStore:function(Q,ne,Pe){var st=zl,lt=Bx();if(en){if(Pe===void 0)throw Error(l(407));Pe=Pe()}else{if(Pe=ne(),Ec===null)throw Error(l(349));gu&30||t2(st,ne,Pe)}lt.memoizedState=Pe;var Ct={value:Pe,getSnapshot:ne};return lt.queue=Ct,pv(j1.bind(null,st,Ct,Q),[Q]),st.flags|=2048,hh(9,w1.bind(null,st,Ct,Pe,ne),void 0,null),Pe},useId:function(){var Q=Bx(),ne=Ec.identifierPrefix;if(en){var Pe=op,st=Vd;Pe=(st&~(1<<32-Ko(st)-1)).toString(32)+Pe,ne=":"+ne+"R"+Pe,Pe=zx++,0Ag&&(ne.flags|=128,st=!0,Nn(lt,!1),ne.lanes=4194304)}else{if(!st)if(Q=Fx(Ct),Q!==null){if(ne.flags|=128,st=!0,Q=Q.updateQueue,Q!==null&&(ne.updateQueue=Q,ne.flags|=4),Nn(lt,!0),lt.tail===null&<.tailMode==="hidden"&&!Ct.alternate&&!en)return Vn(ne),null}else 2*Vl()-lt.renderingStartTime>Ag&&Pe!==1073741824&&(ne.flags|=128,st=!0,Nn(lt,!1),ne.lanes=4194304);lt.isBackwards?(Ct.sibling=ne.child,ne.child=Ct):(Q=lt.last,Q!==null?Q.sibling=Ct:ne.child=Ct,lt.last=Ct)}return lt.tail!==null?(ne=lt.tail,lt.rendering=ne,lt.tail=ne.sibling,lt.renderingStartTime=Vl(),ne.sibling=null,Q=_c.current,ur(_c,st?Q&1|2:Q&1),ne):(Vn(ne),null);case 22:case 23:return bv(),Pe=ne.memoizedState!==null,Q!==null&&Q.memoizedState!==null!==Pe&&(ne.flags|=8192),Pe&&ne.mode&1?em&1073741824&&(Vn(ne),Be&&ne.subtreeFlags&6&&(ne.flags|=8192)):Vn(ne),null;case 24:return null;case 25:return null}throw Error(l(156,ne.tag))}function In(Q,ne){switch(yt(ne),ne.tag){case 1:return Gr(ne.type)&&Qn(),Q=ne.flags,Q&65536?(ne.flags=Q&-65537|128,ne):null;case 3:return dp(),oa(Va),oa(fo),dh(),Q=ne.flags,Q&65536&&!(Q&128)?(ne.flags=Q&-65537|128,ne):null;case 5:return mv(ne),null;case 13:if(oa(_c),Q=ne.memoizedState,Q!==null&&Q.dehydrated!==null){if(ne.alternate===null)throw Error(l(340));ti()}return Q=ne.flags,Q&65536?(ne.flags=Q&-65537|128,ne):null;case 19:return oa(_c),null;case 4:return dp(),null;case 10:return ad(ne.type._context),null;case 22:case 23:return bv(),null;case 24:return null;default:return null}}var Xn=!1,Cr=!1,hr=typeof WeakSet=="function"?WeakSet:Set,On=null;function Pr(Q,ne){var Pe=Q.ref;if(Pe!==null)if(typeof Pe=="function")try{Pe(null)}catch(st){bi(Q,ne,st)}else Pe.current=null}function ga(Q,ne,Pe){try{Pe()}catch(st){bi(Q,ne,st)}}var ca=!1;function Li(Q,ne){for(ue(Q.containerInfo),On=ne;On!==null;)if(Q=On,ne=Q.child,(Q.subtreeFlags&1028)!==0&&ne!==null)ne.return=Q,On=ne;else for(;On!==null;){Q=On;try{var Pe=Q.alternate;if(Q.flags&1024)switch(Q.tag){case 0:case 11:case 15:break;case 1:if(Pe!==null){var st=Pe.memoizedProps,lt=Pe.memoizedState,Ct=Q.stateNode,Ps=Ct.getSnapshotBeforeUpdate(Q.elementType===Q.type?st:Sg(Q.type,st),lt);Ct.__reactInternalSnapshotBeforeUpdate=Ps}break;case 3:Be&&Hs(Q.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(qn){bi(Q,Q.return,qn)}if(ne=Q.sibling,ne!==null){ne.return=Q.return,On=ne;break}On=Q.return}return Pe=ca,ca=!1,Pe}function fi(Q,ne,Pe){var st=ne.updateQueue;if(st=st!==null?st.lastEffect:null,st!==null){var lt=st=st.next;do{if((lt.tag&Q)===Q){var Ct=lt.destroy;lt.destroy=void 0,Ct!==void 0&&ga(ne,Pe,Ct)}lt=lt.next}while(lt!==st)}}function Zo(Q,ne){if(ne=ne.updateQueue,ne=ne!==null?ne.lastEffect:null,ne!==null){var Pe=ne=ne.next;do{if((Pe.tag&Q)===Q){var st=Pe.create;Pe.destroy=st()}Pe=Pe.next}while(Pe!==ne)}}function Si(Q){var ne=Q.ref;if(ne!==null){var Pe=Q.stateNode;switch(Q.tag){case 5:Q=ee(Pe);break;default:Q=Pe}typeof ne=="function"?ne(Q):ne.current=Q}}function Tl(Q){var ne=Q.alternate;ne!==null&&(Q.alternate=null,Tl(ne)),Q.child=null,Q.deletions=null,Q.sibling=null,Q.tag===5&&(ne=Q.stateNode,ne!==null&&Xe(ne)),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 Ad(Q){return Q.tag===5||Q.tag===3||Q.tag===4}function Xo(Q){e:for(;;){for(;Q.sibling===null;){if(Q.return===null||Ad(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 Ti(Q,ne,Pe){var st=Q.tag;if(st===5||st===6)Q=Q.stateNode,ne?Is(Pe,Q,ne):Gt(Pe,Q);else if(st!==4&&(Q=Q.child,Q!==null))for(Ti(Q,ne,Pe),Q=Q.sibling;Q!==null;)Ti(Q,ne,Pe),Q=Q.sibling}function Ya(Q,ne,Pe){var st=Q.tag;if(st===5||st===6)Q=Q.stateNode,ne?At(Pe,Q,ne):zt(Pe,Q);else if(st!==4&&(Q=Q.child,Q!==null))for(Ya(Q,ne,Pe),Q=Q.sibling;Q!==null;)Ya(Q,ne,Pe),Q=Q.sibling}var el=null,io=!1;function qo(Q,ne,Pe){for(Pe=Pe.child;Pe!==null;)yd(Q,ne,Pe),Pe=Pe.sibling}function yd(Q,ne,Pe){if(ki&&typeof ki.onCommitFiberUnmount=="function")try{ki.onCommitFiberUnmount(sp,Pe)}catch{}switch(Pe.tag){case 5:Cr||Pr(Pe,ne);case 6:if(Be){var st=el,lt=io;el=null,qo(Q,ne,Pe),el=st,io=lt,el!==null&&(io?Qs(el,Pe.stateNode):jt(el,Pe.stateNode))}else qo(Q,ne,Pe);break;case 18:Be&&el!==null&&(io?Tn(el,Pe.stateNode):Zs(el,Pe.stateNode));break;case 4:Be?(st=el,lt=io,el=Pe.stateNode.containerInfo,io=!0,qo(Q,ne,Pe),el=st,io=lt):(Ne&&(st=Pe.stateNode.containerInfo,lt=tn(st),Un(st,lt)),qo(Q,ne,Pe));break;case 0:case 11:case 14:case 15:if(!Cr&&(st=Pe.updateQueue,st!==null&&(st=st.lastEffect,st!==null))){lt=st=st.next;do{var Ct=lt,Ps=Ct.destroy;Ct=Ct.tag,Ps!==void 0&&(Ct&2||Ct&4)&&ga(Pe,ne,Ps),lt=lt.next}while(lt!==st)}qo(Q,ne,Pe);break;case 1:if(!Cr&&(Pr(Pe,ne),st=Pe.stateNode,typeof st.componentWillUnmount=="function"))try{st.props=Pe.memoizedProps,st.state=Pe.memoizedState,st.componentWillUnmount()}catch(qn){bi(Pe,ne,qn)}qo(Q,ne,Pe);break;case 21:qo(Q,ne,Pe);break;case 22:Pe.mode&1?(Cr=(st=Cr)||Pe.memoizedState!==null,qo(Q,ne,Pe),Cr=st):qo(Q,ne,Pe);break;default:qo(Q,ne,Pe)}}function Th(Q){var ne=Q.updateQueue;if(ne!==null){Q.updateQueue=null;var Pe=Q.stateNode;Pe===null&&(Pe=Q.stateNode=new hr),ne.forEach(function(st){var lt=ak.bind(null,Q,st);Pe.has(st)||(Pe.add(st),st.then(lt,lt))})}}function vd(Q,ne){var Pe=ne.deletions;if(Pe!==null)for(var st=0;st";case Pu:return":has("+(Td(Q)||"")+")";case km:return'[role="'+Q.value+'"]';case Xu:return'"'+Q.value+'"';case Fc:return'[data-testname="'+Q.value+'"]';default:throw Error(l(365))}}function Xp(Q,ne){var Pe=[];Q=[Q,0];for(var st=0;stlt&&(lt=Ps),st&=~Ct}if(st=lt,st=Vl()-st,st=(120>st?120:480>st?480:1080>st?1080:1920>st?1920:3e3>st?3e3:4320>st?4320:1960*Cm(st/1960))-st,10Q?16:Q,dx===null)var st=!1;else{if(Q=dx,dx=null,Xb=0,yo&6)throw Error(l(331));var lt=yo;for(yo|=4,On=Q.current;On!==null;){var Ct=On,Ps=Ct.child;if(On.flags&16){var qn=Ct.deletions;if(qn!==null){for(var Er=0;ErVl()-kw?Tg(Q,0):gv|=Pe),ef(Q,ne)}function ES(Q,ne){ne===0&&(Q.mode&1?(ne=lh,lh<<=1,!(lh&130023424)&&(lh=4194304)):ne=1);var Pe=bu();Q=Ir(Q,ne),Q!==null&&(Mf(Q,ne,Pe),ef(Q,Pe))}function lC(Q){var ne=Q.memoizedState,Pe=0;ne!==null&&(Pe=ne.retryLane),ES(Q,Pe)}function ak(Q,ne){var Pe=0;switch(Q.tag){case 13:var st=Q.stateNode,lt=Q.memoizedState;lt!==null&&(Pe=lt.retryLane);break;case 19:st=Q.stateNode;break;default:throw Error(l(314))}st!==null&&st.delete(ne),ES(Q,Pe)}var cC;cC=function(Q,ne,Pe){if(Q!==null)if(Q.memoizedProps!==ne.pendingProps||Va.current)Yp=!0;else{if(!(Q.lanes&Pe)&&!(ne.flags&128))return Yp=!1,ht(Q,ne,Pe);Yp=!!(Q.flags&131072)}else Yp=!1,en&&ne.flags&1048576&&Zt(ne,uv,ne.index);switch(ne.lanes=0,ne.tag){case 2:var st=ne.type;Ce(Q,ne),Q=ne.pendingProps;var lt=$a(ne,fo.current);Lu(ne,Pe),lt=mw(null,ne,st,Q,lt,Pe);var Ct=Ub();return ne.flags|=1,typeof lt=="object"&<!==null&&typeof lt.render=="function"&<.$$typeof===void 0?(ne.tag=1,ne.memoizedState=null,ne.updateQueue=null,Gr(st)?(Ct=!0,Wo(ne)):Ct=!1,ne.memoizedState=lt.state!==null&<.state!==void 0?lt.state:null,Sa(ne),lt.updater=Wb,ne.stateNode=lt,lt._reactInternals=ne,Rf(ne,st,Q,Pe),ne=_w(null,ne,st,!0,Ct,Pe)):(ne.tag=0,en&&Ct&&$e(ne),hp(null,ne,lt,Pe),ne=ne.child),ne;case 16:st=ne.elementType;e:{switch(Ce(Q,ne),Q=ne.pendingProps,lt=st._init,st=lt(st._payload),ne.type=st,lt=ne.tag=tr(st),Q=Sg(st,Q),lt){case 0:ne=XN(null,ne,st,Q,Pe);break e;case 1:ne=QN(null,ne,st,Q,Pe);break e;case 11:ne=SS(null,ne,st,Q,Pe);break e;case 14:ne=by(null,ne,st,Sg(st.type,Q),Pe);break e}throw Error(l(306,st,""))}return ne;case 0:return st=ne.type,lt=ne.pendingProps,lt=ne.elementType===st?lt:Sg(st,lt),XN(Q,ne,st,lt,Pe);case 1:return st=ne.type,lt=ne.pendingProps,lt=ne.elementType===st?lt:Sg(st,lt),QN(Q,ne,st,lt,Pe);case 3:e:{if(ww(ne),Q===null)throw Error(l(387));st=ne.pendingProps,Ct=ne.memoizedState,lt=Ct.element,Nm(Q,ne),ox(ne,st,null,Pe);var Ps=ne.memoizedState;if(st=Ps.element,Ge&&Ct.isDehydrated)if(Ct={element:st,isDehydrated:!1,cache:Ps.cache,pendingSuspenseBoundaries:Ps.pendingSuspenseBoundaries,transitions:Ps.transitions},ne.updateQueue.baseState=Ct,ne.memoizedState=Ct,ne.flags&256){lt=Xd(Error(l(423)),ne),ne=Kb(Q,ne,st,Pe,lt);break e}else if(st!==lt){lt=Xd(Error(l(424)),ne),ne=Kb(Q,ne,st,Pe,lt);break e}else for(Ge&&(us=We(ne.stateNode.containerInfo),is=ne,en=!0,er=null,Dn=!1),Pe=b1(ne,null,st,Pe),ne.child=Pe;Pe;)Pe.flags=Pe.flags&-3|4096,Pe=Pe.sibling;else{if(ti(),st===lt){ne=ze(Q,ne,Pe);break e}hp(Q,ne,st,Pe)}ne=ne.child}return ne;case 5:return hv(ne),Q===null&&Hi(ne),st=ne.type,lt=ne.pendingProps,Ct=Q!==null?Q.memoizedProps:null,Ps=lt.children,xe(st,lt)?Ps=null:Ct!==null&&xe(st,Ct)&&(ne.flags|=32),ZN(Q,ne),hp(Q,ne,Ps,Pe),ne.child;case 6:return Q===null&&Hi(ne),null;case 13:return oC(Q,ne,Pe);case 4:return Kc(ne,ne.stateNode.containerInfo),st=ne.pendingProps,Q===null?ne.child=Hl(ne,null,st,Pe):hp(Q,ne,st,Pe),ne.child;case 11:return st=ne.type,lt=ne.pendingProps,lt=ne.elementType===st?lt:Sg(st,lt),SS(Q,ne,st,lt,Pe);case 7:return hp(Q,ne,ne.pendingProps,Pe),ne.child;case 8:return hp(Q,ne,ne.pendingProps.children,Pe),ne.child;case 12:return hp(Q,ne,ne.pendingProps.children,Pe),ne.child;case 10:e:{if(st=ne.type._context,lt=ne.pendingProps,Ct=ne.memoizedProps,Ps=lt.value,yy(ne,st,Ps),Ct!==null)if(Yh(Ct.value,Ps)){if(Ct.children===lt.children&&!Va.current){ne=ze(Q,ne,Pe);break e}}else for(Ct=ne.child,Ct!==null&&(Ct.return=ne);Ct!==null;){var qn=Ct.dependencies;if(qn!==null){Ps=Ct.child;for(var Er=qn.firstContext;Er!==null;){if(Er.context===st){if(Ct.tag===1){Er=id(-1,Pe&-Pe),Er.tag=2;var Ca=Ct.updateQueue;if(Ca!==null){Ca=Ca.shared;var Ei=Ca.pending;Ei===null?Er.next=Er:(Er.next=Ei.next,Ei.next=Er),Ca.pending=Er}}Ct.lanes|=Pe,Er=Ct.alternate,Er!==null&&(Er.lanes|=Pe),gd(Ct.return,Pe,ne),qn.lanes|=Pe;break}Er=Er.next}}else if(Ct.tag===10)Ps=Ct.type===ne.type?null:Ct.child;else if(Ct.tag===18){if(Ps=Ct.return,Ps===null)throw Error(l(341));Ps.lanes|=Pe,qn=Ps.alternate,qn!==null&&(qn.lanes|=Pe),gd(Ps,Pe,ne),Ps=Ct.sibling}else Ps=Ct.child;if(Ps!==null)Ps.return=Ct;else for(Ps=Ct;Ps!==null;){if(Ps===ne){Ps=null;break}if(Ct=Ps.sibling,Ct!==null){Ct.return=Ps.return,Ps=Ct;break}Ps=Ps.return}Ct=Ps}hp(Q,ne,lt.children,Pe),ne=ne.child}return ne;case 9:return lt=ne.type,st=ne.pendingProps.children,Lu(ne,Pe),lt=jm(lt),st=st(lt),ne.flags|=1,hp(Q,ne,st,Pe),ne.child;case 14:return st=ne.type,lt=Sg(st,ne.pendingProps),lt=Sg(st.type,lt),by(Q,ne,st,lt,Pe);case 15:return vw(Q,ne,ne.type,ne.pendingProps,Pe);case 17:return st=ne.type,lt=ne.pendingProps,lt=ne.elementType===st?lt:Sg(st,lt),Ce(Q,ne),ne.tag=1,Gr(st)?(Q=!0,Wo(ne)):Q=!1,Lu(ne,Pe),C1(ne,st,lt),Rf(ne,st,lt,Pe),_w(null,ne,st,!0,Q,Pe);case 19:return Zb(Q,ne,Pe);case 22:return bw(Q,ne,Pe)}throw Error(l(156,ne.tag))};function dC(Q,ne){return ep(Q,ne)}function c2(Q,ne,Pe,st){this.tag=Q,this.key=Pe,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=ne,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=st,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Tm(Q,ne,Pe,st){return new c2(Q,ne,Pe,st)}function sr(Q){return Q=Q.prototype,!(!Q||!Q.isReactComponent)}function tr(Q){if(typeof Q=="function")return sr(Q)?1:0;if(Q!=null){if(Q=Q.$$typeof,Q===y)return 11;if(Q===v)return 14}return 2}function E0(Q,ne){var Pe=Q.alternate;return Pe===null?(Pe=Tm(Q.tag,ne,Q.key,Q.mode),Pe.elementType=Q.elementType,Pe.type=Q.type,Pe.stateNode=Q.stateNode,Pe.alternate=Q,Q.alternate=Pe):(Pe.pendingProps=ne,Pe.type=Q.type,Pe.flags=0,Pe.subtreeFlags=0,Pe.deletions=null),Pe.flags=Q.flags&14680064,Pe.childLanes=Q.childLanes,Pe.lanes=Q.lanes,Pe.child=Q.child,Pe.memoizedProps=Q.memoizedProps,Pe.memoizedState=Q.memoizedState,Pe.updateQueue=Q.updateQueue,ne=Q.dependencies,Pe.dependencies=ne===null?null:{lanes:ne.lanes,firstContext:ne.firstContext},Pe.sibling=Q.sibling,Pe.index=Q.index,Pe.ref=Q.ref,Pe}function pc(Q,ne,Pe,st,lt,Ct){var Ps=2;if(st=Q,typeof Q=="function")sr(Q)&&(Ps=1);else if(typeof Q=="string")Ps=5;else e:switch(Q){case u:return Rs(Pe.children,lt,Ct,ne);case h:Ps=8,lt|=8;break;case m:return Q=Tm(12,Pe,ne,lt|2),Q.elementType=m,Q.lanes=Ct,Q;case g:return Q=Tm(13,Pe,ne,lt),Q.elementType=g,Q.lanes=Ct,Q;case b:return Q=Tm(19,Pe,ne,lt),Q.elementType=b,Q.lanes=Ct,Q;case C:return MS(Pe,lt,Ct,ne);default:if(typeof Q=="object"&&Q!==null)switch(Q.$$typeof){case p:Ps=10;break e;case x:Ps=9;break e;case y:Ps=11;break e;case v:Ps=14;break e;case k:Ps=16,st=null;break e}throw Error(l(130,Q==null?Q:typeof Q,""))}return ne=Tm(Ps,Pe,ne,lt),ne.elementType=Q,ne.type=st,ne.lanes=Ct,ne}function Rs(Q,ne,Pe,st){return Q=Tm(7,Q,st,ne),Q.lanes=Pe,Q}function MS(Q,ne,Pe,st){return Q=Tm(22,Q,st,ne),Q.elementType=C,Q.lanes=Pe,Q.stateNode={isHidden:!1},Q}function ik(Q,ne,Pe){return Q=Tm(6,Q,null,ne),Q.lanes=Pe,Q}function LS(Q,ne,Pe){return ne=Tm(4,Q.children!==null?Q.children:[],Q.key,ne),ne.lanes=Pe,ne.stateNode={containerInfo:Q.containerInfo,pendingChildren:null,implementation:Q.implementation},ne}function uC(Q,ne,Pe,st,lt){this.tag=ne,this.containerInfo=Q,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Le,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ef(0),this.expirationTimes=Ef(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ef(0),this.identifierPrefix=st,this.onRecoverableError=lt,Ge&&(this.mutableSourceEagerHydrationData=null)}function P6(Q,ne,Pe,st,lt,Ct,Ps,qn,Er){return Q=new uC(Q,ne,Pe,qn,Er),ne===1?(ne=1,Ct===!0&&(ne|=8)):ne=0,Ct=Tm(3,null,null,ne),Q.current=Ct,Ct.stateNode=Q,Ct.memoizedState={element:st,isDehydrated:Pe,cache:null,transitions:null,pendingSuspenseBoundaries:null},Sa(Ct),Q}function I6(Q){if(!Q)return ao;Q=Q._reactInternals;e:{if(I(Q)!==Q||Q.tag!==1)throw Error(l(170));var ne=Q;do{switch(ne.tag){case 3:ne=ne.stateNode.context;break e;case 1:if(Gr(ne.type)){ne=ne.stateNode.__reactInternalMemoizedMergedChildContext;break e}}ne=ne.return}while(ne!==null);throw Error(l(171))}if(Q.tag===1){var Pe=Q.type;if(Gr(Pe))return xo(Q,Pe,ne)}return ne}function d2(Q){var ne=Q._reactInternals;if(ne===void 0)throw typeof Q.render=="function"?Error(l(188)):(Q=Object.keys(Q).join(","),Error(l(268,Q)));return Q=q(ne),Q===null?null:Q.stateNode}function R6(Q,ne){if(Q=Q.memoizedState,Q!==null&&Q.dehydrated!==null){var Pe=Q.retryLane;Q.retryLane=Pe!==0&&Pe=Ca&&Ct>=vl&<<=Ei&&Ps<=hi){Q.splice(ne,1);break}else if(st!==Ca||Pe.width!==Er.width||hiPs){if(!(Ct!==vl||Pe.height!==Er.height||Eilt)){Ca>st&&(Er.width+=Ca-st,Er.x=st),EiCt&&(Er.height+=vl-Ct,Er.y=Ct),hiPe&&(Pe=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 ee(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:GO,findFiberByHostInstance:Q.findFiberByHostInstance||mC,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")Q=!1;else{var ne=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(ne.isDisabled||!ne.supportsFiber)Q=!0;else{try{sp=ne.inject(Q),ki=ne}catch{}Q=!!ne.checkDCE}}return Q},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(Q,ne,Pe,st){if(!Qe)throw Error(l(363));Q=Qp(Q,ne);var lt=pt(Q,Pe,st).disconnect;return{disconnect:function(){lt()}}},n.registerMutableSourceForHydration=function(Q,ne){var Pe=ne._getVersion;Pe=Pe(ne._source),Q.mutableSourceEagerHydrationData==null?Q.mutableSourceEagerHydrationData=[ne,Pe]:Q.mutableSourceEagerHydrationData.push(ne,Pe)},n.runWithPriority=function(Q,ne){var Pe=Do;try{return Do=Q,ne()}finally{Do=Pe}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(Q,ne,Pe,st){var lt=ne.current,Ct=bu(),Ps=A0(lt);return Pe=I6(Pe),ne.context===null?ne.context=Pe:ne.pendingContext=Pe,ne=id(Ct,Ps),ne.payload={element:Q},st=st===void 0?null:st,st!==null&&(ne.callback=st),Q=la(lt,ne,Ps),Q!==null&&(Df(Q,lt,Ps,Ct),Ox(Q,lt,Ps)),Ps},n};V6t.exports=yDs;var vDs=V6t.exports;const bDs=sd(vDs);var H6t={exports:{}},kO={};/** * @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. */kO.ConcurrentRoot=1;kO.ContinuousEventPriority=4;kO.DefaultEventPriority=16;kO.DiscreteEventPriority=1;kO.IdleEventPriority=536870912;kO.LegacyRoot=0;H6t.exports=kO;var G6t=H6t.exports;const Nlt={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let klt=!1,Slt=!1;const BHe=".react-konva-event",_Ds=`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 `,wDs=`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 `,jDs={};function vCe(s,t,n=jDs){if(!klt&&"zIndex"in t&&(console.warn(wDs),klt=!0),!Slt&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(_Ds),Slt=!0)}for(var i in n)if(!Nlt[i]){var l=i.slice(0,2)==="on",o=n[i]!==t[i];if(l&&o){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),s.off(c,n[i])}var d=!t.hasOwnProperty(i);d&&s.setAttr(i,void 0)}var u=t._useStrictMode,h={},m=!1;const p={};for(var i in t)if(!Nlt[i]){var l=i.slice(0,2)==="on",x=n[i]!==t[i];if(l&&x){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),t[i]&&(p[c]=t[i])}!l&&(t[i]!==n[i]||u&&t[i]!==s.getAttr(i))&&(m=!0,h[i]=t[i])}m&&(s.setAttrs(h),x6(s));for(var c in p)s.on(c+BHe,p[c])}function x6(s){if(!si.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const W6t={},NDs={};BD.Node.prototype._applyProps=vCe;function kDs(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),x6(s)}function SDs(s,t,n){let r=BD[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=BD.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 vCe(c,i),c}function CDs(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function ADs(s,t,n){return!1}function TDs(s){return s}function EDs(){return null}function MDs(){return null}function LDs(s,t,n,r){return NDs}function PDs(){}function IDs(s){}function RDs(s,t){return!1}function DDs(){return W6t}function ODs(){return W6t}const FDs=setTimeout,zDs=clearTimeout,BDs=-1;function $Ds(s,t){return!1}const UDs=!1,qDs=!0,VDs=!0;function HDs(s,t){t.parent===s?t.moveToTop():s.add(t),x6(s)}function GDs(s,t){t.parent===s?t.moveToTop():s.add(t),x6(s)}function K6t(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),x6(s)}function WDs(s,t,n){K6t(s,t,n)}function KDs(s,t){t.destroy(),t.off(BHe),x6(s)}function YDs(s,t){t.destroy(),t.off(BHe),x6(s)}function ZDs(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function XDs(s,t,n){}function QDs(s,t,n,r,a){vCe(s,a,r)}function JDs(s){s.hide(),x6(s)}function eOs(s){}function tOs(s,t){(t.visible==null||t.visible)&&s.show()}function sOs(s,t){}function nOs(s){}function rOs(){}const aOs=()=>G6t.DefaultEventPriority,iOs=Object.freeze(Object.defineProperty({__proto__:null,appendChild:HDs,appendChildToContainer:GDs,appendInitialChild:kDs,cancelTimeout:zDs,clearContainer:nOs,commitMount:XDs,commitTextUpdate:ZDs,commitUpdate:QDs,createInstance:SDs,createTextInstance:CDs,detachDeletedInstance:rOs,finalizeInitialChildren:ADs,getChildHostContext:ODs,getCurrentEventPriority:aOs,getPublicInstance:TDs,getRootHostContext:DDs,hideInstance:JDs,hideTextInstance:eOs,idlePriority:xW.unstable_IdlePriority,insertBefore:K6t,insertInContainerBefore:WDs,isPrimaryRenderer:UDs,noTimeout:BDs,now:xW.unstable_now,prepareForCommit:EDs,preparePortalMount:MDs,prepareUpdate:LDs,removeChild:KDs,removeChildFromContainer:YDs,resetAfterCommit:PDs,resetTextContent:IDs,run:xW.unstable_runWithPriority,scheduleTimeout:FDs,shouldDeprioritizeSubtree:RDs,shouldSetTextContent:$Ds,supportsMutation:VDs,unhideInstance:tOs,unhideTextInstance:sOs,warnsIfNotActing:qDs},Symbol.toStringTag,{value:"Module"}));var oOs=Object.defineProperty,lOs=Object.defineProperties,cOs=Object.getOwnPropertyDescriptors,Clt=Object.getOwnPropertySymbols,dOs=Object.prototype.hasOwnProperty,uOs=Object.prototype.propertyIsEnumerable,Alt=(s,t,n)=>t in s?oOs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,Tlt=(s,t)=>{for(var n in t||(t={}))dOs.call(t,n)&&Alt(s,n,t[n]);if(Clt)for(var n of Clt(t))uOs.call(t,n)&&Alt(s,n,t[n]);return s},hOs=(s,t)=>lOs(s,cOs(t)),Elt,Mlt;typeof window<"u"&&((Elt=window.document)!=null&&Elt.createElement||((Mlt=window.navigator)==null?void 0:Mlt.product)==="ReactNative")?j.useLayoutEffect:j.useEffect;function Y6t(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=Y6t(r,t,n);if(a)return a;r=r.sibling}}function Z6t(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const Llt=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=Llt;return}return Llt.apply(this,arguments)};const $He=Z6t(j.createContext(null));class X6t extends j.Component{render(){return j.createElement($He.Provider,{value:this._reactInternals},this.props.children)}}function mOs(){const s=j.useContext($He);if(s===null)throw new Error("its-fine: useFiber must be called within a !");const t=j.useId();return j.useMemo(()=>{for(const r of[s,s==null?void 0:s.alternate]){if(!r)continue;const a=Y6t(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 pOs(){const s=mOs(),[t]=j.useState(()=>new Map);t.clear();let n=s;for(;n;){if(n.type&&typeof n.type=="object"){const a=n.type._context===void 0&&n.type.Provider===n.type?n.type:n.type._context;a&&a!==$He&&!t.has(a)&&t.set(a,j.useContext(Z6t(a)))}n=n.return}return t}function fOs(){const s=pOs();return j.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>j.createElement(t,null,j.createElement(n.Provider,hOs(Tlt({},r),{value:s.get(n)}))),t=>j.createElement(X6t,Tlt({},t))),[s])}function xOs(s){const t=Lt.useRef({});return Lt.useLayoutEffect(()=>{t.current=s}),Lt.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const gOs=s=>{const t=Lt.useRef(null),n=Lt.useRef(null),r=Lt.useRef(null),a=xOs(s),i=fOs(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Lt.useLayoutEffect(()=>(n.current=new BD.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=qG.createContainer(n.current,G6t.LegacyRoot,!1,null),qG.updateContainer(Lt.createElement(i,{},s.children),r.current),()=>{BD.isBrowser&&(l(null),qG.updateContainer(null,r.current,null),n.current.destroy())}),[]),Lt.useLayoutEffect(()=>{l(n.current),vCe(n.current,s,a),qG.updateContainer(Lt.createElement(i,{},s.children),r.current,null)}),Lt.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})},yOs="Layer",NT="Group",Mk="Rect",p9="Image",KF="Text",VBn="Transformer",qG=bDs(iOs);qG.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Lt.version,rendererPackageName:"react-konva"});const vOs=Lt.forwardRef((s,t)=>Lt.createElement(X6t,{},Lt.createElement(gOs,{...s,forwardedRef:t})));function bOs({imageUrl:s,preset:t,barStyleId:n,overrides:r,maxDisplayWidth:a=720,stageRef:i}){const l=j.useRef(null),[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState(null),p=(t==null?void 0:t.headshot_url)??"",x=(t==null?void 0:t.brokerage_logo_url)??"";j.useEffect(()=>{if(!s){c(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>c(W),W.onerror=()=>c(null),W.src=s},[s]),j.useEffect(()=>{if(!p){u(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>u(W),W.onerror=()=>u(null),W.src=p},[p]),j.useEffect(()=>{if(!x){m(null);return}const W=new window.Image;W.crossOrigin="anonymous",W.onload=()=>m(W),W.onerror=()=>m(null),W.src=x},[x]);const y=HIs(n),g=(o==null?void 0:o.naturalWidth)??1080,b=(o==null?void 0:o.naturalHeight)??1080,v=j.useMemo(()=>Math.min(1,a/g),[g,a]),k=g*v,C=b*v,T=(r==null?void 0:r.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",M=(r==null?void 0:r.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",P=(r==null?void 0:r.display_name)??(t==null?void 0:t.display_name)??"",L=(r==null?void 0:r.phone)??(t==null?void 0:t.phone)??"",I=(r==null?void 0:r.email)??(t==null?void 0:t.email)??"",O=(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)??[]),q=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(vOs,{ref:W=>{l.current=W,i&&(i.current=W)},width:k,height:C,scaleX:v,scaleY:v,children:e.jsxs(yOs,{children:[o&&e.jsx(p9,{image:o,width:g,height:b,listening:!1}),!o&&e.jsx(Mk,{x:0,y:0,width:g,height:b,fill:"#e2e8f0"}),e.jsx(_Os,{style:y,canvasW:g,canvasH:b,brandColor:T,accentColor:M,name:P,phone:L,email:I,tagline:O,headshot:d,logo:h,hidden:$,has:q})]})})})}function _Os({style:s,canvasW:t,canvasH:n,brandColor:r,accentColor:a,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h}){const m=n*s.heightRatio,p=m*.18,x=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":GIs(r),y=x==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const g=s.position==="bottom"?n-m:0;return e.jsxs(NT,{children:[e.jsx(Mk,{x:0,y:g,width:t,height:m,fill:r}),e.jsx(Mk,{x:0,y:s.position==="bottom"?g:m-4,width:t,height:4,fill:a}),e.jsx(une,{x:p,y:g+p,width:t-p*2,height:m-p*2,textColor:x,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 g=t*.42,b=m,v=t-g-n*.025,k=n-b-n*.025;return e.jsxs(NT,{children:[e.jsx(Mk,{x:v,y:k,width:g,height:b,fill:r,cornerRadius:b*.12,opacity:.92}),e.jsx(Mk,{x:v,y:k+b-4,width:g,height:4,fill:a,cornerRadius:2}),e.jsx(une,{x:v+p,y:k+p,width:g-p*2,height:b-p*2,textColor:x,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 g=Math.max(t*.22,Math.min(t*.3,260)),b=g*.12;return e.jsxs(NT,{children:[e.jsx(Mk,{x:t-g,y:0,width:g,height:n,fill:r}),e.jsx(Mk,{x:t-g,y:0,width:4,height:n,fill:a}),e.jsx(une,{x:t-g+b,y:n*.08,width:g-b*2,height:n*.84,textColor:x,subTextColor:y,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot,vertical:!0,railWidth:g})]})}return s.position==="letterbox"?e.jsxs(NT,{children:[e.jsx(Mk,{x:0,y:0,width:t,height:m,fill:"#0a0a0a"}),e.jsx(Mk,{x:0,y:n-m,width:t,height:m,fill:"#0a0a0a"}),e.jsx(Mk,{x:0,y:n-m,width:t,height:3,fill:a}),e.jsx(une,{x:p,y:n-m+p,width:t-p*2,height:m-p*2,textColor:"#ffffff",subTextColor:"rgba(255,255,255,0.75)",name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot}),u&&h("logo")&&e.jsx(p9,{image:u,x:t-p-m*.7,y:p,height:m-p*2,width:m*.7})]}):null}function une({x:s,y:t,width:n,height:r,textColor:a,subTextColor:i,name:l,phone:o,email:c,tagline:d,headshot:u,logo:h,has:m,circular:p,vertical:x,railWidth:y}){if(x){const W=y??n,G=Math.min(n,W*.7),K=Math.max(14,W*.13),ee=Math.max(11,W*.085),J=W*.08,le=W*.35;let ue=t;const oe=ue;ue+=G+J;const ie=ue,de=l.length>12?2:1;ue+=K*1.15*de+J*.5;const we=ue;m("phone")&&o&&(ue+=ee*1.3+J*.4);const je=ue;m("email")&&c&&(ue+=ee*1.3+J*.4);const xe=ue+J*.5;return e.jsxs(NT,{children:[m("headshot")&&u&&e.jsx(NT,{clipFunc:p?fe=>{fe.beginPath(),fe.arc(s+n/2,oe+G/2,G/2,0,Math.PI*2),fe.closePath()}:void 0,children:e.jsx(p9,{image:u,x:s+(n-G)/2,y:oe,width:G,height:G})}),m("name")&&l&&e.jsx(KF,{text:l,x:s,y:ie,width:n,align:"center",fontSize:K,fontStyle:"bold",fill:a}),m("phone")&&o&&e.jsx(KF,{text:o,x:s,y:we,width:n,align:"center",fontSize:ee,fill:i}),m("email")&&c&&e.jsx(KF,{text:c,x:s,y:je,width:n,align:"center",fontSize:ee,fill:i,ellipsis:!0,wrap:"none"}),m("logo")&&h&&e.jsx(p9,{image:h,x:s,y:xe,width:n,height:le})]})}const g=r*.95,b=u&&m("headshot")?s+g+r*.18:s,v=n-(b-s)-(h&&m("logo")?r*1.6:0),k=Math.max(20,r*.34),C=Math.max(13,r*.22),T=r*.06,M=m("tagline")&&d?1:0,P=m("phone")&&o?1:0,L=m("email")&&c?1:0,I=1+M+(P||L?1:0),O=I*k+(I-1)*T;let q=t+(r-O)/2;return e.jsxs(NT,{children:[m("headshot")&&u&&e.jsx(NT,{clipFunc:p?W=>{W.beginPath(),W.arc(s+g/2,t+g/2,g/2,0,Math.PI*2),W.closePath()}:void 0,children:e.jsx(p9,{image:u,x:s,y:t+(r-g)/2,width:g,height:g})}),m("name")&&l&&e.jsx(KF,{text:l,x:b,y:q,width:v,fontSize:k,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(q+=k+T,null),m("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(KF,{text:d,x:b,y:q,width:v,fontSize:C*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(q+=C*1.1+T,null)]}),P||L?e.jsx(KF,{text:[o,c].filter(Boolean).join(" • "),x:b,y:q,width:v,fontSize:C,fill:i,ellipsis:!0,wrap:"none"}):null,m("logo")&&h&&e.jsx(p9,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function wOs(){const{data:s}=DJ(),t=(s==null?void 0:s.find(q=>q.is_default))??(s==null?void 0:s[0])??null,[n,r]=j.useState(void 0),a=(s==null?void 0:s.find(q=>q.id===n))??t,[i,l]=j.useState([]),[o,c]=j.useState(0),[d,u]=j.useState("minimal-stripe"),[h,m]=j.useState({}),[p,x]=j.useState(!1),y=j.useRef(null),[g,b]=j.useState(780),v=j.useRef(null),k=q=>{if(v.current&&(v.current.disconnect(),v.current=null),!q)return;const W=()=>{const K=q.clientWidth;K>0&&b(Math.min(780,K-16))};W();const G=new ResizeObserver(W);G.observe(q),v.current=G};j.useEffect(()=>()=>{var q;(q=v.current)==null||q.disconnect()},[]);const C=j.useRef(null),T=q=>{if(!q)return;const W=[];Array.from(q).forEach(G=>{G.type.startsWith("image/")&&W.push({id:crypto.randomUUID(),url:URL.createObjectURL(G),file:G,name:G.name})}),l(G=>[...G,...W])},M=q=>{l(W=>{const G=W.find(K=>K.id===q);return G&&URL.revokeObjectURL(G.url),W.filter(K=>K.id!==q)}),c(0)},P=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),L=q=>{var le;const[W,G]=q.split(","),K=((le=W.match(/:(.*?);/))==null?void 0:le[1])??"image/jpeg",ee=atob(G),J=new Uint8Array(ee.length);for(let ue=0;ue{var q;if(C.current){x(!0);try{const W=C.current,G=W.toDataURL({pixelRatio:1/(W.scaleX()||1),mimeType:"image/jpeg",quality:.95}),ee=`${((q=i[o])==null?void 0:q.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,J=L(G),le=URL.createObjectURL(J);if(P)window.open(le,"_blank")||(window.location.href=le),re.success('Long-press the image and tap "Save to Photos"');else{const ue=document.createElement("a");ue.href=le,ue.download=ee,document.body.appendChild(ue),ue.click(),ue.remove(),re.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(le),6e4)}catch(W){re.error(W.message||"Export failed")}finally{x(!1)}}},O=async()=>{if(i.length){x(!0);try{const q=new d6t,W=i.length,G=o;for(let J=0;JsetTimeout(de,600)),!C.current)continue;const le=C.current,oe=le.toDataURL({pixelRatio:1/(le.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],ie=i[J].name.replace(/\.[^.]+$/,"")||`image-${J+1}`;q.file(`${ie}-branded.jpg`,oe,{base64:!0})}c(G);const K=await q.generateAsync({type:"blob"}),ee=document.createElement("a");ee.href=URL.createObjectURL(K),ee.download=`branded-images-${Date.now()}.zip`,ee.click(),URL.revokeObjectURL(ee.href),re.success(`${W} images exported`)}catch(q){re.error(q.message||"Batch export failed")}finally{x(!1)}}},$=i[o];return e.jsx(Vs,{title:"Branding Bar Studio",children:e.jsxs("div",{className:"container max-w-7xl py-4 md:py-6 space-y-4 px-3 md:px-6",children:[e.jsx(ql,{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(Yn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(_a,{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(Yn,{to:"/marketing-studio/brand-kit",children:[e.jsx(Ac,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(be,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(Re,{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(Yn,{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(be,{className:"overflow-hidden",children:e.jsxs(Re,{className:"p-4",children:[$?e.jsx("div",{ref:k,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(bOs,{imageUrl:$.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:g,stageRef:C})}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-12 text-center space-y-3 cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>{var q;return(q=y.current)==null?void 0:q.click()},onDragOver:q=>q.preventDefault(),onDrop:q=>{q.preventDefault(),T(q.dataTransfer.files)},children:[e.jsx(ac,{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(Ja,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:y,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:q=>T(q.target.files)})]})}),i.length>0&&e.jsx(be,{className:"overflow-hidden",children:e.jsx(Re,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((q,W)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(W),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${W===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:q.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>M(q.id),className:"absolute -top-1 -right-1 bg-destructive text-destructive-foreground rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(dr,{className:"h-3 w-3"})})]},q.id)),e.jsx("button",{onClick:()=>{var q;return(q=y.current)==null?void 0:q.click()},className:"flex-shrink-0 h-16 w-16 rounded border-2 border-dashed flex items-center justify-center hover:bg-muted/40",children:e.jsx(Js,{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(q=>URL.revokeObjectURL(q.url)),l([])},children:"Clear all"}),e.jsxs(B,{onClick:I,disabled:p||!$,children:[p?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ii,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs(B,{onClick:O,disabled:p,children:[p?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ii,{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(be,{className:"overflow-hidden",children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-base",children:"Brand preset"})}),e.jsx(Re,{children:e.jsxs(vs,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Choose preset"})}),e.jsx(ys,{children:s==null?void 0:s.map(q=>e.jsxs(Je,{value:q.id,children:[q.name," ",q.is_default?"(default)":""]},q.id))})]})})]}),e.jsxs(be,{className:"overflow-hidden",children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-base",children:"Bar style"})}),e.jsx(Re,{children:e.jsx(WIs,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(be,{className:"overflow-hidden",children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-base",children:"Tweak this design"})}),e.jsx(Re,{children:e.jsxs(fa,{defaultValue:"text",children:[e.jsxs(xa,{className:"grid grid-cols-2 w-full",children:[e.jsx(ss,{value:"text",children:"Text"}),e.jsx(ss,{value:"colors",children:"Colors"})]}),e.jsxs(ns,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Display name"}),e.jsx(ye,{value:h.display_name??(a==null?void 0:a.display_name)??"",onChange:q=>m({...h,display_name:q.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:q=>m({...h,phone:q.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{value:h.email??(a==null?void 0:a.email)??"",onChange:q=>m({...h,email:q.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Tagline"}),e.jsx(ye,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:q=>m({...h,tagline:q.target.value})})]})]}),e.jsxs(ns,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Bar color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:q=>m({...h,brand_color:q.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(ye,{value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:q=>m({...h,brand_color:q.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Accent line"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:q=>m({...h,accent_color:q.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(ye,{value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:q=>m({...h,accent_color:q.target.value})})]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>m({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function jOs(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 NOs=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function pE(s){const t=[];for(let n=0,r=s.length;ns_||s.height>s_)&&(s.width>s_&&s.height>s_?s.width>s.height?(s.height*=s_/s.width,s.width=s_):(s.width*=s_/s.height,s.height=s_):s.width>s_?(s.height*=s_/s.width,s.width=s_):(s.width*=s_/s.height,s.height=s_))}function Gke(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 TOs(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function EOs(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),TOs(a)}const wb=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||wb(n,t)};function MOs(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function LOs(s,t){return Q6t(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function POs(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?MOs(n):LOs(n,r);return document.createTextNode(`${a}{${i}}`)}function Plt(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=NOs();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(POs(l,n,a,r)),t.appendChild(o)}function IOs(s,t,n){Plt(s,t,":before",n),Plt(s,t,":after",n)}const Ilt="application/font-woff",Rlt="image/jpeg",ROs={woff:Ilt,woff2:Ilt,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Rlt,jpeg:Rlt,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function DOs(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function UHe(s){const t=DOs(s).toLowerCase();return ROs[t]||""}function OOs(s){return s.split(/,/)[1]}function PFe(s){return s.search(/^(data:)/)!==-1}function FOs(s,t){return`data:${t};base64,${s}`}async function eMt(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 nPe={};function zOs(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 qHe(s,t,n){const r=zOs(s,t,n.includeQueryParams);if(nPe[r]!=null)return nPe[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await eMt(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),OOs(o)));a=FOs(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 nPe[r]=a,a}async function BOs(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):Gke(t)}async function $Os(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 Gke(o)}const n=s.poster,r=UHe(n),a=await qHe(n,r,t);return Gke(a)}async function UOs(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await bCe(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function qOs(s,t){return wb(s,HTMLCanvasElement)?BOs(s):wb(s,HTMLVideoElement)?$Os(s,t):wb(s,HTMLIFrameElement)?UOs(s,t):s.cloneNode(tMt(s))}const VOs=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",tMt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function HOs(s,t,n){var r,a;if(tMt(t))return t;let i=[];return VOs(s)&&s.assignedNodes?i=pE(s.assignedNodes()):wb(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=pE(s.contentDocument.body.childNodes):i=pE(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||wb(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>bCe(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function GOs(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):Q6t(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`),wb(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 WOs(s,t){wb(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),wb(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function KOs(s,t){if(wb(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function YOs(s,t,n){return wb(t,Element)&&(GOs(s,t,n),IOs(s,t,n),WOs(s,t),KOs(s,t)),t}async function ZOs(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;iqOs(r,t)).then(r=>HOs(s,r,t)).then(r=>YOs(s,r,t)).then(r=>ZOs(r,t))}const sMt=/url\((['"]?)([^'"]+?)\1\)/g,XOs=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,QOs=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function JOs(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function eFs(s){const t=[];return s.replace(sMt,(n,r,a)=>(t.push(a),n)),t.filter(n=>!PFe(n))}async function tFs(s,t,n,r,a){try{const i=n?jOs(t,n):t,l=UHe(t);let o;return a||(o=await qHe(i,l,r)),s.replace(JOs(t),`$1${o}$3`)}catch{}return s}function sFs(s,{preferredFontFormat:t}){return t?s.replace(QOs,n=>{for(;;){const[r,,a]=XOs.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function nMt(s){return s.search(sMt)!==-1}async function rMt(s,t,n){if(!nMt(s))return s;const r=sFs(s,n);return eFs(r).reduce((i,l)=>i.then(o=>tFs(o,l,t,n)),Promise.resolve(r))}async function ZF(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await rMt(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function nFs(s,t){await ZF("background",s,t)||await ZF("background-image",s,t),await ZF("mask",s,t)||await ZF("-webkit-mask",s,t)||await ZF("mask-image",s,t)||await ZF("-webkit-mask-image",s,t)}async function rFs(s,t){const n=wb(s,HTMLImageElement);if(!(n&&!PFe(s.src))&&!(wb(s,SVGImageElement)&&!PFe(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await qHe(r,UHe(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 aFs(s,t){const r=pE(s.childNodes).map(a=>aMt(a,t));await Promise.all(r).then(()=>s)}async function aMt(s,t){wb(s,Element)&&(await nFs(s,t),await rFs(s,t),await aFs(s,t))}function iFs(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 Dlt={};async function Olt(s){let t=Dlt[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},Dlt[s]=t,t}async function Flt(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),eMt(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function zlt(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 oFs(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{pE(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=Olt(c).then(u=>Flt(u,t)).then(u=>zlt(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(Olt(a.href).then(o=>Flt(o,t)).then(o=>zlt(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{pE(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function lFs(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>nMt(t.style.getPropertyValue("src")))}async function cFs(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=pE(s.ownerDocument.styleSheets),r=await oFs(n,t);return lFs(r)}function iMt(s){return s.trim().replace(/["']/g,"")}function dFs(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(iMt(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function uFs(s,t){const n=await cFs(s,t),r=dFs(s);return(await Promise.all(n.filter(i=>r.has(iMt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return rMt(i.cssText,l,t)}))).join(` `)}async function hFs(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await uFs(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 oMt(s,t={}){const{width:n,height:r}=J6t(s,t),a=await bCe(s,t,!0);return await hFs(a,t),await aMt(a,t),iFs(a,t),await EOs(a,n,r)}async function lMt(s,t={}){const{width:n,height:r}=J6t(s,t),a=await oMt(s,t),i=await Gke(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||COs(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||AOs(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 L$(s,t={}){return(await lMt(s,t)).toDataURL()}const cMt=Object.freeze(Object.defineProperty({__proto__:null,toCanvas:lMt,toPng:L$,toSvg:oMt},Symbol.toStringTag,{value:"Module"})),P$=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),_Ce={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},kT={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},mFs=({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})]})]}),VHe=Lt.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=_Ce[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:P$(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",P$(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(mFs,{branding:r,dim:l})]})]})]})});VHe.displayName="LuxuryDarkTemplate";const pFs=({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})]})]}),HHe=Lt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var p;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(p=s.photos)==null?void 0:p[a],d=_Ce[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:P$(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(pFs,{branding:r,dim:l,accentColor:m})]})]})});HHe.displayName="ModernCleanTemplate";const fFs=({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})]})]}),GHe=Lt.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=_Ce[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:P$(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(fFs,{branding:r,dim:l})]})]})]})});GHe.displayName="BoldColorfulTemplate";const xFs=({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})]})]}),WHe=Lt.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=_Ce[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:P$(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",P$(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(xFs,{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"}})]})]})})});WHe.displayName="EditorialTemplate";const gFs=[{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:"📉"}],Blt=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(vm,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(vm,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(sx,{className:"h-4 w-4"})}],yFs=[{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:"📰"}],$lt={"luxury-dark":VHe,"modern-clean":HHe,"bold-colorful":GHe,editorial:WHe},rPe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function vFs(s){var l;const[t,n]=s.split(","),r=((l=t.match(/:(.*?);/))==null?void 0:l[1])||"image/png",a=atob(n),i=new Uint8Array(a.length);for(let o=0;oEe.is_default))??(s==null?void 0:s[0])??null,[n,r]=j.useState(void 0),a=(s==null?void 0:s.find(Ee=>Ee.id===n))??t,i=ei(),[l,o]=j.useState("mine"),[c,d]=j.useState(""),[u,h]=j.useState("address"),[m,p]=j.useState(!1),[x,y]=j.useState([]),[g,b]=j.useState(null),[v,k]=j.useState(0),[C,T]=j.useState("just-listed"),[M,P]=j.useState(["instagram-square"]),[L,I]=j.useState("luxury-dark"),[O,$]=j.useState(!0),[q,W]=j.useState(!1),[G,K]=j.useState([]),[ee,J]=j.useState("search"),le=j.useRef({}),{data:ue=[],isLoading:oe}=mt({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:Ee,error:Le}=await U.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, year_built, property_type, description, created_at, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",i).order("created_at",{ascending:!1}).limit(60);if(Le)throw Le;return(Ee||[]).map(De=>{const Be=(De.listing_photos||[]).slice().sort((Ge,_e)=>(_e.is_primary?1:0)-(Ge.is_primary?1:0)||(Ge.sort_order??0)-(_e.sort_order??0)).map(Ge=>Ge.photo_url).filter(Boolean),Ne=String(De.status||"");return{mlsNumber:De.id,address:De.property_address||"",city:De.city||"",state:De.state||"",zip:"",price:Number(De.price||0),status:Ne,bedrooms:Number(De.bedrooms||0),bathrooms:Number(De.bathrooms||0),sqft:Number(De.square_footage||0),lotSize:"",yearBuilt:De.year_built??null,propertyType:De.property_type||"",description:De.description||"",photos:Be,listDate:De.created_at,soldDate:Ne.toLowerCase().includes("sold")?De.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),ie=j.useMemo(()=>!O||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[O,a]),de=async()=>{if(c.trim()){p(!0),y([]);try{const{data:Ee,error:Le}=await U.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Le)throw Le;if(Ee!=null&&Ee.error)throw new Error(Ee.error);y((Ee==null?void 0:Ee.listings)||[]),((Ee==null?void 0:Ee.listings)||[]).length===0&&re.info("No listings found. Try a different search.")}catch(Ee){re.error(Ee.message||"Search failed")}finally{p(!1)}}},we=Ee=>{var Le;b(Ee),k(0),J("customize"),Ee.soldDate||(Le=Ee.status)!=null&&Le.toLowerCase().includes("sold")?T("just-sold"):T("just-listed")},je=Ee=>P(Le=>Le.includes(Ee)?Le.filter(De=>De!==Ee):[...Le,Ee]),xe=g?{listing:g,postType:C,format:"instagram-square",branding:ie,selectedPhotoIndex:v}:null,fe=j.useCallback(async()=>{if(!(!g||M.length===0)){W(!0),K([]),J("generate");try{await new Promise(Le=>setTimeout(Le,600));const Ee=[];for(const Le of M){const De=`${L}-${Le}`,Be=le.current[De];if(!Be)continue;const Ne=kT[Le],Ge=await L$(Be,{width:Ne.width,height:Ne.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ee.push({format:Le,url:Ge})}K(Ee),re.success(`Generated ${Ee.length} design${Ee.length>1?"s":""}!`)}catch(Ee){re.error(Ee.message||"Generation failed")}finally{W(!1)}}},[g,M,L]),Se=(Ee,Le)=>{const De=`${((g==null?void 0:g.address)||"listing").replace(/\s+/g,"-")}-${C}-${Le}.png`;try{const Be=vFs(Ee),Ne=URL.createObjectURL(Be);if(bFs)window.open(Ne,"_blank"),re.message("Long-press the image to save to Photos");else{const Ge=document.createElement("a");Ge.href=Ne,Ge.download=De,document.body.appendChild(Ge),Ge.click(),document.body.removeChild(Ge)}setTimeout(()=>URL.revokeObjectURL(Ne),6e4)}catch{const Be=document.createElement("a");Be.href=Ee,Be.download=De,Be.click()}};return j.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx(Vs,{title:"Listing Templates",children:e.jsxs("div",{className:"container max-w-6xl py-4 md:py-8 px-3 md:px-6 space-y-5",children:[e.jsxs(ql,{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(Yn,{to:"/marketing-studio",children:[e.jsx(_a,{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(qe,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(yn,{className:"h-3 w-3"})," Listing Templates"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight",children:"Just Listed. Just Stunning."}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl mt-1",children:"Search any MLS listing and get pixel-perfect, on-brand graphics for Instagram, Stories and Facebook in one click."})]}),s&&s.length>0&&e.jsxs("div",{className:"min-w-0 sm:min-w-[220px]",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Default"})}),e.jsx(ys,{children:s.map(Ee=>e.jsxs(Je,{value:Ee.id,children:[Ee.name,Ee.is_default?" (default)":""]},Ee.id))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs sm:text-sm overflow-x-auto -mx-1 px-1 pb-1",children:[e.jsxs("button",{onClick:()=>J("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ee==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(Fr,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>g&&J("customize"),disabled:!g,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${ee==="customize"?"bg-primary text-primary-foreground":g?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(yn,{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 ${ee==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(ii,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),ee==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(fa,{value:l,onValueChange:Ee=>o(Ee),children:e.jsxs(xa,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(ss,{value:"mine",children:[e.jsx(ia,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(ss,{value:"mls",children:[e.jsx(Fr,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:oe?e.jsx(be,{children:e.jsx(Re,{className:"py-12 flex items-center justify-center",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):ue.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-10 text-center space-y-2",children:[e.jsx(ia,{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(Yn,{to:"/mission-control/listings",children:"Go to Listings"})})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[ue.length," listing",ue.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:ue.map((Ee,Le)=>{var De;return e.jsx(be,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>we(Ee),children:e.jsx(Re,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(De=Ee.photos)!=null&&De[0]?e.jsx("img",{src:Ee.photos[0],alt:Ee.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ia,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold",children:Ee.price>0?rPe(Ee.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ee.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ee.city,Ee.state?`, ${Ee.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ee.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(p3,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(t0,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(VR,{className:"h-3 w-3"})," ",Ee.sqft.toLocaleString()]})]}),Ee.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Ee.status})})]})]})})},Ee.mlsNumber||Le)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(be,{className:"overflow-hidden",children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(Fr,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(fr,{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(Re,{className:"space-y-3",children:[e.jsx(fa,{value:u,onValueChange:Ee=>h(Ee),children:e.jsxs(xa,{children:[e.jsxs(ss,{value:"address",children:[e.jsx(oi,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(ss,{value:"mls",children:[e.jsx(wf,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(ye,{value:c,onChange:Ee=>d(Ee.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ee=>Ee.key==="Enter"&&de()}),e.jsxs(B,{onClick:de,disabled:m||!c.trim(),className:"sm:w-auto w-full",children:[m?e.jsx(Wt,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(Fr,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),x.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[x.length," listing",x.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:x.map((Ee,Le)=>{var De;return e.jsx(be,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>we(Ee),children:e.jsx(Re,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(De=Ee.photos)!=null&&De[0]?e.jsx("img",{src:Ee.photos[0],alt:Ee.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ia,{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:rPe(Ee.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Ee.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ee.city,", ",Ee.state," ",Ee.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Ee.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(p3,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(t0,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(VR,{className:"h-3 w-3"})," ",Ee.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[Ee.mlsNumber&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Ee.mlsNumber}),Ee.status&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Ee.status})]})]})]})})},Ee.mlsNumber||Le)})})]})]})]}),ee==="customize"&&g&&xe&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(be,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(Ft,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"Selected listing"})}),e.jsxs(Re,{className:"space-y-3",children:[g.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:g.photos[v],alt:"",className:"w-full h-full object-cover"})}),g.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(Ee=>Math.max(0,Ee-1)),disabled:v===0,children:e.jsx(Cc,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v+1," of ",g.photos.length]}),e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>k(Ee=>Math.min(g.photos.length-1,Ee+1)),disabled:v===g.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:rPe(g.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:g.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.city,", ",g.state," ",g.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[g.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:g.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),g.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:g.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),g.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:g.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:()=>{J("search"),b(null)},children:[e.jsx(bm,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(be,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(yn,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(fr,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Re,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ac,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:yFs.map(Ee=>e.jsxs("button",{onClick:()=>I(Ee.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${L===Ee.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Ee.preview}),e.jsx("span",{className:"text-sm font-medium",children:Ee.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Ee.description})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:gFs.map(Ee=>e.jsxs("button",{onClick:()=>T(Ee.value),className:`flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${C===Ee.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Ee.icon})," ",e.jsx("span",{className:"truncate",children:Ee.label})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:Blt.map(Ee=>e.jsxs("button",{onClick:()=>je(Ee.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${M.includes(Ee.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Ee.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Ee.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ee.dimensions})]})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Eo,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(Mn,{checked:O,onCheckedChange:$})]}),O&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(Yn,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),O&&a&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[a.headshot_url&&e.jsx("img",{src:a.headshot_url,alt:"",className:"w-10 h-10 rounded-full object-cover border"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:a.display_name||"Unnamed agent"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.tagline||a.email||""})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Preview"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-3 md:p-4 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:360,maxWidth:"100%",height:360*(kT[M[0]||"instagram-square"].height/kT[M[0]||"instagram-square"].width)},children:(()=>{const Ee=$lt[L],Le=M[0]||"instagram-square";return e.jsx(Ee,{...xe,format:Le})})()})})]}),e.jsx(B,{onClick:fe,disabled:M.length===0||q,size:"lg",className:"w-full gap-2",children:q?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-5 w-5"})," Generate ",M.length," design",M.length>1?"s":""]})})]})]})]}),ee==="generate"&&e.jsxs("div",{className:"space-y-4",children:[q&&e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Wt,{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:()=>J("customize"),children:[e.jsx(bm,{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((Ee,Le)=>{const De=Blt.find(Be=>Be.value===Ee.format);return e.jsxs(be,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Ee.url,alt:"",className:"w-full rounded"})}),e.jsxs(Re,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[De==null?void 0:De.icon,e.jsx("span",{className:"text-sm font-medium",children:De==null?void 0:De.label})]}),e.jsx(qe,{variant:"outline",className:"text-[10px]",children:De==null?void 0:De.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>Se(Ee.url,Ee.format),children:[e.jsx(ii,{className:"h-3.5 w-3.5"})," Download"]})]})]},Le)})})]})]}),ee==="generate"&&g&&xe&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:M.map(Ee=>{const Le=$lt[L],De=kT[Ee];return e.jsx("div",{style:{width:De.width,height:De.height},children:e.jsx(Le,{ref:Be=>{le.current[`${L}-${Ee}`]=Be},...xe,format:Ee})},`${L}-${Ee}`)})})]})})}var dMt="Toggle",KHe=j.forwardRef((s,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:a,...i}=s,[l,o]=Mx({prop:n,onChange:a,defaultProp:r??!1,caller:dMt});return e.jsx(Ua.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:ua(s.onClick,()=>{s.disabled||o(!l)})})});KHe.displayName=dMt;var uMt=KHe,g6="ToggleGroup",[hMt,HBn]=Zm(g6,[QE]),mMt=QE(),YHe=Lt.forwardRef((s,t)=>{const{type:n,...r}=s;if(n==="single"){const a=r;return e.jsx(wFs,{...a,ref:t})}if(n==="multiple"){const a=r;return e.jsx(jFs,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${g6}\``)});YHe.displayName=g6;var[pMt,fMt]=hMt(g6),wFs=Lt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Mx({prop:n,defaultProp:r??"",onChange:a,caller:g6});return e.jsx(pMt,{scope:s.__scopeToggleGroup,type:"single",value:Lt.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:Lt.useCallback(()=>o(""),[o]),children:e.jsx(xMt,{...i,ref:t})})}),jFs=Lt.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=Mx({prop:n,defaultProp:r??[],onChange:a,caller:g6}),c=Lt.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Lt.useCallback(u=>o((h=[])=>h.filter(m=>m!==u)),[o]);return e.jsx(pMt,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(xMt,{...i,ref:t})})});YHe.displayName=g6;var[NFs,kFs]=hMt(g6),xMt=Lt.forwardRef((s,t)=>{const{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=mMt(n),u=J3(l),h={role:"group",dir:u,...c};return e.jsx(NFs,{scope:n,rovingFocus:a,disabled:r,children:a?e.jsx(e3e,{asChild:!0,...d,orientation:i,dir:u,loop:o,children:e.jsx(Ua.div,{...h,ref:t})}):e.jsx(Ua.div,{...h,ref:t})})}),Wke="ToggleGroupItem",gMt=Lt.forwardRef((s,t)=>{const n=fMt(Wke,s.__scopeToggleGroup),r=kFs(Wke,s.__scopeToggleGroup),a=mMt(s.__scopeToggleGroup),i=n.value.includes(s.value),l=r.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=Lt.useRef(null);return r.rovingFocus?e.jsx(t3e,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(Ult,{...o,ref:t})}):e.jsx(Ult,{...o,ref:t})});gMt.displayName=Wke;var Ult=Lt.forwardRef((s,t)=>{const{__scopeToggleGroup:n,value:r,...a}=s,i=fMt(Wke,n),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(KHe,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(r):i.onItemDeactivate(r)}})}),yMt=YHe,vMt=gMt;const bMt=hO("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"}}),SFs=j.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(uMt,{ref:a,className:Et(bMt({variant:t,size:n,className:s})),...r}));SFs.displayName=uMt.displayName;const _Mt=j.createContext({size:"default",variant:"default"}),Az=j.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(yMt,{ref:i,className:Et("flex items-center justify-center gap-1",s),...a,children:e.jsx(_Mt.Provider,{value:{variant:t,size:n},children:r})}));Az.displayName=yMt.displayName;const aD=j.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=j.useContext(_Mt);return e.jsx(vMt,{ref:i,className:Et(bMt({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});aD.displayName=vMt.displayName;const CFs=[{id:"meet",label:"Meet Your Agent",icon:Eo,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:yN,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:ll,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:xN,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:jh,description:"Personal philosophy, mantra, or rallying call."}],aPe={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"}},AFs=[{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."}],qlt={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 TFs(){const{data:s}=zIs(),{data:t}=DJ(),[n,r]=j.useState(void 0),a=j.useMemo(()=>(t==null?void 0:t.find(x=>x.id===n))??s??null,[t,n,s]),[i,l]=j.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...qlt.meet}),o=x=>l(y=>({...y,...x})),c=x=>l(y=>({...y,template:x,...qlt[x]})),d=j.useRef(null),[u,h]=j.useState(!1),m=async()=>{if(!d.current)return;h(!0);const x=d.current,y=x.style.transform;try{x.style.transform="none",await new Promise(v=>requestAnimationFrame(()=>v(null)));const g=await L$(x,{cacheBust:!0,pixelRatio:2,width:x.offsetWidth,height:x.offsetHeight,backgroundColor:"#ffffff"}),b=document.createElement("a");b.href=g,b.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(b),b.click(),b.remove(),re.success("Downloaded to your device")}catch(g){re.error((g==null?void 0:g.message)||"Export failed")}finally{x.style.transform=y,h(!1)}},p=aPe[i.aspect];return e.jsx(Vs,{title:"Personal Branding",children:e.jsxs("div",{className:"container max-w-7xl py-6 md:py-8 space-y-6 px-4",children:[e.jsxs(ql,{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(Yn,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(_a,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(yn,{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(Yn,{to:"/marketing-studio/brand-kit",children:[e.jsx(Ac,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs(B,{onClick:m,disabled:u,children:[e.jsx(ii,{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(be,{children:e.jsxs(Re,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:CFs.map(x=>{const y=x.icon,g=i.template===x.id;return e.jsxs("button",{onClick:()=>c(x.id),className:`text-left rounded-lg border p-3 transition-all ${g?"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:x.label})]},x.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(Az,{type:"single",value:i.style,onValueChange:x=>x&&o({style:x}),className:"grid grid-cols-2 gap-1",children:AFs.map(x=>e.jsx(aD,{value:x.id,className:"text-xs h-9",children:x.label},x.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx(Az,{type:"single",value:i.aspect,onValueChange:x=>x&&o({aspect:x}),className:"grid grid-cols-3 gap-1",children:Object.keys(aPe).map(x=>e.jsx(aD,{value:x,className:"text-xs h-9",children:aPe[x].label},x))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(vs,{value:n??(s==null?void 0:s.id)??"",onValueChange:r,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Choose preset"})}),e.jsx(ys,{children:t.map(x=>e.jsx(Je,{value:x.id,children:x.name},x.id))})]})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-4 space-y-3",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(Ds,{id:"headline",value:i.headline,onChange:x=>o({headline:x.target.value}),rows:2})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(ye,{id:"subline",value:i.subline,onChange:x=>o({subline:x.target.value})})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(Ds,{id:"body",value:i.body,onChange:x=>o({body:x.target.value}),rows:4})]}),(i.template==="testimonial"||i.template==="quote")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(ye,{id:"attribution",value:i.attribution,onChange:x=>o({attribution:x.target.value}),placeholder:"— Client name / Source"})]}),i.template==="testimonial"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Rating"}),e.jsx(Az,{type:"single",value:String(i.rating),onValueChange:x=>x&&o({rating:Number(x)}),className:"grid grid-cols-5 gap-1",children:[1,2,3,4,5].map(x=>e.jsxs(aD,{value:String(x),className:"text-xs h-9",children:[x,"★"]},x))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(ye,{id:"badge",value:i.badgeText,onChange:x=>o({badgeText:x.target.value})})]})]})})]}),e.jsx(EFs,{aspect:p,canvasRef:d,children:e.jsx(MFs,{form:i,preset:a,width:p.w,height:p.h})})]})]})})}function EFs({aspect:s,canvasRef:t,children:n}){const r=j.useRef(null),[a,i]=j.useState(.5);return j.useEffect(()=>{const l=r.current;if(!l)return;const o=()=>{const d=l.clientWidth-32;i(Math.min(1,d/s.w))};o();const c=new ResizeObserver(o);return c.observe(l),()=>c.disconnect()},[s.w]),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{ref:r,className:"rounded-xl bg-muted/40 p-4 md:p-6 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:s.w*a,height:s.h*a,position:"relative"},className:"shadow-2xl",children:e.jsx("div",{ref:t,style:{width:s.w,height:s.h,transform:`scale(${a})`,transformOrigin:"top left",position:"absolute",top:0,left:0},children:n})})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:["Preview scaled. Export is ",s.w,"×",s.h,"px @ 2× retina."]})]})}function MFs({form:s,preset:t,width:n,height:r}){const a=(t==null?void 0:t.brand_color)||"#0F172A",i=(t==null?void 0:t.accent_color)||"#D4AF37",l=t==null?void 0:t.headshot_url,o=t==null?void 0:t.brokerage_logo_url,c=(t==null?void 0:t.display_name)||"Your Name",d=(t==null?void 0:t.phone)||"",u=(t==null?void 0:t.email)||"",h=(t==null?void 0:t.tagline)||"",m=(t==null?void 0:t.website_url)||"",p={form:s,brandColor:a,accentColor:i,headshot:l,logo:o,name:c,phone:d,email:u,tagline:h,website:m,width:n,height:r};return s.style==="editorial"?e.jsx(LFs,{...p}):s.style==="bold"?e.jsx(PFs,{...p}):s.style==="luxury"?e.jsx(RFs,{...p}):e.jsx(IFs,{...p})}function wMt({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 wCe({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:p?700:480,overflow:"hidden",borderRadius:4},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top",filter:"grayscale(0.15)"}})}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:220,textAlign:t.template==="quote"?"center":"left"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:120,lineHeight:.7,color:r,fontFamily:"Georgia, serif"},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?76:92,lineHeight:1.05,fontWeight:400,margin:0,letterSpacing:"-0.02em",whiteSpace:"pre-wrap"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:22,marginTop:16,color:"#555",fontStyle:"italic"},children:t.subline}),t.body&&e.jsx("p",{style:{fontFamily:"Inter, sans-serif",fontSize:22,lineHeight:1.5,color:"#333",marginTop:28,maxWidth:820},children:t.body}),t.template==="testimonial"&&e.jsxs("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16},children:[e.jsx(wCe,{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(wMt,{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 PFs(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%, ${DFs(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(wCe,{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(wMt,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function IFs(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(wCe,{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 RFs(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(wCe,{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 DFs(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 OFs=()=>{const{swagId:s}=$i(),{user:t}=Ns(),{toast:n}=pi(),r=as(),{trackEngagement:a}=eq(),[i,l]=j.useState(""),{data:o,isLoading:c}=mt({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:b,error:v}=await U.from("social_swag").select("*").eq("id",s).single();if(v)throw v;const{data:k}=await U.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...b,links:k||[]}},enabled:!!s});j.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:b,error:v}=await U.from("social_swag_likes").select("*").eq("swag_id",s);if(v)throw v;return b},enabled:!!s}),{data:u=[]}=mt({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:b,error:v}=await U.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(v)throw v;const k=[...new Set(b.map(M=>M.user_id))],{data:C}=await U.from("profiles").select("id, name").in("id",k),T=new Map((C==null?void 0:C.map(M=>[M.id,M.name]))||[]);return b.map(M=>({...M,user_name:T.get(M.user_id)||"Unknown User"}))},enabled:!!s}),h=vt({mutationFn:async b=>{const{error:v}=await U.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:b});if(v)throw v},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:b=>{n({title:"Error adding comment",description:b.message,variant:"destructive"})}}),m=vt({mutationFn:async b=>{const{error:v}=await U.from("social_swag_comments").delete().eq("id",b);if(v)throw v},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),p=vt({mutationFn:async()=>{const b=d.find(v=>v.user_id===(t==null?void 0:t.id));if(b){const{error:v}=await U.from("social_swag_likes").delete().eq("id",b.id);if(v)throw v}else{const{error:v}=await U.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(v)throw v}},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-likes",s]})}}),x=d.some(b=>b.user_id===(t==null?void 0:t.id)),y=b=>b.split(" ").map(v=>v[0]).join("").toUpperCase().slice(0,2),g=b=>{b.preventDefault(),!(!i.trim()||!t)&&h.mutate(i.trim())};return c?e.jsx(Vs,{title:"Social Swag",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):o?e.jsx(Vs,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/social-swag",children:[e.jsx(_a,{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(rq,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(B,{variant:x?"default":"outline",className:"gap-2 w-fit",onClick:()=>p.mutate(),disabled:!t||p.isPending,children:[e.jsx(mg,{className:`h-4 w-4 ${x?"fill-current":""}`}),d.length," ",d.length===1?"Like":"Likes"]})]})]}),o.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:o.description}})]}),o.links.length>0&&e.jsx(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(vc,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(b=>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(b.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:b.title}),e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground"})]},b.id))})]})}),e.jsx(Xl,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Yd,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:g,className:"flex gap-2",children:[e.jsx(Ds,{placeholder:"Add a comment...",value:i,onChange:b=>l(b.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(Dr,{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(be,{children:e.jsx(Re,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):u.map(b=>e.jsx(be,{children:e.jsx(Re,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ra,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Da,{className:"text-sm",children:y(b.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:b.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:oc(new Date(b.created_at),{addSuffix:!0})}),b.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(b.id),children:e.jsx(Rn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:b.content})]})]})})},b.id))})]})]})}):e.jsx(Vs,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(vc,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Item not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This item may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(Yn,{to:"/social-swag",children:"Back to Social Swag"})})]})})},FFs=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=j.useState(!0),[o,c]=j.useState(!0),[d,u]=j.useState(!0),h=m=>m.split(" ").map(p=>p[0]).join("").toUpperCase().slice(0,2);return e.jsx("aside",{className:"w-64 shrink-0 hidden lg:block relative z-0",children:e.jsx("div",{className:"sticky top-4 space-y-4 max-h-[calc(100vh-8rem)] overflow-y-auto overscroll-contain",children:e.jsxs("div",{className:"space-y-2 pr-4",children:[e.jsxs(B,{variant:n==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>r("all"),children:[e.jsx(HT,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(i0,{open:i,onOpenChange:l,children:[e.jsx(o0,{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(Po,{className:"h-4 w-4"}):e.jsx(Qa,{className:"h-4 w-4"})]})}),e.jsx(l0,{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(i0,{open:o,onOpenChange:c,children:[e.jsx(o0,{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(du,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(Po,{className:"h-4 w-4"}):e.jsx(Qa,{className:"h-4 w-4"})]})}),e.jsx(l0,{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(i0,{open:d,onOpenChange:u,children:[e.jsx(o0,{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(Bn,{className:"h-3 w-3"}),"Online Now",a.length>0&&e.jsx("span",{className:"ml-1 bg-green-500 text-white text-xs rounded-full px-1.5 py-0.5 min-w-[20px] text-center",children:a.length})]}),d?e.jsx(Po,{className:"h-4 w-4"}):e.jsx(Qa,{className:"h-4 w-4"})]})}),e.jsx(l0,{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(Ra,{className:"h-7 w-7",children:[e.jsx(Fi,{src:m.avatarUrl}),e.jsx(Da,{className:"text-xs",children:h(m.name)})]}),e.jsx(Sx,{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))})]})]})})})},zFs=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=j.useState(!1),o=d=>d.split(" ").map(u=>u[0]).join("").toUpperCase().slice(0,2),c=()=>{if(n==="all")return"All Posts";if(n.startsWith("group:")){const u=n.replace("group:",""),h=t.find(m=>m.id===u);return h?`🔒 ${h.name}`:"Private Group"}const d=s.find(u=>u.id===n);return d?`${d.icon||"📂"} ${d.name}`:"Category"};return e.jsxs("div",{className:"lg:hidden flex items-center gap-2 mb-4",children:[e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(Po,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(xd,{className:"w-56 bg-background border",children:[e.jsxs(wa,{onClick:()=>r("all"),children:[e.jsx(HT,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(uy,{}),e.jsx(TE,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(wa,{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(uy,{}),e.jsxs(TE,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(du,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(wa,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(v1,{open:i,onOpenChange:l,children:[e.jsx(yJ,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(Bn,{className:"h-4 w-4"}),a.length>0&&e.jsx("span",{className:"absolute -top-1 -right-1 bg-green-500 text-white text-xs rounded-full h-4 w-4 flex items-center justify-center",children:a.length})]})}),e.jsxs(rv,{children:[e.jsx(Lb,{children:e.jsxs(Pb,{className:"flex items-center gap-2",children:[e.jsx(Bn,{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(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:d.avatarUrl}),e.jsx(Da,{children:o(d.name)})]}),e.jsx(Sx,{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 iPe,jCe="HoverCard",[jMt,GBn]=Zm(jCe,[rS]),NCe=rS(),[BFs,ZHe]=jMt(jCe),NMt=s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=NCe(t),d=j.useRef(0),u=j.useRef(0),h=j.useRef(!1),m=j.useRef(!1),[p,x]=Mx({prop:r,defaultProp:a??!1,onChange:i,caller:jCe}),y=j.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>x(!0),l)},[l,x]),g=j.useCallback(()=>{clearTimeout(d.current),!h.current&&!m.current&&(u.current=window.setTimeout(()=>x(!1),o))},[o,x]),b=j.useCallback(()=>x(!1),[x]);return j.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(BFs,{scope:t,open:p,onOpenChange:x,onOpen:y,onClose:g,onDismiss:b,hasSelectionRef:h,isPointerDownOnContentRef:m,children:e.jsx(oJ,{...c,children:n})})};NMt.displayName=jCe;var kMt="HoverCardTrigger",SMt=j.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=ZHe(kMt,n),i=NCe(n);return e.jsx(FU,{asChild:!0,...i,children:e.jsx(Ua.a,{"data-state":a.open?"open":"closed",...r,ref:t,onPointerEnter:ua(s.onPointerEnter,Yke(a.onOpen)),onPointerLeave:ua(s.onPointerLeave,Yke(a.onClose)),onFocus:ua(s.onFocus,a.onOpen),onBlur:ua(s.onBlur,a.onClose),onTouchStart:ua(s.onTouchStart,l=>l.preventDefault())})})});SMt.displayName=kMt;var $Fs="HoverCardPortal",[WBn,UFs]=jMt($Fs,{forceMount:void 0}),Kke="HoverCardContent",CMt=j.forwardRef((s,t)=>{const n=UFs(Kke,s.__scopeHoverCard),{forceMount:r=n.forceMount,...a}=s,i=ZHe(Kke,s.__scopeHoverCard);return e.jsx(ax,{present:r||i.open,children:e.jsx(qFs,{"data-state":i.open?"open":"closed",...a,onPointerEnter:ua(s.onPointerEnter,Yke(i.onOpen)),onPointerLeave:ua(s.onPointerLeave,Yke(i.onClose)),ref:t})})});CMt.displayName=Kke;var qFs=j.forwardRef((s,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=ZHe(Kke,n),d=NCe(n),u=j.useRef(null),h=ko(t,u),[m,p]=j.useState(!1);return j.useEffect(()=>{if(m){const x=document.body;return iPe=x.style.userSelect||x.style.webkitUserSelect,x.style.userSelect="none",x.style.webkitUserSelect="none",()=>{x.style.userSelect=iPe,x.style.webkitUserSelect=iPe}}},[m]),j.useEffect(()=>{if(u.current){const x=()=>{p(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var g;((g=document.getSelection())==null?void 0:g.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",x),()=>{document.removeEventListener("pointerup",x),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),j.useEffect(()=>{u.current&&GFs(u.current).forEach(y=>y.setAttribute("tabindex","-1"))}),e.jsx(ZE,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:ua(i,x=>{x.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(lJ,{...d,...o,onPointerDown:ua(o.onPointerDown,x=>{x.currentTarget.contains(x.target)&&p(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:h,style:{...o.style,userSelect:m?"text":void 0,WebkitUserSelect:m?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),VFs="HoverCardArrow",HFs=j.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=NCe(n);return e.jsx(cJ,{...a,...r,ref:t})});HFs.displayName=VFs;function Yke(s){return t=>t.pointerType==="touch"?void 0:s()}function GFs(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 WFs=NMt,KFs=SMt,AMt=CMt;const YFs=WFs,ZFs=KFs,TMt=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(AMt,{ref:a,align:t,sideOffset:n,className:Et("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}));TMt.displayName=AMt.displayName;const XFs=[{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"}],QFs=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),EMt=({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(YFs,{openDelay:200,closeDelay:100,children:[e.jsx(ZFs,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(TMt,{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=XFs.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(Ra,{className:"h-6 w-6",children:[e.jsx(Fi,{src:l.user_avatar||void 0}),e.jsx(Da,{className:"text-[10px]",children:QFs(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 JFs({images:s,initialIndex:t=0,open:n,onOpenChange:r}){const[a,i]=j.useState(t),[l,o]=j.useState(!1);j.useEffect(()=>{n&&(i(t),o(!1))},[n,t]);const c=()=>{i(m=>m>0?m-1:s.length-1),o(!1)},d=()=>{i(m=>m{n&&(m.key==="ArrowLeft"&&c(),m.key==="ArrowRight"&&d(),m.key==="Escape"&&r(!1))},[n,s.length]);j.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const h=s[a];return e.jsx(Fs,{open:n,onOpenChange:r,children:e.jsxs(Os,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx(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(dr,{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(Cc,{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(pz,{className:"h-5 w-5"}):e.jsx(iE,{className:"h-5 w-5"})}),e.jsx("div",{className:Et("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:Et("object-contain transition-transform duration-200",l?"max-w-none max-h-none scale-150":"max-w-full max-h-[85vh]")})}),s.length>1&&e.jsx("div",{className:"absolute bottom-12 left-1/2 -translate-x-1/2 z-50 flex gap-2 bg-black/50 p-2 rounded-lg max-w-[90vw] overflow-x-auto",children:s.map((m,p)=>e.jsx("button",{onClick:()=>{i(p),o(!1)},className:Et("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===p?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:m.type==="video"?e.jsx("video",{src:m.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:m.url,alt:"",className:"w-full h-full object-cover"})},p))})]})})}const hne=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],e7s=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=as(),[a,i]=j.useState(!1),l=t.find(h=>h.user_id===n),o=vt({mutationFn:async h=>{l?l.reaction_type===h?await U.from("community_comment_reactions").delete().eq("id",l.id):await U.from("community_comment_reactions").update({reaction_type:h}).eq("id",l.id):await U.from("community_comment_reactions").insert({comment_id:s,user_id:n,reaction_type:h})},onSuccess:()=>{r.invalidateQueries({queryKey:["community-posts"]}),i(!1)}}),c={};return t.forEach(h=>{c[h.reaction_type]=(c[h.reaction_type]||0)+1}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&e.jsx(EMt,{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=hne.find(p=>p.type===h))==null?void 0:m.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(lc,{open:a,onOpenChange:i,children:[e.jsx(cc,{asChild:!0,children:e.jsx("button",{className:`text-xs hover:text-primary transition-colors ${l?"text-primary font-medium":"text-muted-foreground"}`,children:l?e.jsxs("span",{children:[(d=hne.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=hne.find(h=>h.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mo,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(Jl,{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:hne.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 XHe({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(Yn,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:Et("font-medium hover:underline",u?"text-white bg-[#2a4c64] px-1.5 py-0.5 rounded":"text-primary"),onClick:h=>h.stopPropagation(),children:u?c:`@${c}`},`mention-${l++}`))}else if(i[4]){const o=i[4],c=o.replace(/[.,;:!?)]+$/,""),d=o.slice(c.length);let u;try{const h=new URL(c);u=h.hostname+(h.pathname!=="/"?h.pathname.slice(0,20)+(h.pathname.length>20?"...":""):"")}catch{u=c.length>40?c.slice(0,40)+"...":c}r.push(e.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline break-all",onClick:h=>h.stopPropagation(),children:u},`url-${l++}`)),d&&r.push(d)}a=i.index+i[0].length}return ae.jsx(j.Fragment,{children:o},c))})}function Zke({value:s,onChange:t,placeholder:n="What's on your mind? Use @ to mention someone",className:r,minHeight:a="80px",onMentionsChange:i,onTemplatesChange:l,onKeyDown:o,mentionFormat:c="encoded",enableTemplateMentions:d=!1}){const u=j.useRef(null),h=j.useRef(null),[m,p]=j.useState(!1),[x,y]=j.useState("user"),[g,b]=j.useState(""),[v,k]=j.useState(null),[C,T]=j.useState(0),[M,P]=j.useState({top:0,left:0,width:0}),L=j.useRef(new Map),I=j.useRef(new Map),O=de=>{if(c==="plain"){const fe=[];return L.current.forEach((Ee,Le)=>{de.includes(`@${Le}`)&&fe.push(Ee)}),[...new Set(fe)]}const we=/@\[([^\]]+)\]\(([^)]+)\)/g,je=[];let xe;for(;(xe=we.exec(de))!==null;)je.push(xe[2]);return[...new Set(je)]},$=de=>{if(c==="plain"){const fe=[];return I.current.forEach((Ee,Le)=>{de.includes(`#${Le}`)&&fe.push(Ee)}),[...new Set(fe)]}const we=/#\[([^\]]+)\]\(([^)]+)\)/g,je=[];let xe;for(;(xe=we.exec(de))!==null;)je.push(xe[2]);return[...new Set(je)]};j.useEffect(()=>{if(i){const de=O(s);i(de)}if(l){const de=$(s);l(de)}},[s,i,l,c]);const{data:q=[],isLoading:W}=mt({queryKey:["mention-users",g],queryFn:async()=>{const de=U.from("profiles").select("id, name").limit(8),we=g.length>=1?de.ilike("name",`%${g}%`):de.order("name"),{data:je,error:xe}=await we;if(xe)throw xe;const fe=je.map(Ee=>Ee.id),Se=await R3t(fe);return je.map(Ee=>({id:Ee.id,name:Ee.name||"Unknown",avatar_url:Se.get(Ee.id)}))},enabled:m&&x==="user",staleTime:3e4}),{data:G=[],isLoading:K}=mt({queryKey:["mention-templates",g],queryFn:async()=>{let de=U.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);g.length>=1&&(de=de.ilike("name",`%${g}%`));const{data:we,error:je}=await de;if(je)throw je;return we||[]},enabled:m&&x==="template"&&d,staleTime:3e4}),ee=x==="user"?W:K,J=x==="user"?q:G,le=de=>de.split(" ").map(we=>we[0]).join("").toUpperCase().slice(0,2),ue=de=>{const we=de.target.value,je=de.target.selectionStart;t(we);const xe=we.substring(0,je),fe=xe.lastIndexOf("@"),Se=d?xe.lastIndexOf("#"):-1;let Ee=-1,Le="user";if(fe>Se?(Ee=fe,Le="user"):Se>fe&&d&&(Ee=Se,Le="template"),Ee!==-1){const De=xe.substring(Ee+1),Be=De.includes(" "),Ne=De.includes(` `);if(!Be&&!Ne&&De.length<=30){k(Ee),b(De),y(Le),p(!0),T(0);return}}p(!1),k(null)},oe=de=>{if(v===null)return;const we=s.substring(0,v),je=s.substring(v+g.length+1),xe=x==="user"?"@":"#",fe=c==="plain"?`${xe}${de.name} `:`${xe}[${de.name}](${de.id}) `;c==="plain"&&(x==="user"?L.current.set(de.name,de.id):I.current.set(de.name,de.id));const Se=we+fe+je;t(Se),p(!1),k(null),b(""),setTimeout(()=>{if(u.current){const Ee=we.length+fe.length;u.current.focus(),u.current.setSelectionRange(Ee,Ee)}},0)},ie=de=>{if(!(!m||J.length===0))switch(de.key){case"ArrowDown":de.preventDefault(),T(we=>(we+1)%J.length);break;case"ArrowUp":de.preventDefault(),T(we=>(we-1+J.length)%J.length);break;case"Enter":J[C]&&(de.preventDefault(),oe(J[C]));break;case"Escape":de.preventDefault(),p(!1);break;case"Tab":J[C]&&(de.preventDefault(),oe(J[C]));break}};return j.useEffect(()=>{const de=we=>{h.current&&!h.current.contains(we.target)&&u.current&&!u.current.contains(we.target)&&p(!1)};return document.addEventListener("mousedown",de),()=>document.removeEventListener("mousedown",de)},[]),j.useEffect(()=>{if(!m)return;const de=()=>{const we=u.current;if(!we)return;const je=we.getBoundingClientRect();P({top:je.bottom+4,left:je.left,width:je.width})};return de(),window.addEventListener("resize",de),window.addEventListener("scroll",de,!0),()=>{window.removeEventListener("resize",de),window.removeEventListener("scroll",de,!0)}},[m,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ds,{ref:u,value:s,onChange:ue,onKeyDown:de=>{ie(de),de.defaultPrevented||o==null||o(de)},placeholder:n,className:Et("resize-none",r),style:{minHeight:a}}),m&&Hv.createPortal(e.jsxs("div",{ref:h,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:M.top,left:M.left,width:M.width,maxWidth:"320px"},children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground border-b bg-muted/30",children:x==="user"?"👤 Mention a person":"📋 Link a template"}),ee?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):J.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:g.length<1?`Type to search ${x==="user"?"people":"templates"}...`:`No ${x==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:J.map((de,we)=>e.jsx("li",{className:Et("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",we===C?"bg-accent":"hover:bg-accent/50"),onClick:()=>oe(de),onMouseEnter:()=>T(we),children:x==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(Ra,{className:"h-6 w-6",children:[e.jsx(Fi,{src:de.avatar_url}),e.jsx(Da,{className:"text-xs",children:le(de.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:de.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:de.preview_image_url?e.jsx("img",{src:de.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(Ac,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:de.name})]})},de.id))})]}),document.body)]})}function t7s(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const Vlt=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function MMt({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=as(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState([]),x=vt({mutationFn:async({content:v,parentCommentId:k})=>{const{data:C,error:T}=await U.from("community_comments").insert({post_id:t,user_id:n,content:v,parent_comment_id:k}).select("id").single();if(T)throw T;const M=m;if(M.length>0&&C){const P=M.filter(L=>L!==n).map(L=>({comment_id:C.id,mentioned_user_id:L,mentioned_by_user_id:n}));P.length>0&&await U.from("community_comment_mentions").insert(P)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),h(""),p([]),d(!1)}}),y=vt({mutationFn:async v=>{const{error:k}=await U.from("community_comments").delete().eq("id",v);if(k)throw k},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),g=()=>{u.trim()&&x.mutate({content:u,parentCommentId:s.id})};return e.jsxs("div",{className:l>0?"ml-8 border-l-2 border-muted pl-3":"",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ra,{className:"h-8 w-8 shrink-0",children:[e.jsx(Fi,{src:s.user_avatar||void 0}),e.jsx(Da,{className:"text-xs",children:Vlt(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(XHe,{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:oc(new Date(s.created_at),{addSuffix:!0})}),e.jsx(e7s,{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(sK,{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(Ra,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(Fi,{src:r||void 0}),e.jsx(Da,{className:"text-xs",children:Vlt((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(Zke,{placeholder:`Reply to ${s.user_name}...`,value:u,onChange:h,onMentionsChange:p,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:g,disabled:!u.trim()||x.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(Dr,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(v=>e.jsx(MMt,{comment:v,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},v.id))})]})}const mne=[{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"}],s7s=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=Ns(),{avatarUrl:a}=I3t(s==null?void 0:s.id),{onlineUsers:i}=C2t(),{toast:l}=pi(),o=as(),c=j.useRef(null),[d,u]=j.useState("all"),[h,m]=j.useState(""),[p,x]=j.useState(""),[y,g]=j.useState(""),[b,v]=j.useState([]),[k,C]=j.useState([]),[T,M]=j.useState(""),[P,L]=j.useState(!1),[I,O]=j.useState(null),[$,q]=j.useState(""),[W,G]=j.useState(new Set),[K,ee]=j.useState({}),[J,le]=j.useState({}),[ue,oe]=j.useState([]),[ie,de]=j.useState([]),[we,je]=j.useState({open:!1,images:[],index:0});j.useEffect(()=>{if(d.startsWith("group:")){const pt=d.replace("group:","");g(pt),x("")}else d!=="all"?(x(d),g("")):(x(""),g(""))},[d]);const{data:xe=[]}=mt({queryKey:["community-categories"],queryFn:async()=>{const{data:pt,error:zt}=await U.from("community_categories").select("*").order("sort_order");if(zt)throw zt;return pt}}),{data:fe=[]}=mt({queryKey:["community-private-groups"],queryFn:async()=>{const{data:pt,error:zt}=await U.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(zt)throw zt;return pt}}),Se=20,{data:Ee,isLoading:Le,hasNextPage:De,fetchNextPage:Be,isFetchingNextPage:Ne}=uss({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:pt})=>{var it;const zt=pt*Se,Gt=zt+Se;let qs=U.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(zt,Gt);if(d.startsWith("group:")){const gt=d.replace("group:","");qs=qs.eq("private_group_id",gt)}else d==="all"||(qs=qs.eq("category_id",d).is("private_group_id",null));const{data:As,error:Bt}=await qs;if(Bt)throw Bt;const At=((As==null?void 0:As.length)||0)>Se,Is=(As||[]).slice(0,Se);if(Is.length===0)return{posts:[],hasMore:!1,nextPage:pt+1};const jt=Is.map(gt=>gt.id),Qs=[...new Set(Is.filter(gt=>gt.category_id).map(gt=>gt.category_id))].filter(Boolean),[cn,qt,Gs,Ls,sn]=await Promise.all([Qs.length?U.from("community_categories").select("*").in("id",Qs):Promise.resolve({data:[]}),U.from("community_post_media").select("*").in("post_id",jt).order("sort_order"),U.from("community_reactions").select("*").in("post_id",jt),U.from("community_comments").select("*").in("post_id",jt).order("created_at",{ascending:!0}),U.from("community_post_resources").select("*").in("post_id",jt)]),Hs=cn==null?void 0:cn.data,nn=qt==null?void 0:qt.data,tn=Gs==null?void 0:Gs.data,_n=Ls==null?void 0:Ls.data,Cn=sn==null?void 0:sn.data,Un=(_n||[]).map(gt=>gt.id),[Kr,jr]=await Promise.all([Un.length?U.from("community_comment_reactions").select("*").in("comment_id",Un):Promise.resolve({data:[]}),(()=>{const gt=(Cn||[]).filter(St=>St.resource_type==="template").map(St=>St.resource_id);return gt.length===0?Promise.resolve({data:[]}):U.from("canva_templates").select("id, name, preview_image_url").in("id",gt)})()]),Xs=(Kr==null?void 0:Kr.data)||[],Ba=(jr==null?void 0:jr.data)||[],Hr=new Map(Ba.map(gt=>[gt.id,{name:gt.name,preview_image_url:gt.preview_image_url}])),mr=Array.from(new Set([...Is.map(gt=>gt.user_id),...(tn||[]).map(gt=>gt.user_id),...(_n||[]).map(gt=>gt.user_id),...Xs.map(gt=>gt.user_id)])),[pr,rn]=await Promise.all([mr.length?U.from("profiles").select("id, name").in("id",mr):Promise.resolve({data:[]}),R3t(mr)]),Jn=new Map(((it=pr==null?void 0:pr.data)==null?void 0:it.map(gt=>[gt.id,gt.name]))||[]),ea=new Map((Hs||[]).map(gt=>[gt.id,gt])),_s=gt=>{const St=new Map,Ht=[];return gt.forEach(ts=>{St.set(ts.id,{...ts,user_name:Jn.get(ts.user_id)||"Unknown User",user_avatar:rn.get(ts.user_id),reactions:Xs.filter(Ms=>Ms.comment_id===ts.id).map(Ms=>({...Ms,user_name:Jn.get(Ms.user_id)||"Unknown User",user_avatar:rn.get(Ms.user_id)})),replies:[]})}),gt.forEach(ts=>{const Ms=St.get(ts.id);if(ts.parent_comment_id&&St.has(ts.parent_comment_id)){const js=St.get(ts.parent_comment_id);js.replies=js.replies||[],js.replies.push(Ms)}else Ht.push(Ms)}),Ht};return{posts:Is.map(gt=>{const St=(Cn||[]).filter(Ht=>Ht.post_id===gt.id).map(Ht=>{let ts="",Ms=null;if(Ht.resource_type==="template"){const js=Hr.get(Ht.resource_id);ts=(js==null?void 0:js.name)||"Unknown Template",Ms=(js==null?void 0:js.preview_image_url)||null}return{id:Ht.id,resource_type:Ht.resource_type,resource_id:Ht.resource_id,resource_name:ts,resource_preview_url:Ms}});return{...gt,user_name:Jn.get(gt.user_id)||"Unknown User",user_avatar:rn.get(gt.user_id),category:gt.category_id?ea.get(gt.category_id):null,media:(nn||[]).filter(Ht=>Ht.post_id===gt.id),reactions:((tn||[]).filter(Ht=>Ht.post_id===gt.id)||[]).map(Ht=>({...Ht,user_name:Jn.get(Ht.user_id)||"Unknown User",user_avatar:rn.get(Ht.user_id)})),comments:_s((_n||[]).filter(Ht=>Ht.post_id===gt.id)),resources:St}}),hasMore:At,nextPage:pt+1}},getNextPageParam:pt=>pt.hasMore?pt.nextPage:void 0}),Ge=j.useMemo(()=>(Ee==null?void 0:Ee.pages.flatMap(pt=>pt.posts))??[],[Ee]),_e=vt({mutationFn:async()=>{L(!0);const{data:pt,error:zt}=await U.from("community_posts").insert({user_id:s.id,category_id:y?null:p||null,private_group_id:y||null,content:h,link_url:T||null}).select().single();if(zt)throw zt;for(let qs=0;qs0){const qs=ue.filter(As=>As!==s.id).map(As=>({post_id:pt.id,mentioned_user_id:As,mentioned_by_user_id:s.id}));qs.length>0&&await U.from("community_post_mentions").insert(qs)}const Gt=t7s(h);if(Gt.length>0){const qs=Gt.map(As=>({post_id:pt.id,resource_type:"template",resource_id:As}));await U.from("community_post_resources").insert(qs)}return pt},onSuccess:async pt=>{var zt;o.invalidateQueries({queryKey:["community-posts"]}),m(""),oe([]),de([]),x(""),g(""),v([]),C([]),M(""),l({title:"Post created!"});try{const Gt=((zt=s==null?void 0:s.user_metadata)==null?void 0:zt.name)||"Someone",qs=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),As=qs.length>50?qs.substring(0,50)+"...":qs;await U.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${Gt}: ${As}`,url:"/community"}})}catch(Gt){console.error("Failed to send push notification:",Gt)}},onError:pt=>{l({title:"Error creating post",description:pt.message,variant:"destructive"})},onSettled:()=>L(!1)}),Oe=vt({mutationFn:async({postId:pt,content:zt})=>{const{error:Gt}=await U.from("community_posts").update({content:zt}).eq("id",pt);if(Gt)throw Gt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),O(null),q(""),l({title:"Post updated!"})}}),Ae=vt({mutationFn:async pt=>{const{error:zt}=await U.from("community_posts").delete().eq("id",pt);if(zt)throw zt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),Xe=vt({mutationFn:async({postId:pt,isPinned:zt})=>{const{error:Gt}=await U.from("community_posts").update({is_pinned:!zt,pinned_at:zt?null:new Date().toISOString(),pinned_by:zt?null:s==null?void 0:s.id}).eq("id",pt);if(Gt)throw Gt},onSuccess:(pt,{isPinned:zt})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:zt?"Post unpinned":"Post pinned to top"})}}),Ue=vt({mutationFn:async({postId:pt,reactionType:zt})=>{var qs;const Gt=(qs=Ge.find(As=>As.id===pt))==null?void 0:qs.reactions.find(As=>As.user_id===(s==null?void 0:s.id));Gt?Gt.reaction_type===zt?await U.from("community_reactions").delete().eq("id",Gt.id):await U.from("community_reactions").update({reaction_type:zt}).eq("id",Gt.id):await U.from("community_reactions").insert({post_id:pt,user_id:s.id,reaction_type:zt})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Ze=vt({mutationFn:async({postId:pt,content:zt})=>{const{data:Gt,error:qs}=await U.from("community_comments").insert({post_id:pt,user_id:s.id,content:zt}).select("id").single();if(qs)throw qs;const As=J[pt]||[];if(As.length>0&&Gt){const Bt=As.filter(At=>At!==s.id).map(At=>({comment_id:Gt.id,mentioned_user_id:At,mentioned_by_user_id:s.id}));Bt.length>0&&await U.from("community_comment_mentions").insert(Bt)}},onSuccess:(pt,{postId:zt})=>{o.invalidateQueries({queryKey:["community-posts"]}),ee(Gt=>({...Gt,[zt]:""})),le(Gt=>({...Gt,[zt]:[]}))}});vt({mutationFn:async pt=>{const{error:zt}=await U.from("community_comments").delete().eq("id",pt);if(zt)throw zt},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const Qe=pt=>{const zt=Array.from(pt.target.files||[]);if(zt.length+b.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}v(Gt=>[...Gt,...zt]),zt.forEach(Gt=>{const qs=new FileReader;qs.onloadend=()=>{C(As=>[...As,qs.result])},qs.readAsDataURL(Gt)})},Ye=pt=>{v(zt=>zt.filter((Gt,qs)=>qs!==pt)),C(zt=>zt.filter((Gt,qs)=>qs!==pt))},nt=pt=>pt.split(" ").map(zt=>zt[0]).join("").toUpperCase().slice(0,2),rt=pt=>{const zt={};return pt.forEach(Gt=>{zt[Gt.reaction_type]=(zt[Gt.reaction_type]||0)+1}),zt},Fe=pt=>{var zt;return(zt=pt.find(Gt=>Gt.user_id===(s==null?void 0:s.id)))==null?void 0:zt.reaction_type},dt=pt=>pt.reduce((zt,Gt)=>zt+1+(Gt.replies?dt(Gt.replies):0),0),Dt=pt=>{if(r)return!0;if(!t||!pt.private_group_id)return!1;const zt=fe.find(Gt=>Gt.id===pt.private_group_id);return zt!=null&&zt.brokerage_id?n.some(Gt=>Gt.id===zt.brokerage_id):!1};return e.jsx(Vs,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(FFs,{categories:xe,privateGroups:fe,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-2xl mx-auto lg:mx-0 space-y-6",children:[e.jsxs("div",{className:"px-1",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-foreground",children:"Community"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Connect and share with fellow agents"})]}),e.jsx(zFs,{categories:xe,privateGroups:fe,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:a||void 0}),e.jsx(Da,{children:s!=null&&s.email?nt(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(Zke,{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:oe,onTemplatesChange:de,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),k.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:k.map((pt,zt)=>{var Gt;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Gt=b[zt])!=null&&Gt.type.startsWith("video/")?e.jsx("video",{src:pt,className:"w-full h-full object-cover"}):e.jsx("img",{src:pt,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:()=>Ye(zt),children:e.jsx(dr,{className:"h-3 w-3"})})]},zt)})}),T&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:T,onChange:pt=>M(pt.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>M(""),children:e.jsx(dr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[e.jsx("input",{type:"file",ref:c,onChange:Qe,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var pt;return(pt=c.current)==null?void 0:pt.click()},children:[e.jsx(ac,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var pt;return(pt=c.current)==null?void 0:pt.click()},children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>M("https://"),children:[e.jsx(vc,{className:"h-4 w-4 mr-1"}),"Link"]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end",children:[fe.length>0?e.jsxs(vs,{value:y||p||"none",onValueChange:pt=>{pt==="none"?(x(""),g("")):pt.startsWith("group:")?(g(pt.replace("group:","")),x("")):(x(pt),g(""))},children:[e.jsx(gs,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(bs,{placeholder:"Select..."})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No category"}),xe.map(pt=>e.jsxs(Je,{value:pt.id,children:[pt.icon," ",pt.name]},pt.id)),fe.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 py-1 text-xs font-semibold text-muted-foreground border-t mt-1 pt-1",children:"🔒 Private Groups"}),fe.map(pt=>e.jsxs(Je,{value:`group:${pt.id}`,children:[pt.icon||"🔒"," ",pt.name]},pt.id))]})]})]}):e.jsxs(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(bs,{placeholder:"Category"})}),e.jsx(ys,{children:xe.map(pt=>e.jsxs(Je,{value:pt.id,children:[pt.icon," ",pt.name]},pt.id))})]}),e.jsxs(B,{size:"sm",onClick:()=>_e.mutate(),disabled:!h.trim()||P,children:[e.jsx(Dr,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Le?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((pt,zt)=>e.jsx(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(gn,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(gn,{className:"h-4 w-32"}),e.jsx(gn,{className:"h-4 w-full"}),e.jsx(gn,{className:"h-4 w-3/4"})]})]})})},zt))}):Ge.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center",children:[e.jsx(Yd,{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(pt=>{var zt,Gt,qs,As;return e.jsx(be,{children:e.jsxs(Re,{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(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:pt.user_avatar||void 0}),e.jsx(Da,{children:nt(pt.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:pt.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:oc(new Date(pt.created_at),{addSuffix:!0})}),pt.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(qe,{variant:"secondary",className:"text-xs",children:[pt.category.icon," ",pt.category.name]})]})]})]})]}),(pt.user_id===(s==null?void 0:s.id)||Dt(pt))&&e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Hy,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[Dt(pt)&&pt.private_group_id&&e.jsx(wa,{onClick:()=>Xe.mutate({postId:pt.id,isPinned:pt.is_pinned}),children:pt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(JW,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(JT,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),pt.user_id===(s==null?void 0:s.id)&&e.jsxs(wa,{onClick:()=>{O(pt),q(pt.content)},children:[e.jsx(Za,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(wa,{className:"text-destructive",onClick:()=>Ae.mutate(pt.id),children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"}),pt.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),pt.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(JT,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(XHe,{content:pt.content})}),pt.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${pt.media.length===1?"grid-cols-1":pt.media.length===2?"grid-cols-2":pt.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:pt.media.slice(0,4).map((Bt,At)=>{const Is=At===3&&pt.media.length>4,jt=pt.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${pt.media.length===1?"max-h-[500px]":pt.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>je({open:!0,images:pt.media.map(Qs=>({url:Qs.media_url,type:Qs.media_type==="video"?"video":"image"})),index:At}),children:[Bt.media_type==="video"?e.jsx("video",{src:Bt.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:Bt.media_url,alt:"",className:"w-full h-full object-cover transition-transform group-hover:scale-105"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center",children:e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity text-white",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"})})})}),Is&&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:["+",jt]})})]},Bt.id)})}),pt.link_url&&e.jsxs("a",{href:pt.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[pt.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:pt.link_image,alt:pt.link_title||"Link preview",className:"w-full h-full object-cover",onError:Bt=>{Bt.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:pt.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:pt.link_title}),pt.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:pt.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(pt.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(vc,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:pt.link_url})]})})]}),pt.reactions.length>0&&e.jsx(EMt,{reactions:pt.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(pt.reactions)).slice(0,3).map(([Bt])=>{var At;return e.jsx("span",{className:"text-base",children:(At=mne.find(Is=>Is.type===Bt))==null?void 0:At.emoji},Bt)})}),e.jsx("span",{children:pt.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",children:[Fe(pt.reactions)?e.jsx("span",{className:"mr-1",children:(zt=mne.find(Bt=>Bt.type===Fe(pt.reactions)))==null?void 0:zt.emoji}):e.jsx(mg,{className:"h-4 w-4 mr-1"}),Fe(pt.reactions)?(Gt=mne.find(Bt=>Bt.type===Fe(pt.reactions)))==null?void 0:Gt.label:"Like"]})}),e.jsx(Jl,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:mne.map(Bt=>e.jsx("button",{onClick:()=>Ue.mutate({postId:pt.id,reactionType:Bt.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:Bt.label,children:Bt.emoji},Bt.type))})})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>G(Bt=>{const At=new Set(Bt);return At.has(pt.id)?At.delete(pt.id):At.add(pt.id),At}),children:[e.jsx(Yd,{className:"h-4 w-4 mr-1"}),(()=>{const Bt=dt(pt.comments);return Bt>0?`Comment (${Bt})`:"Comment"})()]})]}),W.has(pt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[pt.comments.map(Bt=>e.jsx(MMt,{comment:Bt,postId:pt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:Dt(pt)},Bt.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:a||void 0}),e.jsx(Da,{className:"text-xs",children:nt(((qs=s.email)==null?void 0:qs.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(Zke,{placeholder:"Write a comment... (use @ to mention)",value:K[pt.id]||"",onChange:Bt=>ee(At=>({...At,[pt.id]:Bt})),onMentionsChange:Bt=>le(At=>({...At,[pt.id]:Bt})),mentionFormat:"plain",onKeyDown:Bt=>{var At;Bt.defaultPrevented||Bt.key==="Enter"&&!Bt.shiftKey&&((At=K[pt.id])!=null&&At.trim())&&(Bt.preventDefault(),Ze.mutate({postId:pt.id,content:K[pt.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var Bt;(Bt=K[pt.id])!=null&&Bt.trim()&&Ze.mutate({postId:pt.id,content:K[pt.id]})},disabled:!((As=K[pt.id])!=null&&As.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(Dr,{className:"h-4 w-4"})})]})]})]})]})},pt.id)}),De&&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(Fs,{open:!!I,onOpenChange:()=>O(null),children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Edit Post"})}),e.jsx(Ds,{value:$,onChange:pt=>q(pt.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>O(null),children:"Cancel"}),e.jsx(B,{onClick:()=>{I&&Oe.mutate({postId:I.id,content:$})},disabled:!$.trim(),children:"Save Changes"})]})]})}),e.jsx(JFs,{images:we.images,initialIndex:we.index,open:we.open,onOpenChange:pt=>je(zt=>({...zt,open:pt}))})]})]})})},n7s=50*1024*1024;function LMt({value:s,onChange:t,disabled:n}){const{user:r}=Ns(),a=j.useRef(null),[i,l]=j.useState(!1),o=async d=>{if(!d||!r)return;const u=[];l(!0);try{for(const h of Array.from(d)){if(!h.type.startsWith("image/")&&!h.type.startsWith("video/")){re.error(`${h.name}: only images and videos allowed`);continue}if(h.size>n7s){re.error(`${h.name}: must be under 50MB`);continue}const m=h.name.split(".").pop()||"bin",p=`${r.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${m}`,{error:x}=await U.storage.from("support-attachments").upload(p,h,{contentType:h.type,upsert:!1});if(x){re.error(`${h.name}: ${x.message}`);continue}u.push({path:p,type:h.type,name:h.name,size:h.size})}u.length&&t([...s,...u])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const u=s[d];t(s.filter((h,m)=>m!==d)),await U.storage.from("support-attachments").remove([u.path])};return e.jsxs("div",{className:"space-y-2",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md border bg-muted/40 text-xs",children:[d.type.startsWith("video/")?e.jsx(FW,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(g3,{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(dr,{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(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ZT,{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 PMt({attachments:s}){const[t,n]=j.useState({}),[r,a]=j.useState(!0);return j.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await U.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,u)=>{d.signedUrl&&(c[l[u]]=d.signedUrl)}),n(c),a(!1)})(),()=>{i=!0}},[s]),s!=null&&s.length?r?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-2",children:[e.jsx(Wt,{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 XF={open:{label:"Open",icon:Vr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Yd,color:"bg-blue-500"},resolved:{label:"Resolved",icon:To,color:"bg-green-500"},closed:{label:"Closed",icon:Rd,color:"bg-muted-foreground"}},Hlt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function r7s(){const{user:s}=Ns(),t=as(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState([]),{data:c=[],isLoading:d}=mt({queryKey:["support-tickets"],queryFn:async()=>{const{data:p,error:x}=await U.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(x)throw x;return p},enabled:!!s}),{data:u=[]}=mt({queryKey:["ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:p,error:x}=await U.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(x)throw x;return p},enabled:!!n}),h=vt({mutationFn:async({content:p,attachments:x})=>{if(!n||!s)throw new Error("Missing data");const{error:y}=await U.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:p,is_admin_reply:!1,attachments:x});if(y)throw y},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",n==null?void 0:n.id]}),i(""),o([]),re.success("Reply sent!")},onError:()=>{re.error("Failed to send reply")}}),m=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const p=XF[n.status].icon;return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(_a,{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(qe,{variant:"secondary",children:Hlt[n.category]}),e.jsxs(qe,{className:XF[n.status].color,children:[e.jsx(p,{className:"h-3 w-3 mr-1"}),XF[n.status].label]})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(fr,{children:["Created on ",Bs(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Re,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Conversation"})}),e.jsxs(Re,{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(x=>{var y;return e.jsxs("div",{className:`p-4 rounded-lg ${x.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:x.is_admin_reply?"Support Team":((y=x.profiles)==null?void 0:y.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Bs(new Date(x.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:x.content}),x.attachments&&x.attachments.length>0&&e.jsx(PMt,{attachments:x.attachments})]},x.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(Xl,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ds,{placeholder:"Type your reply...",value:a,onChange:x=>i(x.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(Dr,{className:"h-4 w-4"})})]}),e.jsx(LMt,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(be,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Re,{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(c5,{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(EOe,{trigger:e.jsxs(B,{size:"lg",className:"gap-2",children:[e.jsx(Js,{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(pa,{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(EOe,{trigger:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(Js,{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(be,{className:"border-dashed",children:e.jsxs(Re,{className:"text-center py-12",children:[e.jsx(Yd,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't submitted any support tickets. Use the button above to get started!"})]})}):e.jsx("div",{className:"space-y-3",children:c.map(p=>{const x=XF[p.status].icon;return e.jsx(be,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(p),children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:p.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(qe,{variant:"outline",className:"text-xs",children:Hlt[p.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Bs(new Date(p.created_at),"MMM d, yyyy")})]})]}),e.jsxs(qe,{className:XF[p.status].color,children:[e.jsx(x,{className:"h-3 w-3 mr-1"}),XF[p.status].label]})]})})},p.id)})})]})})}function a7s({open:s,onOpenChange:t}){return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx($s,{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(ra,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zs,{children:"Schedule Agent Onboarding"}),e.jsx(kr,{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 i7s({open:s,onOpenChange:t}){const{brokerageId:n}=Ns(),[r,a]=j.useState(""),[i,l]=j.useState([]),[o,c]=j.useState(!1),{data:d,isLoading:u}=mt({queryKey:["brokerage-agents-for-onboarding",n],queryFn:async()=>{if(!n)return[];const{data:y,error:g}=await U.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(g)throw g;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(g=>g.includes(y)?g.filter(b=>b!==y):[...g,y])},p=async()=>{if(i.length===0){re.error("Please select at least one agent");return}c(!0);try{const{data:y,error:g}=await U.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(g)throw g;re.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(y){console.error("Error sending onboarding link:",y),re.error(y.message||"Failed to send onboarding link")}finally{c(!1)}},x=y=>{y||(l([]),a("")),t(y)};return e.jsx(Fs,{open:s,onOpenChange:x,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx($s,{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(Dr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zs,{children:"Send Onboarding Link"}),e.jsx(kr,{children:"Select agents to receive the onboarding booking link"})]})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{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(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(h==null?void 0:h.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Bn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(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(wi,{checked:i.includes(y.id),onCheckedChange:()=>m(y.id)}),e.jsx(Ra,{className:"h-8 w-8",children:e.jsx(Da,{className:"text-xs",children:y.name.split(" ").map(g=>g[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(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx(B,{onClick:p,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function o7s(){const[s,t]=j.useState(!1),[n,r]=j.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(be,{className:"mb-8",children:[e.jsx(Ft,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Bn,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ut,{children:"Agent Onboarding"}),e.jsx(fr,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Re,{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(ra,{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(Dr,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(a7s,{open:s,onOpenChange:t}),e.jsx(i7s,{open:n,onOpenChange:r})]})}function l7s({open:s,onOpenChange:t}){return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx($s,{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(oy,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zs,{children:"Schedule Launch Meeting"}),e.jsx(kr,{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 c7s(){const[s,t]=j.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(be,{className:"mb-8",children:[e.jsx(Ft,{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(oy,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ut,{children:"Launch or ReLaunch Meeting"}),e.jsx(fr,{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(Re,{children:e.jsxs(B,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(oy,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(l7s,{open:s,onOpenChange:t})]})}function d7s(){const s=Hn(),[t,n]=j.useState(""),[r,a]=j.useState(null),{data:i,isLoading:l}=mt({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:y,error:g}=await U.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(g)throw g;return y}}),{data:o}=mt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:y,error:g}=await U.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(g)throw g;return y}}),{data:c}=mt({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:y,error:g}=await U.from("brokerage_resource_pdfs").select("resource_id");if(g)throw g;return y}}),{data:d}=mt({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:y,error:g}=await U.from("brokerage_resource_videos").select("resource_id");if(g)throw g;return y}}),{data:u}=mt({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:y,error:g}=await U.from("brokerage_resource_links").select("resource_id");if(g)throw g;return y}}),h=i==null?void 0:i.filter(y=>{var v;const g=y.title.toLowerCase().includes(t.toLowerCase())||((v=y.description)==null?void 0:v.toLowerCase().includes(t.toLowerCase())),b=!r||y.category_id===r;return g&&b}),m=o==null?void 0:o.filter(y=>i==null?void 0:i.some(g=>g.category_id===y.id)),p=y=>{const g=(c==null?void 0:c.filter(k=>k.resource_id===y).length)||0,b=(d==null?void 0:d.filter(k=>k.resource_id===y).length)||0,v=(u==null?void 0:u.filter(k=>k.resource_id===y).length)||0;return{pdfCount:g,videoCount:b,linkCount:v}},x=y=>{s(`/brokerage-resources/${y}`)};return e.jsx(Vs,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(o7s,{}),e.jsx(c7s,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{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(qe,{variant:r===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),m.map(y=>e.jsx(qe,{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,g)=>e.jsxs(be,{children:[e.jsx(gn,{className:"h-40 w-full"}),e.jsx(Ft,{children:e.jsx(gn,{className:"h-5 w-3/4"})}),e.jsxs(Re,{children:[e.jsx(gn,{className:"h-4 w-full mb-2"}),e.jsx(gn,{className:"h-4 w-2/3"})]})]},g))}):(h==null?void 0:h.length)===0?e.jsxs(be,{className:"p-12 text-center",children:[e.jsx(kx,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resources found"}),e.jsx("p",{className:"text-muted-foreground",children:t||r?"Try adjusting your filters":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:h==null?void 0:h.map(y=>{const{pdfCount:g,videoCount:b,linkCount:v}=p(y.id),k=o==null?void 0:o.find(C=>C.id===y.category_id);return e.jsxs(be,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>x(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(kx,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(Ft,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(Ut,{className:"text-lg line-clamp-1",children:y.title}),k&&e.jsx(qe,{variant:"secondary",className:"shrink-0 text-xs",children:k.name})]})}),e.jsxs(Re,{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:[g>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($r,{className:"h-4 w-4"}),g]}),b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-4 w-4"}),b]}),v>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vc,{className:"h-4 w-4"}),v]})]})]})]},y.id)})})]})})}const u7s=()=>{const{resourceId:s}=$i(),{data:t,isLoading:n}=mt({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await U.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await U.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await U.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await U.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),r=a=>a?a<1024?a+" B":a<1024*1024?(a/1024).toFixed(1)+" KB":(a/(1024*1024)).toFixed(1)+" MB":"";return n?e.jsx(Vs,{title:"Brokerage Resources",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):t?e.jsx(Vs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/brokerage-resources",children:[e.jsx(_a,{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(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Zr,{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(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx($r,{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($r,{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(ii,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(be,{children:e.jsxs(Re,{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(Vs,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(kx,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(Yn,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function h7s(){const{onlineUsers:s,totalOnline:t}=C2t();return e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(qe,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(Sx,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Re,{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(Ra,{className:"h-9 w-9",children:[e.jsx(Fi,{src:n.avatarUrl,alt:n.name}),e.jsx(Da,{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 ",oc(new Date(n.onlineSince),{addSuffix:!1})]})]})]},n.id)})})})})]})}const Glt={users:{label:"Users & Access",sections:[{title:"Member Broadcasts",description:"Email a filtered group of members (paste HTML or write it)",icon:jh,path:"/admin/broadcasts",color:"bg-rose-500/10 text-rose-600"},{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:Bn,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:mK,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:ty,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:IW,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:wf,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:zd,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:Bn,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:uu,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:Sl,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:ll,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:Ac,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:Uh,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:Uh,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:O5,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:yn,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:yn,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:V_,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:V_,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:Vc,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:iy,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:kx,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:kx,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:on,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:jh,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:BR,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:k_,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:on,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:jh,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:x3,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:D5,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:zo,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:ll,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:Rc,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:Bn,path:"/admin/agent-cards",color:"bg-gradient-to-br from-violet-500/20 to-purple-500/10 text-violet-600"},{title:"Notification Settings",description:"Test and manage push notifications",icon:jh,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:ro,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:q9,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:xN,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:on,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:ol,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:Op,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:yb,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:Uh,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:mo,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:ia,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:Sl,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:Sl,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:yb,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:$r,path:"/admin/listing-presentation-studio",color:"bg-gradient-to-br from-slate-500/20 to-zinc-500/10 text-slate-600"},{title:"Listing Revival",description:"Track expired-listing campaigns, seller leads, and manage who has access",icon:yn,path:"/admin/listing-revival",color:"bg-gradient-to-br from-amber-500/20 to-yellow-500/10 text-amber-600"},{title:"Weekly Reels",description:"Manage Weekly Reels access, generation runs, and email delivery",icon:wh,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:Op,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:ac,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:on,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:VT,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:Ql,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:RW,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:kl,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:$r,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:$r,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:Od,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function Wlt(){const s=Hn();return console.log("[AdminDashboard] render"),e.jsx(Vs,{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(h7s,{})})]}),e.jsxs(fa,{defaultValue:"users",className:"w-full",children:[e.jsx(xa,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(Glt).map(([t,n])=>e.jsx(ss,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(Glt).map(([t,n])=>e.jsx(ns,{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(be,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(r.path),children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center ${r.color} mb-2 group-hover:scale-110 transition-transform`,children:e.jsx(r.icon,{className:"h-5 w-5"})}),e.jsx(Ut,{className:"text-base",children:r.title})]}),e.jsx(Re,{className:"pt-0",children:e.jsx(fr,{className:"text-sm",children:r.description})})]},r.path))})},t))]})]})})}const m7s=()=>{const{isAdmin:s}=Ns(),t=Hn(),[n,r]=j.useState([]),[a,i]=j.useState(!0),[l,o]=j.useState(!1),[c,d]=j.useState(null);j.useEffect(()=>{if(!s){t("/dashboard");return}u()},[s]);const u=async()=>{try{const{data:y,error:g}=await U.from("app_tiles").select("*").order("name");if(g)throw g;r(y||[])}catch(y){console.error("Error loading apps:",y),re.error("Failed to load apps")}finally{i(!1)}},h=async y=>{y.preventDefault();const g=new FormData(y.currentTarget),b={name:g.get("name"),description:g.get("description"),icon:g.get("icon"),app_id:g.get("app_id"),target_url:g.get("target_url"),required_tags:g.get("required_tags").split(",").map(v=>v.trim()).filter(Boolean)};try{if(c){const{error:v}=await U.from("app_tiles").update(b).eq("id",c.id);if(v)throw v;re.success("App updated successfully")}else{const{error:v}=await U.from("app_tiles").insert([b]);if(v)throw v;re.success("App created successfully")}o(!1),d(null),u()}catch(v){console.error("Error saving app:",v),re.error("Failed to save app")}},m=async y=>{if(await Bi("Are you sure you want to delete this app?"))try{const{error:g}=await U.from("app_tiles").delete().eq("id",y);if(g)throw g;re.success("App deleted successfully"),u()}catch(g){console.error("Error deleting app:",g),re.error("Failed to delete app")}},p=y=>{d(y),o(!0)},x=()=>{d(null),o(!0)};return a?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(_a,{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(Fs,{open:l,onOpenChange:o,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{onClick:x,children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs($s,{children:[e.jsx(zs,{children:c?"Edit App":"Create New App"}),e.jsx(kr,{children:"Configure the application tile settings"})]}),e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"App Name"}),e.jsx(ye,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"app_id",children:"App ID"}),e.jsx(ye,{id:"app_id",name:"app_id",defaultValue:c==null?void 0:c.app_id,placeholder:"agent_connect",required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ds,{id:"description",name:"description",defaultValue:c==null?void 0:c.description})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(ye,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"target_url",children:"Target URL"}),e.jsx(ye,{id:"target_url",name:"target_url",type:"url",defaultValue:c==null?void 0:c.target_url,required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(ye,{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(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Application Tiles"}),e.jsx(fr,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Re,{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:x,children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"App ID"}),e.jsx(Tt,{children:"Target URL"}),e.jsx(Tt,{children:"Tags"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:n.map(y=>e.jsxs(un,{children:[e.jsx(xt,{className:"text-2xl",children:y.icon}),e.jsx(xt,{className:"font-medium",children:y.name}),e.jsx(xt,{className:"font-mono text-sm",children:y.app_id}),e.jsx(xt,{className:"text-sm text-muted-foreground max-w-xs truncate",children:y.target_url}),e.jsx(xt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:y.required_tags.map(g=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:g},g))})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(y),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(y.id),children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},y.id))})]})})]})})]})};function oh({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Yn,{to:"/admin",children:e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(_a,{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 Klt=({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(qe,{variant:"destructive",className:Et("gap-1",t),children:[e.jsx(hd,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(qe,{variant:"destructive",className:Et("gap-1",t),children:[e.jsx(Vr,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(qe,{className:Et("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(Vr,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(qe,{variant:"secondary",className:Et("gap-1",t),children:[e.jsx(Vr,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},IMt=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=pi(),l=j.useRef(null),[o,c]=j.useState([]),[d,u]=j.useState(""),[h,m]=j.useState(!1),[p,x]=j.useState("upload"),[y,g]=j.useState(null),b=()=>{c([]),u(""),x("upload"),g(null),l.current&&(l.current.value="")},v=()=>{b(),t(!1)},k=L=>{const I=L.split(` `).map(G=>G.trim()).filter(G=>G);if(I.length===0)return[];const O=I[0].toLowerCase(),q=O.includes("first")||O.includes("last")||O.includes("email")||O.includes("name")||O.includes("phone")||O.includes("sms")||O.includes("consent")?I.slice(1):I,W=[];for(const G of q){const ee=(G.includes(" ")?G.split(" "):G.split(",")).map(J=>J.trim().replace(/^["']|["']$/g,""));if(ee.length>=2){let J="",le="",ue="",oe="",ie;if(ee.length===2){const je=ee[0].split(" ");J=je[0]||"",le=je.slice(1).join(" ")||"",ue=ee[1]}else if(ee.length===3)J=ee[0],le=ee[1],ue=ee[2];else if(ee.length===4)J=ee[0],le=ee[1],ue=ee[2],oe=ee[3];else if(ee.length>=5){J=ee[0],le=ee[1],ue=ee[2],oe=ee[3];const je=ee[4].toLowerCase();ie=je==="true"||je==="yes"||je==="1"||je==="y"}const we=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ue);W.push({firstName:J.trim(),lastName:le.trim(),email:ue.trim().toLowerCase(),phone:oe.trim()||void 0,smsConsent:ie,isValid:we&&J.trim().length>0,error:we?J.trim()?void 0:"Missing name":"Invalid email"})}}return W},C=L=>{var $;const I=($=L.target.files)==null?void 0:$[0];if(!I)return;const O=new FileReader;O.onload=q=>{var K;const W=(K=q.target)==null?void 0:K.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),x("preview")},O.readAsText(I)},T=async()=>{const L=o.filter(O=>O.isValid);if(L.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const I=r||d||null;m(!0);try{const{data:{session:O}}=await U.auth.getSession(),$=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O==null?void 0:O.access_token}`},body:JSON.stringify({users:L.map(W=>({firstName:W.firstName,lastName:W.lastName,email:W.email,phone:W.phone,smsConsent:W.smsConsent})),brokerageId:I})}),q=await $.json();if(!$.ok)throw new Error(q.error||"Failed to import users");g(q),x("result"),q.created>0&&a(),i({title:"Import Complete",description:`${q.created} user(s) created successfully.${q.failed>0?` ${q.failed} failed.`:""}`})}catch(O){console.error("Import error:",O),i({title:"Import Failed",description:O.message||"Failed to import users",variant:"destructive"})}finally{m(!1)}},M=o.filter(L=>L.isValid).length,P=o.filter(L=>!L.isValid).length;return e.jsx(Fs,{open:s,onOpenChange:v,children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(pN,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(kr,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),p==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:C,className:"hidden"}),e.jsx(Ja,{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 L;return(L=l.current)==null?void 0:L.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Expected CSV Format:"}),e.jsxs("code",{className:"text-xs block bg-background p-2 rounded",children:["First Name, Last Name, Email, Phone, SMS Consent",e.jsx("br",{}),"John, Doe, john@example.com, 555-123-4567, yes",e.jsx("br",{}),"Jane, Smith, jane@example.com, 555-987-6543, true"]}),e.jsx("p",{className:"text-muted-foreground mt-2 text-xs",children:"Phone and SMS Consent columns are optional. SMS Consent accepts: yes/no, true/false, 1/0, y/n."})]})]}),p==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!r&&n&&n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Assign to Brokerage (optional)"}),e.jsxs(vs,{value:d||"none",onValueChange:L=>u(L==="none"?"":L),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a brokerage..."})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No brokerage"}),n.map(L=>e.jsx(Je,{value:L.id,children:L.name},L.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(Rr,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[M," valid"]})]}),P>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(po,{className:"h-4 w-4"}),e.jsxs("span",{children:[P," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/30",children:[e.jsx(Tt,{children:"First Name"}),e.jsx(Tt,{children:"Last Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"SMS"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(za,{children:o.slice(0,100).map((L,I)=>e.jsxs(un,{children:[e.jsx(xt,{children:L.firstName}),e.jsx(xt,{children:L.lastName}),e.jsx(xt,{children:L.email}),e.jsx(xt,{className:"text-muted-foreground",children:L.phone||"-"}),e.jsx(xt,{className:"text-muted-foreground",children:L.smsConsent===!0?"✓":L.smsConsent===!1?"✗":"-"}),e.jsx(xt,{children:L.isValid?e.jsx(qe,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(qe,{variant:"destructive",children:L.error||"Invalid"})})]},I))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),p==="result"&&y&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(Rr,{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((L,I)=>e.jsxs("li",{children:["• ",L]},I)),y.errors.length>10&&e.jsxs("li",{children:["...and ",y.errors.length-10," more"]})]})]})]}),e.jsxs(Nr,{children:[p==="upload"&&e.jsx(B,{variant:"outline",onClick:v,children:"Cancel"}),p==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:b,children:"Back"}),e.jsx(B,{onClick:T,disabled:h||M===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${M} Agent${M!==1?"s":""}`})]}),p==="result"&&e.jsx(B,{onClick:v,children:"Done"})]})]})})};function Wu({sortKey:s,currentSortKey:t,currentDirection:n,onSort:r,children:a,className:i,...l}){const o=t===s;return e.jsx(Tt,{className:Et("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(Gm,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(tx,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(_x,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function FJ(s=null,t=null){const[n,r]=j.useState(s),[a,i]=j.useState(t),l=j.useCallback(c=>{n===c?a==="asc"?i("desc"):a==="desc"?(r(null),i(null)):i("asc"):(r(c),i("asc"))},[n,a]),o=j.useCallback((c,d)=>{if(!n||!a||!d[n])return c;const u=d[n];return[...c].sort((h,m)=>{const p=u(h),x=u(m);if(p==null&&x==null)return 0;if(p==null)return 1;if(x==null)return-1;let y;return typeof p=="string"&&typeof x=="string"?y=p.localeCompare(x,void 0,{sensitivity:"base"}):y=p-x,a==="asc"?y:-y})},[n,a]);return{sortKey:n,sortDirection:a,handleSort:l,sortData:o}}const p7s=[{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:ll},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:bf}];function RMt({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=j.useState("custom"),[l,o]=j.useState(""),[c,d]=j.useState(""),u=Jos(),h=p=>{i(p.type),o(p.title),d(p.message)},m=async p=>{if(p.preventDefault(),!l.trim()){ba({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}),ba({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{ba({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(bf,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(kr,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(se,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:p7s.map((p,x)=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(p),className:"text-xs",children:[e.jsx(p.icon,{className:"h-3 w-3 mr-1"}),p.title]},x))})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(vs,{value:a,onValueChange:p=>i(p),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wa,{className:"h-4 w-4"})," Custom"]})}),e.jsx(Je,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ll,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(Je,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(Je,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Od,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:l,onChange:p=>o(p.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"message",children:"Message (optional)"}),e.jsx(Ds,{id:"message",value:c,onChange:p=>d(p.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:u.isPending,children:[e.jsx(bf,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const oPe={points_earned:{label:"Points Earned",icon:ll,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:ia,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:Od,color:"bg-green-500"},custom:{label:"Custom",icon:yn,color:"bg-purple-500"}};function f7s(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),{data:l=[],isLoading:o}=mt({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:u,error:h}=await U.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(h)throw h;const m=[...new Set([...u.map(y=>y.user_id),...u.map(y=>y.created_by).filter(Boolean)])],{data:p}=await U.from("profiles").select("id, name, email").in("id",m),x=new Map((p==null?void 0:p.map(y=>[y.id,y]))||[]);return u.map(y=>{var g,b,v;return{...y,user_name:((g=x.get(y.user_id))==null?void 0:g.name)||"Unknown",user_email:((b=x.get(y.user_id))==null?void 0:b.email)||"",creator_name:y.created_by?((v=x.get(y.created_by))==null?void 0:v.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var x,y;const h=((x=u.user_name)==null?void 0:x.toLowerCase().includes(s.toLowerCase()))||((y=u.user_email)==null?void 0:y.toLowerCase().includes(s.toLowerCase()))||u.title.toLowerCase().includes(s.toLowerCase()),m=n==="all"||u.celebration_type===n,p=a==="all"||a==="seen"&&u.seen_at||a==="unseen"&&!u.seen_at;return h&&m&&p}),d={total:l.length,seen:l.filter(u=>u.seen_at).length,unseen:l.filter(u=>!u.seen_at).length,byType:Object.keys(oPe).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(Wt,{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(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(bf,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(fr,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"Filter by type"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Types"}),Object.entries(oPe).map(([u,h])=>e.jsx(Je,{value:u,children:h.label},u))]})]}),e.jsxs(vs,{value:a,onValueChange:i,children:[e.jsx(gs,{className:"w-[140px]",children:e.jsx(bs,{placeholder:"Status"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Status"}),e.jsx(Je,{value:"seen",children:"Seen"}),e.jsx(Je,{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(Tt,{children:"Type"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Points"}),e.jsx(Tt,{children:"Created By"}),e.jsx(Tt,{children:"Created"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(za,{children:c.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=oPe[u.celebration_type],m=h.icon;return e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(m,{className:"h-3 w-3"}),h.label]})}),e.jsx(xt,{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(xt,{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(xt,{children:u.points_amount?e.jsxs(qe,{variant:"secondary",children:["+",u.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(xt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:u.creator_name})}),e.jsx(xt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Bs(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(xt,{children:u.seen_at?e.jsx(qe,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(qe,{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 x7s=()=>{const{user:s}=Ns(),{toast:t}=pi(),[n,r]=j.useState([]),[a,i]=j.useState(!0),[l,o]=j.useState(!1),[c,d]=j.useState("all"),[u,h]=j.useState("all"),[m,p]=j.useState("new"),[x,y]=j.useState(new Set),g=j.useCallback(async()=>{try{i(!0);const{data:W,error:G}=await U.from("profiles").select("id, name, email, phone, is_trial, trial_started_at, trial_expires_at, subscription_status, subscription_end_date, converted_from_trial_at, created_at, last_login").or("is_trial.eq.true,subscription_status.eq.trialing,converted_from_trial_at.not.is.null");if(G)throw G;const{data:K,error:ee}=await U.from("trial_email_exports").select("user_id");if(ee)throw ee;const J=new Set((K||[]).map(ue=>ue.user_id)),le=(W||[]).map(ue=>({...ue,converted_from_trial_at:ue.converted_from_trial_at??null,already_exported:J.has(ue.id)}));le.sort((ue,oe)=>new Date(oe.created_at).getTime()-new Date(ue.created_at).getTime()),r(le)}catch(W){console.error("Error loading trial users:",W),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);j.useEffect(()=>{g()},[g]);const b=W=>W.trial_started_at?"ghl":"stripe",v=W=>W.trial_expires_at?W.trial_expires_at:W.subscription_end_date?W.subscription_end_date:null,k=W=>W.converted_from_trial_at!==null,C=W=>{if(k(W))return!1;const G=v(W);return G?new Date(G).getTime()<=Date.now():!1},T=n.filter(W=>!(c!=="all"&&b(W)!==c||u==="active"&&(C(W)||k(W))||u==="expired"&&!C(W)||u==="converted"&&!k(W)||m==="new"&&W.already_exported||m==="exported"&&!W.already_exported)),M=()=>{x.size===T.length?y(new Set):y(new Set(T.map(W=>W.id)))},P=W=>{const G=new Set(x);G.has(W)?G.delete(W):G.add(W),y(G)},L=async()=>{if(x.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const W=n.filter(ie=>x.has(ie.id)),G="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",K=W.map(ie=>{const de=(ie.name||"").split(" "),we=de[0]||"",je=de.slice(1).join(" ")||"",xe=b(ie)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",fe=k(ie)?"Converted":C(ie)?"Expired":"Active",Se=ie.created_at?new Date(ie.created_at).toLocaleDateString():"",Ee=v(ie)?new Date(v(ie)).toLocaleDateString():"";return`"${we}","${je}","${ie.email}","${ie.phone||""}","${xe}","${fe}","${Se}","${Ee}"`}),ee=[G,...K].join(` `),J=new Blob([ee],{type:"text/csv"}),le=URL.createObjectURL(J),ue=document.createElement("a");ue.href=le,ue.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,ue.click(),URL.revokeObjectURL(le);const oe=W.filter(ie=>!ie.already_exported).map(ie=>({user_id:ie.id,exported_by:s.id}));if(oe.length>0){const{error:ie}=await U.from("trial_email_exports").upsert(oe,{onConflict:"user_id"});ie&&console.error("Error marking exports:",ie)}t({title:"Export complete",description:`Downloaded ${W.length} trial user(s). ${oe.length} newly marked as exported.`}),y(new Set),g()}catch(W){console.error("Export error:",W),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},I=n.filter(W=>!W.already_exported).length,O=n.filter(W=>W.already_exported).length,$=n.filter(W=>k(W)).length,q=n.filter(W=>!C(W)&&!k(W)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Wt,{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(be,{children:e.jsxs(Ft,{className:"pb-2",children:[e.jsx(fr,{children:"Total"}),e.jsx(Ut,{className:"text-2xl",children:n.length})]})}),e.jsx(be,{children:e.jsxs(Ft,{className:"pb-2",children:[e.jsx(fr,{children:"New (Not Exported)"}),e.jsx(Ut,{className:"text-2xl text-green-600",children:I})]})}),e.jsx(be,{children:e.jsxs(Ft,{className:"pb-2",children:[e.jsx(fr,{children:"Active Trials"}),e.jsx(Ut,{className:"text-2xl",children:q})]})}),e.jsx(be,{children:e.jsxs(Ft,{className:"pb-2",children:[e.jsx(fr,{children:"Converted 🎉"}),e.jsx(Ut,{className:"text-2xl text-primary",children:$})]})}),e.jsx(be,{children:e.jsxs(Ft,{className:"pb-2",children:[e.jsx(fr,{children:"Already Exported"}),e.jsx(Ut,{className:"text-2xl text-muted-foreground",children:O})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(vs,{value:m,onValueChange:W=>p(W),children:[e.jsx(gs,{className:"w-[160px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Users"}),e.jsx(Je,{value:"new",children:"New Only"}),e.jsx(Je,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(vs,{value:c,onValueChange:W=>d(W),children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Trial Types"}),e.jsx(Je,{value:"stripe",children:"Credit Card Trial"}),e.jsx(Je,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(vs,{value:u,onValueChange:W=>h(W),children:[e.jsx(gs,{className:"w-[160px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Statuses"}),e.jsx(Je,{value:"active",children:"Active Trial"}),e.jsx(Je,{value:"expired",children:"Expired"}),e.jsx(Je,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(B,{onClick:L,disabled:l||x.size===0,children:[l?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ii,{className:"h-4 w-4 mr-2"}),"Export Selected (",x.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(Tt,{className:"w-[40px]",children:e.jsx(wi,{checked:T.length>0&&x.size===T.length,onCheckedChange:M})}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Trial Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Signup Date"}),e.jsx(Tt,{children:"Last Login"}),e.jsx(Tt,{children:"Expires / Renews"}),e.jsx(Tt,{children:"Exported"})]})}),e.jsx(za,{children:T.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):T.map(W=>{const G=b(W),K=k(W),ee=C(W),J=v(W);return e.jsxs(un,{className:`hover:bg-muted/30 ${K?"bg-primary/5":""}`,children:[e.jsx(xt,{children:e.jsx(wi,{checked:x.has(W.id),onCheckedChange:()=>P(W.id)})}),e.jsx(xt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[W.name,K&&e.jsx(kl,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(xt,{className:"text-muted-foreground",children:W.email}),e.jsx(xt,{children:G==="stripe"?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(ty,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(on,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(xt,{children:K?e.jsxs(qe,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(kl,{className:"h-3 w-3"}),"Converted"]}):ee?e.jsx(qe,{variant:"destructive",children:"Expired"}):e.jsx(qe,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(xt,{className:"text-sm",children:W.created_at?new Date(W.created_at).toLocaleDateString():"—"}),e.jsx(xt,{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(xt,{className:"text-sm",children:K&&J?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(J).toLocaleDateString()]}):J?new Date(J).toLocaleDateString():"—"}),e.jsx(xt,{children:W.already_exported?e.jsx(Rr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(qe,{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"]})]})},g7s=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,y7s=()=>{const[s,t]=j.useState([]),[n,r]=j.useState(!0);j.useEffect(()=>{(async()=>{const{data:l,error:o}=await U.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),r(!1)})()},[]);const a=()=>{if(s.length===0){re.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(h=>[Bs(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(g7s).join(","))].join(` `),c=new Blob([o],{type:"text/csv"}),d=URL.createObjectURL(c),u=document.createElement("a");u.href=d,u.download=`deletion-log-${new Date().toISOString().split("T")[0]}.csv`,u.click(),URL.revokeObjectURL(d),re.success(`Exported ${s.length} deletion record(s)`)};return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Rn,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{className:"text-lg",children:"User Deletion History"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(ii,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Re,{children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Deleted By"})]})}),e.jsx(za,{children:s.map(i=>e.jsxs(un,{children:[e.jsx(xt,{className:"whitespace-nowrap text-sm",children:Bs(new Date(i.created_at),"MMM d, yyyy h:mm a")}),e.jsx(xt,{className:"font-medium",children:i.deleted_user_name||"—"}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:i.deleted_user_email||"—"}),e.jsx(xt,{children:i.brokerage_name||"—"}),e.jsx(xt,{children:e.jsx(qe,{variant:i.deletion_type==="deleted"?"destructive":"secondary",children:i.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(xt,{className:"text-sm",children:i.deleted_by_name||i.deleted_by_email||"—"})]},i.id))})]})})]})},SO=s=>{const{user:t}=Ns(),n=as(),r=mt({queryKey:["teams",s],queryFn:async()=>{let h=U.from("teams").select("*").order("created_at",{ascending:!1});s&&(h=h.eq("brokerage_id",s));const{data:m,error:p}=await h;if(p)throw p;return m||[]},enabled:!!t}),a=h=>mt({queryKey:["team-members",h],queryFn:async()=>{const{data:m,error:p}=await U.from("team_members").select("*").eq("team_id",h).order("role",{ascending:!0});if(p)throw p;const x=(m||[]).map(b=>b.user_id),{data:y}=await U.from("profiles").select("id, name, email, avatar_url").in("id",x),g=new Map((y||[]).map(b=>[b.id,b]));return(m||[]).map(b=>({...b,profile:g.get(b.user_id)||null}))},enabled:!!h}),i=vt({mutationFn:async h=>{const m={name:h.name,created_by:t.id,description:h.description,contact_visibility:h.contact_visibility,lead_pond_enabled:h.lead_pond_enabled,shared_assets_enabled:h.shared_assets_enabled};h.brokerage_id&&(m.brokerage_id=h.brokerage_id);const{data:p,error:x}=await U.from("teams").insert(m).select().single();if(x)throw x;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),re.success("Team created!")},onError:h=>{re.error("Failed to create team: "+h.message)}}),l=vt({mutationFn:async({id:h,...m})=>{const{data:p,error:x}=await U.from("teams").update(m).eq("id",h).select().single();if(x)throw x;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),re.success("Team updated")},onError:h=>{re.error("Failed to update team: "+h.message)}}),o=vt({mutationFn:async h=>{const{error:m}=await U.from("teams").delete().eq("id",h);if(m)throw m},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),re.success("Team deleted")},onError:h=>{re.error("Failed to delete team: "+h.message)}}),c=vt({mutationFn:async h=>{const{data:m,error:p}=await U.from("team_members").insert({team_id:h.team_id,user_id:h.user_id,role:h.role||"team_member"}).select().single();if(p)throw p.message.includes("duplicate")||p.message.includes("unique")?new Error("This agent is already on a team. They must be removed from their current team first."):p;return m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),re.success("Member added to team")},onError:h=>{re.error(h.message)}}),d=vt({mutationFn:async h=>{const{error:m}=await U.from("team_members").delete().eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),re.success("Member removed from team")},onError:h=>{re.error("Failed to remove member: "+h.message)}}),u=vt({mutationFn:async h=>{const{error:m}=await U.from("team_members").update({role:h.role}).eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),re.success("Member role updated")},onError:h=>{re.error("Failed to update role: "+h.message)}});return{teams:r.data||[],isLoading:r.isLoading,createTeam:i,updateTeam:l,deleteTeam:o,addMember:c,removeMember:d,updateMemberRole:u,useTeamMembers:a}},v7s=()=>{const{user:s}=Ns();return mt({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.rpc("get_team_contacts",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},DMt=s=>{const{user:t}=Ns(),n=as(),r=mt({queryKey:["lead-pond",s],queryFn:async()=>{const{data:o,error:c}=await U.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(b=>b.contact_id),u=[...new Set(o.map(b=>b.added_by))],h=o.filter(b=>b.claimed_by).map(b=>b.claimed_by),m=[...new Set([...u,...h])],[p,x]=await Promise.all([U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",d),U.from("profiles").select("id, name, avatar_url").in("id",m)]),y=new Map((p.data||[]).map(b=>[b.id,b])),g=new Map((x.data||[]).map(b=>[b.id,b]));return o.map(b=>({...b,status:b.claimed_by?"claimed":"available",contact:y.get(b.contact_id)||null,contributor:g.get(b.added_by)||null,claimer:b.claimed_by&&g.get(b.claimed_by)||null}))},enabled:!!s&&!!t}),a=vt({mutationFn:async o=>{const{data:c,error:d}=await U.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"]}),re.success("Contact added to Lead Pond")},onError:o=>{re.error(o.message)}}),i=vt({mutationFn:async o=>{const{error:c}=await U.rpc("claim_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),re.success("Lead claimed!")},onError:o=>{re.error(o.message)}}),l=vt({mutationFn:async o=>{const{error:c}=await U.rpc("return_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),re.success("Lead returned to pond")},onError:o=>{re.error(o.message)}});return{leadPondItems:r.data||[],isLoading:r.isLoading,addToLeadPond:a,claimLead:i,returnLead:l}},b7s=()=>{const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.rpc("transfer_contact",{_contact_id:t.contactId,_to_user_id:t.toUserId,_notes:t.notes||null});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["team-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),re.success("Contact transferred successfully")},onError:t=>{re.error(t.message||"Failed to transfer contact")}})};function OMt({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var T;const{user:i}=Ns(),{data:l}=Hj(),{useTeamMembers:o}=SO(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=b7s(),[u,h]=j.useState(null),[m,p]=j.useState(""),[x,y]=j.useState(!1),g=c.filter(M=>M.user_id!==(i==null?void 0:i.id)),b=async()=>{if(u){y(!0);try{for(const M of n)await d.mutateAsync({contactId:M,toUserId:u,notes:m||void 0});t(!1),h(null),p(""),a==null||a()}catch{}finally{y(!1)}}},v=g.find(M=>M.user_id===u),k=n.length>1,C=r.length>0?k?`${r.length} contacts`:r[0]:k?`${n.length} contacts`:"this contact";return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(M5,{className:"h-5 w-5"}),"Transfer ",C]}),e.jsxs(kr,{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(se,{className:"text-sm font-medium mb-2 block",children:"Transfer to:"}),e.jsx("div",{className:"space-y-1 max-h-[240px] overflow-y-auto",children:g.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):g.map(M=>{var P,L,I;return e.jsxs("button",{onClick:()=>h(M.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===M.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:((P=M.profile)==null?void 0:P.avatar_url)||""}),e.jsx(Da,{className:"text-xs",children:(((L=M.profile)==null?void 0:L.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((I=M.profile)==null?void 0:I.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:M.role.replace("_"," ")})]})]},M.user_id)})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(Ds,{id:"transfer-notes",value:m,onChange:M=>p(M.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:b,disabled:!u||x,children:[x?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(M5,{className:"h-4 w-4 mr-2"}),"Transfer",v?` to ${(T=v.profile)==null?void 0:T.name}`:""]})]})]})})}const QHe=()=>{const s=Hn(),{data:t,isLoading:n}=v7s(),{data:r}=Hj(),[a,i]=j.useState(""),[l,o]=j.useState("all"),[c,d]=j.useState(null),[u,h]=j.useState(""),m=(r==null?void 0:r.role)==="team_leader",p=j.useMemo(()=>{if(!t)return[];const y=new Map;return t.forEach(g=>{y.has(g.owner_user_id)||y.set(g.owner_user_id,{id:g.owner_user_id,name:g.owner_name||"Unknown",avatar:g.owner_avatar_url})}),Array.from(y.values())},[t]),x=j.useMemo(()=>{if(!t)return[];let y=t;if(l!=="all"&&(y=y.filter(g=>g.owner_user_id===l)),a.trim()){const g=a.toLowerCase();y=y.filter(b=>{var v,k,C;return(b.first_name+" "+(b.last_name||"")).toLowerCase().includes(g)||((v=b.email)==null?void 0:v.toLowerCase().includes(g))||((k=b.phone)==null?void 0:k.includes(g))||((C=b.owner_name)==null?void 0:C.toLowerCase().includes(g))})}return y},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(gn,{className:"h-10 w-full"}),e.jsx(gn,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Bn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Team Contacts"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Team contact sharing is not enabled, or you're not on a team. Ask your manager about contact visibility settings."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:y=>i(y.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-[200px]",children:e.jsx(bs,{placeholder:"Filter by agent"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Team Members"}),p.map(y=>e.jsx(Je,{value:y.id,children:y.name},y.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[x.length," contact",x.length!==1?"s":""," from ",p.length," teammate",p.length!==1?"s":""]}),e.jsx(be,{children:e.jsx(Re,{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(Tt,{children:"Name"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Contact Info"}),e.jsx(Tt,{children:"Address"}),e.jsx(Tt,{children:"Lead Source"}),e.jsx(Tt,{children:"Date Added"}),m&&e.jsx(Tt,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(za,{children:x.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:m?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):x.map(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(xt,{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(xt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ra,{className:"h-6 w-6",children:[e.jsx(Fi,{src:y.owner_avatar_url||""}),e.jsx(Da,{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(xt,{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(on,{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(pa,{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(xt,{children:y.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(oi,{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(xt,{children:y.lead_source?e.jsx(qe,{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(xt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Bs(new Date(y.created_at),"MMM d, yyyy")})}),m&&e.jsx(xt,{children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:g=>{g.stopPropagation(),d(y.id),h(`${y.first_name} ${y.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(M5,{className:"h-4 w-4"})})})]},y.id))})]})})}),e.jsx(OMt,{open:!!c,onOpenChange:y=>{y||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},JHe=({teamId:s})=>{const{user:t}=Ns(),{leadPondItems:n,isLoading:r,claimLead:a,returnLead:i}=DMt(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(gn,{className:"h-20 w-full"},c))});if(n.length===0)return e.jsx(be,{children:e.jsxs(Re,{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-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,p,x,y;return e.jsx(be,{children:e.jsxs(Re,{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(on,{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(pa,{className:"h-3 w-3"})," ",c.contact.phone]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs(Ra,{className:"h-4 w-4",children:[e.jsx(Fi,{src:((p=c.contributor)==null?void 0:p.avatar_url)||""}),e.jsx(Da,{className:"text-[8px]",children:(((x=c.contributor)==null?void 0:x.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($W,{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(be,{className:"opacity-75",children:e.jsxs(Re,{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(qe,{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(bm,{className:"mr-1 h-3 w-3"}),"Return"]})]})},c.id)})})]})]})},FMt=({teamId:s})=>{const{useTeamMembers:t}=SO(),{data:n=[]}=t(s),r=n.map(p=>p.user_id),a=new Map(n.map(p=>[p.user_id,p.profile])),{data:i=[],isLoading:l}=mt({queryKey:["team-shared-presentations",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:x}=await U.from("smart_presentations").select("id, owner_user_id, title, client_name, status, view_count, cta_clicked_count, share_token, created_at, published_at").in("owner_user_id",r).neq("status","archived").order("created_at",{ascending:!1});if(x)throw x;return p||[]},enabled:r.length>0}),{data:o=[],isLoading:c}=mt({queryKey:["team-shared-open-houses",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:x}=await U.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",r).order("event_date",{ascending:!1});if(x)throw x;return p||[]},enabled:r.length>0}),{data:d=[],isLoading:u}=mt({queryKey:["team-shared-videos",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:x}=await U.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",r).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(x)throw x;return p||[]},enabled:r.length>0});if(l||c||u)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(p=>e.jsx(gn,{className:"h-20 w-full"},p))});const m=p=>{const x=a.get(p);return{name:(x==null?void 0:x.name)||"Unknown",avatar:(x==null?void 0:x.avatar_url)||"",initials:((x==null?void 0:x.name)||"?").charAt(0).toUpperCase()}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsx(be,{children:e.jsxs(Re,{className:"flex items-center gap-3 p-4",children:[e.jsx(yb,{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(be,{children:e.jsxs(Re,{className:"flex items-center gap-3 p-4",children:[e.jsx(ia,{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(be,{children:e.jsxs(Re,{className:"flex items-center gap-3 p-4",children:[e.jsx(Zr,{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(fa,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(ss,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(ss,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(ns,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(lPe,{icon:e.jsx(yb,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(p=>{const x=m(p.owner_user_id);return e.jsx(be,{children:e.jsxs(Re,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Ra,{className:"h-8 w-8 shrink-0",children:[e.jsx(Fi,{src:x.avatar}),e.jsx(Da,{className:"text-xs",children:x.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[x.name," · ",Bs(new Date(p.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(qe,{variant:p.status==="published"?"default":"secondary",className:"text-xs capitalize",children:p.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ma,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})}),e.jsx(ns,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(lPe,{icon:e.jsx(ia,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(p=>{const x=m(p.agent_id);return e.jsx(be,{children:e.jsxs(Re,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Ra,{className:"h-8 w-8 shrink-0",children:[e.jsx(Fi,{src:x.avatar}),e.jsx(Da,{className:"text-xs",children:x.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[x.name," · ",Bs(new Date(p.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[p.is_active?e.jsx(qe,{className:"text-xs",children:"Active"}):e.jsx(qe,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Bn,{className:"h-3 w-3"}),p.visitor_count||0]})]})]})},p.id)})}),e.jsx(ns,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(lPe,{icon:e.jsx(Zr,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(p=>{const x=m(p.owner_user_id);return e.jsx(be,{children:e.jsxs(Re,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Ra,{className:"h-8 w-8 shrink-0",children:[e.jsx(Fi,{src:x.avatar}),e.jsx(Da,{className:"text-xs",children:x.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.title||p.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[x.name," · ",Bs(new Date(p.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(qe,{variant:"secondary",className:"text-xs capitalize",children:p.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ma,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})})]})]})},lPe=({icon:s,label:t})=>e.jsx(be,{children:e.jsxs(Re,{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})]})}),zMt=({team:s,brokerageAgents:t,onBack:n,onUpdate:r,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var P,L;const{useTeamMembers:u}=SO(),{data:h=[],isLoading:m}=u(s.id),[p,x]=j.useState(!1),[y,g]=j.useState(""),[b,v]=j.useState("team_member"),{data:k}=mt({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:I}=await U.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),O=new Map;return(I||[]).forEach($=>{var q;O.set($.user_id,((q=$.teams)==null?void 0:q.name)||"another team")}),O}}),C=new Set(h.map(I=>I.user_id)),T=t.filter(I=>!C.has(I.id)),M=async()=>{y&&(await a(y,b),g(""),v("team_member"),x(!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(fa,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"members",children:"Members"}),e.jsxs(ss,{value:"contacts",children:[e.jsx(DR,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(ss,{value:"lead-pond",children:[e.jsx(mN,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(ss,{value:"shared-assets",children:[e.jsx(ny,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(ss,{value:"settings",children:"Settings"})]}),e.jsxs(ns,{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(Fs,{open:p,onOpenChange:x,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Sl,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Add Team Member"}),e.jsxs(kr,{children:["Select an agent from your brokerage to add to ",s.name,"."]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Agent"}),e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[y&&(((P=T.find(I=>I.id===y))==null?void 0:P.name)||((L=T.find(I=>I.id===y))==null?void 0:L.email))||"Select an agent",e.jsx(fb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Jl,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Sb,{children:[e.jsx(Cb,{placeholder:"Search agents..."}),e.jsxs(Ab,{children:[e.jsx(Tb,{children:"No agents found."}),e.jsx(Eb,{children:T.map(I=>{const O=k==null?void 0:k.get(I.id);return e.jsxs(Yy,{value:I.name||I.email||I.id,disabled:!!O,onSelect:()=>g(I.id),children:[e.jsx(da,{className:Et("mr-2 h-4 w-4",y===I.id?"opacity-100":"opacity-0")}),I.name||I.email,O&&e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(on ",O,")"]})]},I.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Role"}),e.jsxs(vs,{value:b,onValueChange:v,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"team_leader",children:"Team Leader"}),e.jsx(Je,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx(B,{onClick:M,disabled:!y||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),m?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(I=>e.jsx(gn,{className:"h-16 w-full"},I))}):h.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Bn,{className:"h-10 w-10 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No members yet. Add agents to this team."})]})}):e.jsx("div",{className:"space-y-2",children:h.map(I=>{var O,$,q,W,G;return e.jsx(be,{children:e.jsxs(Re,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:((O=I.profile)==null?void 0:O.avatar_url)||""}),e.jsx(Da,{children:((($=I.profile)==null?void 0:$.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((q=I.profile)==null?void 0:q.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(W=I.profile)==null?void 0:W.email})]}),I.role==="team_leader"?e.jsxs(qe,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(sy,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(qe,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(vs,{value:I.role,onValueChange:K=>l(I.id,K),children:[e.jsx(gs,{className:"w-[140px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"team_leader",children:"Team Leader"}),e.jsx(Je,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(uz,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Remove Member?"}),e.jsxs(xl,{children:["Remove ",((G=I.profile)==null?void 0:G.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>i(I.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},I.id)})})]}),e.jsx(ns,{value:"contacts",className:"space-y-4",children:e.jsx(QHe,{})}),s.lead_pond_enabled&&e.jsx(ns,{value:"lead-pond",className:"space-y-4",children:e.jsx(JHe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(ns,{value:"shared-assets",className:"space-y-4",children:e.jsx(FMt,{teamId:s.id})}),e.jsxs(ns,{value:"settings",className:"space-y-4",children:[e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{className:"text-lg",children:"Team Settings"}),e.jsx(fr,{children:"Configure how this team operates."})]}),e.jsxs(Re,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Team Name"}),e.jsx(ye,{defaultValue:s.name,onBlur:I=>{I.target.value!==s.name&&r({name:I.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{defaultValue:s.description||"",onBlur:I=>{I.target.value!==(s.description||"")&&r({description:I.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contact Visibility"}),e.jsxs(vs,{defaultValue:s.contact_visibility,onValueChange:I=>r({contact_visibility:I}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(Je,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(Je,{value:"full_team",children:"Full Team — All team members can see shared contacts"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls whether team leaders and members can view each other's contacts."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Lead Pond"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enable a shared lead pool where leaders can drop leads for members to claim."})]}),e.jsx(Mn,{checked:s.lead_pond_enabled,onCheckedChange:I=>r({lead_pond_enabled:I})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Shared Assets"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Allow team members to access shared presentations, guest books, and videos."})]}),e.jsx(Mn,{checked:s.shared_assets_enabled,onCheckedChange:I=>r({shared_assets_enabled:I})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Shared Video Library"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Let team members browse and use each other's videos from the Video Library."})]}),e.jsx(Mn,{checked:s.shared_videos_enabled??!1,onCheckedChange:I=>r({shared_videos_enabled:I})})]})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsxs(B,{variant:"destructive",size:"sm",children:[e.jsx(Rn,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete Team?"}),e.jsxs(xl,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},BMt=({open:s,onOpenChange:t,onCreateTeam:n,isCreating:r,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=j.useState(1),[u,h]=j.useState(""),[m,p]=j.useState(""),[x,y]=j.useState(""),[g,b]=j.useState(""),[v,k]=j.useState([]),C=()=>{d(1),h(""),p(""),y(""),b(""),k([])},T=I=>{I||C(),t(I)},M=async()=>{const I=x&&x!=="none"?x:o||null;await n({name:u.trim(),description:m.trim()||void 0,brokerage_id:I,leaderId:g||void 0,memberIds:v.length>0?v:void 0}),C()},P=I=>{I!==g&&k(O=>O.includes(I)?O.filter($=>$!==I):[...O,I])},L=a.filter(I=>I.id!==g);return e.jsx(Fs,{open:s,onOpenChange:T,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs($s,{children:[e.jsx(zs,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(kr,{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:Et("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:Et("h-1.5 flex-1 rounded-full transition-colors",c===2?"bg-primary":"bg-muted")})]})]}),e.jsx("div",{className:"overflow-y-auto flex-1 pr-1",children:c===1?e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(ye,{id:"team-name",value:u,onChange:I=>h(I.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"team-desc",children:"Description"}),e.jsx(Ds,{id:"team-desc",value:m,onChange:I=>p(I.target.value),placeholder:"What is this team focused on?",rows:3})]}),i&&l&&l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Brokerage"}),e.jsxs(vs,{value:x,onValueChange:y,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"No brokerage (independent team)"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No brokerage (independent)"}),l.map(I=>e.jsx(Je,{value:I.id,children:I.name},I.id))]})]})]})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-1.5",children:[e.jsx(sy,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(vs,{value:g,onValueChange:I=>{b(I),k(O=>O.filter($=>$!==I))},children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a team leader (optional)"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No leader for now"}),a.map(I=>e.jsx(Je,{value:I.id,children:I.name||I.email||"Unknown"},I.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-1.5",children:[e.jsx(Sl,{className:"h-3.5 w-3.5"}),"Initial Members",v.length>0&&e.jsxs(qe,{variant:"secondary",className:"ml-1 text-xs",children:[v.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click agents to add them. You can always add more later."}),e.jsx("div",{className:"border rounded-lg max-h-[240px] overflow-y-auto divide-y",children:L.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(Bn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):L.map(I=>{const O=v.includes(I.id);return e.jsxs("button",{type:"button",className:Et("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",O&&"bg-primary/5"),onClick:()=>P(I.id),children:[e.jsxs(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:I.avatar_url||""}),e.jsx(Da,{className:"text-xs",children:(I.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:I.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:I.email})]}),e.jsx("div",{className:Et("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",O?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:O&&e.jsx(da,{className:"h-3 w-3"})})]},I.id)})})]})]})}),e.jsx(Nr,{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(Xa,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>d(1),children:[e.jsx(_a,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx(B,{onClick:M,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},_7s=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=SO(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(""),{data:x}=mt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:T,error:M}=await U.from("brokerages").select("id, name").order("name");if(M)throw M;return T||[]}}),{data:y}=mt({queryKey:["admin-team-member-info",s.map(T=>T.id).join(",")],queryFn:async()=>{var I;if(s.length===0)return{};const{data:T}=await U.from("team_members").select("team_id, user_id, role").in("team_id",s.map(O=>O.id));if(!T)return{};const M=T.filter(O=>O.role==="team_leader").map(O=>O.user_id);let P={};if(M.length>0){const{data:O}=await U.from("profiles").select("id, name").in("id",M);O&&(P=Object.fromEntries(O.map($=>[$.id,{name:$.name}])))}const L={};for(const O of s){const $=T.filter(W=>W.team_id===O.id),q=$.find(W=>W.role==="team_leader");L[O.id]={count:$.length,leaderName:q&&((I=P[q.user_id])==null?void 0:I.name)||null}}return L},enabled:s.length>0}),g=(u==null?void 0:u.brokerage_id)||null,{data:b}=mt({queryKey:["brokerage-agents-for-teams",g],queryFn:async()=>{let T=U.from("profiles").select("id, name, email, avatar_url").order("name");g&&(T=T.eq("brokerage_id",g));const{data:M,error:P}=await T;if(P)throw P;return M||[]},enabled:!!u}),v=Object.fromEntries((x||[]).map(T=>[T.id,T.name])),k=async T=>{const M=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:M.id,user_id:T.leaderId,role:"team_leader"}),T.memberIds)for(const P of T.memberIds)await i.mutateAsync({team_id:M.id,user_id:P,role:"team_member"});d(!1)};if(u)return e.jsx(zMt,{team:u,brokerageAgents:b||[],onBack:()=>h(null),onUpdate:T=>r.mutateAsync({id:u.id,...T}).then(M=>h(M)),onAddMember:(T,M)=>i.mutateAsync({team_id:u.id,user_id:T,role:M}),onRemoveMember:T=>l.mutateAsync({team_id:u.id,member_id:T}),onUpdateRole:(T,M)=>o.mutateAsync({team_id:u.id,member_id:T,role:M}),onDeleteTeam:()=>{a.mutate(u.id),h(null)},isUpdating:r.isPending,isAddingMember:i.isPending});const C=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(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search teams...",value:m,onChange:T=>p(T.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[C.length," of ",s.length," teams"]})]}),e.jsxs(B,{size:"sm",onClick:()=>d(!0),children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(BMt,{open:c,onOpenChange:d,onCreateTeam:k,isCreating:n.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:x,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(Tt,{className:"font-semibold",children:"Team Name"}),e.jsx(Tt,{className:"font-semibold",children:"Brokerage"}),e.jsx(Tt,{className:"font-semibold",children:"Leader"}),e.jsx(Tt,{className:"font-semibold",children:"Members"}),e.jsx(Tt,{className:"font-semibold",children:"Visibility"}),e.jsx(Tt,{className:"w-[100px]"})]})}),e.jsx(za,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(T=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsx(gn,{className:"h-4 w-32"})}),e.jsx(xt,{children:e.jsx(gn,{className:"h-4 w-24"})}),e.jsx(xt,{children:e.jsx(gn,{className:"h-4 w-28"})}),e.jsx(xt,{children:e.jsx(gn,{className:"h-4 w-12"})}),e.jsx(xt,{children:e.jsx(gn,{className:"h-4 w-20"})}),e.jsx(xt,{children:e.jsx(gn,{className:"h-4 w-16"})})]},T))}):C.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:m?"No teams match your search":"No teams found. Create one to get started."})}):C.map(T=>{const M=y==null?void 0:y[T.id];return e.jsxs(un,{className:"hover:bg-muted/30",children:[e.jsxs(xt,{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(xt,{children:T.brokerage_id?e.jsx("span",{className:"text-sm",children:v[T.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(xt,{children:M!=null&&M.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(sy,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),M.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(xt,{children:e.jsxs(qe,{variant:"secondary",className:"text-xs",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),(M==null?void 0:M.count)??0]})}),e.jsx(xt,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(_f,{className:"h-3 w-3"}),T.contact_visibility.replace("_"," ")]})}),e.jsx(xt,{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(Za,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:async()=>{await Bi(`Delete team "${T.name}"? This cannot be undone.`)&&a.mutate(T.id)},title:"Delete team",children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})})]},T.id)})})]})})]})};function Ylt(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 w7s({open:s,onOpenChange:t,recipients:n}){const{toast:r}=pi(),[a,i]=j.useState([]),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(""),[x,y]=j.useState(!1),[g,b]=j.useState(!1),v=j.useMemo(()=>a.find(M=>M.id===c)||null,[a,c]);j.useEffect(()=>{s&&(o(!0),(async()=>{const M=new Date().toISOString(),{data:P,error:L}=await U.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",M).order("event_date",{ascending:!0}).limit(50);L?r({title:"Could not load events",description:L.message,variant:"destructive"}):i(P||[]),o(!1)})())},[s,r]);const k=j.useMemo(()=>n.filter(M=>M.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(M.email)),[n]),C=()=>{if(!v){r({title:"Pick an event first",variant:"destructive"});return}if(k.length===0){r({title:"No valid recipient emails",variant:"destructive"});return}b(!0)},T=async()=>{if(v){b(!1),y(!0);try{const{data:{session:M}}=await U.auth.getSession(),P=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M==null?void 0:M.access_token}`},body:JSON.stringify({event_id:v.id,recipients:k.map(q=>({email:q.email,name:q.name,user_id:q.id})),custom_subject:u.trim()||void 0,custom_intro:m.trim()||void 0})}),L=await P.json().catch(()=>({}));if(!P.ok)throw new Error((L==null?void 0:L.error)||"Failed to send event invite");const I=(L==null?void 0:L.sent)??0,O=(L==null?void 0:L.failed)??0,$=(L==null?void 0:L.already_invited)??0;r({title:"Invites sent",description:`Sent: ${I}${$?` · Skipped (already invited): ${$}`:""}${O?` · Failed: ${O}`:""}`}),t(!1),p(""),h(""),d("")}catch(M){const P=M instanceof Error?M.message:"Send failed";r({title:"Send failed",description:P,variant:"destructive"})}finally{y(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(kr,{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(se,{htmlFor:"event-select",children:"Event"}),l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Loading upcoming events..."]}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No upcoming events found. Create an event first."}):e.jsxs(vs,{value:c,onValueChange:d,children:[e.jsx(gs,{id:"event-select",children:e.jsx(bs,{placeholder:"Pick an upcoming event..."})}),e.jsx(ys,{children:a.map(M=>e.jsx(Je,{value:M.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:M.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Ylt(M.event_date),!M.is_published&&" · (Draft)"]})]})},M.id))})]})]}),v&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(ra,{className:"h-4 w-4 text-primary"}),v.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ylt(v.event_date)}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:v.description})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(ye,{id:"subject",placeholder:v?`You're invited: ${v.title}`:"You're invited to...",value:u,onChange:M=>h(M.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank to use the default."})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(Ds,{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:M=>p(M.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(M=>e.jsx(qe,{variant:"secondary",className:"text-xs font-normal",children:M.name||M.email},M.id)),k.length>30&&e.jsxs(qe,{variant:"outline",className:"text-xs",children:["+",k.length-30," more"]})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:x,children:"Cancel"}),e.jsx(B,{onClick:C,disabled:x||!c||k.length===0,children:x?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"})," Send to ",k.length]})})]})]})}),e.jsx(Nl,{open:g,onOpenChange:b,children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Send event invite?"}),e.jsx(xl,{children:v?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',v.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[k.length," member",k.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsxs(cl,{onClick:T,children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const j7s=()=>{const s=Hn(),{user:t,isAdmin:n}=Ns(),{startImpersonation:r,isLoading:a}=Q4e(),{toast:i}=pi(),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,p]=j.useState({}),[x,y]=j.useState(!0);j.useState({});const[g,b]=j.useState(!1),[v,k]=j.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[C,T]=j.useState(!1),[M,P]=j.useState(""),[L,I]=j.useState(1),[O,$]=j.useState(50),[q,W]=j.useState("all"),[G,K]=j.useState("all"),[ee,J]=j.useState("all"),[le,ue]=j.useState("all"),[oe,ie]=j.useState("all"),[de,we]=j.useState(!1),[je,xe]=j.useState(!1),[fe,Se]=j.useState(!1),[Ee,Le]=j.useState(null),[De,Be]=j.useState(null),[Ne,Ge]=j.useState(!1),[_e,Oe]=j.useState({name:"",email:"",brokerage_id:"",phone:""}),[Ae,Xe]=j.useState(null),[Ue,Ze]=j.useState(!1),[Qe,Ye]=j.useState(""),[nt,rt]=j.useState(!1),[Fe,dt]=j.useState(!1),[Dt,pt]=j.useState(null),[zt,Gt]=j.useState(""),[qs,As]=j.useState(!1),[Bt,At]=j.useState(!1),[Is,jt]=j.useState(null),[Qs,cn]=j.useState(!1),[qt,Gs]=j.useState(!1),[Ls,sn]=j.useState(null),[Hs,nn]=j.useState(""),[tn,_n]=j.useState(!1),[Cn,Un]=j.useState({email:"",name:"",password:"",phone:""}),[Kr,jr]=j.useState(!1),[Xs,Ba]=j.useState(!1),[Hr,mr]=j.useState(""),[pr,rn]=j.useState(!1),[Jn,ea]=j.useState(!1),[_s,We]=j.useState(""),[it,gt]=j.useState(new Set),[St,Ht]=j.useState(!1),[ts,Ms]=j.useState(!1),[js,Zs]=j.useState(null),[Tn,vn]=j.useState(!1),[_r,Jr]=j.useState(null),[ha,Mr]=j.useState([]),[Xr,Qt]=j.useState([]),[Zn,aa]=j.useState(!1),[zr,Na]=j.useState({});j.useEffect(()=>{!t||!n||(ur(),ao())},[t,n]);const oa=async()=>{try{const{data:Zt,error:$e}=await U.from("brokerage_manager_assignments").select("user_id, brokerage_id");if($e)throw $e;const yt={};for(const is of Zt??[])yt[is.brokerage_id]||(yt[is.brokerage_id]=[]),yt[is.brokerage_id].push(is.user_id);p(yt)}catch(Zt){console.error("Error loading brokerage manager assignments:",Zt)}},ur=async()=>{try{y(!0);const{data:Zt,error:$e}=await U.functions.invoke("get-user-details");if($e)throw $e;const yt=Zt.users||[];o(yt),h(Zt.brokerages||[]),await oa();const is=yt.filter(us=>us.roles.includes("assistant"));if(is.length>0){const us=is.map(Dn=>Dn.id),{data:en}=await U.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",us);if(en&&en.length>0){const Dn=[...new Set(en.map(Ha=>Ha.agent_id))],{data:er}=await U.from("profiles").select("id, name, email").in("id",Dn),xr={};for(const Ha of en){const Zi=er==null?void 0:er.find(Hi=>Hi.id===Ha.agent_id);Zi&&(xr[Ha.assistant_id]={agent_name:Zi.name||"",agent_email:Zi.email||""})}Na(xr)}}}catch(Zt){console.error("Error loading members:",Zt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{y(!1)}},ao=async()=>{try{const{data:Zt,error:$e}=await U.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if($e)throw $e;d(Zt||[])}catch(Zt){console.error("Error loading apps:",Zt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},fo=async Zt=>{if(!_e.name.trim()||!_e.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(_e.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:yt}=await U.from("profiles").update({name:_e.name.trim(),email:_e.email.trim(),brokerage_id:_e.brokerage_id||null,phone:_e.phone.trim()||null}).eq("id",Zt);if(yt)throw yt;i({title:"Success",description:"Member details updated successfully"}),Le(null),ur()}catch(yt){console.error("Error updating member:",yt),i({title:"Error",description:yt.message||"Failed to update member",variant:"destructive"})}},Va=async Zt=>{try{const{data:{session:$e}}=await U.auth.getSession(),yt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$e==null?void 0:$e.access_token}`},body:JSON.stringify({userId:Zt})}),is=await yt.json();if(!yt.ok)throw new Error(is.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch($e){console.error("Error resending welcome email:",$e),i({title:"Error",description:$e.message||"Failed to resend welcome email",variant:"destructive"})}},So=async(Zt,$e)=>{try{const{error:yt}=await U.functions.invoke("send-password-reset",{body:{email:Zt,redirectTo:window.location.origin}});if(yt)throw yt;i({title:"Password Reset Sent",description:`Password reset email sent to ${$e}`})}catch(yt){console.error("Error sending password reset:",yt),i({title:"Error",description:yt.message||"Failed to send password reset email",variant:"destructive"})}},$a=async(Zt,$e)=>{if(await Bi(`Are you sure you want to delete ${$e}? This action cannot be undone.`))try{const{data:{session:yt}}=await U.auth.getSession(),is=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${yt==null?void 0:yt.access_token}`},body:JSON.stringify({userId:Zt})}),us=await is.json();if(!is.ok)throw new Error(us.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),ur()}catch(yt){console.error("Error deleting user:",yt),i({title:"Error",description:yt.message||"Failed to delete user",variant:"destructive"})}},Gr=async()=>{if(!v.email||!v.name||!v.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(v.role==="brokerage_manager"&&!v.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}b(!0);try{const{data:{session:Zt}}=await U.auth.getSession(),$e=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Zt==null?void 0:Zt.access_token}`},body:JSON.stringify(v)}),yt=await $e.json();if(!$e.ok)throw new Error(yt.error||"Failed to create user");if(v.role&&v.role!=="user"&&yt.userId){const is=v.role==="brokerage_manager"?v.brokerage_id:void 0;await Qn(yt.userId,v.role,"add",is)}i({title:"Success",description:`User ${v.email} created successfully`}),k({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),T(!1),ur()}catch(Zt){console.error("Error creating user:",Zt),i({title:"Error",description:Zt.message||"Failed to create user",variant:"destructive"})}finally{b(!1)}},Qn=async(Zt,$e,yt,is)=>{try{const{data:{session:us}}=await U.auth.getSession(),en={userId:Zt,role:$e,action:yt};if($e==="brokerage_manager"){if(!is){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}en.brokerageId=is}const Dn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${us==null?void 0:us.access_token}`},body:JSON.stringify(en)}),er=await Dn.json();if(!Dn.ok)throw new Error(er.error||"Failed to manage user role");i({title:"Success",description:`Role ${yt==="add"?"added":"removed"} successfully`}),ur()}catch(us){console.error("Error managing user role:",us),i({title:"Error",description:us.message||"Failed to manage user role",variant:"destructive"})}},qa=(Zt,$e)=>$e.length===0?!0:$e.some(yt=>Zt.includes(yt)),xo=async(Zt,$e,yt)=>{const is=`${Zt}-${$e.id}`;Xe(is);try{if(yt){const us=l.find(Dn=>Dn.id===Zt),en=$e.required_tags.filter(Dn=>us==null?void 0:us.tags.includes(Dn));for(const Dn of en){const{error:er}=await U.from("user_tags").delete().eq("user_id",Zt).eq("tag",Dn);if(er)throw er}i({title:"Access Removed",description:`Removed access to ${$e.name}`})}else if($e.required_tags.length>0){const{error:us}=await U.from("user_tags").insert({user_id:Zt,tag:$e.required_tags[0]});if(us)throw us;i({title:"Access Granted",description:`Granted access to ${$e.name}`})}await ur()}catch(us){console.error("Error toggling access:",us),i({title:"Error",description:us.message||"Failed to update access",variant:"destructive"})}finally{Xe(null)}},Wo=async()=>{const Zt=Qe.trim();if(!Zt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Zt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(yt=>yt.name.toLowerCase()===Zt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}rt(!0);try{const{error:yt}=await U.from("brokerages").insert({name:Zt});if(yt)throw yt;i({title:"Success",description:`Brokerage "${Zt}" created successfully`}),Ye(""),Ze(!1),ur()}catch(yt){console.error("Error creating brokerage:",yt),i({title:"Error",description:yt.message||"Failed to create brokerage",variant:"destructive"})}finally{rt(!1)}},Co=Zt=>{pt(Zt),Gt(Zt.name),dt(!0)},Ko=()=>{pt(null),Gt(""),dt(!1)},Ud=async()=>{if(!Dt)return;const Zt=zt.trim();if(!Zt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Zt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}As(!0);try{const{error:$e}=await U.from("brokerages").update({name:Zt}).eq("id",Dt.id);if($e)throw $e;i({title:"Success",description:"Brokerage updated successfully"}),Ko(),ur()}catch($e){console.error("Error updating brokerage:",$e),i({title:"Error",description:$e.message||"Failed to update brokerage",variant:"destructive"})}finally{As(!1)}},Mu=async(Zt,$e)=>{var yt;if(!$e||typeof $e!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const is={userId:Zt,role:"brokerage_manager",action:"add",brokerageId:$e};console.debug("[assignManagerToBrokerage] payload",is);const{data:{session:us}}=await U.auth.getSession(),en=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${us==null?void 0:us.access_token}`},body:JSON.stringify(is)}),Dn=await en.json();if(!en.ok&&!((yt=Dn.error)!=null&&yt.includes("duplicate")))throw new Error(Dn.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await ur()}catch(is){console.error("Error assigning manager:",is),i({title:"Error",description:is.message||"Failed to assign manager",variant:"destructive"})}},Qm=Zt=>{jt(Zt),At(!0)},Gc=async()=>{if(Is){cn(!0);try{const Zt=l.filter(is=>is.brokerage_id===Is.id),{data:{session:$e}}=await U.auth.getSession();for(const is of Zt){const us=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$e==null?void 0:$e.access_token}`},body:JSON.stringify({userId:is.id})});if(!us.ok){const en=await us.json();console.error(`Failed to delete user ${is.email}:`,en.error)}}const{error:yt}=await U.from("brokerages").delete().eq("id",Is.id);if(yt)throw yt;i({title:"Success",description:`Brokerage "${Is.name}" and ${Zt.length} member(s) deleted`}),At(!1),jt(null),ur()}catch(Zt){console.error("Error deleting brokerage:",Zt),i({title:"Error",description:Zt.message||"Failed to delete brokerage",variant:"destructive"})}finally{cn(!1)}}},lh=Zt=>{sn(Zt),nn(""),Gs(!0)},qd=()=>{sn(null),nn(""),Gs(!1)},Wc=async Zt=>{try{const{error:$e}=await U.from("profiles").update({brokerage_id:null}).eq("id",Zt);if($e)throw $e;i({title:"Success",description:"User removed from brokerage"}),ur()}catch($e){console.error("Error removing user from brokerage:",$e),i({title:"Error",description:$e.message||"Failed to remove user",variant:"destructive"})}},Kh=async(Zt,$e)=>{try{const{error:yt}=await U.from("profiles").update({brokerage_id:$e}).eq("id",Zt);if(yt)throw yt;i({title:"Success",description:"User added to brokerage"}),ur()}catch(yt){console.error("Error adding user to brokerage:",yt),i({title:"Error",description:yt.message||"Failed to add user",variant:"destructive"})}},zb=async()=>{if(!Ls||!Cn.email||!Cn.name||!Cn.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}jr(!0);try{const{data:{session:Zt}}=await U.auth.getSession(),$e=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Zt==null?void 0:Zt.access_token}`},body:JSON.stringify({...Cn,brokerage_id:Ls.id,role:"user"})}),yt=await $e.json();if(!$e.ok)throw new Error(yt.error||"Failed to create agent");i({title:"Success",description:`Agent ${Cn.email} created successfully`}),Un({email:"",name:"",password:"",phone:""}),_n(!1),ur()}catch(Zt){console.error("Error creating agent:",Zt),i({title:"Error",description:Zt.message||"Failed to create agent",variant:"destructive"})}finally{jr(!1)}},Jm=Zt=>l.filter($e=>$e.brokerage_id===Zt),xy=Zt=>{const $e=Jm(Zt);if(!Hs)return $e;const yt=Hs.toLowerCase();return $e.filter(is=>is.name.toLowerCase().includes(yt)||is.email.toLowerCase().includes(yt))},Ef=Zt=>l.filter($e=>$e.brokerage_id!==Zt),Mf=l.filter(Zt=>{var yt;if(M){const is=M.toLowerCase();if(!(Zt.name.toLowerCase().includes(is)||Zt.email.toLowerCase().includes(is)||((yt=Zt.brokerage_name)==null?void 0:yt.toLowerCase().includes(is))))return!1}if(q==="claimed"&&!Zt.claimed||q==="unclaimed"&&Zt.claimed||G!=="all"&&!Zt.roles.includes(G))return!1;const $e=Zt.is_trial||Zt.subscription_status==="trialing";if(ee==="trial"&&!$e||ee==="non-trial"&&$e||le==="none"&&Zt.brokerage_id||le!=="all"&&le!=="none"&&Zt.brokerage_id!==le)return!1;if(oe!=="all"){if(!Zt.created_at)return!1;const is=parseInt(oe,10),us=Date.now()-is*24*60*60*1e3;if(new Date(Zt.created_at).getTime(){var $e;return(($e=Zt.name)==null?void 0:$e.toLowerCase())||""},brokerage:Zt=>{var $e;return(($e=Zt.brokerage_name)==null?void 0:$e.toLowerCase())||""},status:Zt=>Zt.claimed?"active":"pending",role:Zt=>Zt.roles[0]||"",last_login:Zt=>Zt.last_sign_in_at?new Date(Zt.last_sign_in_at).getTime():null,created_at:Zt=>Zt.created_at?new Date(Zt.created_at).getTime():null}),_m=ep.length,Ix=O===0,Ah=Ix?1:Math.ceil(_m/O),Vl=Ix?0:(L-1)*O,tp=Ix?_m:Vl+O,Cd=ep.slice(Vl,tp),g0=Zt=>{P(Zt),I(1)},Bb=Zt=>{$(Zt),I(1)},sp=(Zt,$e)=>{Zt($e),I(1)},ki=async(Zt,$e)=>{xe(!0);try{const yt=l.find(Dn=>Dn.id===Zt);if(!yt)return;const is=yt.trial_expires_at?new Date(yt.trial_expires_at):new Date,us=new Date(is.getTime()+$e*24*60*60*1e3),{error:en}=await U.from("profiles").update({trial_expires_at:us.toISOString()}).eq("id",Zt);if(en)throw en;i({title:"Trial Extended",description:`Trial extended by ${$e} days`}),ur()}catch(yt){console.error("Error extending trial:",yt),i({title:"Error",description:yt.message||"Failed to extend trial",variant:"destructive"})}finally{xe(!1)}},np=async Zt=>{Se(!0);try{const{error:$e}=await U.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",Zt);if($e)throw $e;i({title:"Account Converted",description:"User has been converted to a full account"}),ur(),ix()}catch($e){console.error("Error converting trial:",$e),i({title:"Error",description:$e.message||"Failed to convert account",variant:"destructive"})}finally{Se(!1)}},[gy,Yh]=j.useState(!1),Hp=async(Zt,$e)=>{if(await Bi(`Revert this user to a ${$e}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){Yh(!0);try{const yt=new Date,is=new Date(yt.getTime()+$e*24*60*60*1e3),{error:us}=await U.from("profiles").update({is_trial:!0,trial_started_at:yt.toISOString(),trial_expires_at:is.toISOString(),trial_claimed_at:yt.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",Zt);if(us)throw us;i({title:"Reverted to Trial",description:`User is now on a ${$e}-day free trial.`}),ur()}catch(yt){console.error("Error reverting to trial:",yt),i({title:"Error",description:yt.message||"Failed to revert to trial",variant:"destructive"})}finally{Yh(!1)}}},rp=async Zt=>{aa(!0);try{const{data:$e}=await U.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",Zt);if($e&&$e.length>0){const is=$e.map(en=>en.assistant_id),{data:us}=await U.from("profiles").select("id, name, email").in("id",is);Mr($e.map(en=>{const Dn=us==null?void 0:us.find(er=>er.id===en.assistant_id);return{id:en.id,assistant_id:en.assistant_id,assistant_name:(Dn==null?void 0:Dn.name)||"Unknown",assistant_email:(Dn==null?void 0:Dn.email)||"",permissions:en.permissions||{}}}))}else Mr([]);const{data:yt}=await U.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",Zt);if(yt&&yt.length>0){const is=yt.map(en=>en.agent_id),{data:us}=await U.from("profiles").select("id, name, email").in("id",is);Qt(yt.map(en=>{const Dn=us==null?void 0:us.find(er=>er.id===en.agent_id);return{id:en.id,agent_id:en.agent_id,agent_name:(Dn==null?void 0:Dn.name)||"Unknown",agent_email:(Dn==null?void 0:Dn.email)||"",permissions:en.permissions||{}}}))}else Qt([])}catch($e){console.error("Error loading assistant data:",$e)}finally{aa(!1)}},wm=Zt=>{Be(Zt),Oe({name:Zt.name,email:Zt.email,brokerage_id:Zt.brokerage_id||"",phone:Zt.phone||""}),Ge(!0),rp(Zt.id)},ix=()=>{Be(null),Ge(!1),Oe({name:"",email:"",brokerage_id:"",phone:""})},_g=async()=>{De&&(await fo(De.id),ix())},ap=Zt=>{gt($e=>{const yt=new Set($e);return yt.has(Zt)?yt.delete(Zt):yt.add(Zt),yt})},Zh=()=>{if(it.size===Cd.length&&Cd.every(Zt=>it.has(Zt.id))){const Zt=new Set(it);Cd.forEach($e=>Zt.delete($e.id)),gt(Zt)}else{const Zt=new Set(it);Cd.forEach($e=>Zt.add($e.id)),gt(Zt)}},Gp=()=>{gt(new Set)},Rx=async()=>{if(it.size===0)return;Ht(!0);let Zt=0,$e=0;try{const{data:{session:yt}}=await U.auth.getSession();for(const is of it)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${yt==null?void 0:yt.access_token}`},body:JSON.stringify({userId:is})})).ok?Zt++:$e++}catch{$e++}i({title:"Bulk Email Complete",description:`Sent ${Zt} emails${$e>0?`, ${$e} failed`:""}`}),Gp()}catch(yt){i({title:"Error",description:yt.message||"Failed to send emails",variant:"destructive"})}finally{Ht(!1)}},uv=async()=>{if(it.size===0)return;Ht(!0);let Zt=0,$e=0;try{const{data:{session:yt}}=await U.auth.getSession();for(const is of it)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${yt==null?void 0:yt.access_token}`},body:JSON.stringify({userId:is})})).ok?Zt++:$e++}catch{$e++}i({title:"Bulk Password Reset Complete",description:`Sent ${Zt} reset emails${$e>0?`, ${$e} failed`:""}`}),Gp()}catch(yt){i({title:"Error",description:yt.message||"Failed to send password reset emails",variant:"destructive"})}finally{Ht(!1)}},rd=async()=>{if(it.size===0)return;const Zt=l.filter(us=>it.has(us.id)).map(us=>us.name).slice(0,5).join(", "),$e=it.size>5?` and ${it.size-5} more`:"";if(!await Bi(`Are you sure you want to delete ${it.size} users (${Zt}${$e})? This action cannot be undone.`))return;Ht(!0);let yt=0,is=0;try{const{data:{session:us}}=await U.auth.getSession();for(const en of it)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${us==null?void 0:us.access_token}`},body:JSON.stringify({userId:en})})).ok?yt++:is++}catch{is++}i({title:"Bulk Delete Complete",description:`Deleted ${yt} users${is>0?`, ${is} failed`:""}`}),Gp(),ur()}catch(us){i({title:"Error",description:us.message||"Failed to delete users",variant:"destructive"})}finally{Ht(!1)}},Tc=async()=>{Ms(!0);try{const{data:{session:Zt}}=await U.auth.getSession(),$e=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Zt==null?void 0:Zt.access_token}`}});if(!$e.ok){const is=await $e.json();throw new Error(is.error||"Failed to sync phones")}const yt=await $e.json();i({title:"Phone Sync Complete",description:`Pulled ${yt.summary.pulledFromGHL} from GHL, pushed ${yt.summary.pushedToGHL} to GHL, ${yt.summary.alreadySynced} already synced`}),ur()}catch(Zt){i({title:"Error",description:Zt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{Ms(!1)}},ip=async(Zt,$e)=>{Zs(Zt);try{const{data:{session:yt}}=await U.auth.getSession(),{data:is}=await U.from("profiles").select("phone").eq("id",Zt).single(),us=(is==null?void 0:is.phone)||"",en=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${yt==null?void 0:yt.access_token}`},body:JSON.stringify({email:$e,action:"update",phone:us||void 0})});if(!en.ok){const er=await en.json();throw new Error(er.error||"Failed to sync with GHL")}const Dn=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent($e)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:us?`Phone ${us} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),ur()}catch(yt){i({title:"Error",description:yt.message||"Failed to sync phone",variant:"destructive"})}finally{Zs(null)}},Vd=async Zt=>{await r(Zt)},op=()=>{if(it.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const Zt=l.filter(er=>it.has(er.id)),$e=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],yt=Zt.map(er=>[er.name,er.email,er.phone||"",er.brokerage_name||"",er.roles.join("; "),er.claimed?"Claimed":"Unclaimed",new Date(er.created_at).toLocaleDateString()]),is=[$e.join(","),...yt.map(er=>er.map(xr=>`"${(xr||"").replace(/"/g,'""')}"`).join(","))].join(` `),us=new Blob([is],{type:"text/csv"}),en=URL.createObjectURL(us),Dn=document.createElement("a");Dn.href=en,Dn.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Dn.click(),URL.revokeObjectURL(en),i({title:"Export complete",description:`Exported ${Zt.length} member(s)`})},Xh=()=>{if(Mf.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const Zt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],$e=Mf.map(er=>[er.name,er.email,er.phone||"",er.brokerage_name||"",er.roles.join("; "),er.claimed?"Claimed":"Unclaimed",er.created_at?new Date(er.created_at).toLocaleDateString():""]),yt=[Zt.join(","),...$e.map(er=>er.map(xr=>`"${(xr||"").replace(/"/g,'""')}"`).join(","))].join(` `),is=new Blob([yt],{type:"text/csv"}),us=URL.createObjectURL(is),en=document.createElement("a"),Dn=oe!=="all"?`-last-${oe}days`:"";en.href=us,en.download=`members-export${Dn}-${new Date().toISOString().split("T")[0]}.csv`,en.click(),URL.revokeObjectURL(us),i({title:"Export complete",description:`Exported ${Mf.length} member(s)`})};return x?e.jsx(Vs,{title:"Members",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(Vs,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{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(hd,{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:Tc,disabled:ts,children:[ts?e.jsx(Wt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(pa,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:ts?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:ts?"Syncing...":"Sync GHL"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Ba(!0),children:[e.jsx(pN,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Import CSV"}),e.jsx("span",{className:"sm:hidden",children:"Import"})]}),e.jsxs(Fs,{open:C,onOpenChange:T,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Sl,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Add Member"}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})}),e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Create New User"}),e.jsx(kr,{children:"Add a new user to the system. They'll be able to sign in immediately."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",placeholder:"John Doe",value:v.name,onChange:Zt=>k({...v,name:Zt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",placeholder:"john@example.com",value:v.email,onChange:Zt=>k({...v,email:Zt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"password",children:"Password"}),e.jsx(ye,{id:"password",type:"password",placeholder:"Min 6 characters",value:v.password,onChange:Zt=>k({...v,password:Zt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(ye,{id:"phone",type:"tel",placeholder:"555-123-4567",value:v.phone,onChange:Zt=>k({...v,phone:Zt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"brokerage",children:["Brokerage",v.role==="brokerage_manager"?" (required)":""]}),e.jsxs(vs,{value:v.brokerage_id||"none",onValueChange:Zt=>k({...v,brokerage_id:Zt==="none"?"":Zt}),children:[e.jsx(gs,{id:"brokerage",children:e.jsx(bs,{placeholder:v.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"None"}),u.map(Zt=>e.jsx(Je,{value:Zt.id,children:Zt.name},Zt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"role",children:"Role"}),e.jsxs(vs,{value:v.role,onValueChange:Zt=>k({...v,role:Zt}),children:[e.jsx(gs,{id:"role",children:e.jsx(bs,{placeholder:"Select role"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"user",children:"User"}),e.jsx(Je,{value:"moderator",children:"Moderator"}),e.jsx(Je,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(Je,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(vs,{value:v.trial_days||"none",onValueChange:Zt=>k({...v,trial_days:Zt==="none"?"":Zt}),children:[e.jsx(gs,{id:"trial_days",children:e.jsx(bs,{placeholder:"No trial (full access)"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No trial (full access)"}),e.jsx(Je,{value:"7",children:"7-day trial"}),e.jsx(Je,{value:"30",children:"30-day trial"}),e.jsx(Je,{value:"60",children:"60-day trial"}),e.jsx(Je,{value:"90",children:"90-day trial"}),e.jsx(Je,{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(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>T(!1),children:"Cancel"}),e.jsx(B,{onClick:Gr,disabled:g,children:g?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(fa,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"members",children:"Members"}),e.jsx(ss,{value:"brokerages",children:"Brokerages"}),e.jsx(ss,{value:"teams",children:"Teams"}),e.jsx(ss,{value:"trials",children:"Trial Users"}),e.jsx(ss,{value:"access",children:"Access Matrix"}),e.jsx(ss,{value:"celebrations",children:"Celebrations"}),e.jsx(ss,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(ns,{value:"members",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search members...",value:M,onChange:Zt=>g0(Zt.target.value),className:"pl-10 h-9"})]}),e.jsxs(vs,{value:q,onValueChange:Zt=>sp(W,Zt),children:[e.jsx(gs,{className:"w-[130px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Status"}),e.jsx(Je,{value:"claimed",children:"Active"}),e.jsx(Je,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(vs,{value:G,onValueChange:Zt=>sp(K,Zt),children:[e.jsx(gs,{className:"w-[130px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Roles"}),e.jsx(Je,{value:"admin",children:"Admin"}),e.jsx(Je,{value:"brokerage_manager",children:"Manager"}),e.jsx(Je,{value:"assistant",children:"Assistant"}),e.jsx(Je,{value:"user",children:"User"})]})]}),e.jsxs(vs,{value:ee,onValueChange:Zt=>sp(J,Zt),children:[e.jsx(gs,{className:"w-[130px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Users"}),e.jsx(Je,{value:"trial",children:"Trial Only"}),e.jsx(Je,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(vs,{value:le,onValueChange:Zt=>sp(ue,Zt),children:[e.jsx(gs,{className:"w-[150px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Brokerages"}),e.jsx(Je,{value:"none",children:"No Brokerage"}),u.map(Zt=>e.jsx(Je,{value:Zt.id,children:Zt.name},Zt.id))]})]}),e.jsxs(vs,{value:oe,onValueChange:Zt=>sp(ie,Zt),children:[e.jsx(gs,{className:"w-[150px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"Any Join Date"}),e.jsx(Je,{value:"30",children:"Joined Last 30 Days"}),e.jsx(Je,{value:"60",children:"Joined Last 60 Days"}),e.jsx(Je,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-9",onClick:Xh,title:"Export currently filtered members to CSV",children:[e.jsx(ii,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(M||q!=="all"||G!=="all"||ee!=="all"||le!=="all"||oe!=="all")&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{P(""),W("all"),K("all"),J("all"),ue("all"),ie("all"),I(1)},children:[e.jsx(dr,{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:Ix?`Showing all ${_m} members`:`Showing ${Vl+1}-${Math.min(tp,_m)} of ${_m} members`}),e.jsxs(vs,{value:O.toString(),onValueChange:Zt=>Bb(Number(Zt)),children:[e.jsx(gs,{className:"h-9 w-[110px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"50",children:"50 / page"}),e.jsx(Je,{value:"100",children:"100 / page"}),e.jsx(Je,{value:"250",children:"250 / page"}),e.jsx(Je,{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:[Cd.length>0&&Cd.every(Zt=>it.has(Zt.id))&&ep.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:()=>gt(new Set(ep.map(Zt=>Zt.id))),children:["Select all ",ep.length," filtered members"]})]}),ep.length>0&&it.size===ep.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",ep.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(k4,{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:Rx,disabled:St,children:[St?e.jsx(Wt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(on,{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:uv,disabled:St,children:[St?e.jsx(Wt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(gb,{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:()=>we(!0),disabled:St,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(hN,{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:op,children:[e.jsx(ii,{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:rd,disabled:St,children:[St?e.jsx(Wt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Rn,{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:Gp,disabled:St,children:e.jsx(dr,{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(Tt,{className:"w-[50px]",children:e.jsx(wi,{checked:Cd.length>0&&Cd.every(Zt=>it.has(Zt.id)),onCheckedChange:Zh,"aria-label":"Select all on page"})}),e.jsx(Wu,{sortKey:"name",currentSortKey:pu,currentDirection:Px,onSort:Do,children:"Name"}),e.jsx(Wu,{sortKey:"brokerage",currentSortKey:pu,currentDirection:Px,onSort:Do,children:"Brokerage"}),e.jsx(Wu,{sortKey:"status",currentSortKey:pu,currentDirection:Px,onSort:Do,children:"Status"}),e.jsx(Wu,{sortKey:"role",currentSortKey:pu,currentDirection:Px,onSort:Do,children:"Role"}),e.jsx(Wu,{sortKey:"last_login",currentSortKey:pu,currentDirection:Px,onSort:Do,children:"Last Login"}),e.jsx(Wu,{sortKey:"created_at",currentSortKey:pu,currentDirection:Px,onSort:Do,children:"Member Since"}),e.jsx(Tt,{className:"w-[100px]"})]})}),e.jsx(za,{children:Cd.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):Cd.map(Zt=>e.jsxs(un,{className:`hover:bg-muted/30 ${it.has(Zt.id)?"bg-primary/5":""}`,children:[e.jsx(xt,{children:e.jsx(wi,{checked:it.has(Zt.id),onCheckedChange:()=>ap(Zt.id),"aria-label":`Select ${Zt.name}`})}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>wm(Zt),className:"text-primary hover:underline font-medium text-left",children:Zt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Zt.email})]})}),e.jsx(xt,{className:"text-muted-foreground",children:Zt.brokerage_name||"—"}),e.jsx(xt,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const $e=Zt.trial_expires_at||Zt.subscription_end_date;if((Zt.is_trial||Zt.subscription_status==="trialing")&&$e){const is=Math.ceil((new Date($e).getTime()-Date.now())/864e5),us=is<=0,en=is<=3;return e.jsx(qe,{variant:"outline",className:Et("w-fit",us?"border-destructive text-destructive":en?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:us?"Trial Expired":`Trial · ${is}d left`})}return e.jsx(qe,{variant:Zt.claimed?"default":"secondary",className:Zt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:Zt.claimed?"Active":"Pending"})})()})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-col",children:[Zt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:Zt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),Zt.roles.includes("assistant")&&zr[Zt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",zr[Zt.id].agent_name||zr[Zt.id].agent_email]})]})}),e.jsx(xt,{className:"text-muted-foreground",children:Zt.last_sign_in_at?new Date(Zt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(xt,{className:"text-muted-foreground",children:Zt.created_at?new Date(Zt.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(xt,{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:()=>{Jr(Zt),vn(!0)},title:"Send celebration",children:e.jsx(bf,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>wm(Zt),title:"Edit member",children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>ip(Zt.id,Zt.email),disabled:js===Zt.id,title:"Sync phone with GHL",children:js===Zt.id?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(pa,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Va(Zt.id),title:"Resend welcome email",children:e.jsx(on,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>So(Zt.email,Zt.name),title:"Send password reset",children:e.jsx(b3,{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:()=>Vd(Zt.id),disabled:a||Zt.id===(t==null?void 0:t.id),title:Zt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Zt.name}`,children:a?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx($R,{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:()=>$a(Zt.id,Zt.name),title:"Delete user",children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},Zt.id))})]})}),Ah>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 ",L," of ",Ah]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>I(1),disabled:L===1,children:"First"}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(Zt=>Math.max(1,Zt-1)),disabled:L===1,children:e.jsx(Cc,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,Ah)},(Zt,$e)=>{let yt;return Ah<=5||L<=3?yt=$e+1:L>=Ah-2?yt=Ah-4+$e:yt=L-2+$e,e.jsx(B,{variant:L===yt?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>I(yt),children:yt},yt)})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(Zt=>Math.min(Ah,Zt+1)),disabled:L===Ah,children:e.jsx(Qa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>I(Ah),disabled:L===Ah,children:"Last"})]})]})]}),e.jsx(Fs,{open:Ne,onOpenChange:Ge,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Edit Member"}),e.jsx(kr,{children:"Update member details, roles, and app access"})]}),De&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Basic Information"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-name",children:"Name"}),e.jsx(ye,{id:"edit-name",value:_e.name,onChange:Zt=>Oe({..._e,name:Zt.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-email",children:"Email"}),e.jsx(ye,{id:"edit-email",type:"email",value:_e.email,onChange:Zt=>Oe({..._e,email:Zt.target.value}),maxLength:255})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(ye,{id:"edit-phone",type:"tel",value:_e.phone,onChange:Zt=>Oe({..._e,phone:Zt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(vs,{value:_e.brokerage_id||"none",onValueChange:Zt=>Oe({..._e,brokerage_id:Zt==="none"?"":Zt}),children:[e.jsx(gs,{id:"edit-brokerage",children:e.jsx(bs,{placeholder:"Select brokerage"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"None"}),u.map(Zt=>e.jsx(Je,{value:Zt.id,children:Zt.name},Zt.id))]})]})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Roles"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[De.roles.map(Zt=>e.jsxs(qe,{variant:"default",className:"gap-1",children:[e.jsx(_f,{className:"h-3 w-3"}),Zt,Zt==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>Qn(De.id,Zt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(dr,{className:"h-3 w-3"})})]},Zt)),De.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(vs,{onValueChange:Zt=>Qn(De.id,Zt,"add"),children:[e.jsx(gs,{className:"w-[200px]",children:e.jsx(bs,{placeholder:"Add role..."})}),e.jsxs(ys,{children:[!De.roles.includes("admin")&&e.jsx(Je,{value:"admin",children:"Admin"}),!De.roles.includes("user")&&e.jsx(Je,{value:"user",children:"User"})]})]}),!De.roles.includes("brokerage_manager")&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"To add as brokerage manager, use Brokerages tab → Manage"})]}),(ha.length>0||Xr.length>0||De.roles.includes("assistant"))&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),"Assistant Relationships"]}),Zn?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[ha.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:"}),ha.map(Zt=>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:Zt.assistant_name}),e.jsx(qe,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Zt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Zt.permissions).filter(([,$e])=>$e).map(([$e])=>e.jsx(qe,{variant:"secondary",className:"text-[10px] capitalize",children:$e},$e))})]},Zt.id))]}),Xr.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:"}),Xr.map(Zt=>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:Zt.agent_name}),e.jsx(qe,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Zt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Zt.permissions).filter(([,$e])=>$e).map(([$e])=>e.jsx(qe,{variant:"secondary",className:"text-[10px] capitalize",children:$e},$e))})]},Zt.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(Zt=>{const $e=qa(De.tags,Zt.required_tags),yt=`${De.id}-${Zt.id}`,is=Ae===yt,us=Zt.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:Zt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:Zt.name}),us&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:is?e.jsx(Wt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):us?e.jsx(qe,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(Mn,{checked:$e,onCheckedChange:()=>xo(De.id,Zt,$e)})})]},Zt.id)})})]}),(De.is_trial||De.subscription_status==="trialing")&&e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Vr,{className:"h-4 w-4"}),"Trial Status"]}),e.jsxs("div",{className:"p-4 rounded-lg border bg-amber-50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-800",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[De.trial_expires_at&&e.jsx(Klt,{expiresAt:De.trial_expires_at}),!De.trial_expires_at&&De.subscription_status==="trialing"&&De.subscription_end_date&&e.jsx(Klt,{expiresAt:De.subscription_end_date})]}),(De.trial_expires_at||De.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(De.trial_expires_at||De.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>ki(De.id,7),disabled:je,children:[e.jsx(Wy,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>ki(De.id,14),disabled:je,children:[e.jsx(Wy,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>ki(De.id,30),disabled:je,children:[e.jsx(Wy,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(B,{size:"sm",variant:"default",onClick:()=>np(De.id),disabled:fe,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(bN,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),De.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(De.trial_started_at).toLocaleDateString(),De.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(De.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(De.is_trial||De.subscription_status==="trialing")&&e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Vr,{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(Zt=>e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Hp(De.id,Zt),disabled:gy,children:[e.jsx(Wy,{className:"h-4 w-4 mr-1"}),Zt,"-day trial"]},Zt))})]})]}),e.jsxs("div",{className:"space-y-2 pt-4 border-t",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Account Information"}),e.jsxs("div",{className:"text-sm space-y-1 text-muted-foreground",children:[De.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(De.email_confirmed_at).toLocaleString()]}),De.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(De.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(De.created_at).toLocaleString()]})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:ix,children:"Cancel"}),e.jsx(B,{onClick:_g,children:"Save Changes"})]})]})}),e.jsxs(ns,{value:"access",children:[c.length===0?e.jsx(be,{children:e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Member Access Matrix"}),e.jsx(fr,{children:"Toggle switches to grant or revoke app access for each member"})]}),e.jsxs("div",{className:"relative w-full sm:w-72",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents by name or email...",value:M,onChange:Zt=>{P(Zt.target.value),I(1)},className:"pl-9"})]})]}),e.jsxs(Re,{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(Zt=>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:Zt.icon}),e.jsx("span",{className:"text-sm",children:Zt.name})]})},Zt.id))]})}),e.jsxs("tbody",{children:[Cd.map(Zt=>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:Zt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Zt.email})]})}),c.map($e=>{const yt=qa(Zt.tags,$e.required_tags),is=`${Zt.id}-${$e.id}`,us=Ae===is;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:us?e.jsx(Wt,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(Mn,{checked:yt,onCheckedChange:()=>xo(Zt.id,$e,yt),disabled:$e.required_tags.length===0})})},$e.id)})]},Zt.id)),Cd.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"})})]})]})}),Ah>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 ",Vl+1,"-",Math.min(tp,_m)," of ",_m," • Page ",L," of ",Ah]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(Zt=>Math.max(1,Zt-1)),disabled:L===1,children:e.jsx(Cc,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>I(Zt=>Math.min(Ah,Zt+1)),disabled:L===Ah,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(ns,{value:"brokerages",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search brokerages...",value:Hr,onChange:Zt=>mr(Zt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(Zt=>Zt.name.toLowerCase().includes(Hr.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 Zt=[];for(const Dn of u){const er=m[Dn.id]??[];for(const xr of er){const Ha=l.find(Zi=>Zi.id===xr);if(Ha){const Zi=(Ha.name||"").trim().split(/\s+/),Hi=Zi[0]||"",rl=Zi.slice(1).join(" ")||"";Zt.push({firstName:Hi,lastName:rl,email:Ha.email,brokerageName:Dn.name})}}}if(Zt.length===0){i({title:"No managers found to export"});return}const yt=[["First Name","Last Name","Email","Brokerage Name"].join(","),...Zt.map(Dn=>[Dn.firstName,Dn.lastName,Dn.email,Dn.brokerageName].map(er=>`"${(er||"").replace(/"/g,'""')}"`).join(","))].join(` `),is=new Blob([yt],{type:"text/csv"}),us=URL.createObjectURL(is),en=document.createElement("a");en.href=us,en.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,en.click(),URL.revokeObjectURL(us),i({title:`Exported ${Zt.length} managers`})},children:[e.jsx(ii,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(Fs,{open:Ue,onOpenChange:Ze,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Ni,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Create New Brokerage"}),e.jsx(kr,{children:"Add a new brokerage to the system."})]}),e.jsx("div",{className:"space-y-4 py-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(ye,{id:"brokerage-name",placeholder:"Enter brokerage name",value:Qe,onChange:Zt=>Ye(Zt.target.value),maxLength:100})]})}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ze(!1),children:"Cancel"}),e.jsx(B,{onClick:Wo,disabled:nt,children:nt?"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(Tt,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Tt,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Tt,{className:"font-semibold",children:"Agents"}),e.jsx(Tt,{className:"w-[150px]"})]})}),e.jsx(za,{children:(()=>{const Zt=u.filter($e=>$e.name.toLowerCase().includes(Hr.toLowerCase()));return Zt.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:Hr?"No brokerages match your search":"No brokerages found"})}):Zt.map($e=>{const yt=l.filter(Dn=>Dn.brokerage_id===$e.id),us=(m[$e.id]??[]).map(Dn=>l.find(er=>er.id===Dn)).filter(Boolean),en=yt.length;return e.jsxs(un,{className:"hover:bg-muted/30",children:[e.jsx(xt,{children:e.jsx("button",{onClick:()=>Co($e),className:"text-primary hover:underline font-medium",children:$e.name})}),e.jsx(xt,{children:us.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:us.map(Dn=>e.jsx(qe,{variant:"secondary",className:"text-xs",children:Dn.name},Dn.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(xt,{children:[en," member",en!==1?"s":""]}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"h-8",onClick:()=>lh($e),children:[e.jsx(Bn,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Co($e),title:"Edit brokerage",children:e.jsx(Za,{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:()=>Qm($e),title:"Delete brokerage",children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},$e.id)})})()})]})}),e.jsx(Fs,{open:Fe,onOpenChange:dt,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Edit Brokerage"}),e.jsx(kr,{children:"Update brokerage details and manage managers"})]}),Dt&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(ye,{id:"edit-brokerage-name",value:zt,onChange:Zt=>Gt(Zt.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Managers"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click × to remove manager access for this brokerage (keeps them as a member)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(()=>{const $e=(m[Dt.id]??[]).map(yt=>l.find(is=>is.id===yt)).filter(Boolean);return $e.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):$e.map(yt=>e.jsxs(qe,{variant:"default",className:"gap-1",children:[e.jsx(_f,{className:"h-3 w-3"}),yt.name,e.jsx("button",{onClick:()=>Qn(yt.id,"brokerage_manager","remove",Dt.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(dr,{className:"h-3 w-3"})})]},yt.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(lc,{open:pr,onOpenChange:rn,children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":pr,className:"w-full justify-between",children:["Search for a member...",e.jsx(Fr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Jl,{className:"w-full p-0",align:"start",children:e.jsxs(Sb,{children:[e.jsx(Cb,{placeholder:"Search by name or email..."}),e.jsxs(Ab,{className:"max-h-[200px]",children:[e.jsx(Tb,{children:"No members found."}),e.jsx(Eb,{children:(()=>{const Zt=new Set(m[Dt.id]??[]);return l.filter($e=>!Zt.has($e.id)&&(n||$e.brokerage_id===Dt.id)).map($e=>e.jsxs(Yy,{value:`${$e.name} ${$e.email}`,onSelect:()=>{Mu($e.id,Dt.id),rn(!1)},children:[$e.name," (",$e.email,")"]},$e.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(Zt=>Zt.brokerage_id===Dt.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(Zt=>Zt.brokerage_id===Dt.id).map(Zt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:Zt.name}),Zt.roles.includes("brokerage_manager")&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"Manager"})]},Zt.id))})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:Ko,children:"Cancel"}),e.jsx(B,{onClick:Ud,disabled:qs,children:qs?"Saving...":"Save Changes"})]})]})}),e.jsx(Fs,{open:Bt,onOpenChange:At,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(kr,{children:['Are you sure you want to delete "',Is==null?void 0:Is.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 "',Is==null?void 0:Is.name,'"']}),e.jsxs("li",{children:["All ",l.filter(Zt=>Zt.brokerage_id===(Is==null?void 0:Is.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>At(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Gc,disabled:Qs,children:Qs?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(Fs,{open:qt,onOpenChange:Gs,children:e.jsxs(Os,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Ni,{className:"h-5 w-5"}),"Manage ",Ls==null?void 0:Ls.name]}),e.jsx(kr,{children:"Add, remove, or manage users in this brokerage"})]}),Ls&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search members...",value:Hs,onChange:Zt=>nn(Zt.target.value),className:"pl-10 h-9"})]}),e.jsxs(Fs,{open:tn,onOpenChange:_n,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Sl,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Add New Agent"}),e.jsxs(kr,{children:["Create a new agent for ",Ls.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-name",children:"Name"}),e.jsx(ye,{id:"agent-name",placeholder:"John Doe",value:Cn.name,onChange:Zt=>Un({...Cn,name:Zt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-email",children:"Email"}),e.jsx(ye,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Cn.email,onChange:Zt=>Un({...Cn,email:Zt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-password",children:"Password"}),e.jsx(ye,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Cn.password,onChange:Zt=>Un({...Cn,password:Zt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(ye,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Cn.phone,onChange:Zt=>Un({...Cn,phone:Zt.target.value})})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>_n(!1),children:"Cancel"}),e.jsx(B,{onClick:zb,disabled:Kr,children:Kr?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(lc,{open:Jn,onOpenChange:ea,children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":Jn,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(Fr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Jl,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Sb,{children:[e.jsx(Cb,{placeholder:"Search users...",value:_s,onValueChange:We}),e.jsxs(Ab,{children:[e.jsx(Tb,{children:"No users found."}),e.jsx(Eb,{children:Ef(Ls.id).filter(Zt=>_s===""||Zt.name.toLowerCase().includes(_s.toLowerCase())||Zt.email.toLowerCase().includes(_s.toLowerCase())).map(Zt=>e.jsxs(Yy,{value:`${Zt.name} ${Zt.email}`,onSelect:()=>{Kh(Zt.id,Ls.id),ea(!1),We("")},children:[Zt.name," (",Zt.email,")"]},Zt.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(Tt,{className:"font-semibold",children:"Name"}),e.jsx(Tt,{className:"font-semibold",children:"Email"}),e.jsx(Tt,{className:"font-semibold",children:"Status"}),e.jsx(Tt,{className:"font-semibold",children:"Role"}),e.jsx(Tt,{className:"w-[120px]"})]})}),e.jsx(za,{children:xy(Ls.id).length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:Hs?"No matching members found":"No members in this brokerage"})}):xy(Ls.id).map(Zt=>e.jsxs(un,{className:"hover:bg-muted/30",children:[e.jsx(xt,{className:"font-medium",children:Zt.name}),e.jsx(xt,{className:"text-muted-foreground",children:Zt.email}),e.jsx(xt,{children:Zt.claimed?e.jsx(qe,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(qe,{variant:"secondary",children:"Pending"})}),e.jsx(xt,{children:Zt.roles.includes("brokerage_manager")?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(_f,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!Zt.claimed&&e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Va(Zt.id),title:"Resend welcome email",children:e.jsx(on,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Wc(Zt.id),title:"Remove from brokerage",children:e.jsx(dr,{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:()=>Vd(Zt.id),disabled:a||Zt.id===(t==null?void 0:t.id),title:Zt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Zt.name}`,children:a?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx($R,{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:()=>$a(Zt.id,Zt.name),title:"Delete user",children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},Zt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Jm(Ls.id).length," total member",Jm(Ls.id).length!==1?"s":""," •",Jm(Ls.id).filter(Zt=>Zt.roles.includes("brokerage_manager")).length," manager",Jm(Ls.id).filter(Zt=>Zt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(Nr,{children:e.jsx(B,{variant:"outline",onClick:qd,children:"Close"})})]})})]}),e.jsx(ns,{value:"teams",children:e.jsx(_7s,{})}),e.jsx(ns,{value:"trials",children:e.jsx(x7s,{})}),e.jsx(ns,{value:"celebrations",children:e.jsx(f7s,{})}),e.jsx(ns,{value:"deletions",children:e.jsx(y7s,{})})]})]}),e.jsx(IMt,{open:Xs,onOpenChange:Ba,brokerages:u,onSuccess:ur}),_r&&e.jsx(RMt,{open:Tn,onOpenChange:Zt=>{vn(Zt),Zt||Jr(null)},userId:_r.id,userName:_r.name}),e.jsx(w7s,{open:de,onOpenChange:we,recipients:l.filter(Zt=>it.has(Zt.id)).map(Zt=>({id:Zt.id,name:Zt.name,email:Zt.email}))})]})};function N7s(){const{toast:s}=pi(),t=as(),[n,r]=j.useState(""),[a,i]=j.useState(new Set),[l,o]=j.useState({}),[c,d]=j.useState({}),[u,h]=j.useState(""),[m,p]=j.useState(!1),{data:x=[],isLoading:y}=mt({queryKey:["unassigned-members"],queryFn:async()=>{const{data:L,error:I}=await U.from("profiles").select("id, name, email, phone, created_at, subscription_status").is("brokerage_id",null).or("subscription_status.is.null,subscription_status.eq.none").order("created_at",{ascending:!1});if(I)throw I;return L||[]}}),{data:g=[]}=mt({queryKey:["brokerages-all"],queryFn:async()=>{const{data:L,error:I}=await U.from("brokerages").select("id, name").order("name");if(I)throw I;return L||[]}}),b=j.useMemo(()=>{const L=n.toLowerCase().trim();return L?x.filter(I=>(I.name||"").toLowerCase().includes(L)||(I.email||"").toLowerCase().includes(L)||(I.phone||"").toLowerCase().includes(L)):x},[x,n]),v=j.useMemo(()=>{var I;const L=new Map;for(const O of x){const $=(I=(O.email||"").split("@")[1])==null?void 0:I.toLowerCase();$&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes($)||L.set($,(L.get($)||0)+1))}return Array.from(L.entries()).sort((O,$)=>$[1]-O[1]).slice(0,10)},[x]),k=L=>{i(I=>{const O=new Set(I);return O.has(L)?O.delete(L):O.add(L),O})},C=()=>{a.size===b.length?i(new Set):i(new Set(b.map(L=>L.id)))},T=async(L,I)=>{if(I){d(O=>({...O,[L]:!0}));try{const{data:O,error:$}=await U.functions.invoke("assign-brokerage",{body:{userId:L,brokerageId:I}});if($)throw $;if(O!=null&&O.error)throw new Error(O.error);s({title:"Assigned",description:"Member added to brokerage."}),t.invalidateQueries({queryKey:["unassigned-members"]}),i(q=>{const W=new Set(q);return W.delete(L),W})}catch(O){s({title:"Failed",description:O.message,variant:"destructive"})}finally{d(O=>({...O,[L]:!1}))}}},M=async()=>{if(!u||a.size===0)return;p(!0);let L=0,I=0;for(const O of a)try{const{data:$,error:q}=await U.functions.invoke("assign-brokerage",{body:{userId:O,brokerageId:u}});if(q||$!=null&&$.error)throw new Error((q==null?void 0:q.message)||$.error);L++}catch{I++}p(!1),s({title:`Assigned ${L}${I?`, ${I} failed`:""}`,description:"Bulk assignment complete.",variant:I?"destructive":"default"}),i(new Set),h(""),t.invalidateQueries({queryKey:["unassigned-members"]})},P=(L,I)=>{const O={...l};for(const $ of x)($.email||"").toLowerCase().endsWith(`@${L}`)&&(O[$.id]=I);o(O),s({title:"Suggestions applied",description:`Pre-filled brokerage for @${L}`})};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{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(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(Re,{children:e.jsx("div",{className:"text-3xl font-bold",children:x.length})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Ni,{className:"h-4 w-4"})," Selected"]})}),e.jsx(Re,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4"})," Top email domains"]})}),e.jsx(Re,{children:e.jsx("div",{className:"text-3xl font-bold",children:v.length})})]})]}),v.length>0&&e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Domain suggestions"})}),e.jsx(Re,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:v.map(([L,I])=>{const O=g.find($=>$.name.toLowerCase().replace(/[^a-z0-9]/g,"").includes(L.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:["@",L]}),e.jsx(qe,{variant:"secondary",children:I}),e.jsxs(vs,{onValueChange:$=>P(L,$),defaultValue:O==null?void 0:O.id,children:[e.jsx(gs,{className:"h-8 w-[220px]",children:e.jsx(bs,{placeholder:"Apply brokerage…"})}),e.jsx(ys,{children:g.map($=>e.jsx(Je,{value:$.id,children:$.name},$.id))})]})]},L)})})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"relative w-full md:w-96",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:n,onChange:L=>r(L.target.value),placeholder:"Search name, email, phone…",className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(vs,{value:u,onValueChange:h,children:[e.jsx(gs,{className:"w-[240px]",children:e.jsx(bs,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(ys,{children:g.map(L=>e.jsx(Je,{value:L.id,children:L.name},L.id))})]}),e.jsxs(B,{onClick:M,disabled:!u||a.size===0||m,children:[m&&e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(Re,{children:y?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length===0?e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"🎉 No unassigned members."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{className:"w-10",children:e.jsx(wi,{checked:a.size===b.length&&b.length>0,onCheckedChange:C})}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Signed up"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Assign to brokerage"}),e.jsx(Tt,{className:"w-24"})]})}),e.jsx(za,{children:b.map(L=>{const I=l[L.id]||"";return e.jsxs(un,{children:[e.jsx(xt,{children:e.jsx(wi,{checked:a.has(L.id),onCheckedChange:()=>k(L.id)})}),e.jsx(xt,{className:"font-medium",children:L.name||"—"}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:L.email}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:oc(new Date(L.created_at),{addSuffix:!0})}),e.jsx(xt,{children:e.jsx(qe,{variant:"outline",children:L.subscription_status||"none"})}),e.jsx(xt,{children:e.jsxs(vs,{value:I,onValueChange:O=>o($=>({...$,[L.id]:O})),children:[e.jsx(gs,{className:"h-9 w-[240px]",children:e.jsx(bs,{placeholder:"Pick brokerage…"})}),e.jsx(ys,{children:g.map(O=>e.jsx(Je,{value:O.id,children:O.name},O.id))})]})}),e.jsx(xt,{children:e.jsx(B,{size:"sm",disabled:!I||c[L.id],onClick:()=>T(L.id,I),children:c[L.id]?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},L.id)})})]})})})]})]})})}const k7s=()=>{const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState("");j.useEffect(()=>{x()},[]);const x=async()=>{const{data:T,error:M}=await U.from("invite_codes").select("*").order("created_at",{ascending:!1});M?(re.error("Failed to load invite codes"),console.error(M)):t(T||[]),r(!1)},y=async T=>{if(T.preventDefault(),!l.trim()){re.error("Please enter a code");return}i(!0);const{error:M}=await U.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:u?parseInt(u):null,trial_days:m?parseInt(m):null});M?M.code==="23505"?re.error("This code already exists"):(re.error("Failed to create invite code"),console.error(M)):(re.success("Invite code created"),o(""),d(""),h(""),p(""),x()),i(!1)},g=async(T,M)=>{const{error:P}=await U.from("invite_codes").update({is_active:!M}).eq("id",T);P?re.error("Failed to update code"):t(s.map(L=>L.id===T?{...L,is_active:!M}:L))},b=async T=>{const{error:M}=await U.from("invite_codes").delete().eq("id",T);M?re.error("Failed to delete code"):(re.success("Code deleted"),t(s.filter(P=>P.id!==T)))},v="https://dashboard.relevelup.com",k=T=>{const M=`${v}/join?code=${T}`;navigator.clipboard.writeText(M),re.success("Link copied to clipboard")},C=`${v}/join`;return e.jsx(Vs,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Create New Code"}),e.jsxs(fr,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:C})]})]}),e.jsx(Re,{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(se,{htmlFor:"code",children:"Code"}),e.jsx(ye,{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(se,{htmlFor:"description",children:"Description (optional)"}),e.jsx(ye,{id:"description",placeholder:"For marketing campaign",value:c,onChange:T=>d(T.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(ye,{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(se,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(ye,{id:"trialDays",type:"number",placeholder:"None",value:m,onChange:T=>p(T.target.value),className:"w-28"})]}),e.jsxs(B,{type:"submit",disabled:a,children:[a?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Active Codes"})}),e.jsx(Re,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Wt,{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(Tt,{children:"Code"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Uses"}),e.jsx(Tt,{children:"Trial"}),e.jsx(Tt,{children:"Created"}),e.jsx(Tt,{children:"Active"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:s.map(T=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-mono font-medium",children:T.code}),e.jsx(xt,{className:"text-muted-foreground",children:T.description||"—"}),e.jsxs(xt,{children:[T.uses_count,T.max_uses&&` / ${T.max_uses}`]}),e.jsx(xt,{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(xt,{className:"text-muted-foreground",children:Bs(new Date(T.created_at),"MMM d, yyyy")}),e.jsx(xt,{children:e.jsx(Mn,{checked:T.is_active,onCheckedChange:()=>g(T.id,T.is_active)})}),e.jsx(xt,{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(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>b(T.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},T.id))})]})})]})]})})},l3=U;function KBn(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 S7s(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}const C7s="https://dashboard.relevelup.com";function YBn(s,t){const r=`${typeof window<"u"&&window.location.hostname==="localhost"?window.location.origin:C7s}/live/${s}`;return t?`${r}?i=${t}`:r}function ZBn(){const s=as(),t=mt({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await l3.from("live_events").select("*").order("starts_at",{ascending:!1});if(l)throw l;return i||[]}}),n=vt({mutationFn:async i=>{var d;const{data:l}=await U.auth.getUser(),{data:o,error:c}=await l3.from("live_events").insert({...i,created_by:(d=l.user)==null?void 0:d.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),re.success("Live event created")},onError:i=>re.error((i==null?void 0:i.message)||"Could not create event")}),r=vt({mutationFn:async({id:i,...l})=>{const{error:o}=await l3.from("live_events").update(l).eq("id",i);if(o)throw o},onSuccess:(i,l)=>{s.invalidateQueries({queryKey:["live-events"]}),s.invalidateQueries({queryKey:["live-event",l.id]}),re.success("Saved")},onError:i=>re.error((i==null?void 0:i.message)||"Could not save")}),a=vt({mutationFn:async i=>{const{error:l}=await l3.from("live_events").delete().eq("id",i);if(l)throw l},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),re.success("Event deleted")},onError:i=>re.error((i==null?void 0:i.message)||"Could not delete")});return{list:t,create:n,update:r,remove:a}}function XBn(s){return mt({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await l3.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function QBn(s){return mt({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await l3.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function JBn(s){const t=as(),n=mt({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await l3.from("live_invites").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(l)throw l;return i||[]}}),r=vt({mutationFn:async i=>{const{data:l}=await U.auth.getUser(),o=i.map(u=>{var h;return{event_id:s,code:crypto.randomUUID().replace(/-/g,"").slice(0,12),name:u.name||null,email:u.email||null,phone:u.phone||null,brokerage:u.brokerage||null,created_by:(h=l.user)==null?void 0:h.id}}),{data:c,error:d}=await l3.from("live_invites").insert(o).select();if(d)throw d;return c||[]},onSuccess:i=>{t.invalidateQueries({queryKey:["live-invites",s]}),re.success(`${i.length} invite link${i.length===1?"":"s"} created`)},onError:i=>re.error((i==null?void 0:i.message)||"Could not create invites")}),a=vt({mutationFn:async i=>{const{error:l}=await l3.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 zJ=async s=>{try{const{data:t,error:n}=await U.from("push_notification_settings").select("is_enabled").eq("setting_key",s).maybeSingle();return n?(console.error("Error checking notification setting:",n),!0):(t==null?void 0:t.is_enabled)??!0}catch(t){return console.error("Error checking notification setting:",t),!0}},oq=async s=>{try{const{data:t,error:n}=await U.functions.invoke("send-push-notification",{body:s});return n?(console.error("Error sending notification:",n),{success:!1,error:n}):(console.log("Notification sent:",t),{success:!0,data:t})}catch(t){return console.error("Error sending notification:",t),{success:!1,error:t}}},A7s=async(s,t)=>await zJ("new_templates")?oq({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}),T7s=async(s,t)=>oq({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),E7s=async(s,t)=>await zJ("new_events")?oq({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),M7s=async(s,t)=>await zJ("new_toolbox")?oq({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),IFe=async(s,t)=>await zJ("new_social_swag")?oq({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}),L7s=async(s,t)=>await zJ("new_newsletters")?oq({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),cPe=400;function P7s(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 I7s(){const s=[];let t=0;const n=1e3;for(;;){const{data:r,error:a}=await U.from("profiles").select("id, name, email, event_invite_opt_out").not("email","is",null).neq("email","").eq("event_invite_opt_out",!1).order("created_at",{ascending:!1}).range(t,t+n-1);if(a)throw a;if(!r||r.length===0)break;for(const i of r)i.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i.email)&&s.push({id:i.id,name:i.name||"",email:i.email});if(r.length{if(!s||!n)return;let ee=!1;return(async()=>{h(!0);try{const[J,le,ue]=await Promise.all([I7s(),Zlt("event_registrations",n.id),Zlt("event_attendees",n.id)]);if(ee)return;p(J),y(le),b(ue)}catch(J){ee||r({title:"Could not load audience",description:J instanceof Error?J.message:"Unknown error",variant:"destructive"})}finally{ee||h(!1)}})(),()=>{ee=!0}},[s,n,r]),j.useEffect(()=>{s||(T(null),d(""),o(""),i("not_registered"))},[s]);const O=j.useMemo(()=>a==="all"?m:a==="not_registered"?m.filter(ee=>!x.has(ee.id)):m.filter(ee=>x.has(ee.id)&&!g.has(ee.id)),[a,m,x,g]),$={all:m.length,not_registered:m.filter(ee=>!x.has(ee.id)).length,registered_never_attended:m.filter(ee=>x.has(ee.id)&&!g.has(ee.id)).length},q=async(ee,J=!1)=>{const{data:{session:le}}=await U.auth.getSession(),ue=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${le==null?void 0:le.access_token}`},body:JSON.stringify({event_id:n.id,recipients:ee.map(ie=>({email:ie.email,name:ie.name,user_id:ie.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0,force_resend:J||void 0})}),oe=await ue.json().catch(()=>({}));if(!ue.ok)throw new Error((oe==null?void 0:oe.error)||`HTTP ${ue.status}`);return{sent:(oe==null?void 0:oe.sent)??0,failed:(oe==null?void 0:oe.failed)??0,alreadyInvited:(oe==null?void 0:oe.already_invited)??0}},W=async()=>{var ee;if(n){I(!0);try{const{data:{session:J}}=await U.auth.getSession(),le=J==null?void 0:J.user;if(!(le!=null&&le.email))throw new Error("No signed-in email found");const ue=await q([{id:le.id,name:((ee=le.user_metadata)==null?void 0:ee.name)||"",email:le.email}],!0);r({title:"Test sent",description:`Sent to ${le.email} · Sent: ${ue.sent} · Failed: ${ue.failed}`})}catch(J){r({title:"Test failed",description:J instanceof Error?J.message:"Unknown error",variant:"destructive"})}finally{I(!1)}}},G=async()=>{if(!(!n||O.length===0)){P(!1),k(!0),T({done:0,total:O.length,sent:0,failed:0});try{let ee=0,J=0,le=0;for(let ue=0;ue!v&&t(ee),children:e.jsxs(Os,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(kr,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ym,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:P7s(n.event_date)})]}):"Send a beautiful branded invite to members."})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"})," Audience"]}),u?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(ob,{value:a,onValueChange:ee=>i(ee),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(eh,{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(eh,{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(eh,{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(se,{htmlFor:"ev-inv-subject",children:"Subject line (optional)"}),e.jsx(ye,{id:"ev-inv-subject",placeholder:n?`You're invited: ${n.title}`:"You're invited to...",value:l,onChange:ee=>o(ee.target.value),disabled:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for the default."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Ds,{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:ee=>d(ee.target.value),rows:4,disabled:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Appears at the top of the email above the event details."})]}),C&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Sending ",C.done.toLocaleString()," / ",C.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",C.sent.toLocaleString(),C.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",C.failed.toLocaleString()]})]})]}),e.jsx(qi,{value:K})]})]}),e.jsxs(Nr,{className:"gap-2 sm:gap-2",children:[e.jsx(B,{variant:"outline",onClick:W,disabled:v||L||u,children:L?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(on,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:v,children:"Cancel"}),e.jsx(B,{onClick:()=>P(!0),disabled:v||u||O.length===0,children:v?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"})," Send to ",O.length.toLocaleString()]})})]})]})}),e.jsx(Nl,{open:M,onOpenChange:P,children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Send event invite?"}),e.jsxs(xl,{children:["This will send a branded invite to"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[O.length.toLocaleString()," member",O.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(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsxs(cl,{onClick:G,children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const pne={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 D7s(){const s=Hn(),t=as(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState(pne),[c,d]=j.useState(null),[u,h]=j.useState(null),[m,p]=j.useState(!1),x=j.useRef(null),[y,g]=j.useState(!1),[b,v]=j.useState(null),[k,C]=j.useState(!1),[T,M]=j.useState(null),[P,L]=j.useState(null),[I,O]=j.useState(!0),[$,q]=j.useState(""),[W,G]=j.useState(!1),[K,ee]=j.useState(null),{data:J,isLoading:le}=mt({queryKey:["admin-events"],queryFn:async()=>{const{data:Fe,error:dt}=await U.from("events").select("*").order("event_date",{ascending:!0});if(dt)throw dt;return Fe}}),{data:ue}=mt({queryKey:["event-registrations-count"],queryFn:async()=>{let Fe=[],dt=0;const Dt=1e3;for(;;){const{data:zt,error:Gt}=await U.from("event_registrations").select("event_id").range(dt,dt+Dt-1);if(Gt)throw Gt;if(!zt||zt.length===0||(Fe=Fe.concat(zt),zt.length{pt[zt.event_id]=(pt[zt.event_id]||0)+1}),pt}}),{data:oe,isLoading:ie}=mt({queryKey:["event-registrations-details",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:Fe,error:dt}=await U.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",b.id).order("registered_at",{ascending:!1});if(dt)throw dt;if(!Fe||Fe.length===0)return[];const Dt=Fe.map(Gt=>Gt.user_id).filter(Boolean);let pt=[];if(Dt.length>0){const{data:Gt,error:qs}=await U.from("profiles").select("id, name, email").in("id",Dt);if(qs)throw qs;pt=Gt||[]}const zt=new Map((pt==null?void 0:pt.map(Gt=>[Gt.id,Gt]))||[]);return Fe.map(Gt=>({...Gt,profiles:Gt.user_id&&zt.get(Gt.user_id)||null}))},enabled:!!b}),{data:de,isLoading:we}=mt({queryKey:["event-attendees-details",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:Fe,error:dt}=await U.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",b.id).order("created_at",{ascending:!1});if(dt)throw dt;if(!Fe||Fe.length===0)return[];const Dt=Fe.map(As=>As.user_id).filter(Boolean);let pt=[];if(Dt.length>0){const{data:As,error:Bt}=await U.from("profiles").select("id, name, email").in("id",Dt);if(Bt)throw Bt;pt=As||[]}const{data:zt}=await U.from("agent_points").select("user_id").eq("event_id",b.id),Gt=new Set((zt==null?void 0:zt.map(As=>As.user_id))||[]),qs=new Map((pt==null?void 0:pt.map(As=>[As.id,As]))||[]);return Fe.map(As=>({...As,profiles:As.user_id&&qs.get(As.user_id)||null,points_awarded:As.user_id?Gt.has(As.user_id):!1}))},enabled:!!b}),je=Fe=>{v(Fe),g(!0)},xe=vt({mutationFn:async Fe=>{const{data:{session:dt}}=await U.auth.getSession();if(!dt)throw new Error("Not authenticated");const Dt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dt.access_token}`},body:JSON.stringify({event_id:Fe})}),pt=await Dt.json();if(!Dt.ok){const zt=new Error(pt.error||"Failed to sync");throw zt.scopeError=!!pt.scope_error,zt.details=pt.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,zt}return pt},onSuccess:Fe=>{if(t.invalidateQueries({queryKey:["event-registrations-details",b==null?void 0:b.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),Fe!=null&&Fe.scope_error||(Fe==null?void 0:Fe.success)===!1){re.error("Zoom needs one more authorization step",{description:Fe!=null&&Fe.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.":(Fe==null?void 0:Fe.message)||"Zoom registration sync could not complete.",duration:2e4});return}re.success(Fe.message)},onError:Fe=>{re.error("Failed to sync Zoom registrations",{description:Fe.scopeError&&Fe.details||Fe.message,duration:Fe.scopeError?2e4:5e3})}}),fe=vt({mutationFn:async Fe=>{const{data:{session:dt}}=await U.auth.getSession();if(!dt)throw new Error("Not authenticated");const Dt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dt.access_token}`},body:JSON.stringify({event_id:Fe})}),pt=await Dt.json();if(!Dt.ok)throw new Error(pt.error||"Failed to sync attendees");return pt},onSuccess:Fe=>{if(t.invalidateQueries({queryKey:["event-attendees-details",b==null?void 0:b.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Fe!=null&&Fe.scope_error||(Fe==null?void 0:Fe.success)===!1){re.error((Fe==null?void 0:Fe.message)||"Zoom sync failed",{description:Fe!=null&&Fe.scope_error?"Zoom must be re-authorized after adding the missing report scope.":void 0,duration:15e3});return}Fe!=null&&Fe.message?re.success(Fe.message):re.success(`Synced ${Fe.synced||0} attendees. ${Fe.points_awarded||0} points awarded!`)},onError:Fe=>{re.error("Failed to sync attendees: "+Fe.message)}}),Se=vt({mutationFn:async()=>{const{data:Fe,error:dt}=await U.functions.invoke("zoom-retry-registrations",{body:{}});if(dt)throw dt;return Fe},onSuccess:Fe=>{t.invalidateQueries({queryKey:["event-registrations-details",b==null?void 0:b.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),re.success(`Retry complete: ${(Fe==null?void 0:Fe.successCount)??0} fixed, ${(Fe==null?void 0:Fe.failCount)??0} still failing, ${(Fe==null?void 0:Fe.rateLimitedCount)??0} rate-limited`)},onError:Fe=>{re.error("Retry failed: "+Fe.message)}}),Ee=vt({mutationFn:async({eventId:Fe,testMode:dt})=>{const{data:{session:Dt}}=await U.auth.getSession();if(!Dt)throw new Error("Not authenticated");const pt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Dt.access_token}`},body:JSON.stringify({event_id:Fe,test_mode:dt})}),zt=await pt.json();if(!pt.ok)throw new Error(zt.error||"Failed to send reminders");return zt},onSuccess:Fe=>{Fe.test?re.success(Fe.message||"Test email sent!"):re.success(Fe.message||`Reminder emails sent to ${Fe.sent} registrants!`)},onError:Fe=>{re.error("Failed to send reminders: "+Fe.message)}}),{data:Le}=mt({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Fe=[],dt=0;const Dt=1e3;for(;;){const{data:pt,error:zt}=await U.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(dt,dt+Dt-1);if(zt)throw zt;if(!pt||pt.length===0||(Fe=[...Fe,...pt],pt.length{const{error:zt}=await U.from("event_attendees").update({user_id:dt}).eq("id",Fe);if(zt)throw zt;if(pt&&Dt){const{error:qs}=await U.from("zoom_email_aliases").upsert({user_id:dt,zoom_email:Dt.toLowerCase()},{onConflict:"zoom_email"});qs&&console.error("Failed to save alias:",qs)}const Gt=b==null?void 0:b.id;if(Gt){const{data:qs}=await U.from("user_roles").select("id").eq("user_id",dt).eq("role","admin").single();if(!qs){const{data:As}=await U.from("agent_points").select("id").eq("user_id",dt).eq("event_id",Gt).single();As||(await U.rpc("award_attendance_points",{p_user_id:dt,p_event_id:Gt,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await U.rpc("check_and_award_badges",{p_user_id:dt}))}}return{userId:dt,zoomEmail:Dt,shouldSaveAlias:pt}},onSuccess:Fe=>{t.invalidateQueries({queryKey:["event-attendees-details",b==null?void 0:b.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let dt="Attendee linked and points awarded!";Fe.shouldSaveAlias&&Fe.zoomEmail&&(dt+=` Email "${Fe.zoomEmail}" will be auto-matched in the future.`),re.success(dt),C(!1),M(null),L(null),q("")},onError:Fe=>{re.error("Failed to link attendee: "+Fe.message)}}),Be=Fe=>{M(Fe),L(null),O(!0),q(""),C(!0)},Ne=()=>{!T||!P||De.mutate({attendeeId:T.id,userId:P,zoomEmail:T.zoom_email,shouldSaveAlias:I})},Ge=(Le==null?void 0:Le.filter(Fe=>{var Dt,pt;if(!$)return!0;const dt=$.toLowerCase();return((Dt=Fe.name)==null?void 0:Dt.toLowerCase().includes(dt))||((pt=Fe.email)==null?void 0:pt.toLowerCase().includes(dt))}))||[],_e=async Fe=>{const dt=Fe.name.split(".").pop(),pt=`${`${crypto.randomUUID()}.${dt}`}`,{error:zt}=await U.storage.from("event-images").upload(pt,Fe);if(zt)throw zt;const{data:{publicUrl:Gt}}=U.storage.from("event-images").getPublicUrl(pt);return Gt},Oe=Fe=>{var Dt;const dt=(Dt=Fe.target.files)==null?void 0:Dt[0];if(dt){if(dt.size>5*1024*1024){re.error("Image must be less than 5MB");return}d(dt),h(URL.createObjectURL(dt))}},Ae=()=>{d(null),h(null),o({...l,image_url:""}),x.current&&(x.current.value="")},Xe=vt({mutationFn:async Fe=>{p(!0);let dt=Fe.image_url;c&&(dt=await _e(c)||"");const Dt=new Date(Fe.event_date),[pt,zt]=Fe.event_time.split(":");Dt.setHours(parseInt(pt),parseInt(zt));const Gt=[new Date(Dt)];if(Fe.is_recurring&&Fe.recurrence_end_date){let At=new Date(Dt);for(;Fe.recurrence_pattern==="weekly"?At=i3(At,1):Fe.recurrence_pattern==="biweekly"?At=i3(At,2):At=Ax(At,1),!(At>Fe.recurrence_end_date);)Gt.push(new Date(At))}const qs=Gt.map(At=>({title:Fe.title,description:Fe.description||null,image_url:dt||null,video_url:Fe.video_url||null,event_date:At.toISOString(),zoom_link:Fe.zoom_link,zoom_meeting_id:Fe.zoom_meeting_id||null,capacity:Fe.capacity?parseInt(Fe.capacity):null,is_published:Fe.is_published})),{data:As,error:Bt}=await U.from("events").insert(qs).select();if(Bt)throw Bt;return As&&As.length>0&&E7s(Fe.title,As[0].id),Gt.length},onSuccess:Fe=>{t.invalidateQueries({queryKey:["admin-events"]}),re.success(Fe>1?`${Fe} recurring events created successfully`:"Event created successfully"),r(!1),o(pne),d(null),h(null),p(!1)},onError:Fe=>{re.error("Failed to create event: "+Fe.message),p(!1)}}),Ue=vt({mutationFn:async({id:Fe,data:dt})=>{p(!0);let Dt=dt.image_url;c&&(Dt=await _e(c)||"");const pt=new Date(dt.event_date),[zt,Gt]=dt.event_time.split(":");pt.setHours(parseInt(zt),parseInt(Gt));const{error:qs}=await U.from("events").update({title:dt.title,description:dt.description||null,image_url:Dt||null,video_url:dt.video_url||null,event_date:pt.toISOString(),zoom_link:dt.zoom_link,zoom_meeting_id:dt.zoom_meeting_id||null,capacity:dt.capacity?parseInt(dt.capacity):null,is_published:dt.is_published}).eq("id",Fe);if(qs)throw qs},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),re.success("Event updated successfully"),r(!1),i(null),o(pne),d(null),h(null),p(!1)},onError:Fe=>{re.error("Failed to update event: "+Fe.message),p(!1)}}),Ze=vt({mutationFn:async Fe=>{const{error:dt}=await U.from("events").delete().eq("id",Fe);if(dt)throw dt},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),re.success("Event deleted successfully")},onError:Fe=>{re.error("Failed to delete event: "+Fe.message)}}),Qe=vt({mutationFn:async Fe=>{var At;const{data:dt}=await U.auth.getUser(),Dt=new Date(Fe.event_date),pt=new Date(Dt.getTime()+60*60*1e3),zt=S7s(Fe.title),Gt=Math.random().toString(36).slice(2,7),qs=`${zt}-${Gt}`,{data:As,error:Bt}=await U.from("live_events").insert({slug:qs,title:Fe.title,description:Fe.description||null,hero_image_url:Fe.image_url||null,starts_at:Fe.event_date,ends_at:pt.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:Fe.zoom_meeting_id||null,cta_label:"Join the training",cta_url:Fe.zoom_link||"https://dashboard.relevelup.com/trial",created_by:(At=dt.user)==null?void 0:At.id,agenda:[],offer_bullets:[]}).select().single();if(Bt)throw Bt;return As},onSuccess:Fe=>{t.invalidateQueries({queryKey:["live-events"]}),re.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${Fe.id}`)},onError:Fe=>{re.error("Failed to clone to LevelUp Live: "+Fe.message)}}),Ye=Fe=>{var Dt;const dt=new Date(Fe.event_date);i(Fe),o({title:Fe.title,description:Fe.description||"",image_url:Fe.image_url||"",video_url:Fe.video_url||"",event_date:dt,event_time:Bs(dt,"HH:mm"),zoom_link:Fe.zoom_link,zoom_meeting_id:Fe.zoom_meeting_id||"",capacity:((Dt=Fe.capacity)==null?void 0:Dt.toString())||"",is_published:Fe.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),h(Fe.image_url||null),d(null),r(!0)},nt=Fe=>{if(Fe.preventDefault(),!l.event_date){re.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){re.error("Please select an end date for recurring events");return}a?Ue.mutate({id:a.id,data:l}):Xe.mutate(l)},rt=()=>{r(!1),i(null),o(pne),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(oh,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(be,{className:"mb-6",children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{children:"All Events"}),e.jsxs(Fs,{open:n,onOpenChange:Fe=>!Fe&&rt(),children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:nt,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:l.title,onChange:Fe=>o({...l,title:Fe.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Kj,{content:l.description,onChange:Fe=>o({...l,description:Fe}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Event Image"}),e.jsx("input",{type:"file",ref:x,accept:"image/*",onChange:Oe,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(dr,{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 Fe;return(Fe=x.current)==null?void 0:Fe.click()},children:[e.jsx(Ja,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Click to upload image"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Date *"}),e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(ra,{className:"mr-2 h-4 w-4"}),l.event_date?Bs(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(Jl,{className:"w-auto p-0",align:"start",children:e.jsx(o1,{mode:"single",selected:l.event_date,onSelect:Fe=>o({...l,event_date:Fe}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"time",children:"Time *"}),e.jsx(ye,{id:"time",type:"time",value:l.event_time,onChange:Fe=>o({...l,event_time:Fe.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(ye,{id:"zoom_link",value:l.zoom_link,onChange:Fe=>o({...l,zoom_link:Fe.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(ye,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:Fe=>o({...l,zoom_meeting_id:Fe.target.value}),placeholder:"e.g., 1234567890 (find in Zoom dashboard)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional: Enter the numeric meeting ID for automatic Zoom registration"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(ye,{id:"video_url",value:l.video_url,onChange:Fe=>o({...l,video_url:Fe.target.value}),placeholder:"YouTube, Vimeo, or Bunny.net embed URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add a preview/promo video for this event"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(ye,{id:"capacity",type:"number",value:l.capacity,onChange:Fe=>o({...l,capacity:Fe.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(nz,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(Mn,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:Fe=>o({...l,is_recurring:Fe})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Frequency"}),e.jsxs(vs,{value:l.recurrence_pattern,onValueChange:Fe=>o({...l,recurrence_pattern:Fe}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"weekly",children:"Weekly"}),e.jsx(Je,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(Je,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Repeat Until"}),e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(ra,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?Bs(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(Jl,{className:"w-auto p-0",align:"start",children:e.jsx(o1,{mode:"single",selected:l.recurrence_end_date,onSelect:Fe=>o({...l,recurrence_end_date:Fe}),disabled:Fe=>Fe<(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 Fe=1,dt=new Date(l.event_date);for(;dt=l.recurrence_pattern==="weekly"?i3(dt,1):l.recurrence_pattern==="biweekly"?i3(dt,2):Ax(dt,1),!(dt>l.recurrence_end_date);)Fe++;return Fe})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{htmlFor:"is_published",children:"Published"}),e.jsx(Mn,{id:"is_published",checked:l.is_published,onCheckedChange:Fe=>o({...l,is_published:Fe})})]}),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||Ue.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(Re,{children:le?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(J==null?void 0:J.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):(()=>{const Fe=new Date,dt=[...J||[]],Dt=dt.filter(As=>new Date(As.event_date)>=Fe).sort((As,Bt)=>new Date(As.event_date).getTime()-new Date(Bt.event_date).getTime()),pt=dt.filter(As=>new Date(As.event_date)new Date(Bt.event_date).getTime()-new Date(As.event_date).getTime()),zt=Dt[0],Gt=As=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:As.title}),e.jsx(xt,{className:"whitespace-nowrap",children:Bs(new Date(As.event_date),"PPP p")}),e.jsx(xt,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>je(As),children:[e.jsx(Bn,{className:"h-4 w-4"}),(ue==null?void 0:ue[As.id])||0,As.capacity&&` / ${As.capacity}`]})}),e.jsx(xt,{children:e.jsx("span",{className:Et("px-2 py-1 rounded-full text-xs font-medium",As.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:As.is_published?"Published":"Draft"})}),e.jsx(xt,{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:()=>{ee(As),G(!0)},title:"Send invite email to members",children:[e.jsx(Dr,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Invite Members"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Qe.mutate(As),disabled:Qe.isPending,title:"Clone to LevelUp Live",children:[e.jsx(iy,{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(As.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(Tr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Ye(As),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Bi("Are you sure you want to delete this event?")&&Ze.mutate(As.id)},children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})})]},As.id),qs=(As,Bt)=>As.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:Bt}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Date & Time"}),e.jsx(Tt,{children:"Registrations"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:As.map(Gt)})]});return e.jsxs("div",{className:"space-y-6",children:[zt&&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(Vr,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:zt.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Bs(new Date(zt.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(ue==null?void 0:ue[zt.id])||0," registered",zt.capacity?` of ${zt.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>{ee(zt),G(!0)},children:[e.jsx(Dr,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>je(zt),children:[e.jsx(Bn,{className:"h-4 w-4"}),"Registrations"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Qe.mutate(zt),disabled:Qe.isPending,children:[e.jsx(iy,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(zt.zoom_link,"_blank"),children:[e.jsx(Tr,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(fa,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"upcoming",className:"gap-2",children:[e.jsx(Vr,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:Dt.length})]}),e.jsxs(ss,{value:"past",className:"gap-2",children:[e.jsx(Rr,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:pt.length})]})]}),e.jsx(ns,{value:"upcoming",className:"mt-4",children:qs(Dt,"No upcoming events scheduled.")}),e.jsx(ns,{value:"past",className:"mt-4",children:qs(pt,"No past events.")})]})]})})()})]}),e.jsx(R7s,{open:W,onOpenChange:G,event:K}),e.jsx(Fs,{open:y,onOpenChange:g,children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),b==null?void 0:b.title]}),e.jsx(kr,{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:()=>Ee.mutate({eventId:b.id,testMode:!0}),disabled:Ee.isPending,children:[e.jsx(on,{className:Et("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Ee.mutate({eventId:b.id}),disabled:Ee.isPending||!(oe!=null&&oe.length),children:[e.jsx(on,{className:Et("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),Ee.isPending?"Sending...":"Send Reminder to All"]}),(b==null?void 0:b.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>xe.mutate(b.id),disabled:xe.isPending,children:[e.jsx(Ki,{className:Et("h-4 w-4 mr-2",xe.isPending&&"animate-spin")}),xe.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Se.mutate(),disabled:Se.isPending,children:[e.jsx(Ki,{className:Et("h-4 w-4 mr-2",Se.isPending&&"animate-spin")}),Se.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(B,{variant:"default",size:"sm",onClick:()=>fe.mutate(b.id),disabled:fe.isPending,children:[e.jsx(ll,{className:Et("h-4 w-4 mr-2",fe.isPending&&"animate-spin")}),fe.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(fa,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(xa,{className:"grid w-full grid-cols-2",children:[e.jsxs(ss,{value:"registrations",className:"gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),"Registrations (",(oe==null?void 0:oe.length)||0,")"]}),e.jsxs(ss,{value:"attendees",className:"gap-2",children:[e.jsx(Rr,{className:"h-4 w-4"}),"Attendees (",(de==null?void 0:de.length)||0,")"]})]}),e.jsx(ns,{value:"registrations",className:"mt-4",children:ie?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(oe==null?void 0:oe.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(b==null?void 0:b.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Registered"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(za,{children:oe==null?void 0:oe.map(Fe=>{var zt,Gt;const dt=((zt=Fe.profiles)==null?void 0:zt.name)||Fe.zoom_name||"Unknown",Dt=((Gt=Fe.profiles)==null?void 0:Gt.email)||Fe.zoom_email||null,pt=!Fe.user_id;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[dt,pt&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(xt,{children:Dt?e.jsxs("a",{href:`mailto:${Dt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(on,{className:"h-3 w-3"}),Dt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(xt,{className:"text-muted-foreground text-sm",children:Bs(new Date(Fe.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(xt,{children:Fe.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"})})]},Fe.id)})})]})}),e.jsx(ns,{value:"attendees",className:"mt-4",children:we?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(de==null?void 0:de.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(b==null?void 0:b.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Attendees & Award Points" after the event ends to import actual participants from Zoom.'})]}):e.jsxs(e.Fragment,{children:[(de==null?void 0:de.filter(Fe=>!Fe.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(po,{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 (",de==null?void 0:de.filter(Fe=>!Fe.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:de==null?void 0:de.filter(Fe=>!Fe.user_id).map(Fe=>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:Fe.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Fe.zoom_email||"No email"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Be(Fe),className:"gap-1",children:[e.jsx(Rc,{className:"h-3 w-3"}),"Link to Profile"]})]},Fe.id))})]}),e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Points"})]})}),e.jsx(za,{children:de==null?void 0:de.filter(Fe=>Fe.user_id).map(Fe=>{var pt,zt;const dt=((pt=Fe.profiles)==null?void 0:pt.name)||Fe.zoom_name||"Unknown",Dt=((zt=Fe.profiles)==null?void 0:zt.email)||Fe.zoom_email||null;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[dt,Fe.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(xt,{children:Dt?e.jsxs("a",{href:`mailto:${Dt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(on,{className:"h-3 w-3"}),Dt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(xt,{children:Fe.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(Vr,{className:"h-3 w-3"}),Fe.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(xt,{children:Fe.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(ll,{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"})})]},Fe.id)})})]})]})})]})]})}),e.jsx(Fs,{open:k,onOpenChange:C,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Rc,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(kr,{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(se,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:$,onChange:Fe=>q(Fe.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(Fe=>e.jsxs("button",{type:"button",onClick:()=>L(Fe.id),className:Et("w-full p-3 text-left hover:bg-muted/50 transition-colors",P===Fe.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:Fe.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Fe.email})]},Fe.id))})}),T.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(wi,{id:"save-alias",checked:I,onCheckedChange:Fe=>O(Fe)}),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:()=>C(!1),children:"Cancel"}),e.jsx(B,{onClick:Ne,disabled:!P||De.isPending,children:De.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const O7s={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 F7s(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState("issues");async function l(){r(!0);let o=U.from("mcp_audit_log").select("id, user_id, tool_name, outcome, error_message, duration_ms, client_id, created_at").order("created_at",{ascending:!1}).limit(200);a==="issues"&&(o=o.in("outcome",["denied","rate_limited","error"]));const{data:c,error:d}=await o;d||t(c??[]),r(!1)}return j.useEffect(()=>{l()},[a]),e.jsx(Vs,{title:"MCP Audit Log",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(iz,{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(Ki,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(Re,{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(qe,{className:O7s[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 z7s({selectedKitIds:s,onChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l=[]}=mt({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:h,error:m}=await U.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(m)throw m;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(m=>m!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(Eu,{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(qe,{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(dr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(lc,{open:a,onOpenChange:i,children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(Eu,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(Jl,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Fr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{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(Eu,{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 B7s=()=>{const{user:s}=Ns(),{toast:t}=pi(),n=as(),[r,a]=dc(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),[h,m]=j.useState(null),[p,x]=j.useState(0),[y,g]=j.useState(!1),[b,v]=j.useState(null),[k,C]=j.useState(""),[T,M]=j.useState([]),[P,L]=j.useState(""),[I,O]=j.useState(""),[$,q]=j.useState(!1),[W,G]=j.useState(!1),{data:K=[]}=mt({queryKey:["template-categories"],queryFn:async()=>{const{data:Ae,error:Xe}=await U.from("template_categories").select("*").order("name");if(Xe)throw Xe;return Ae}}),{data:ee=[]}=mt({queryKey:["template-types"],queryFn:async()=>{const{data:Ae,error:Xe}=await U.from("template_types").select("*").order("name");if(Xe)throw Xe;return Ae}}),{data:J=[],isLoading:le}=mt({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Ae,error:Xe}=await U.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:Ue,error:Ze}=await U.from("template_links").select("*").order("sort_order");if(Ze)throw Ze;const{data:Qe,error:Ye}=await U.from("template_guides").select("*").order("sort_order");if(Ye)throw Ye;return Ae.map(rt=>({...rt,links:(Ue==null?void 0:Ue.filter(Fe=>Fe.template_id===rt.id))||[],guides:(Qe==null?void 0:Qe.filter(Fe=>Fe.template_id===rt.id))||[]}))}});j.useEffect(()=>{const Ae=r.get("edit");if(Ae&&J.length>0){const Xe=J.find(Ue=>Ue.id===Ae);Xe&&(xe(Xe),a({},{replace:!0}))}},[J,r]);const ue=vt({mutationFn:async Ae=>{const{data:Xe,error:Ue}=await U.from("template_categories").insert({name:Ae}).select().single();if(Ue)throw Ue;return Xe},onSuccess:Ae=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:Ae.id}),L(""),q(!1),t({title:"Category added"})},onError:Ae=>{t({title:"Error adding category",description:Ae.message,variant:"destructive"})}}),oe=vt({mutationFn:async Ae=>{const{data:Xe,error:Ue}=await U.from("template_types").insert({name:Ae}).select().single();if(Ue)throw Ue;return Xe},onSuccess:Ae=>{n.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:Ae.id}),O(""),G(!1),t({title:"Type added"})},onError:Ae=>{t({title:"Error adding type",description:Ae.message,variant:"destructive"})}}),ie=vt({mutationFn:async Ae=>{var Ye;let Xe=Ae.existingImageUrl;if(Ae.image){const nt=Ae.image.name.split(".").pop(),rt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${nt}`,{error:Fe}=await U.storage.from("template-previews").upload(rt,Ae.image);if(Fe)throw Fe;const{data:dt}=U.storage.from("template-previews").getPublicUrl(rt);Xe=dt.publicUrl}const Ue={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 Ze=Ae.templateId;if(Ze){const{error:nt}=await U.from("canva_templates").update(Ue).eq("id",Ze);if(nt)throw nt;const{error:rt}=await U.from("template_links").delete().eq("template_id",Ze);if(rt)throw rt;const Fe=((Ye=Ae.existingGuides)==null?void 0:Ye.map(pt=>pt.id).filter(Boolean))||[],dt=Ae.template.guides.map(pt=>pt.id).filter(Boolean),Dt=Fe.filter(pt=>!dt.includes(pt));Dt.length>0&&await U.from("template_guides").delete().in("id",Dt)}else{const{data:nt,error:rt}=await U.from("canva_templates").insert(Ue).select().single();if(rt)throw rt;Ze=nt.id,A7s(Ae.template.name,nt.id)}const Qe=Ae.template.links.filter(nt=>nt.title.trim()&&nt.canva_share_link.trim());if(Qe.length>0){const nt=Qe.map((Fe,dt)=>({template_id:Ze,title:Fe.title.trim(),canva_share_link:Fe.canva_share_link.trim(),sort_order:dt})),{error:rt}=await U.from("template_links").insert(nt);if(rt)throw rt}for(let nt=0;nt0)){const{error:nt}=await U.from("resource_kit_templates").insert(Ae.linkedKitIds.map(rt=>({template_id:Ze,kit_id:rt})));if(nt)throw nt}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),je(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Ae=>{t({title:"Error saving template",description:Ae.message,variant:"destructive"})}}),de=vt({mutationFn:async Ae=>{const{error:Xe}=await U.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"})}}),we=vt({mutationFn:async({id:Ae,is_featured:Xe})=>{const{error:Ue}=await U.from("canva_templates").update({is_featured:Xe}).eq("id",Ae);if(Ue)throw Ue},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:Ae=>{t({title:"Error updating featured",description:Ae.message,variant:"destructive"})}}),je=()=>{u({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),v(null),C(""),c(null),q(!1),G(!1),L(""),O(""),m(null),x(0),g(!1),M([])},xe=async Ae=>{var Ue;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(Ze=>({id:Ze.id,title:Ze.title,canva_share_link:Ze.canva_share_link,sort_order:Ze.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((Ue=Ae.guides)==null?void 0:Ue.map(Ze=>({id:Ze.id,name:Ze.name,file_url:Ze.file_url,file_type:Ze.file_type,file_size:Ze.file_size,sort_order:Ze.sort_order})))||[],video_url:Ae.video_url||""}),C(Ae.preview_image_url||""),m(null);const{data:Xe}=await U.from("resource_kit_templates").select("kit_id").eq("template_id",Ae.id);M((Xe||[]).map(Ze=>Ze.kit_id)),l(!0)},fe=Ae=>{var Ue;const Xe=(Ue=Ae.target.files)==null?void 0:Ue[0];Xe&&(v(Xe),C(URL.createObjectURL(Xe)))},Se=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},Ee=Ae=>{if(d.links.length<=1)return;const Xe=d.links.filter((Ue,Ze)=>Ze!==Ae);u({...d,links:Xe})},Le=(Ae,Xe,Ue)=>{const Ze=[...d.links];Ze[Ae]={...Ze[Ae],[Xe]:Ue},u({...d,links:Ze})},De=Ae=>{const Xe=Ae.target.files;if(!Xe)return;const Ue=Array.from(Xe).map((Ze,Qe)=>({name:Ze.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Ze.type,file_size:Ze.size,sort_order:d.guides.length+Qe,file:Ze}));u({...d,guides:[...d.guides,...Ue]}),Ae.target.value=""},Be=Ae=>{const Xe=d.guides.filter((Ue,Ze)=>Ze!==Ae);u({...d,guides:Xe})},Ne=(Ae,Xe)=>{const Ue=[...d.guides];Ue[Ae]={...Ue[Ae],name:Xe},u({...d,guides:Ue})},Ge=async()=>{if(!h)return null;g(!0),x(0);try{const{data:Ae,error:Xe}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if(Xe)throw new Error(Xe.message);const{videoId:Ue,libraryId:Ze}=Ae,{data:Qe,error:Ye}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ue}});if(Ye)throw new Error(Ye.message);const nt=new XMLHttpRequest;return await new Promise((Fe,dt)=>{nt.upload.addEventListener("progress",Dt=>{if(Dt.lengthComputable){const pt=Math.round(Dt.loaded/Dt.total*100);x(pt)}}),nt.addEventListener("load",()=>{nt.status>=200&&nt.status<300?Fe():dt(new Error(`Upload failed with status ${nt.status}`))}),nt.addEventListener("error",()=>dt(new Error("Upload failed"))),nt.open("PUT",Qe.uploadUrl),nt.setRequestHeader("AccessKey",Qe.apiKey),nt.send(h)}),`https://player.mediadelivery.net/embed/${Ze}/${Ue}`}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{g(!1)}},_e=Ae=>{var Ue;const Xe=(Ue=Ae.target.files)==null?void 0:Ue[0];Xe&&m(Xe),Ae.target.value=""},Oe=async Ae=>{if(Ae.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(Ze=>Ze.title.trim()&&Ze.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let Ue=d.video_url;if(h){const Ze=await Ge();if(!Ze)return;Ue=Ze}ie.mutate({template:d,image:b,existingImageUrl:(o==null?void 0:o.preview_image_url)||null,templateId:o==null?void 0:o.id,existingGuides:o==null?void 0:o.guides,videoUrl:Ue,linkedKitIds:T})};return e.jsx(Vs,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{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(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:J.length})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:K.length})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:ee.length})})]})]}),e.jsxs(Fs,{open:i,onOpenChange:Ae=>{l(Ae),Ae||je()},children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:Oe,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name *"}),e.jsx(ye,{id:"name",value:d.name,onChange:Ae=>u({...d,name:Ae.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Kj,{content:d.description,onChange:Ae=>u({...d,description:Ae}),placeholder:"Brief description of the template",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Canva Links *"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Se,className:"gap-1",children:[e.jsx(Js,{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(ye,{value:Ae.title,onChange:Ue=>Le(Xe,"title",Ue.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(ye,{value:Ae.canva_share_link,onChange:Ue=>Le(Xe,"canva_share_link",Ue.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:()=>Ee(Xe),children:e.jsx(dr,{className:"h-4 w-4"})})]},Xe))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Category"}),$?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:P,onChange:Ae=>L(Ae.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>P.trim()&&ue.mutate(P.trim()),disabled:ue.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{q(!1),L("")},children:e.jsx(dr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:d.category_id,onValueChange:Ae=>u({...d,category_id:Ae}),children:[e.jsx(gs,{className:"flex-1",children:e.jsx(bs,{placeholder:"Select category"})}),e.jsx(ys,{children:K.map(Ae=>e.jsx(Je,{value:Ae.id,children:Ae.name},Ae.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>q(!0),children:e.jsx(Js,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Template Type"}),W?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:I,onChange:Ae=>O(Ae.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>I.trim()&&oe.mutate(I.trim()),disabled:oe.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{G(!1),O("")},children:e.jsx(dr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:d.type_id,onValueChange:Ae=>u({...d,type_id:Ae}),children:[e.jsx(gs,{className:"flex-1",children:e.jsx(bs,{placeholder:"Select type"})}),e.jsx(ys,{children:ee.map(Ae=>e.jsx(Je,{value:Ae.id,children:Ae.name},Ae.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>G(!0),children:e.jsx(Js,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ae=>u({...d,publish_date:Ae.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Templates are sorted by publish date (newest first) on the member page"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[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:()=>{v(null),C("")},children:e.jsx(dr,{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(ac,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ye,{type:"file",accept:"image/*",onChange:fe,className:"cursor-pointer"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Upload a preview image for this template"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Video (Optional)"}),d.video_url&&!h?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(Zr,{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(Wt,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",p,"%"]})]}),e.jsx(qi,{value:p,className:"h-2"})]}):h?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(Zr,{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(dr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(ye,{type:"file",accept:"video/*",onChange:_e,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(Zr,{className:"h-8 w-8 text-muted-foreground/50"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Click to upload a video"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload a video to embed on the template page (Bunny.net)"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(ye,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:De,className:"hidden"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Ja,{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($r,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(ye,{value:Ae.name,onChange:Ue=>Ne(Xe,Ue.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(dr,{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(z7s,{selectedKitIds:T,onChange:M}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{l(!1),je()},children:"Cancel"}),e.jsx(B,{type:"submit",disabled:ie.isPending,children:ie.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:le?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):J.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Preview"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Links"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:J.map(Ae=>{var Xe,Ue,Ze,Qe,Ye;return e.jsxs(un,{children:[e.jsx(xt,{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(ac,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(xt,{className:"font-medium",children:Ae.name}),e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(qe,{variant:"secondary",children:[((Xe=Ae.links)==null?void 0:Xe.length)||0," link",(((Ue=Ae.links)==null?void 0:Ue.length)||0)!==1?"s":""]}),(((Ze=Ae.guides)==null?void 0:Ze.length)||0)>0&&e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx($r,{className:"h-3 w-3"}),(Qe=Ae.guides)==null?void 0:Qe.length," guide",(((Ye=Ae.guides)==null?void 0:Ye.length)||0)!==1?"s":""]})]})}),e.jsx(xt,{children:Ae.category?e.jsx(qe,{variant:"secondary",children:Ae.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(xt,{children:Ae.type?e.jsx(qe,{variant:"outline",children:Ae.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(xt,{className:"text-muted-foreground",children:new Date(Ae.publish_date).toLocaleDateString()}),e.jsx(xt,{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:()=>we.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(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>xe(Ae),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:async()=>{await Bi("Delete this template?")&&de.mutate(Ae.id)},children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},Ae.id)})})]})})})]})})};function $Mt({selectedTemplateIds:s,onChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l=[]}=mt({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:h,error:m}=await U.from("canva_templates").select("id, name, preview_image_url").order("name");if(m)throw m;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(m=>m!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:[e.jsx(q_,{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(qe,{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(dr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(lc,{open:a,onOpenChange:i,children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(q_,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(Jl,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Fr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{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(q_,{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 $7s=[{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"}],U7s=()=>{const{user:s}=Ns(),[t,n]=dc(),{toast:r}=pi(),a=as(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[h,m]=j.useState(null),[p,x]=j.useState(""),[y,g]=j.useState([]),[b,v]=j.useState([]),[k,C]=j.useState([]),[T,M]=j.useState([]),[P,L]=j.useState(""),[I,O]=j.useState(!1),[$,q]=j.useState(null),[W,G]=j.useState(0),[K,ee]=j.useState(!1),[J,le]=j.useState(null),{data:ue=[]}=mt({queryKey:["academy-categories"],queryFn:async()=>{const{data:Ae,error:Xe}=await U.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(Xe)throw Xe;return Ae}}),{data:oe=[],isLoading:ie}=mt({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:Ae,error:Xe}=await U.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(Xe)throw Xe;const{data:Ue,error:Ze}=await U.from("academy_resources").select("*").order("sort_order");if(Ze)throw Ze;return Ae.map(Ye=>({...Ye,resources:(Ue==null?void 0:Ue.filter(nt=>nt.video_id===Ye.id))||[]}))}});j.useEffect(()=>{const Ae=t.get("edit");if(Ae&&oe.length>0){const Xe=oe.find(Ue=>Ue.id===Ae);Xe&&(Le(Xe),n({},{replace:!0}))}},[oe,t]);const de=vt({mutationFn:async Ae=>{const{data:Xe,error:Ue}=await U.from("academy_categories").insert({name:Ae,sort_order:ue.length}).select().single();if(Ue)throw Ue;return Xe},onSuccess:Ae=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:Ae.id}),L(""),O(!1),r({title:"Category added"})},onError:Ae=>{r({title:"Error adding category",description:Ae.message,variant:"destructive"})}}),we=vt({mutationFn:async Ae=>{let Xe=Ae.existingThumbnailUrl;if(Ae.thumbnail){const Qe=Ae.thumbnail.name.split(".").pop(),Ye=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${Qe}`,{error:nt}=await U.storage.from("academy-resources").upload(Ye,Ae.thumbnail);if(nt)throw nt;const{data:rt}=U.storage.from("academy-resources").getPublicUrl(Ye);Xe=rt.publicUrl}const Ue={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 Ze=Ae.videoId;if(Ze){const{error:Qe}=await U.from("academy_videos").update(Ue).eq("id",Ze);if(Qe)throw Qe}else{const{data:Qe,error:Ye}=await U.from("academy_videos").insert(Ue).select().single();if(Ye)throw Ye;Ze=Qe.id,T7s(Ae.video.title,Qe.id)}if(Ae.resourcesToDelete.length>0){const{error:Qe}=await U.from("academy_resources").delete().in("id",Ae.resourcesToDelete);if(Qe)throw Qe}for(let Qe=0;Qe0){const{error:Qe}=await U.from("academy_video_templates").insert(T.map(Ye=>({video_id:Ze,template_id:Ye})));if(Qe)throw Qe}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),Ee(),l(!1),r({title:o?"Video updated":"Video created"})},onError:Ae=>{r({title:"Error saving video",description:Ae.message,variant:"destructive"})}}),je=vt({mutationFn:async Ae=>{const{error:Xe}=await U.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"})}}),xe=vt({mutationFn:async({id:Ae,is_published:Xe})=>{const{error:Ue}=await U.from("academy_videos").update({is_published:Xe}).eq("id",Ae);if(Ue)throw Ue},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:Ae=>{r({title:"Error updating video",description:Ae.message,variant:"destructive"})}}),fe=async Ae=>{try{let Xe=Ae.public_slug||null,Ue=!!Ae.is_public;if(!Xe||!Ue){const Qe=(Ae.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!Xe){let nt=Qe;const{data:rt}=await U.from("academy_videos").select("id").eq("public_slug",nt).maybeSingle();rt&&rt.id!==Ae.id&&(nt=`${Qe}-${Ae.id.slice(0,6)}`),Xe=nt}const{error:Ye}=await U.from("academy_videos").update({public_slug:Xe,is_public:!0}).eq("id",Ae.id);if(Ye)throw Ye;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const Ze=`${window.location.origin}/watch/${Xe}`;await navigator.clipboard.writeText(Ze),r({title:"Public link copied",description:Ze})}catch(Xe){r({title:"Could not copy link",description:Xe.message,variant:"destructive"})}},Se=async Ae=>{if(!await Bi("Disable the public teaser link for this video?"))return;const{error:Xe}=await U.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"})},Ee=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),m(null),x(""),g([]),v([]),C([]),c(null),M([]),L(""),q(null),G(0),ee(!1),le(null)},Le=async Ae=>{c(Ae),u({title:Ae.title,description:Ae.description||"",video_url:Ae.video_url,video_type:Ae.video_type,duration:Ae.duration||"",category_id:Ae.category_id||"",publish_date:Ae.publish_date?new Date(Ae.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:Ae.is_published}),x(Ae.thumbnail_url||""),v(Ae.resources||[]),g([]),C([]);const{data:Xe}=await U.from("academy_video_templates").select("template_id").eq("video_id",Ae.id);M((Xe||[]).map(Ue=>Ue.template_id)),l(!0)},De=Ae=>{var Ue;const Xe=(Ue=Ae.target.files)==null?void 0:Ue[0];Xe&&(m(Xe),x(URL.createObjectURL(Xe)))},Be=Ae=>{const Xe=Ae.target.files;if(Xe){const Ue=Array.from(Xe).map(Ze=>({file:Ze,title:Ze.name.replace(/\.[^/.]+$/,"")}));g([...y,...Ue])}Ae.target.value=""},Ne=Ae=>{g(y.filter((Xe,Ue)=>Ue!==Ae))},Ge=Ae=>{C([...k,Ae]),v(b.filter(Xe=>Xe.id!==Ae))},_e=async()=>{if(!$)return null;ee(!0),G(0);try{const{data:Ae,error:Xe}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||$.name}});if(Xe)throw new Error(Xe.message);const{videoId:Ue,libraryId:Ze}=Ae;le(Ue);const{data:Qe,error:Ye}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ue}});if(Ye)throw new Error(Ye.message);const nt=new XMLHttpRequest;return await new Promise((Fe,dt)=>{nt.upload.addEventListener("progress",Dt=>{if(Dt.lengthComputable){const pt=Math.round(Dt.loaded/Dt.total*100);G(pt)}}),nt.addEventListener("load",()=>{nt.status>=200&&nt.status<300?Fe():dt(new Error(`Upload failed with status ${nt.status}`))}),nt.addEventListener("error",()=>dt(new Error("Upload failed"))),nt.open("PUT",Qe.uploadUrl),nt.setRequestHeader("AccessKey",Qe.apiKey),nt.send($)}),`https://player.mediadelivery.net/embed/${Ze}/${Ue}`}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{ee(!1)}},Oe=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 Ue=await _e();if(!Ue)return;Xe=Ue}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}we.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(Vs,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{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(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:oe.length})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:oe.filter(Ae=>Ae.is_published).length})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:oe.filter(Ae=>Ae.is_public).length})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:oe.reduce((Ae,Xe)=>Ae+(Xe.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(Fs,{open:i,onOpenChange:Ae=>{l(Ae),Ae||Ee()},children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:Oe,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:d.title,onChange:Ae=>u({...d,title:Ae.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Kj,{content:d.description,onChange:Ae=>u({...d,description:Ae}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Video Type"}),e.jsxs(vs,{value:d.video_type,onValueChange:Ae=>{u({...d,video_type:Ae,video_url:""}),q(null)},disabled:K,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:$7s.map(Ae=>e.jsx(Je,{value:Ae.value,children:Ae.label},Ae.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(se,{children:["Upload Video File ",!o&&"*"]}),o&&d.video_url&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Current video: ",e.jsx("a",{href:d.video_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"View"})]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(ye,{type:"file",accept:"video/*",onChange:Ae=>{var Ue;const Xe=(Ue=Ae.target.files)==null?void 0:Ue[0];Xe&&q(Xe)},disabled:K}),$&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Zr,{className:"h-4 w-4"}),$.name," (",($.size/(1024*1024)).toFixed(1)," MB)"]}),K&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(qi,{value:W,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[W,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(ye,{id:"video_url",value:d.video_url,onChange:Ae=>u({...d,video_url:Ae.target.value}),placeholder:"https://...",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"duration",children:"Duration"}),e.jsx(ye,{id:"duration",value:d.duration,onChange:Ae=>u({...d,duration:Ae.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{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(se,{children:"Category"}),I?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:P,onChange:Ae=>L(Ae.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>P.trim()&&de.mutate(P.trim()),disabled:de.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{O(!1),L("")},children:e.jsx(dr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:d.category_id,onValueChange:Ae=>u({...d,category_id:Ae}),children:[e.jsx(gs,{className:"flex-1",children:e.jsx(bs,{placeholder:"Select category"})}),e.jsx(ys,{children:ue.map(Ae=>e.jsx(Je,{value:Ae.id,children:Ae.name},Ae.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>O(!0),children:e.jsx(Js,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[p&&e.jsx("img",{src:p,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ye,{type:"file",accept:"image/*",onChange:De,className:"cursor-pointer"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Recommended: 16:9 aspect ratio"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Resource Files"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(Ja,{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"})]})})]}),(b.length>0||y.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[b.map(Ae=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:Ae.title}),e.jsx(qe,{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(dr,{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($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:Ae.title,onChange:Ue=>{const Ze=[...y];Ze[Xe].title=Ue.target.value,g(Ze)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(qe,{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(dr,{className:"h-4 w-4"})})]},Xe))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx($Mt,{selectedTemplateIds:T,onChange:M}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{id:"is_published",checked:d.is_published,onCheckedChange:Ae=>u({...d,is_published:Ae})}),e.jsx(se,{htmlFor:"is_published",children:"Published"})]}),e.jsxs(Nr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:K,children:"Cancel"}),e.jsx(B,{type:"submit",disabled:we.isPending||K,children:K?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):we.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:ie?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"})}):oe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Zr,{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(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Resources"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Public Views"}),e.jsx(Tt,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(za,{children:oe.map(Ae=>e.jsxs(un,{children:[e.jsx(xt,{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(Zr,{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(xt,{children:Ae.category?e.jsx(qe,{variant:"outline",children:Ae.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(xt,{children:Ae.duration||"-"}),e.jsx(xt,{children:Ae.resources&&Ae.resources.length>0?e.jsxs(qe,{variant:"secondary",children:[Ae.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(xt,{children:new Date(Ae.publish_date).toLocaleDateString()}),e.jsx(xt,{children:e.jsx(Mn,{checked:Ae.is_published,onCheckedChange:Xe=>xe.mutate({id:Ae.id,is_published:Xe})})}),e.jsx(xt,{children:Ae.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ma,{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(xt,{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:()=>fe(Ae),children:Ae.is_public?e.jsx(ja,{className:"h-4 w-4 text-primary"}):e.jsx(zd,{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(Ql,{className:"h-4 w-4 text-emerald-500"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Le(Ae),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>je.mutate(Ae.id),className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},Ae.id))})]})})})]})})};function q7s(){var we,je,xe;const s=as(),[t,n]=dc(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=j.useState(null),[h,m]=j.useState(""),[p,x]=j.useState([]),[y,g]=j.useState([]),[b,v]=j.useState([]),[k,C]=j.useState(null),{data:T,isLoading:M}=mt({queryKey:["resource-kits"],queryFn:async()=>{const{data:fe,error:Se}=await U.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Se)throw Se;return fe}}),{data:P}=mt({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:fe,error:Se}=await U.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Se)throw Se;return fe}}),{data:L}=mt({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:fe,error:Se}=await U.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Se)throw Se;return fe}});j.useEffect(()=>{const fe=t.get("edit");if(fe&&T&&T.length>0&&P&&L){const Se=T.find(Ee=>Ee.id===fe);Se&&(O(Se),n({},{replace:!0}))}},[T,P,L,t]);const I=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),x([]),g([]),v([]),l(null)},O=async fe=>{l(fe),c({name:fe.name,description:fe.description||"",publish_date:fe.publish_date.split("T")[0],is_published:fe.is_published}),m(fe.featured_image_url||"");const Se=(P==null?void 0:P.filter(De=>De.kit_id===fe.id))||[];x(Se.map(De=>({id:De.id,name:De.name,file_url:De.file_url,file_type:De.file_type,file_size:De.file_size,sort_order:De.sort_order})));const Ee=(L==null?void 0:L.filter(De=>De.kit_id===fe.id))||[];g(Ee.map(De=>({id:De.id,title:De.title,canva_share_link:De.canva_share_link,sort_order:De.sort_order})));const{data:Le}=await U.from("resource_kit_templates").select("template_id").eq("kit_id",fe.id);v((Le||[]).map(De=>De.template_id)),a(!0)},$=fe=>{var Ee;const Se=(Ee=fe.target.files)==null?void 0:Ee[0];Se&&(u(Se),m(URL.createObjectURL(Se)))},q=()=>{x([...p,{name:"",file_url:"",sort_order:p.length}])},W=fe=>{x(p.filter((Se,Ee)=>Ee!==fe))},G=(fe,Se,Ee)=>{const Le=[...p];Le[fe]={...Le[fe],[Se]:Ee},x(Le)},K=()=>{g([...y,{title:"",canva_share_link:"",sort_order:y.length}])},ee=fe=>{g(y.filter((Se,Ee)=>Ee!==fe))},J=(fe,Se,Ee)=>{const Le=[...y];Le[fe]={...Le[fe],[Se]:Ee},g(Le)},le=(fe,Se)=>{var Le;const Ee=(Le=Se.target.files)==null?void 0:Le[0];if(Ee){const De=[...p],Be=Ee.name.replace(/\.[^/.]+$/,"");De[fe]={...De[fe],file:Ee,file_type:Ee.type,file_size:Ee.size,name:De[fe].name||Be},x(De)}},ue=vt({mutationFn:async()=>{let fe=(i==null?void 0:i.featured_image_url)||null;if(d){const Be=d.name.split(".").pop(),Ne=`${Date.now()}.${Be}`,{error:Ge}=await U.storage.from("resource-kits").upload(`featured/${Ne}`,d);if(Ge)throw Ge;const{data:_e}=U.storage.from("resource-kits").getPublicUrl(`featured/${Ne}`);fe=_e.publicUrl}const Se={name:o.name,description:o.description||null,featured_image_url:fe,publish_date:o.publish_date,is_published:o.is_published};let Ee;const Le=!i,De=(i==null?void 0:i.is_published)||!1;if(i){const{error:Be}=await U.from("resource_kits").update(Se).eq("id",i.id);if(Be)throw Be;Ee=i.id;const Ne=(P==null?void 0:P.filter(Ue=>Ue.kit_id===i.id).map(Ue=>Ue.id))||[],Ge=p.filter(Ue=>Ue.id).map(Ue=>Ue.id),_e=Ne.filter(Ue=>!Ge.includes(Ue));_e.length>0&&await U.from("resource_kit_files").delete().in("id",_e);const Oe=(L==null?void 0:L.filter(Ue=>Ue.kit_id===i.id).map(Ue=>Ue.id))||[],Ae=y.filter(Ue=>Ue.id).map(Ue=>Ue.id),Xe=Oe.filter(Ue=>!Ae.includes(Ue));Xe.length>0&&await U.from("resource_kit_links").delete().in("id",Xe)}else{const{data:Be,error:Ne}=await U.from("resource_kits").insert(Se).select().single();if(Ne)throw Ne;Ee=Be.id}for(let Be=0;Be0){const{error:Be}=await U.from("resource_kit_templates").insert(b.map(Ne=>({kit_id:Ee,template_id:Ne})));if(Be)throw Be}return{kitId:Ee,kitName:o.name,isNewKit:Le,wasPublished:De,isPublished:o.is_published}},onSuccess:fe=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),re.success(i?"Resource kit updated":"Resource kit created"),fe.isPublished&&(fe.isNewKit||!fe.wasPublished)&&M7s(fe.kitName,fe.kitId),a(!1),I()},onError:fe=>{re.error("Failed to save resource kit: "+fe.message)}}),oe=vt({mutationFn:async fe=>{const{error:Se}=await U.from("resource_kits").delete().eq("id",fe);if(Se)throw Se},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),re.success("Resource kit deleted")},onError:fe=>{re.error("Failed to delete: "+fe.message)}}),ie=fe=>{if(fe.preventDefault(),!o.name){re.error("Please enter a name");return}ue.mutate()},de=fe=>(P==null?void 0:P.filter(Se=>Se.kit_id===fe).length)||0;return e.jsx(Vs,{title:"Toolbox Management",description:"Create and manage resource kits for agents",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:(T==null?void 0:T.length)||0})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:(T==null?void 0:T.filter(fe=>fe.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{I(),a(!0)},children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Files"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:M?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(T==null?void 0:T.length)===0?e.jsx(un,{children:e.jsx(xt,{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(fe=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[fe.featured_image_url?e.jsx("img",{src:fe.featured_image_url,alt:fe.name,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Eu,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:fe.name}),fe.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:fe.description})]})]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}),de(fe.id)]})}),e.jsx(xt,{children:Bs(new Date(fe.publish_date),"MMM d, yyyy")}),e.jsx(xt,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${fe.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:fe.is_published?"Published":"Draft"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{const Se=(P==null?void 0:P.filter(Le=>Le.kit_id===fe.id))||[],Ee=(L==null?void 0:L.filter(Le=>Le.kit_id===fe.id))||[];C({...fe,files:Se,links:Ee})},children:e.jsx(ma,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>O(fe),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Bi("Delete this resource kit?")&&oe.mutate(fe.id)},children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})})]},fe.id))})]})})}),e.jsx(Fs,{open:r,onOpenChange:a,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:ie,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Featured Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[h?e.jsx("img",{src:h,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):e.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:e.jsx(Eu,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(ye,{type:"file",accept:"image/*",onChange:$})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name *"}),e.jsx(ye,{id:"name",value:o.name,onChange:fe=>c({...o,name:fe.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Kj,{content:o.description,onChange:fe=>c({...o,description:fe}),placeholder:"Brief description of this resource kit",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{id:"publish_date",type:"date",value:o.publish_date,onChange:fe=>c({...o,publish_date:fe.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Mn,{checked:o.is_published,onCheckedChange:fe=>c({...o,is_published:fe})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:o.is_published?"Visible to agents":"Hidden from agents"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Resource Files"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:q,children:[e.jsx(Js,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),p.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed",children:'No files added yet. Click "Add File" to include resources.'}):e.jsx("div",{className:"space-y-3",children:p.map((fe,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(dr,{className:"h-4 w-4"})})]}),e.jsx(ye,{placeholder:"File name (e.g., Getting Started Guide)",value:fe.name,onChange:Ee=>G(Se,"name",Ee.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"file",onChange:Ee=>le(Se,Ee),className:"flex-1"}),fe.file_url&&!fe.file&&e.jsx("a",{href:fe.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),fe.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Se))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:K,children:[e.jsx(Js,{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((fe,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:()=>ee(Se),children:e.jsx(dr,{className:"h-4 w-4"})})]}),e.jsx(ye,{placeholder:"Link title (e.g., Social Media Post Template)",value:fe.title,onChange:Ee=>J(Se,"title",Ee.target.value)}),e.jsx(ye,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:fe.canva_share_link,onChange:Ee=>J(Se,"canva_share_link",Ee.target.value)})]},Se))})]}),e.jsx($Mt,{selectedTemplateIds:b,onChange:v}),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(Fs,{open:!!k,onOpenChange:()=>C(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx($s,{children:e.jsx(zs,{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 (",((we=k==null?void 0:k.files)==null?void 0:we.length)||0,")"]}),((je=k==null?void 0:k.files)==null?void 0:je.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:(xe=k==null?void 0:k.files)==null?void 0:xe.map(fe=>e.jsxs("a",{href:fe.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx($r,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:fe.name})]},fe.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(fe=>e.jsxs("a",{href:fe.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(vc,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:fe.title})]},fe.id))})]})]})]})})]})})}const V7s=()=>{const{user:s}=Ns(),{toast:t}=pi(),n=as(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,u]=j.useState(null),[h,m]=j.useState(""),{data:p=[],isLoading:x}=mt({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:L,error:I}=await U.from("social_swag").select("*").order("publish_date",{ascending:!1});if(I)throw I;const{data:O,error:$}=await U.from("social_swag_links").select("*").order("sort_order");if($)throw $;return L.map(W=>({...W,links:(O==null?void 0:O.filter(G=>G.swag_id===W.id))||[]}))}}),y=vt({mutationFn:async L=>{let I=L.existingImageUrl;if(L.image){const K=L.image.name.split(".").pop(),ee=`${Date.now()}-${Math.random().toString(36).substring(7)}.${K}`,{error:J}=await U.storage.from("template-previews").upload(ee,L.image);if(J)throw J;const{data:le}=U.storage.from("template-previews").getPublicUrl(ee);I=le.publicUrl}const O={title:L.item.title,description:L.item.description||null,preview_image_url:I,publish_date:L.item.publish_date?new Date(L.item.publish_date).toISOString():new Date().toISOString(),is_published:L.item.is_published,created_by:s==null?void 0:s.id};let $=L.itemId;const q=!$,W=(i==null?void 0:i.is_published)||!1;if($){const{error:K}=await U.from("social_swag").update(O).eq("id",$);if(K)throw K;await U.from("social_swag_links").delete().eq("swag_id",$)}else{const{data:K,error:ee}=await U.from("social_swag").insert(O).select().single();if(ee)throw ee;$=K.id}const G=L.item.links.filter(K=>K.title.trim()&&K.canva_share_link.trim());if(G.length>0){const K=G.map((J,le)=>({swag_id:$,title:J.title.trim(),canva_share_link:J.canva_share_link.trim(),sort_order:le})),{error:ee}=await U.from("social_swag_links").insert(K);if(ee)throw ee}return{itemId:$,itemTitle:L.item.title,isNewItem:q,wasPublished:W,isPublished:L.item.is_published}},onSuccess:L=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),L.isPublished&&(L.isNewItem||!L.wasPublished)&&IFe(L.itemTitle,L.itemId),a(!1),b()},onError:L=>{t({title:"Error saving item",description:L.message,variant:"destructive"})}}),g=vt({mutationFn:async L=>{const{error:I}=await U.from("social_swag").delete().eq("id",L);if(I)throw I},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:L=>{t({title:"Error deleting item",description:L.message,variant:"destructive"})}}),b=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),u(null),m(""),l(null)},v=L=>{l(L),c({title:L.title,description:L.description||"",publish_date:L.publish_date?new Date(L.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:L.is_published,links:L.links&&L.links.length>0?L.links.map(I=>({id:I.id,title:I.title,canva_share_link:I.canva_share_link,sort_order:I.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),m(L.preview_image_url||""),a(!0)},k=L=>{var O;const I=(O=L.target.files)==null?void 0:O[0];I&&(u(I),m(URL.createObjectURL(I)))},C=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},T=L=>{if(o.links.length<=1)return;const I=o.links.filter((O,$)=>$!==L);c({...o,links:I})},M=(L,I,O)=>{const $=[...o.links];$[L]={...$[L],[I]:O},c({...o,links:$})},P=L=>{if(L.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(Vs,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{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(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(L=>L.is_published).length})})]})]}),e.jsxs(Fs,{open:r,onOpenChange:L=>{a(L),L||b()},children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:P,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:o.title,onChange:L=>c({...o,title:L.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Kj,{content:o.description,onChange:L=>c({...o,description:L}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{id:"publish_date",type:"date",value:o.publish_date,onChange:L=>c({...o,publish_date:L.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Mn,{id:"is_published",checked:o.is_published,onCheckedChange:L=>c({...o,is_published:L})}),e.jsx(se,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(dr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(ac,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(ye,{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(se,{children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:C,children:[e.jsx(Js,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((L,I)=>e.jsx(be,{children:e.jsxs(Re,{className:"pt-4 pb-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Link ",I+1]}),o.links.length>1&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>T(I),children:e.jsx(dr,{className:"h-3 w-3"})})]}),e.jsx(ye,{placeholder:"Link title (e.g., Instagram Post)",value:L.title,onChange:O=>M(I,"title",O.target.value)}),e.jsx(ye,{placeholder:"Canva share link",value:L.canva_share_link,onChange:O=>M(I,"canva_share_link",O.target.value)})]})},I))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:y.isPending,children:y.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:x?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):p.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No items yet. Click "Add Item" to create your first one.'}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{className:"w-16",children:"Preview"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Links"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:p.map(L=>{var I;return e.jsxs(un,{children:[e.jsx(xt,{children:L.preview_image_url?e.jsx("img",{src:L.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(ac,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(xt,{className:"font-medium",children:L.title}),e.jsxs(xt,{children:[((I=L.links)==null?void 0:I.length)||0," links"]}),e.jsx(xt,{children:new Date(L.publish_date).toLocaleDateString()}),e.jsx(xt,{children:e.jsx(qe,{variant:L.is_published?"default":"secondary",children:L.is_published?"Published":"Draft"})}),e.jsx(xt,{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/${L.id}`,"_blank"),children:e.jsx(ma,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>v(L),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Bi("Are you sure you want to delete this item?")&&g.mutate(L.id)},children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},L.id)})})]})})})]})})};function H7s(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const kCe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function lq(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function eGe(s){return"nodeType"in s}function Rb(s){var t,n;return s?lq(s)?s:eGe(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function tGe(s){const{Document:t}=Rb(s);return s instanceof t}function BJ(s){return lq(s)?!1:s instanceof Rb(s).HTMLElement}function UMt(s){return s instanceof Rb(s).SVGElement}function cq(s){return s?lq(s)?s.document:eGe(s)?tGe(s)?s:BJ(s)||UMt(s)?s.ownerDocument:document:document:document}const Q5=kCe?j.useLayoutEffect:j.useEffect;function sGe(s){const t=j.useRef(s);return Q5(()=>{t.current=s}),j.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a{s.current=setInterval(r,a)},[]),n=j.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,n]}function wZ(s,t){t===void 0&&(t=[s]);const n=j.useRef(s);return Q5(()=>{n.current!==s&&(n.current=s)},t),n}function $J(s,t){const n=j.useRef();return j.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function Xke(s){const t=sGe(s),n=j.useRef(null),r=j.useCallback(a=>{a!==n.current&&(t==null||t(a,n.current)),n.current=a},[]);return[n,r]}function RFe(s){const t=j.useRef();return j.useEffect(()=>{t.current=s},[s]),t.current}let dPe={};function UJ(s,t){return j.useMemo(()=>{if(t)return t;const n=dPe[s]==null?0:dPe[s]+1;return dPe[s]=n,s+"-"+n},[s,t])}function qMt(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 Tz=qMt(1),jZ=qMt(-1);function W7s(s){return"clientX"in s&&"clientY"in s}function nGe(s){if(!s)return!1;const{KeyboardEvent:t}=Rb(s.target);return t&&s instanceof t}function K7s(s){if(!s)return!1;const{TouchEvent:t}=Rb(s.target);return t&&s instanceof t}function DFe(s){if(K7s(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 W7s(s)?{x:s.clientX,y:s.clientY}:null}const RE=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[RE.Translate.toString(s),RE.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),Xlt="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Y7s(s){return s.matches(Xlt)?s:s.querySelector(Xlt)}const Z7s={display:"none"};function X7s(s){let{id:t,value:n}=s;return Lt.createElement("div",{id:t,style:Z7s},n)}function Q7s(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 Lt.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function J7s(){const[s,t]=j.useState("");return{announce:j.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const VMt=j.createContext(null);function e9s(s){const t=j.useContext(VMt);j.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function t9s(){const[s]=j.useState(()=>new Set),t=j.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[j.useCallback(r=>{let{type:a,event:i}=r;s.forEach(l=>{var o;return(o=l[a])==null?void 0:o.call(l,i)})},[s]),t]}const s9s={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. `},n9s={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 r9s(s){let{announcements:t=n9s,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=s9s}=s;const{announce:i,announcement:l}=J7s(),o=UJ("DndLiveRegion"),[c,d]=j.useState(!1);if(j.useEffect(()=>{d(!0)},[]),e9s(j.useMemo(()=>({onDragStart(h){let{active:m}=h;i(t.onDragStart({active:m}))},onDragMove(h){let{active:m,over:p}=h;t.onDragMove&&i(t.onDragMove({active:m,over:p}))},onDragOver(h){let{active:m,over:p}=h;i(t.onDragOver({active:m,over:p}))},onDragEnd(h){let{active:m,over:p}=h;i(t.onDragEnd({active:m,over:p}))},onDragCancel(h){let{active:m,over:p}=h;i(t.onDragCancel({active:m,over:p}))}}),[i,t])),!c)return null;const u=Lt.createElement(Lt.Fragment,null,Lt.createElement(X7s,{id:r,value:a.draggable}),Lt.createElement(Q7s,{id:o,announcement:l}));return n?Hv.createPortal(u,n):u}var tg;(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"})(tg||(tg={}));function Qke(){}function I$(s,t){return j.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function SCe(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const EN=Object.freeze({x:0,y:0});function HMt(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function GMt(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function a9s(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function Qlt(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 WMt(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function Jlt(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 CCe=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=Jlt(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=HMt(Jlt(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(GMt)},i9s=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=Qlt(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=Qlt(c),u=a.reduce((m,p,x)=>m+HMt(d[x],p),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(GMt)};function o9s(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=o9s(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(a9s)};function c9s(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function KMt(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:EN}function d9s(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 u9s=d9s(1);function h9s(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 m9s(s,t,n){const r=h9s(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 p9s={ignoreTransform:!1};function dq(s,t){t===void 0&&(t=p9s);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=Rb(s).getComputedStyle(s);d&&(n=m9s(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 ect(s){return dq(s,{ignoreTransform:!0})}function f9s(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function x9s(s,t){return t===void 0&&(t=Rb(s).getComputedStyle(s)),t.position==="fixed"}function g9s(s,t){t===void 0&&(t=Rb(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 ACe(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(tGe(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!BJ(a)||UMt(a)||n.includes(a))return n;const i=Rb(s).getComputedStyle(a);return a!==s&&g9s(a,i)&&n.push(a),x9s(a,i)?n:r(a.parentNode)}return s?r(s):n}function YMt(s){const[t]=ACe(s,1);return t??null}function uPe(s){return!kCe||!s?null:lq(s)?s:eGe(s)?tGe(s)||s===cq(s).scrollingElement?window:BJ(s)?s:null:null}function ZMt(s){return lq(s)?s.scrollX:s.scrollLeft}function XMt(s){return lq(s)?s.scrollY:s.scrollTop}function OFe(s){return{x:ZMt(s),y:XMt(s)}}var Kg;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(Kg||(Kg={}));function QMt(s){return!kCe||!s?!1:s===document.scrollingElement}function JMt(s){const t={x:0,y:0},n=QMt(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 y9s={x:.2,y:.2};function v9s(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=y9s);const{isTop:d,isBottom:u,isLeft:h,isRight:m}=JMt(s),p={x:0,y:0},x={x:0,y:0},y={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+y.height?(p.y=Kg.Backward,x.y=r*Math.abs((t.top+y.height-i)/y.height)):!u&&c>=t.bottom-y.height&&(p.y=Kg.Forward,x.y=r*Math.abs((t.bottom-y.height-c)/y.height)),!m&&o>=t.right-y.width?(p.x=Kg.Forward,x.x=r*Math.abs((t.right-y.width-o)/y.width)):!h&&l<=t.left+y.width&&(p.x=Kg.Backward,x.x=r*Math.abs((t.left+y.width-l)/y.width)),{direction:p,speed:x}}function b9s(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 eLt(s){return s.reduce((t,n)=>Tz(t,OFe(n)),EN)}function _9s(s){return s.reduce((t,n)=>t+ZMt(n),0)}function w9s(s){return s.reduce((t,n)=>t+XMt(n),0)}function j9s(s,t){if(t===void 0&&(t=dq),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);YMt(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const N9s=[["x",["left","right"],_9s],["y",["top","bottom"],w9s]];class rGe{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=ACe(n),a=eLt(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of N9s)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 ZK{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 k9s(s){const{EventTarget:t}=Rb(s);return s instanceof t?s:cq(s)}function hPe(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 rj;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(rj||(rj={}));function tct(s){s.preventDefault()}function S9s(s){s.stopPropagation()}var dd;(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"})(dd||(dd={}));const tLt={start:[dd.Space,dd.Enter],cancel:[dd.Esc],end:[dd.Space,dd.Enter,dd.Tab]},C9s=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case dd.Right:return{...n,x:n.x+25};case dd.Left:return{...n,x:n.x-25};case dd.Down:return{...n,y:n.y+25};case dd.Up:return{...n,y:n.y-25}}};class TCe{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 ZK(cq(n)),this.windowListeners=new ZK(Rb(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(rj.Resize,this.handleCancel),this.windowListeners.add(rj.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(rj.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&j9s(r),n(EN)}handleKeyDown(t){if(nGe(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=tLt,coordinateGetter:l=C9s,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}:EN;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const m=jZ(h,u),p={x:0,y:0},{scrollableAncestors:x}=r.current;for(const y of x){const g=t.code,{isTop:b,isRight:v,isLeft:k,isBottom:C,maxScroll:T,minScroll:M}=JMt(y),P=b9s(y),L={x:Math.min(g===dd.Right?P.right-P.width/2:P.right,Math.max(g===dd.Right?P.left:P.left+P.width/2,h.x)),y:Math.min(g===dd.Down?P.bottom-P.height/2:P.bottom,Math.max(g===dd.Down?P.top:P.top+P.height/2,h.y))},I=g===dd.Right&&!v||g===dd.Left&&!k,O=g===dd.Down&&!C||g===dd.Up&&!b;if(I&&L.x!==h.x){const $=y.scrollLeft+m.x,q=g===dd.Right&&$<=T.x||g===dd.Left&&$>=M.x;if(q&&!m.y){y.scrollTo({left:$,behavior:o});return}q?p.x=y.scrollLeft-$:p.x=g===dd.Right?y.scrollLeft-T.x:y.scrollLeft-M.x,p.x&&y.scrollBy({left:-p.x,behavior:o});break}else if(O&&L.y!==h.y){const $=y.scrollTop+m.y,q=g===dd.Down&&$<=T.y||g===dd.Up&&$>=M.y;if(q&&!m.x){y.scrollTo({top:$,behavior:o});return}q?p.y=y.scrollTop-$:p.y=g===dd.Down?y.scrollTop-T.y:y.scrollTop-M.y,p.y&&y.scrollBy({top:-p.y,behavior:o});break}}this.handleMove(t,Tz(jZ(h,this.referenceCoordinates),p))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}TCe.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=tLt,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 sct(s){return!!(s&&"distance"in s)}function nct(s){return!!(s&&"delay"in s)}class aGe{constructor(t,n,r){var a;r===void 0&&(r=k9s(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=cq(l),this.documentListeners=new ZK(this.document),this.listeners=new ZK(r),this.windowListeners=new ZK(Rb(l)),this.initialCoordinates=(a=DFe(i))!=null?a:EN,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(rj.Resize,this.handleCancel),this.windowListeners.add(rj.DragStart,tct),this.windowListeners.add(rj.VisibilityChange,this.handleCancel),this.windowListeners.add(rj.ContextMenu,tct),this.documentListeners.add(rj.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(nct(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(sct(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(rj.Click,S9s,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(rj.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=DFe(t))!=null?n:EN,d=jZ(a,c);if(!r&&o){if(sct(o)){if(o.tolerance!=null&&hPe(d,o.tolerance))return this.handleCancel();if(hPe(d,o.distance))return this.handleStart()}if(nct(o)&&hPe(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===dd.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const A9s={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class uq extends aGe{constructor(t){const{event:n}=t,r=cq(n.target);super(t,A9s,r)}}uq.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 T9s={move:{name:"mousemove"},end:{name:"mouseup"}};var FFe;(function(s){s[s.RightClick=2]="RightClick"})(FFe||(FFe={}));class E9s extends aGe{constructor(t){super(t,T9s,cq(t.event.target))}}E9s.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===FFe.RightClick?!1:(r==null||r({event:n}),!0)}}];const mPe={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class M9s extends aGe{constructor(t){super(t,mPe)}static setup(){return window.addEventListener(mPe.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(mPe.move.name,t)};function t(){}}}M9s.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 XK;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(XK||(XK={}));var Jke;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(Jke||(Jke={}));function L9s(s){let{acceleration:t,activator:n=XK.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=Jke.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:m}=s;const p=I9s({delta:h,disabled:!i}),[x,y]=G7s(),g=j.useRef({x:0,y:0}),b=j.useRef({x:0,y:0}),v=j.useMemo(()=>{switch(n){case XK.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case XK.DraggableRect:return a}},[n,a,c]),k=j.useRef(null),C=j.useCallback(()=>{const M=k.current;if(!M)return;const P=g.current.x*b.current.x,L=g.current.y*b.current.y;M.scrollBy(P,L)},[]),T=j.useMemo(()=>o===Jke.TreeOrder?[...d].reverse():d,[o,d]);j.useEffect(()=>{if(!i||!d.length||!v){y();return}for(const M of T){if((r==null?void 0:r(M))===!1)continue;const P=d.indexOf(M),L=u[P];if(!L)continue;const{direction:I,speed:O}=v9s(M,L,v,t,m);for(const $ of["x","y"])p[$][I[$]]||(O[$]=0,I[$]=0);if(O.x>0||O.y>0){y(),k.current=M,x(C,l),g.current=O,b.current=I;return}}g.current={x:0,y:0},b.current={x:0,y:0},y()},[t,C,r,y,i,l,JSON.stringify(v),JSON.stringify(p),x,d,T,u,JSON.stringify(m)])}const P9s={x:{[Kg.Backward]:!1,[Kg.Forward]:!1},y:{[Kg.Backward]:!1,[Kg.Forward]:!1}};function I9s(s){let{delta:t,disabled:n}=s;const r=RFe(t);return $J(a=>{if(n||!r||!a)return P9s;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[Kg.Backward]:a.x[Kg.Backward]||i.x===-1,[Kg.Forward]:a.x[Kg.Forward]||i.x===1},y:{[Kg.Backward]:a.y[Kg.Backward]||i.y===-1,[Kg.Forward]:a.y[Kg.Forward]||i.y===1}}},[n,t,r])}function R9s(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return $J(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function D9s(s,t){return j.useMemo(()=>s.reduce((n,r)=>{const{sensor:a}=r,i=a.activators.map(l=>({eventName:l.eventName,handler:t(l.handler,r)}));return[...n,...i]},[]),[s,t])}var NZ;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(NZ||(NZ={}));var zFe;(function(s){s.Optimized="optimized"})(zFe||(zFe={}));const rct=new Map;function O9s(s,t){let{dragging:n,dependencies:r,config:a}=t;const[i,l]=j.useState(null),{frequency:o,measure:c,strategy:d}=a,u=j.useRef(s),h=g(),m=wZ(h),p=j.useCallback(function(b){b===void 0&&(b=[]),!m.current&&l(v=>v===null?b:v.concat(b.filter(k=>!v.includes(k))))},[m]),x=j.useRef(null),y=$J(b=>{if(h&&!n)return rct;if(!b||b===rct||u.current!==s||i!=null){const v=new Map;for(let k of s){if(!k)continue;if(i&&i.length>0&&!i.includes(k.id)&&k.rect.current){v.set(k.id,k.rect.current);continue}const C=k.node.current,T=C?new rGe(c(C),C):null;k.rect.current=T,T&&v.set(k.id,T)}return v}return b},[s,i,n,h,c]);return j.useEffect(()=>{u.current=s},[s]),j.useEffect(()=>{h||p()},[n,h]),j.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),j.useEffect(()=>{h||typeof o!="number"||x.current!==null||(x.current=setTimeout(()=>{p(),x.current=null},o))},[o,h,p,...r]),{droppableRects:y,measureDroppableContainers:p,measuringScheduled:i!=null};function g(){switch(d){case NZ.Always:return!1;case NZ.BeforeDragging:return n;default:return!n}}}function sLt(s,t){return $J(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function F9s(s,t){return sLt(s,t)}function z9s(s){let{callback:t,disabled:n}=s;const r=sGe(t),a=j.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return j.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function ECe(s){let{callback:t,disabled:n}=s;const r=sGe(t),a=j.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return j.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function B9s(s){return new rGe(dq(s),s)}function act(s,t,n){t===void 0&&(t=B9s);const[r,a]=j.useState(null);function i(){a(c=>{if(!s)return null;if(s.isConnected===!1){var d;return(d=c??n)!=null?d:null}const u=t(s);return JSON.stringify(c)===JSON.stringify(u)?c:u})}const l=z9s({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=ECe({callback:i});return Q5(()=>{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 $9s(s){const t=sLt(s);return KMt(s,t)}const ict=[];function U9s(s){const t=j.useRef(s),n=$J(r=>s?r&&r!==ict&&s&&t.current&&s.parentNode===t.current.parentNode?r:ACe(s):ict,[s]);return j.useEffect(()=>{t.current=s},[s]),n}function q9s(s){const[t,n]=j.useState(null),r=j.useRef(s),a=j.useCallback(i=>{const l=uPe(i.target);l&&n(o=>o?(o.set(l,OFe(l)),new Map(o)):null)},[]);return j.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=uPe(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,OFe(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=uPe(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),j.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>Tz(i,l),EN):eLt(s):EN,[s,t])}function oct(s,t){t===void 0&&(t=[]);const n=j.useRef(null);return j.useEffect(()=>{n.current=null},t),j.useEffect(()=>{const r=s!==EN;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?jZ(s,n.current):EN}function V9s(s){j.useEffect(()=>{if(!kCe)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 H9s(s,t){return j.useMemo(()=>s.reduce((n,r)=>{let{eventName:a,handler:i}=r;return n[a]=l=>{i(l,t)},n},{}),[s,t])}function nLt(s){return j.useMemo(()=>s?f9s(s):null,[s])}const lct=[];function G9s(s,t){t===void 0&&(t=dq);const[n]=s,r=nLt(n?Rb(n):null),[a,i]=j.useState(lct);function l(){i(()=>s.length?s.map(c=>QMt(c)?r:new rGe(t(c),c)):lct)}const o=ECe({callback:l});return Q5(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function W9s(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return BJ(t)?t:s}function K9s(s){let{measure:t}=s;const[n,r]=j.useState(null),a=j.useCallback(d=>{for(const{target:u}of d)if(BJ(u)){r(h=>{const m=t(u);return h?{...h,width:m.width,height:m.height}:m});break}},[t]),i=ECe({callback:a}),l=j.useCallback(d=>{const u=W9s(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=Xke(l);return j.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const Y9s=[{sensor:uq,options:{}},{sensor:TCe,options:{}}],Z9s={current:{}},Oje={draggable:{measure:ect},droppable:{measure:ect,strategy:NZ.WhileDragging,frequency:zFe.Optimized},dragOverlay:{measure:dq}};class QK 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 X9s={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new QK,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Qke},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Oje,measureDroppableContainers:Qke,windowRect:null,measuringScheduled:!1},Q9s={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Qke,draggableNodes:new Map,over:null,measureDroppableContainers:Qke},MCe=j.createContext(Q9s),rLt=j.createContext(X9s);function J9s(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new QK}}}function ezs(s,t){switch(t.type){case tg.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case tg.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 tg.DragEnd:case tg.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case tg.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new QK(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case tg.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 QK(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case tg.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new QK(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function tzs(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=j.useContext(MCe),i=RFe(r),l=RFe(n==null?void 0:n.id);return j.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!nGe(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=Y7s(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function szs(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function nzs(s){return j.useMemo(()=>({draggable:{...Oje.draggable,...s==null?void 0:s.draggable},droppable:{...Oje.droppable,...s==null?void 0:s.droppable},dragOverlay:{...Oje.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 rzs(s){let{activeNode:t,measure:n,initialRect:r,config:a=!0}=s;const i=j.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;Q5(()=>{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=KMt(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=YMt(d);m&&m.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const aLt=j.createContext({...EN,scaleX:1,scaleY:1});var xA;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(xA||(xA={}));const LCe=j.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=Y9s,collisionDetection:h=l9s,measuring:m,modifiers:p,...x}=t;const y=j.useReducer(ezs,void 0,J9s),[g,b]=y,[v,k]=t9s(),[C,T]=j.useState(xA.Uninitialized),M=C===xA.Initialized,{draggable:{active:P,nodes:L,translate:I},droppable:{containers:O}}=g,$=P!=null?L.get(P):null,q=j.useRef({initial:null,translated:null}),W=j.useMemo(()=>{var Hs;return P!=null?{id:P,data:(Hs=$==null?void 0:$.data)!=null?Hs:Z9s,rect:q}:null},[P,$]),G=j.useRef(null),[K,ee]=j.useState(null),[J,le]=j.useState(null),ue=wZ(x,Object.values(x)),oe=UJ("DndDescribedBy",l),ie=j.useMemo(()=>O.getEnabled(),[O]),de=nzs(m),{droppableRects:we,measureDroppableContainers:je,measuringScheduled:xe}=O9s(ie,{dragging:M,dependencies:[I.x,I.y],config:de.droppable}),fe=R9s(L,P),Se=j.useMemo(()=>J?DFe(J):null,[J]),Ee=sn(),Le=F9s(fe,de.draggable.measure);rzs({activeNode:P!=null?L.get(P):null,config:Ee.layoutShiftCompensation,initialRect:Le,measure:de.draggable.measure});const De=act(fe,de.draggable.measure,Le),Be=act(fe?fe.parentElement:null),Ne=j.useRef({activatorEvent:null,active:null,activeNode:fe,collisionRect:null,collisions:null,droppableRects:we,draggableNodes:L,draggingNode:null,draggingNodeRect:null,droppableContainers:O,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ge=O.getNodeFor((n=Ne.current.over)==null?void 0:n.id),_e=K9s({measure:de.dragOverlay.measure}),Oe=(r=_e.nodeRef.current)!=null?r:fe,Ae=M?(a=_e.rect)!=null?a:De:null,Xe=!!(_e.nodeRef.current&&_e.rect),Ue=$9s(Xe?null:De),Ze=nLt(Oe?Rb(Oe):null),Qe=U9s(M?Ge??fe:null),Ye=G9s(Qe),nt=szs(p,{transform:{x:I.x-Ue.x,y:I.y-Ue.y,scaleX:1,scaleY:1},activatorEvent:J,active:W,activeNodeRect:De,containerNodeRect:Be,draggingNodeRect:Ae,over:Ne.current.over,overlayNodeRect:_e.rect,scrollableAncestors:Qe,scrollableAncestorRects:Ye,windowRect:Ze}),rt=Se?Tz(Se,I):null,Fe=q9s(Qe),dt=oct(Fe),Dt=oct(Fe,[De]),pt=Tz(nt,dt),zt=Ae?u9s(Ae,nt):null,Gt=W&&zt?h({active:W,collisionRect:zt,droppableRects:we,droppableContainers:ie,pointerCoordinates:rt}):null,qs=WMt(Gt,"id"),[As,Bt]=j.useState(null),At=Xe?nt:Tz(nt,Dt),Is=c9s(At,(i=As==null?void 0:As.rect)!=null?i:null,De),jt=j.useRef(null),Qs=j.useCallback((Hs,nn)=>{let{sensor:tn,options:_n}=nn;if(G.current==null)return;const Cn=L.get(G.current);if(!Cn)return;const Un=Hs.nativeEvent,Kr=new tn({active:G.current,activeNode:Cn,event:Un,options:_n,context:Ne,onAbort(Xs){if(!L.get(Xs))return;const{onDragAbort:Hr}=ue.current,mr={id:Xs};Hr==null||Hr(mr),v({type:"onDragAbort",event:mr})},onPending(Xs,Ba,Hr,mr){if(!L.get(Xs))return;const{onDragPending:rn}=ue.current,Jn={id:Xs,constraint:Ba,initialCoordinates:Hr,offset:mr};rn==null||rn(Jn),v({type:"onDragPending",event:Jn})},onStart(Xs){const Ba=G.current;if(Ba==null)return;const Hr=L.get(Ba);if(!Hr)return;const{onDragStart:mr}=ue.current,pr={activatorEvent:Un,active:{id:Ba,data:Hr.data,rect:q}};Hv.unstable_batchedUpdates(()=>{mr==null||mr(pr),T(xA.Initializing),b({type:tg.DragStart,initialCoordinates:Xs,active:Ba}),v({type:"onDragStart",event:pr}),ee(jt.current),le(Un)})},onMove(Xs){b({type:tg.DragMove,coordinates:Xs})},onEnd:jr(tg.DragEnd),onCancel:jr(tg.DragCancel)});jt.current=Kr;function jr(Xs){return async function(){const{active:Hr,collisions:mr,over:pr,scrollAdjustedTranslate:rn}=Ne.current;let Jn=null;if(Hr&&rn){const{cancelDrop:ea}=ue.current;Jn={activatorEvent:Un,active:Hr,collisions:mr,delta:rn,over:pr},Xs===tg.DragEnd&&typeof ea=="function"&&await Promise.resolve(ea(Jn))&&(Xs=tg.DragCancel)}G.current=null,Hv.unstable_batchedUpdates(()=>{b({type:Xs}),T(xA.Uninitialized),Bt(null),ee(null),le(null),jt.current=null;const ea=Xs===tg.DragEnd?"onDragEnd":"onDragCancel";if(Jn){const _s=ue.current[ea];_s==null||_s(Jn),v({type:ea,event:Jn})}})}}},[L]),cn=j.useCallback((Hs,nn)=>(tn,_n)=>{const Cn=tn.nativeEvent,Un=L.get(_n);if(G.current!==null||!Un||Cn.dndKit||Cn.defaultPrevented)return;const Kr={active:Un};Hs(tn,nn.options,Kr)===!0&&(Cn.dndKit={capturedBy:nn.sensor},G.current=_n,Qs(tn,nn))},[L,Qs]),qt=D9s(u,cn);V9s(u),Q5(()=>{De&&C===xA.Initializing&&T(xA.Initialized)},[De,C]),j.useEffect(()=>{const{onDragMove:Hs}=ue.current,{active:nn,activatorEvent:tn,collisions:_n,over:Cn}=Ne.current;if(!nn||!tn)return;const Un={active:nn,activatorEvent:tn,collisions:_n,delta:{x:pt.x,y:pt.y},over:Cn};Hv.unstable_batchedUpdates(()=>{Hs==null||Hs(Un),v({type:"onDragMove",event:Un})})},[pt.x,pt.y]),j.useEffect(()=>{const{active:Hs,activatorEvent:nn,collisions:tn,droppableContainers:_n,scrollAdjustedTranslate:Cn}=Ne.current;if(!Hs||G.current==null||!nn||!Cn)return;const{onDragOver:Un}=ue.current,Kr=_n.get(qs),jr=Kr&&Kr.rect.current?{id:Kr.id,rect:Kr.rect.current,data:Kr.data,disabled:Kr.disabled}:null,Xs={active:Hs,activatorEvent:nn,collisions:tn,delta:{x:Cn.x,y:Cn.y},over:jr};Hv.unstable_batchedUpdates(()=>{Bt(jr),Un==null||Un(Xs),v({type:"onDragOver",event:Xs})})},[qs]),Q5(()=>{Ne.current={activatorEvent:J,active:W,activeNode:fe,collisionRect:zt,collisions:Gt,droppableRects:we,draggableNodes:L,draggingNode:Oe,draggingNodeRect:Ae,droppableContainers:O,over:As,scrollableAncestors:Qe,scrollAdjustedTranslate:pt},q.current={initial:Ae,translated:zt}},[W,fe,Gt,zt,L,Oe,Ae,we,O,As,Qe,pt]),L9s({...Ee,delta:I,draggingRect:zt,pointerCoordinates:rt,scrollableAncestors:Qe,scrollableAncestorRects:Ye});const Gs=j.useMemo(()=>({active:W,activeNode:fe,activeNodeRect:De,activatorEvent:J,collisions:Gt,containerNodeRect:Be,dragOverlay:_e,draggableNodes:L,droppableContainers:O,droppableRects:we,over:As,measureDroppableContainers:je,scrollableAncestors:Qe,scrollableAncestorRects:Ye,measuringConfiguration:de,measuringScheduled:xe,windowRect:Ze}),[W,fe,De,J,Gt,Be,_e,L,O,we,As,je,Qe,Ye,de,xe,Ze]),Ls=j.useMemo(()=>({activatorEvent:J,activators:qt,active:W,activeNodeRect:De,ariaDescribedById:{draggable:oe},dispatch:b,draggableNodes:L,over:As,measureDroppableContainers:je}),[J,qt,W,De,b,oe,L,As,je]);return Lt.createElement(VMt.Provider,{value:k},Lt.createElement(MCe.Provider,{value:Ls},Lt.createElement(rLt.Provider,{value:Gs},Lt.createElement(aLt.Provider,{value:Is},d)),Lt.createElement(tzs,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Lt.createElement(r9s,{...o,hiddenTextDescribedById:oe}));function sn(){const Hs=(K==null?void 0:K.autoScrollEnabled)===!1,nn=typeof c=="object"?c.enabled===!1:c===!1,tn=M&&!Hs&&!nn;return typeof c=="object"?{...c,enabled:tn}:{enabled:tn}}}),azs=j.createContext(null),cct="button",izs="Draggable";function ozs(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=UJ(izs),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:m}=j.useContext(MCe),{role:p=cct,roleDescription:x="draggable",tabIndex:y=0}=a??{},g=(c==null?void 0:c.id)===t,b=j.useContext(g?aLt:azs),[v,k]=Xke(),[C,T]=Xke(),M=H9s(l,t),P=wZ(n);Q5(()=>(h.set(t,{id:t,key:i,node:v,activatorNode:C,data:P}),()=>{const I=h.get(t);I&&I.key===i&&h.delete(t)}),[h,t]);const L=j.useMemo(()=>({role:p,tabIndex:y,"aria-disabled":r,"aria-pressed":g&&p===cct?!0:void 0,"aria-roledescription":x,"aria-describedby":u.draggable}),[r,p,y,g,x,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:L,isDragging:g,listeners:r?void 0:M,node:v,over:m,setNodeRef:k,setActivatorNodeRef:T,transform:b}}function lzs(){return j.useContext(rLt)}const czs="Droppable",dzs={timeout:25};function uzs(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=UJ(czs),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=j.useContext(MCe),u=j.useRef({disabled:n}),h=j.useRef(!1),m=j.useRef(null),p=j.useRef(null),{disabled:x,updateMeasurementsFor:y,timeout:g}={...dzs,...a},b=wZ(y??r),v=j.useCallback(()=>{if(!h.current){h.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{d(Array.isArray(b.current)?b.current:[b.current]),p.current=null},g)},[g]),k=ECe({callback:v,disabled:x||!l}),C=j.useCallback((L,I)=>{k&&(I&&(k.unobserve(I),h.current=!1),L&&k.observe(L))},[k]),[T,M]=Xke(C),P=wZ(t);return j.useEffect(()=>{!k||!T.current||(k.disconnect(),h.current=!1,k.observe(T.current))},[T,k]),j.useEffect(()=>(o({type:tg.RegisterDroppable,element:{id:r,key:i,disabled:n,node:T,rect:m,data:P}}),()=>o({type:tg.UnregisterDroppable,key:i,id:r})),[r]),j.useEffect(()=>{n!==u.current.disabled&&(o({type:tg.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:M}}function PCe(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function hzs(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function fne(s){return s!==null&&s>=0}function mzs(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=fzs(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...xne}:l=i?{x:o.width+c,y:0,...xne}:{x:0,y:0,...xne}};function fzs(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=PCe(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}},gne={scaleX:1,scaleY:1},xzs=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,...gne}:a=l?{x:0,y:o.height+c,...gne}:{x:0,y:0,...gne}};function gzs(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return r?nr.map(M=>typeof M=="object"&&"id"in M?M.id:M),[r]),x=l!=null,y=l?p.indexOf(l.id):-1,g=d?p.indexOf(d.id):-1,b=j.useRef(p),v=!mzs(p,b.current),k=g!==-1&&y===-1||v,C=pzs(i);Q5(()=>{v&&x&&u(p)},[v,p,x,u]),j.useEffect(()=>{b.current=p},[p]);const T=j.useMemo(()=>({activeIndex:y,containerId:h,disabled:C,disableTransforms:k,items:p,overIndex:g,useDragOverlay:m,sortedRects:hzs(p,c),strategy:a}),[y,h,C.draggable,C.droppable,k,p,g,c,m,a]);return Lt.createElement(oLt.Provider,{value:T},t)}const yzs=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return PCe(n,r,a).indexOf(t)},vzs=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},bzs={duration:200,easing:"ease"},lLt="transform",_zs=RE.Transition.toString({property:lLt,duration:0,easing:"linear"}),wzs={roleDescription:"sortable"};function jzs(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=j.useState(null),o=j.useRef(n);return Q5(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=dq(r.current,{ignoreTransform:!0}),u={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(u.x||u.y)&&l(u)}}n!==o.current&&(o.current=n)},[t,n,r,a]),j.useEffect(()=>{i&&l(null)},[i]),i}function RCe(s){let{animateLayoutChanges:t=vzs,attributes:n,disabled:r,data:a,getNewIndex:i=yzs,id:l,strategy:o,resizeObserverConfig:c,transition:d=bzs}=s;const{items:u,containerId:h,activeIndex:m,disabled:p,disableTransforms:x,sortedRects:y,overIndex:g,useDragOverlay:b,strategy:v}=j.useContext(oLt),k=Nzs(r,p),C=u.indexOf(l),T=j.useMemo(()=>({sortable:{containerId:h,index:C,items:u},...a}),[h,a,C,u]),M=j.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:P,node:L,isOver:I,setNodeRef:O}=uzs({id:l,data:T,disabled:k.droppable,resizeObserverConfig:{updateMeasurementsFor:M,...c}}),{active:$,activatorEvent:q,activeNodeRect:W,attributes:G,setNodeRef:K,listeners:ee,isDragging:J,over:le,setActivatorNodeRef:ue,transform:oe}=ozs({id:l,data:T,attributes:{...wzs,...n},disabled:k.draggable}),ie=H7s(O,K),de=!!$,we=de&&!x&&fne(m)&&fne(g),je=!b&&J,xe=je&&we?oe:null,Se=we?xe??(o??v)({rects:y,activeNodeRect:W,activeIndex:m,overIndex:g,index:C}):null,Ee=fne(m)&&fne(g)?i({id:l,items:u,activeIndex:m,overIndex:g}):C,Le=$==null?void 0:$.id,De=j.useRef({activeId:Le,items:u,newIndex:Ee,containerId:h}),Be=u!==De.current.items,Ne=t({active:$,containerId:h,isDragging:J,isSorting:de,id:l,index:C,items:u,newIndex:De.current.newIndex,previousItems:De.current.items,previousContainerId:De.current.containerId,transition:d,wasDragging:De.current.activeId!=null}),Ge=jzs({disabled:!Ne,index:C,node:L,rect:P});return j.useEffect(()=>{de&&De.current.newIndex!==Ee&&(De.current.newIndex=Ee),h!==De.current.containerId&&(De.current.containerId=h),u!==De.current.items&&(De.current.items=u)},[de,Ee,h,u]),j.useEffect(()=>{if(Le===De.current.activeId)return;if(Le!=null&&De.current.activeId==null){De.current.activeId=Le;return}const Oe=setTimeout(()=>{De.current.activeId=Le},50);return()=>clearTimeout(Oe)},[Le]),{active:$,activeIndex:m,attributes:G,data:T,rect:P,index:C,newIndex:Ee,items:u,isOver:I,isSorting:de,isDragging:J,listeners:ee,node:L,overIndex:g,over:le,setNodeRef:ie,setActivatorNodeRef:ue,setDroppableNodeRef:O,setDraggableNodeRef:K,transform:Ge??Se,transition:_e()};function _e(){if(Ge||Be&&De.current.newIndex===C)return _zs;if(!(je&&!nGe(q)||!d)&&(de||Ne))return RE.Transition.toString({...d,property:lLt})}}function Nzs(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 e5e(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 kzs=[dd.Down,dd.Right,dd.Up,dd.Left],cLt=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(kzs.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 dd.Down:r.topm.top&&c.push(h);break;case dd.Left:r.left>m.left&&c.push(h);break;case dd.Right:r.left1&&(u=d[1].id),u!=null){const h=i.get(n.id),m=i.get(u),p=m?a.get(m.id):null,x=m==null?void 0:m.node.current;if(x&&p&&h&&m){const g=ACe(x).some((M,P)=>o[P]!==M),b=dLt(h,m),v=Szs(h,m),k=g||!b?{x:0,y:0}:{x:v?r.width-p.width:0,y:v?r.height-p.height:0},C={x:p.left,y:p.top};return k.x&&k.y?C:jZ(C,k)}}}};function dLt(s,t){return!e5e(s)||!e5e(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function Szs(s,t){return!e5e(s)||!e5e(t)||!dLt(s,t)?!1:s.data.current.sortable.indext(s),children:e.jsx(Za,{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(Rn,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(qe,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(ra,{className:"h-2.5 w-2.5"}),Bs(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Re,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:Et("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(ra,{className:"h-3 w-3"}),s.post_date?Bs(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(Jl,{className:"w-auto p-0",align:"start",children:[e.jsx(o1,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?Bs(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 Azs=()=>{const s=as(),[t,n]=j.useState("all"),[r,a]=j.useState(!1),[i,l]=j.useState(Bs(new Date,"yyyy-MM")),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,x]=j.useState(null),[y,g]=j.useState(""),[b,v]=j.useState(null),[k,C]=j.useState(!1),[T,M]=j.useState(!1),[P,L]=j.useState(Bs(new Date,"yyyy-MM")),[I,O]=j.useState(null),[$,q]=j.useState(""),[W,G]=j.useState(""),[K,ee]=j.useState(""),[J,le]=j.useState(!1),ue=SCe(I$(uq,{activationConstraint:{distance:5}}),I$(TCe,{coordinateGetter:cLt})),{data:oe=[],isLoading:ie}=mt({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:rt,error:Fe}=await U.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(Fe)throw Fe;return rt}}),{data:de=[]}=mt({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:rt,error:Fe}=await U.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(Fe)throw Fe;return rt}}),{data:we=[]}=mt({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:rt,error:Fe}=await U.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(Fe)throw Fe;return rt}}),je=[...new Set(oe.map(rt=>rt.month))].sort((rt,Fe)=>Fe.localeCompare(rt)),xe=t==="all"?oe:oe.filter(rt=>rt.month===t),fe=rt=>{const Fe=hqe(rt,"yyyy-MM",new Date);return Bs(Fe,"MMMM yyyy")},Se=rt=>{x(rt),g(rt.caption),v(rt.post_date)},Ee=async()=>{if(p){C(!0);try{const{error:rt}=await U.from("social_swag_2").update({caption:y,post_date:b}).eq("id",p.id);if(rt)throw rt;re.success("Image updated"),x(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{re.error("Failed to update image")}finally{C(!1)}}},Le=async rt=>{const{active:Fe,over:dt}=rt;if(!dt||Fe.id===dt.id)return;const Dt=xe,pt=Dt.findIndex(qs=>qs.id===Fe.id),zt=Dt.findIndex(qs=>qs.id===dt.id);if(pt===-1||zt===-1)return;const Gt=PCe(Dt,pt,zt);s.setQueryData(["admin-social-swag-2"],qs=>{if(!qs)return qs;const As={};return Gt.forEach((Bt,At)=>{As[Bt.id]=At}),qs.map(Bt=>As[Bt.id]!==void 0?{...Bt,sort_order:As[Bt.id]}:Bt).sort((Bt,At)=>Bt.month!==At.month?At.month.localeCompare(Bt.month):Bt.sort_order-At.sort_order)});try{await Promise.all(Gt.map((qs,As)=>U.from("social_swag_2").update({sort_order:As}).eq("id",qs.id)))}catch{re.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},De=rt=>{const dt=Array.from(rt.target.files||[]).sort((Dt,pt)=>Dt.name.localeCompare(pt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(Dt=>({file:Dt,preview:URL.createObjectURL(Dt),caption:""}));c(Dt=>[...Dt,...dt].slice(0,16))},Be=rt=>{c(Fe=>{const dt=[...Fe];return URL.revokeObjectURL(dt[rt].preview),dt.splice(rt,1),dt})},Ne=(rt,Fe)=>{c(dt=>{const Dt=[...dt];return Dt[rt]={...Dt[rt],caption:Fe},Dt})},Ge=async()=>{var Fe;if(o.length===0){re.error("Please add at least one image");return}if(o.filter(dt=>!dt.caption.trim()).length>0){re.error("Please add captions to all images");return}u(!0);try{const{data:dt}=await U.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),Dt=(((Fe=dt==null?void 0:dt[0])==null?void 0:Fe.sort_order)??-1)+1;for(let pt=0;pt{const Fe=rt.image_url.split("/social-swag-2/");Fe[1]&&await U.storage.from("social-swag-2").remove([Fe[1]]);const{error:dt}=await U.from("social_swag_2").delete().eq("id",rt.id);if(dt)throw dt},onSuccess:()=>{re.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>re.error("Failed to delete image")}),Oe=vt({mutationFn:async({id:rt,postDate:Fe})=>{const{error:dt}=await U.from("social_swag_2").update({post_date:Fe}).eq("id",rt);if(dt)throw dt},onSuccess:()=>{re.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>re.error("Failed to update post date")}),Ae=vt({mutationFn:async({month:rt,link:Fe})=>{const{error:dt}=await U.from("social_swag_2_months").upsert({month:rt,canva_link:Fe||null},{onConflict:"month"});if(dt)throw dt},onSuccess:()=>{re.success("Canva link updated"),m(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>re.error("Failed to update Canva link")}),Xe=rt=>{var Fe;return((Fe=de.find(dt=>dt.month===rt))==null?void 0:Fe.canva_link)||""},Ue=rt=>we.find(Fe=>Fe.month===rt)||null,Ze=rt=>{var dt;const Fe=(dt=rt.target.files)==null?void 0:dt[0];Fe&&(O(Fe),q(URL.createObjectURL(Fe)))},Qe=()=>{$&&URL.revokeObjectURL($),O(null),q(""),G(""),ee("")},Ye=async()=>{if(!I){re.error("Please select an image");return}le(!0);try{const rt=I.name.split(".").pop(),Fe=`reels/${P}-${Date.now()}.${rt}`,{error:dt}=await U.storage.from("social-swag-2").upload(Fe,I);if(dt)throw dt;const{data:{publicUrl:Dt}}=U.storage.from("social-swag-2").getPublicUrl(Fe),{error:pt}=await U.from("social_swag_2_reels").upsert({month:P,image_url:Dt,canva_link:K||null,caption:W||null},{onConflict:"month"});if(pt)throw pt;re.success("Reel uploaded successfully!"),IFe(`${fe(P)} Reel`,"social-swag-2"),Qe(),M(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(rt){console.error("Reel upload error:",rt),re.error("Failed to upload reel")}finally{le(!1)}},nt=vt({mutationFn:async rt=>{const Fe=rt.image_url.split("/social-swag-2/");Fe[1]&&await U.storage.from("social-swag-2").remove([Fe[1]]);const{error:dt}=await U.from("social_swag_2_reels").delete().eq("id",rt.id);if(dt)throw dt},onSuccess:()=>{re.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>re.error("Failed to delete reel")});return e.jsxs(Vs,{title:"Admin - Social Swag 2.0",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Social Swag 2.0"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage monthly social media images and captions"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Fs,{open:r,onOpenChange:a,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Month"}),e.jsx(ye,{type:"month",value:i,onChange:rt=>l(rt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{children:["Images (",o.length,"/16)"]}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:De,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(Ja,{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,Fe)=>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 ${Fe+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(Fe),children:e.jsx(dr,{className:"h-3 w-3"})})]}),e.jsx(Ds,{placeholder:"Caption...",value:rt.caption,onChange:dt=>Ne(Fe,dt.target.value),className:"text-xs h-20"})]},Fe))}),e.jsx(B,{onClick:Ge,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(Fs,{open:T,onOpenChange:rt=>{M(rt),rt||Qe()},children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(wh,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(Os,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Month"}),e.jsx(ye,{type:"month",value:P,onChange:rt=>L(rt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{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($),O(null),q("")},children:e.jsx(dr,{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:Ze,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(wh,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select reel preview image"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Canva Download Link"}),e.jsx(ye,{value:K,onChange:rt=>ee(rt.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Caption"}),e.jsx(Ds,{value:W,onChange:rt=>G(rt.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(B,{onClick:Ye,disabled:J||!I,className:"w-full gap-2",children:J?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:oe.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:je.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(fa,{value:t,onValueChange:n,children:e.jsxs(xa,{children:[e.jsx(ss,{value:"all",children:"All"}),je.map(rt=>e.jsx(ss,{value:rt,children:fe(rt)},rt))]})}),t!=="all"&&e.jsx(be,{children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(vc,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(se,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",fe(t)]}),(h==null?void 0:h.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(ye,{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(be,{children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(wh,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(se,{className:"text-sm text-muted-foreground",children:["Reel for ",fe(t)]}),(()=>{const rt=Ue(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:()=>nt.mutate(rt),children:e.jsx(Rn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),ie?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):xe.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ac,{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(LCe,{sensors:ue,collisionDetection:CCe,onDragEnd:Le,children:e.jsx(ICe,{items:xe.map(rt=>rt.id),strategy:qJ,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:xe.map(rt=>e.jsx(Czs,{item:rt,onEdit:Se,onDelete:Fe=>_e.mutate(Fe),onDateChange:(Fe,dt)=>Oe.mutate({id:Fe,postDate:dt})},rt.id))})})})]}),e.jsx(Fs,{open:!!p,onOpenChange:rt=>{rt||x(null)},children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{children:"Edit Image"})}),p&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"aspect-[4/5] max-h-48 w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:p.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Caption"}),e.jsx(Ds,{value:y,onChange:rt=>g(rt.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("flex-1 justify-start gap-2 font-normal",!b&&"text-muted-foreground"),children:[e.jsx(ra,{className:"h-4 w-4"}),b?Bs(new Date(b+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(Jl,{className:"w-auto p-0",align:"start",children:e.jsx(o1,{mode:"single",selected:b?new Date(b+"T00:00:00"):void 0,onSelect:rt=>v(rt?Bs(rt,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),b&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>v(null),children:e.jsx(dr,{className:"h-4 w-4"})})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>x(null),children:"Cancel"}),e.jsx(B,{onClick:Ee,disabled:k,className:"gap-2",children:k?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},Tzs=()=>{const{toast:s}=pi(),t=as(),[n,r]=j.useState("categories"),[a,i]=j.useState(!1),[l,o]=j.useState(null),[c,d]=j.useState({name:"",description:"",icon:""}),[u,h]=j.useState(!1),[m,p]=j.useState(null),[x,y]=j.useState({name:"",description:"",icon:""}),[g,b]=j.useState(!1),[v,k]=j.useState(null),[C,T]=j.useState(""),{data:M=[],isLoading:P}=mt({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Le,error:De}=await U.from("community_categories").select("*").order("sort_order");if(De)throw De;return Le}}),{data:L=[],isLoading:I}=mt({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Le,error:De}=await U.from("community_private_groups").select("*").order("sort_order");if(De)throw De;return Le}}),{data:O=[]}=mt({queryKey:["admin-group-members",v==null?void 0:v.id],queryFn:async()=>{if(!v)return[];const{data:Le,error:De}=await U.from("community_private_group_members").select("*").eq("group_id",v.id);if(De)throw De;return Le},enabled:!!v}),{data:$=[]}=mt({queryKey:["admin-all-profiles"],queryFn:async()=>{let De=[],Be=0,Ne=!0;for(;Ne;){const{data:Ge,error:_e}=await U.from("profiles").select("id, name, email, brokerage_id").order("name").range(Be,Be+1e3-1);if(_e)throw _e;Ge&&Ge.length>0?(De=[...De,...Ge],Be+=1e3,Ne=Ge.length===1e3):Ne=!1}return De}}),{data:q=[]}=mt({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Le,error:De}=await U.from("brokerages").select("*").order("name");if(De)throw De;return Le}}),W=vt({mutationFn:async Le=>{if(Le.id){const{error:De}=await U.from("community_categories").update({name:Le.name,description:Le.description||null,icon:Le.icon||null}).eq("id",Le.id);if(De)throw De}else{const De=Math.max(...M.map(Ne=>Ne.sort_order),0),{error:Be}=await U.from("community_categories").insert({name:Le.name,description:Le.description||null,icon:Le.icon||null,sort_order:De+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:Le=>{s({title:"Error",description:Le.message,variant:"destructive"})}}),G=vt({mutationFn:async Le=>{const{error:De}=await U.from("community_categories").delete().eq("id",Le);if(De)throw De},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),K=vt({mutationFn:async({id:Le,direction:De})=>{const Be=M.findIndex(Ne=>Ne.id===Le);if(De==="up"&&Be>0){const Ne=M[Be-1],Ge=M[Be];await U.from("community_categories").update({sort_order:Ge.sort_order}).eq("id",Ne.id),await U.from("community_categories").update({sort_order:Ne.sort_order}).eq("id",Ge.id)}else if(De==="down"&&Bet.invalidateQueries({queryKey:["admin-community-categories"]})}),ee=vt({mutationFn:async Le=>{if(Le.id){const{error:De}=await U.from("community_private_groups").update({name:Le.name,description:Le.description||null,icon:Le.icon||null}).eq("id",Le.id);if(De)throw De}else{const De=Math.max(...L.map(Ne=>Ne.sort_order),0),{error:Be}=await U.from("community_private_groups").insert({name:Le.name,description:Le.description||null,icon:Le.icon||null,sort_order:De+1});if(Be)throw Be}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),p(null),y({name:"",description:"",icon:""}),s({title:m?"Private group updated!":"Private group created!"})},onError:Le=>{s({title:"Error",description:Le.message,variant:"destructive"})}}),J=vt({mutationFn:async Le=>{const{error:De}=await U.from("community_private_groups").delete().eq("id",Le);if(De)throw De},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),le=vt({mutationFn:async({id:Le,direction:De})=>{const Be=L.findIndex(Ne=>Ne.id===Le);if(De==="up"&&Be>0){const Ne=L[Be-1],Ge=L[Be];await U.from("community_private_groups").update({sort_order:Ge.sort_order}).eq("id",Ne.id),await U.from("community_private_groups").update({sort_order:Ne.sort_order}).eq("id",Ge.id)}else if(De==="down"&&Bet.invalidateQueries({queryKey:["admin-private-groups"]})}),ue=vt({mutationFn:async({groupId:Le,userId:De,isMember:Be})=>{if(Be){const{error:Ne}=await U.from("community_private_group_members").delete().eq("group_id",Le).eq("user_id",De);if(Ne)throw Ne}else{const{error:Ne}=await U.from("community_private_group_members").insert({group_id:Le,user_id:De});if(Ne)throw Ne}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",v==null?void 0:v.id]})}}),oe=vt({mutationFn:async({groupId:Le,brokerageId:De,isMember:Be})=>{if(Be){const{error:Ne}=await U.from("community_private_group_members").delete().eq("group_id",Le).eq("brokerage_id",De);if(Ne)throw Ne}else{const{error:Ne}=await U.from("community_private_group_members").insert({group_id:Le,brokerage_id:De});if(Ne)throw Ne}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",v==null?void 0:v.id]})}}),ie=Le=>{o(Le),d({name:Le.name,description:Le.description||"",icon:Le.icon||""}),i(!0)},de=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},we=Le=>{p(Le),y({name:Le.name,description:Le.description||"",icon:Le.icon||""}),h(!0)},je=()=>{p(null),y({name:"",description:"",icon:""}),h(!0)},xe=Le=>{k(Le),T(""),b(!0)},fe=Le=>O.some(De=>De.user_id===Le),Se=Le=>O.some(De=>De.brokerage_id===Le),Ee=$.filter(Le=>Le.name.toLowerCase().includes(C.toLowerCase())||Le.email.toLowerCase().includes(C.toLowerCase()));return e.jsx(Vs,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(fa,{value:n,onValueChange:r,children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"categories",children:"Public Categories"}),e.jsxs(ss,{value:"private-groups",children:[e.jsx(du,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(ns,{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:de,children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{className:"w-[50px]",children:"Order"}),e.jsx(Tt,{className:"w-[80px]",children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(za,{children:P?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):M.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):M.map((Le,De)=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:De===0,onClick:()=>K.mutate({id:Le.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:De===M.length-1,onClick:()=>K.mutate({id:Le.id,direction:"down"}),children:"↓"})]})}),e.jsx(xt,{className:"text-2xl",children:Le.icon||"📁"}),e.jsx(xt,{className:"font-medium",children:Le.name}),e.jsx(xt,{className:"text-muted-foreground",children:Le.description||"—"}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ie(Le),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await Bi("Delete this category? Posts will be uncategorized.")&&G.mutate(Le.id)},children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},Le.id))})]})})})]}),e.jsxs(ns,{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(Ni,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs(B,{onClick:je,children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{className:"w-[50px]",children:"Order"}),e.jsx(Tt,{className:"w-[80px]",children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"w-[120px]",children:"Members"}),e.jsx(Tt,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(za,{children:I?e.jsx(un,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):L.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):L.map((Le,De)=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:De===0,onClick:()=>le.mutate({id:Le.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:De===L.length-1,onClick:()=>le.mutate({id:Le.id,direction:"down"}),children:"↓"})]})}),e.jsx(xt,{className:"text-2xl",children:Le.icon||"🔒"}),e.jsx(xt,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Le.name,Le.brokerage_id?e.jsxs(qe,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(Ni,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(qe,{variant:"secondary",className:"text-xs",children:[e.jsx(du,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(xt,{className:"text-muted-foreground",children:Le.description||"—"}),e.jsx(xt,{children:e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>xe(Le),children:[e.jsx(Bn,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1",children:[!Le.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>we(Le),children:e.jsx(Za,{className:"h-4 w-4"})}),!Le.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await Bi("Delete this private group? All posts in this group will be deleted.")&&J.mutate(Le.id)},children:e.jsx(Rn,{className:"h-4 w-4"})}),Le.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Le.id))})]})})})]})]}),e.jsx(Fs,{open:a,onOpenChange:i,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:l?"Edit Category":"Create Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(ye,{value:c.icon,onChange:Le=>d(De=>({...De,icon:Le.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(ye,{value:c.name,onChange:Le=>d(De=>({...De,name:Le.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Ds,{value:c.description,onChange:Le=>d(De=>({...De,description:Le.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(Fs,{open:u,onOpenChange:h,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:m?"Edit Private Group":"Create Private Group"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(ye,{value:x.icon,onChange:Le=>y(De=>({...De,icon:Le.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(ye,{value:x.name,onChange:Le=>y(De=>({...De,name:Le.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(Ds,{value:x.description,onChange:Le=>y(De=>({...De,description:Le.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:()=>ee.mutate({...x,id:m==null?void 0:m.id}),disabled:!x.name.trim(),children:m?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(Fs,{open:g,onOpenChange:b,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx($s,{children:e.jsxs(zs,{children:["Manage Members: ",v==null?void 0:v.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(fa,{defaultValue:"brokerages",children:[e.jsxs(xa,{className:"w-full",children:[e.jsx(ss,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(ss,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(ns,{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:[q.map(Le=>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(wi,{checked:Se(Le.id),onCheckedChange:()=>{v&&oe.mutate({groupId:v.id,brokerageId:Le.id,isMember:Se(Le.id)})}}),e.jsx("span",{className:"font-medium",children:Le.name})]}),e.jsxs(qe,{variant:"secondary",children:[$.filter(De=>De.brokerage_id===Le.id).length," agents"]})]},Le.id)),q.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(ns,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search users...",value:C,onChange:Le=>T(Le.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:[Ee.map(Le=>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(wi,{checked:fe(Le.id),onCheckedChange:()=>{v&&ue.mutate({groupId:v.id,userId:Le.id,isMember:fe(Le.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Le.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Le.email})]})]})},Le.id)),Ee.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No users found"})]})})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{onClick:()=>b(!1),children:"Done"})})]})]})})]})})},dct=s=>{switch(s){case"academy_video":return e.jsx(fd,{className:"h-3 w-3"});case"template":return e.jsx($r,{className:"h-3 w-3"});case"toolbox":return e.jsx(Eu,{className:"h-3 w-3"});case"newsletter":return e.jsx(V_,{className:"h-3 w-3"});case"social_swag":return e.jsx(yn,{className:"h-3 w-3"});default:return e.jsx(Tr,{className:"h-3 w-3"})}},Ezs=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}},Mzs=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}},Lzs=()=>{const{toast:s}=pi(),[t,n]=j.useState([]),[r,a]=j.useState([]),[i,l]=j.useState([]),[o,c]=j.useState(!0),[d,u]=j.useState(""),[h,m]=j.useState(null),[p,x]=j.useState([]),[y,g]=j.useState([]);j.useEffect(()=>{b()},[]);const b=async()=>{try{c(!0);const{data:O,error:$}=await U.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if($)throw $;const{data:q,error:W}=await U.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(W)throw W;const G=[...new Set((q==null?void 0:q.map(ie=>ie.user_id))||[])],{data:K}=await U.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",G),ee=new Map((K==null?void 0:K.map(ie=>[ie.id,ie]))||[]),J=(O==null?void 0:O.map(ie=>{var de,we,je,xe;return{id:ie.id,user_id:ie.user_id,app_name:ie.app_name,launched_at:ie.launched_at,user_name:((de=ie.profiles)==null?void 0:de.name)||"Unknown",user_email:((we=ie.profiles)==null?void 0:we.email)||"Unknown",brokerage_name:((xe=(je=ie.profiles)==null?void 0:je.brokerages)==null?void 0:xe.name)||null}}))||[],le=(q==null?void 0:q.map(ie=>{var we;const de=ee.get(ie.user_id);return{id:ie.id,user_id:ie.user_id,resource_type:ie.resource_type,resource_id:ie.resource_id,resource_title:ie.resource_title,action_type:ie.action_type,created_at:ie.created_at,user_name:(de==null?void 0:de.name)||"Unknown",user_email:(de==null?void 0:de.email)||"Unknown",brokerage_name:((we=de==null?void 0:de.brokerages)==null?void 0:we.name)||null}}))||[];n(J),a(le);const ue=new Map;J.forEach(ie=>{if(!ue.has(ie.user_id))ue.set(ie.user_id,{user_id:ie.user_id,user_name:ie.user_name,user_email:ie.user_email,brokerage_name:ie.brokerage_name,last_activity_type:"app",last_activity_name:ie.app_name,last_activity_at:ie.launched_at,total_app_launches:1,total_content_views:0});else{const de=ue.get(ie.user_id);de.total_app_launches++,new Date(ie.launched_at)>new Date(de.last_activity_at)&&(de.last_activity_type="app",de.last_activity_name=ie.app_name,de.last_activity_at=ie.launched_at)}}),le.forEach(ie=>{if(!ue.has(ie.user_id))ue.set(ie.user_id,{user_id:ie.user_id,user_name:ie.user_name,user_email:ie.user_email,brokerage_name:ie.brokerage_name,last_activity_type:ie.resource_type,last_activity_name:ie.resource_title,last_activity_at:ie.created_at,total_app_launches:0,total_content_views:1});else{const de=ue.get(ie.user_id);de.total_content_views++,new Date(ie.created_at)>new Date(de.last_activity_at)&&(de.last_activity_type=ie.resource_type,de.last_activity_name=ie.resource_title,de.last_activity_at=ie.created_at)}});const oe=Array.from(ue.values()).sort((ie,de)=>new Date(de.last_activity_at).getTime()-new Date(ie.last_activity_at).getTime());l(oe)}catch(O){console.error("Error loading activity:",O),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},v=O=>{m({id:O.user_id,name:O.user_name,email:O.user_email});const $=t.filter(W=>W.user_id===O.user_id),q=r.filter(W=>W.user_id===O.user_id);x($),g(q)},k=()=>{m(null),x([]),g([])},{sortKey:C,sortDirection:T,handleSort:M,sortData:P}=FJ("last_activity_at","desc"),L=i.filter(O=>{var q;if(!d)return!0;const $=d.toLowerCase();return O.user_name.toLowerCase().includes($)||O.user_email.toLowerCase().includes($)||((q=O.brokerage_name)==null?void 0:q.toLowerCase().includes($))}),I=P(L,{user:O=>{var $;return(($=O.user_name)==null?void 0:$.toLowerCase())||""},brokerage:O=>{var $;return(($=O.brokerage_name)==null?void 0:$.toLowerCase())||""},last_activity_at:O=>new Date(O.last_activity_at).getTime(),apps:O=>O.total_app_launches,content:O=>O.total_content_views});return o?e.jsx(be,{children:e.jsx(Re,{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(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"User Activity"}),e.jsx(fr,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Re,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:O=>u(O.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(Wu,{sortKey:"user",currentSortKey:C,currentDirection:T,onSort:M,children:"User"}),e.jsx(Wu,{sortKey:"brokerage",currentSortKey:C,currentDirection:T,onSort:M,children:"Brokerage"}),e.jsx(Tt,{children:"Last Activity"}),e.jsx(Wu,{sortKey:"last_activity_at",currentSortKey:C,currentDirection:T,onSort:M,children:"Last Active"}),e.jsx(Wu,{sortKey:"apps",currentSortKey:C,currentDirection:T,onSort:M,className:"text-right",children:"Apps"}),e.jsx(Wu,{sortKey:"content",currentSortKey:C,currentDirection:T,onSort:M,className:"text-right",children:"Content"})]})}),e.jsx(za,{children:I.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):I.map(O=>e.jsxs(un,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>v(O),children:[e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:O.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:O.user_email})]})}),e.jsx(xt,{children:O.brokerage_name?e.jsx(qe,{variant:"outline",children:O.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(xt,{children:e.jsx("div",{className:"flex items-center gap-2",children:O.last_activity_type==="app"?e.jsxs(qe,{variant:"secondary",children:[e.jsx(Tr,{className:"h-3 w-3 mr-1"}),O.last_activity_name]}):e.jsxs(qe,{variant:"outline",className:"flex items-center gap-1",children:[dct(O.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:O.last_activity_name})]})})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:oc(new Date(O.last_activity_at),{addSuffix:!0})}),e.jsx(xt,{className:"text-right",children:e.jsx(qe,{variant:"outline",children:O.total_app_launches})}),e.jsx(xt,{className:"text-right",children:e.jsx(qe,{variant:"outline",children:O.total_content_views})})]},O.user_id))})]})})]})]}),e.jsx(Fs,{open:!!h,onOpenChange:O=>!O&&k(),children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs($s,{children:[e.jsxs(zs,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(kr,{children:h==null?void 0:h.email})]}),e.jsxs(fa,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(xa,{className:"grid w-full grid-cols-2",children:[e.jsxs(ss,{value:"content",children:["Content (",y.length,")"]}),e.jsxs(ss,{value:"apps",children:["App Launches (",p.length,")"]})]}),e.jsx(ns,{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(Tt,{children:"Type"}),e.jsx(Tt,{children:"Resource"}),e.jsx(Tt,{children:"Action"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(za,{children:y.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):y.map(O=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs(qe,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[dct(O.resource_type),Ezs(O.resource_type)]})}),e.jsx(xt,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:O.resource_title})}),e.jsx(xt,{children:e.jsx(qe,{variant:"secondary",children:Mzs(O.action_type)})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:oc(new Date(O.created_at),{addSuffix:!0})})]},O.id))})]})})}),e.jsx(ns,{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(Tt,{children:"App"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(za,{children:p.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):p.map(O=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsx(qe,{variant:"secondary",children:O.app_name})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:oc(new Date(O.launched_at),{addSuffix:!0})})]},O.id))})]})})})]})]})})]})},Pzs=()=>{const{toast:s}=pi(),[t,n]=j.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[r,a]=j.useState(!0);j.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await U.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await U.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await U.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await U.from("activity_logs").select("*",{count:"exact",head:!0}),h=new Date;h.setDate(h.getDate()-7);const{count:m}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",h.toISOString()),p=new Date;p.setMonth(p.getMonth()-1);const{count:x}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",p.toISOString()),{data:y}=await U.from("activity_logs").select("user_id").gte("launched_at",h.toISOString()),g=new Set(y==null?void 0:y.map(b=>b.user_id)).size;n({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:m||0,launchesThisMonth:x||0,uniqueActiveThisWeek:g})}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(be,{children:e.jsx(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(To,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Vr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(Ni,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(vf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(vf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(vf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(kl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},uct={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},hct={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 uLt({brokerageOnly:s=!1,brokerageId:t}){const[n,r]=j.useState([]),[a,i]=j.useState(!0),[l,o]=j.useState(""),[c,d]=j.useState("all");j.useEffect(()=>{u()},[t]);const u=async()=>{i(!0);try{let M=[];if(s&&t){const{data:G}=await U.from("profiles").select("id").eq("brokerage_id",t);if(M=(G==null?void 0:G.map(K=>K.id))||[],M.length===0){r([]),i(!1);return}}let P=U.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&M.length>0&&(P=P.or(`sender_id.in.(${M.join(",")}),recipient_id.in.(${M.join(",")})`));const{data:L,error:I}=await P;if(I)throw I;const O=new Set;L==null||L.forEach(G=>{O.add(G.sender_id),O.add(G.recipient_id)});const{data:$}=await U.from("profiles").select("id, name, email").in("id",Array.from(O)),q=new Map(($==null?void 0:$.map(G=>[G.id,G]))||[]),W=(L==null?void 0:L.map(G=>({...G,sender:q.get(G.sender_id),recipient:q.get(G.recipient_id)})))||[];r(W)}catch(M){console.error("Error loading shares:",M)}finally{i(!1)}},{sortKey:h,sortDirection:m,handleSort:p,sortData:x}=FJ("created_at","desc"),y=n.filter(M=>{var I,O;const P=l===""||M.resource_title.toLowerCase().includes(l.toLowerCase())||((I=M.sender)==null?void 0:I.name.toLowerCase().includes(l.toLowerCase()))||((O=M.recipient)==null?void 0:O.name.toLowerCase().includes(l.toLowerCase())),L=c==="all"||M.resource_type===c;return P&&L}),g=x(y,{resource:M=>{var P;return((P=M.resource_title)==null?void 0:P.toLowerCase())||""},type:M=>M.resource_type,sender:M=>{var P,L;return((L=(P=M.sender)==null?void 0:P.name)==null?void 0:L.toLowerCase())||""},recipient:M=>{var P,L;return((L=(P=M.recipient)==null?void 0:P.name)==null?void 0:L.toLowerCase())||""},status:M=>M.is_read?1:0,created_at:M=>new Date(M.created_at).getTime()}),b=n.length,v=new Set(n.map(M=>M.sender_id)).size,k=new Set(n.map(M=>M.recipient_id)).size,C=n.length>0?Math.round(n.filter(M=>M.is_read).length/n.length*100):0,T=n.reduce((M,P)=>(M[P.resource_type]=(M[P.resource_type]||0)+1,M),{});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((M,P)=>e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(gn,{className:"h-4 w-20"})}),e.jsx(Re,{children:e.jsx(gn,{className:"h-8 w-16"})})]},P))}),e.jsx(be,{children:e.jsx(Re,{className:"p-6",children:e.jsx(gn,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(zd,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:b})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:v})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(kl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:k})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx($r,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Re,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[C,"%"]})})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Re,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(T).map(([M,P])=>e.jsxs(qe,{variant:"secondary",className:hct[M],children:[uct[M],": ",P]},M)),Object.keys(T).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Share History"}),e.jsxs(fr,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Re,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:M=>o(M.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:c,onValueChange:d,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"Resource type"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Types"}),e.jsx(Je,{value:"event",children:"Events"}),e.jsx(Je,{value:"template",children:"Templates"}),e.jsx(Je,{value:"academy_video",children:"Academy Videos"}),e.jsx(Je,{value:"resource_kit",children:"Resource Kits"}),e.jsx(Je,{value:"newsletter",children:"Newsletters"}),e.jsx(Je,{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(Wu,{sortKey:"resource",currentSortKey:h,currentDirection:m,onSort:p,children:"Resource"}),e.jsx(Wu,{sortKey:"type",currentSortKey:h,currentDirection:m,onSort:p,children:"Type"}),e.jsx(Wu,{sortKey:"sender",currentSortKey:h,currentDirection:m,onSort:p,children:"Sender"}),e.jsx(Wu,{sortKey:"recipient",currentSortKey:h,currentDirection:m,onSort:p,children:"Recipient"}),e.jsx(Wu,{sortKey:"status",currentSortKey:h,currentDirection:m,onSort:p,children:"Status"}),e.jsx(Wu,{sortKey:"created_at",currentSortKey:h,currentDirection:m,onSort:p,children:"Date"})]})}),e.jsx(za,{children:g.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):g.map(M=>{var P,L;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium max-w-[200px] truncate",children:M.resource_title}),e.jsx(xt,{children:e.jsx(qe,{variant:"secondary",className:hct[M.resource_type],children:uct[M.resource_type]})}),e.jsx(xt,{children:((P=M.sender)==null?void 0:P.name)||"Unknown"}),e.jsx(xt,{children:((L=M.recipient)==null?void 0:L.name)||"Unknown"}),e.jsx(xt,{children:e.jsx(qe,{variant:M.is_read?"default":"outline",children:M.is_read?"Read":"Unread"})}),e.jsx(xt,{className:"text-muted-foreground",children:Bs(new Date(M.created_at),"MMM d, yyyy")})]},M.id)})})]})})]})]})]})}const pPe={academy_video:{label:"Academy Videos",icon:Zr,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:ma},template:{label:"Templates",icon:N4,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:ag},toolbox:{label:"Toolkit",icon:O5,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:ii},newsletter:{label:"Newsletters",icon:on,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:ag},social_swag:{label:"Social Swag",icon:Ac,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:ag},event:{label:"Events",icon:ra,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:ag}};function mct(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function Izs(s,t){return s==="toolbox"?t.downloads:t.clicks}function Rzs(){var M;const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(null),l=j.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=FJ("total_views","desc");j.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:P,error:L}=await U.rpc("get_admin_content_engagement");if(L)throw L;t(P||[])}catch(P){console.error("Error loading content engagement:",P)}finally{r(!1)}},m=P=>{i(L=>{const I=L===P?null:P;return requestAnimationFrame(()=>{var O;(O=l.current)==null||O.scrollIntoView({behavior:"smooth",block:"start"})}),I})};if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-4",children:[...Array(4)].map((P,L)=>e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(gn,{className:"h-4 w-20"})}),e.jsx(Re,{children:e.jsx(gn,{className:"h-8 w-16"})})]},L))}),e.jsx(be,{children:e.jsx(Re,{className:"py-8",children:e.jsx(gn,{className:"h-64 w-full"})})})]});const p=s.reduce((P,L)=>P+L.total_views,0),x=s.reduce((P,L)=>P+L.total_clicks,0),y=s.reduce((P,L)=>P+L.total_downloads,0),g=s.length,b=s.reduce((P,L)=>(P[L.resource_type]||(P[L.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),P[L.resource_type].views+=L.total_views,P[L.resource_type].clicks+=L.total_clicks,P[L.resource_type].downloads+=L.total_downloads,P[L.resource_type].assets+=1,P[L.resource_type].uniqueUsers+=L.unique_users,P),{}),v=a?s.filter(P=>P.resource_type===a):s,k=u(v,{asset:P=>{var L;return((L=P.resource_title)==null?void 0:L.toLowerCase())||""},type:P=>P.resource_type,views:P=>P.total_views,actions:P=>mct(P),unique_users:P=>P.unique_users,last_activity:P=>P.last_engaged_at?new Date(P.last_engaged_at).getTime():0}),C=a?pPe[a]||{label:a,icon:ma,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:ag}:null,T=C==null?void 0:C.icon;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-5",children:[e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(ma,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{children:[e.jsx("div",{className:"text-2xl font-bold",children:p.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(ag,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{children:[e.jsx("div",{className:"text-2xl font-bold",children:x.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(ii,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(kl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{children:[e.jsx("div",{className:"text-2xl font-bold",children:g}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(ag,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[p>0?Math.round((x+y)/p*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(fr,{children:"Click a category to see individual asset performance"})]}),e.jsx(Re,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(b).map(([P,L])=>{const I=pPe[P]||{label:P,icon:ma,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:ag},O=I.icon,$=a===P;return e.jsxs("button",{type:"button",onClick:()=>m(P),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${$?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${I.color}`,children:e.jsx(O,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:I.label}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ma,{className:"h-3 w-3"})," ",L.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(I.actionIcon,{className:"h-3 w-3"})," ",Izs(P,L)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," ",L.uniqueUsers]})]})]}),e.jsxs(qe,{variant:"secondary",className:"text-[10px]",children:[L.assets," items"]})]},P)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{className:"text-sm font-medium flex items-center gap-2",children:C&&T?e.jsxs(e.Fragment,{children:[e.jsx(T,{className:"h-4 w-4"}),C.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(fr,{children:a?`${v.length} ${((M=C==null?void 0:C.label)==null?void 0:M.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(_a,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Re,{children:v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No engagement data yet. As users view and click content, stats will appear here."}):e.jsx(lo,{className:"h-[400px]",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{className:"w-[40px]",children:"#"}),e.jsx(Wu,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Wu,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Wu,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Wu,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:C?C.actionLabel:"Actions"}),e.jsx(Wu,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Wu,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(za,{children:k.map((P,L)=>{const I=pPe[P.resource_type]||{label:P.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:ag};return e.jsxs(un,{children:[e.jsx(xt,{className:"text-muted-foreground text-xs",children:L+1}),e.jsx(xt,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:P.resource_title})}),!a&&e.jsx(xt,{children:e.jsx(qe,{className:`text-[10px] ${I.color}`,children:I.label})}),e.jsx(xt,{className:"text-right font-medium",children:P.total_views}),e.jsx(xt,{className:"text-right font-medium",children:mct(P)}),e.jsx(xt,{className:"text-right",children:P.unique_users}),e.jsx(xt,{className:"text-xs text-muted-foreground",children:P.last_engaged_at?oc(new Date(P.last_engaged_at),{addSuffix:!0}):"—"})]},`${P.resource_type}-${P.resource_id}`)})})]})})})]})})]})}var Dzs=Array.isArray,Db=Dzs,Ozs=typeof Xf=="object"&&Xf&&Xf.Object===Object&&Xf,hLt=Ozs,Fzs=hLt,zzs=typeof self=="object"&&self&&self.Object===Object&&self,Bzs=Fzs||zzs||Function("return this")(),dS=Bzs,$zs=dS,Uzs=$zs.Symbol,VJ=Uzs,pct=VJ,mLt=Object.prototype,qzs=mLt.hasOwnProperty,Vzs=mLt.toString,IH=pct?pct.toStringTag:void 0;function Hzs(s){var t=qzs.call(s,IH),n=s[IH];try{s[IH]=void 0;var r=!0}catch{}var a=Vzs.call(s);return r&&(t?s[IH]=n:delete s[IH]),a}var Gzs=Hzs,Wzs=Object.prototype,Kzs=Wzs.toString;function Yzs(s){return Kzs.call(s)}var Zzs=Yzs,fct=VJ,Xzs=Gzs,Qzs=Zzs,Jzs="[object Null]",eBs="[object Undefined]",xct=fct?fct.toStringTag:void 0;function tBs(s){return s==null?s===void 0?eBs:Jzs:xct&&xct in Object(s)?Xzs(s):Qzs(s)}var nC=tBs;function sBs(s){return s!=null&&typeof s=="object"}var rC=sBs,nBs=nC,rBs=rC,aBs="[object Symbol]";function iBs(s){return typeof s=="symbol"||rBs(s)&&nBs(s)==aBs}var hq=iBs,oBs=Db,lBs=hq,cBs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,dBs=/^\w*$/;function uBs(s,t){if(oBs(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||lBs(s)?!0:dBs.test(s)||!cBs.test(s)||t!=null&&s in Object(t)}var iGe=uBs;function hBs(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var y6=hBs;const mq=sd(y6);var mBs=nC,pBs=y6,fBs="[object AsyncFunction]",xBs="[object Function]",gBs="[object GeneratorFunction]",yBs="[object Proxy]";function vBs(s){if(!pBs(s))return!1;var t=mBs(s);return t==xBs||t==gBs||t==fBs||t==yBs}var oGe=vBs;const nl=sd(oGe);var bBs=dS,_Bs=bBs["__core-js_shared__"],wBs=_Bs,fPe=wBs,gct=function(){var s=/[^.]+$/.exec(fPe&&fPe.keys&&fPe.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function jBs(s){return!!gct&&gct in s}var NBs=jBs,kBs=Function.prototype,SBs=kBs.toString;function CBs(s){if(s!=null){try{return SBs.call(s)}catch{}try{return s+""}catch{}}return""}var pLt=CBs,ABs=oGe,TBs=NBs,EBs=y6,MBs=pLt,LBs=/[\\^$.*+?()[\]{}|]/g,PBs=/^\[object .+?Constructor\]$/,IBs=Function.prototype,RBs=Object.prototype,DBs=IBs.toString,OBs=RBs.hasOwnProperty,FBs=RegExp("^"+DBs.call(OBs).replace(LBs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function zBs(s){if(!EBs(s)||TBs(s))return!1;var t=ABs(s)?FBs:PBs;return t.test(MBs(s))}var BBs=zBs;function $Bs(s,t){return s==null?void 0:s[t]}var UBs=$Bs,qBs=BBs,VBs=UBs;function HBs(s,t){var n=VBs(s,t);return qBs(n)?n:void 0}var CO=HBs,GBs=CO,WBs=GBs(Object,"create"),DCe=WBs,yct=DCe;function KBs(){this.__data__=yct?yct(null):{},this.size=0}var YBs=KBs;function ZBs(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var XBs=ZBs,QBs=DCe,JBs="__lodash_hash_undefined__",e$s=Object.prototype,t$s=e$s.hasOwnProperty;function s$s(s){var t=this.__data__;if(QBs){var n=t[s];return n===JBs?void 0:n}return t$s.call(t,s)?t[s]:void 0}var n$s=s$s,r$s=DCe,a$s=Object.prototype,i$s=a$s.hasOwnProperty;function o$s(s){var t=this.__data__;return r$s?t[s]!==void 0:i$s.call(t,s)}var l$s=o$s,c$s=DCe,d$s="__lodash_hash_undefined__";function u$s(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=c$s&&t===void 0?d$s:t,this}var h$s=u$s,m$s=YBs,p$s=XBs,f$s=n$s,x$s=l$s,g$s=h$s;function pq(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var I$s=P$s,R$s=OCe;function D$s(s,t){var n=this.__data__,r=R$s(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var O$s=D$s,F$s=b$s,z$s=A$s,B$s=M$s,$$s=I$s,U$s=O$s;function fq(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},c8=function(t){return $D(t)&&t.indexOf("%")===t.length-1},La=function(t){return dqs(t)&&!gq(t)},pqs=function(t){return Al(t)},lg=function(t){return La(t)||$D(t)},fqs=0,AO=function(t){var n=++fqs;return"".concat(t||"").concat(n)},Xv=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(!La(t)&&!$D(t))return r;var i;if(c8(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return gq(i)&&(i=r),a&&i>n&&(i=n),i},EA=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},xqs=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 jqs(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 $Fe(s){"@babel/helpers - typeof";return $Fe=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},$Fe(s)}var kct={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"},S3=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},Sct=null,gPe=null,gGe=function s(t){if(t===Sct&&Array.isArray(gPe))return gPe;var n=[];return j.Children.forEach(t,function(r){Al(r)||(aqs.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),gPe=n,Sct=t,n};function Z_(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return S3(a)}):r=[S3(t)],gGe(s).forEach(function(a){var i=Y_(a,"type.displayName")||Y_(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function T_(s,t){var n=Z_(s,t);return n&&n[0]}var Cct=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!La(r)||r<=0||!La(a)||a<=0)},Nqs=["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"],kqs=function(t){return t&&t.type&&$D(t.type)&&Nqs.indexOf(t.type)>=0},NLt=function(t){return t&&$Fe(t)==="object"&&"clipDot"in t},Sqs=function(t,n,r,a){var i,l=(i=xPe==null?void 0:xPe[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!nl(t)&&(a&&l.includes(n)||vqs.includes(n))||r&&xGe.includes(n)},bo=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(j.isValidElement(t)&&(a=t.props),!mq(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;Sqs((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},UFe=function s(t,n){if(t===n)return!0;var r=j.Children.count(t);if(r!==j.Children.count(n))return!1;if(r===0)return!0;if(r===1)return Act(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 Mqs(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 VFe(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=Eqs(s,Tqs),u=a||{width:n,height:r,x:0,y:0},h=Il("recharts-surface",i);return Lt.createElement("svg",qFe({},bo(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),Lt.createElement("title",null,o),Lt.createElement("desc",null,c),t)}var Lqs=["children","className"];function HFe(){return HFe=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 Iqs(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 qc=Lt.forwardRef(function(s,t){var n=s.children,r=s.className,a=Pqs(s,Lqs),i=Il("recharts-layer",r);return Lt.createElement("g",HFe({className:i},bo(a,!0),{ref:t}),n)}),wN=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:Oqs(s,t,n)}var zqs=Fqs,Bqs="\\ud800-\\udfff",$qs="\\u0300-\\u036f",Uqs="\\ufe20-\\ufe2f",qqs="\\u20d0-\\u20ff",Vqs=$qs+Uqs+qqs,Hqs="\\ufe0e\\ufe0f",Gqs="\\u200d",Wqs=RegExp("["+Gqs+Bqs+Vqs+Hqs+"]");function Kqs(s){return Wqs.test(s)}var kLt=Kqs;function Yqs(s){return s.split("")}var Zqs=Yqs,SLt="\\ud800-\\udfff",Xqs="\\u0300-\\u036f",Qqs="\\ufe20-\\ufe2f",Jqs="\\u20d0-\\u20ff",eVs=Xqs+Qqs+Jqs,tVs="\\ufe0e\\ufe0f",sVs="["+SLt+"]",GFe="["+eVs+"]",WFe="\\ud83c[\\udffb-\\udfff]",nVs="(?:"+GFe+"|"+WFe+")",CLt="[^"+SLt+"]",ALt="(?:\\ud83c[\\udde6-\\uddff]){2}",TLt="[\\ud800-\\udbff][\\udc00-\\udfff]",rVs="\\u200d",ELt=nVs+"?",MLt="["+tVs+"]?",aVs="(?:"+rVs+"(?:"+[CLt,ALt,TLt].join("|")+")"+MLt+ELt+")*",iVs=MLt+ELt+aVs,oVs="(?:"+[CLt+GFe+"?",GFe,ALt,TLt,sVs].join("|")+")",lVs=RegExp(WFe+"(?="+WFe+")|"+oVs+iVs,"g");function cVs(s){return s.match(lVs)||[]}var dVs=cVs,uVs=Zqs,hVs=kLt,mVs=dVs;function pVs(s){return hVs(s)?mVs(s):uVs(s)}var fVs=pVs,xVs=zqs,gVs=kLt,yVs=fVs,vVs=yLt;function bVs(s){return function(t){t=vVs(t);var n=gVs(t)?yVs(t):void 0,r=n?n[0]:t.charAt(0),a=n?xVs(n,1).join(""):t.slice(1);return r[s]()+a}}var _Vs=bVs,wVs=_Vs,jVs=wVs("toUpperCase"),NVs=jVs;const XCe=sd(NVs);function zh(s){return function(){return s}}const LLt=Math.cos,n5e=Math.sin,BN=Math.sqrt,r5e=Math.PI,QCe=2*r5e,KFe=Math.PI,YFe=2*KFe,LI=1e-6,kVs=YFe-LI;function PLt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return PLt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;aLI)if(!(Math.abs(h*c-d*u)>LI)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let p=r-l,x=a-o,y=c*c+d*d,g=p*p+x*x,b=Math.sqrt(y),v=Math.sqrt(m),k=i*Math.tan((KFe-Math.acos((y+m-g)/(2*b*v)))/2),C=k/v,T=k/b;Math.abs(C-1)>LI&&this._append`L${t+C*u},${n+C*h}`,this._append`A${i},${i},0,0,${+(h*p>u*x)},${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)>LI||Math.abs(this._y1-u)>LI)&&this._append`L${d},${u}`,r&&(m<0&&(m=m%YFe+YFe),m>kVs?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>LI&&this._append`A${r},${r},0,${+(m>=KFe)},${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 yGe(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 CVs(t)}function vGe(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function ILt(s){this._context=s}ILt.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 JCe(s){return new ILt(s)}function RLt(s){return s[0]}function DLt(s){return s[1]}function OLt(s,t){var n=zh(!0),r=null,a=JCe,i=null,l=yGe(o);s=typeof s=="function"?s:s===void 0?RLt:zh(s),t=typeof t=="function"?t:t===void 0?DLt:zh(t);function o(c){var d,u=(c=vGe(c)).length,h,m=!1,p;for(r==null&&(i=a(p=l())),d=0;d<=u;++d)!(d=p;--x)o.point(k[x],C[x]);o.lineEnd(),o.areaEnd()}b&&(k[m]=+s(g,m,h),C[m]=+t(g,m,h),o.point(r?+r(g,m,h):k[m],n?+n(g,m,h):C[m]))}if(v)return o=null,v+""||null}function u(){return OLt().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:zh(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:zh(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:zh(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:zh(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:zh(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:zh(+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:zh(!!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 FLt{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 AVs(s){return new FLt(s,!0)}function TVs(s){return new FLt(s,!1)}const bGe={draw(s,t){const n=BN(t/r5e);s.moveTo(n,0),s.arc(0,0,n,0,QCe)}},EVs={draw(s,t){const n=BN(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()}},zLt=BN(1/3),MVs=zLt*2,LVs={draw(s,t){const n=BN(t/MVs),r=n*zLt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},PVs={draw(s,t){const n=BN(t),r=-n/2;s.rect(r,r,n,n)}},IVs=.8908130915292852,BLt=n5e(r5e/10)/n5e(7*r5e/10),RVs=n5e(QCe/10)*BLt,DVs=-LLt(QCe/10)*BLt,OVs={draw(s,t){const n=BN(t*IVs),r=RVs*n,a=DVs*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=QCe*i/5,o=LLt(l),c=n5e(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},yPe=BN(3),FVs={draw(s,t){const n=-BN(t/(yPe*3));s.moveTo(0,n*2),s.lineTo(-yPe*n,-n),s.lineTo(yPe*n,-n),s.closePath()}},Ow=-.5,Fw=BN(3)/2,ZFe=1/BN(12),zVs=(ZFe/2+1)*3,BVs={draw(s,t){const n=BN(t/zVs),r=n/2,a=n*ZFe,i=r,l=n*ZFe+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(Ow*r-Fw*a,Fw*r+Ow*a),s.lineTo(Ow*i-Fw*l,Fw*i+Ow*l),s.lineTo(Ow*o-Fw*c,Fw*o+Ow*c),s.lineTo(Ow*r+Fw*a,Ow*a-Fw*r),s.lineTo(Ow*i+Fw*l,Ow*l-Fw*i),s.lineTo(Ow*o+Fw*c,Ow*c-Fw*o),s.closePath()}};function $Vs(s,t){let n=null,r=yGe(a);s=typeof s=="function"?s:zh(s||bGe),t=typeof t=="function"?t:zh(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:zh(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:zh(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function a5e(){}function i5e(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 $Lt(s){this._context=s}$Lt.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:i5e(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:i5e(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function UVs(s){return new $Lt(s)}function ULt(s){this._context=s}ULt.prototype={areaStart:a5e,areaEnd:a5e,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:i5e(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function qVs(s){return new ULt(s)}function qLt(s){this._context=s}qLt.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:i5e(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function VVs(s){return new qLt(s)}function VLt(s){this._context=s}VLt.prototype={areaStart:a5e,areaEnd:a5e,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 HVs(s){return new VLt(s)}function Ect(s){return s<0?-1:1}function Mct(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(Ect(i)+Ect(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function Lct(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function vPe(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 o5e(s){this._context=s}o5e.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:vPe(this,this._t0,Lct(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,vPe(this,Lct(this,n=Mct(this,s,t)),n);break;default:vPe(this,this._t0,n=Mct(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function HLt(s){this._context=new GLt(s)}(HLt.prototype=Object.create(o5e.prototype)).point=function(s,t){o5e.prototype.point.call(this,t,s)};function GLt(s){this._context=s}GLt.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 GVs(s){return new o5e(s)}function WVs(s){return new HLt(s)}function WLt(s){this._context=s}WLt.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=Pct(s),a=Pct(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 YVs(s){return new eAe(s,.5)}function ZVs(s){return new eAe(s,0)}function XVs(s){return new eAe(s,1)}function R$(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 QVs(s,t){return s[t]}function JVs(s){const t=[];return t.key=s,t}function eHs(){var s=zh([]),t=XFe,n=R$,r=QVs;function a(i){var l=Array.from(s.apply(this,arguments),JVs),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 cHs(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 KLt={symbolCircle:bGe,symbolCross:EVs,symbolDiamond:LVs,symbolSquare:PVs,symbolStar:OVs,symbolTriangle:FVs,symbolWye:BVs},dHs=Math.PI/180,uHs=function(t){var n="symbol".concat(XCe(t));return KLt[n]||bGe},hHs=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*dHs;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}},mHs=function(t,n){KLt["symbol".concat(XCe(t))]=n},_Ge=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=lHs(t,rHs),d=Rct(Rct({},c),{},{type:r,size:i,sizeType:o}),u=function(){var g=uHs(r),b=$Vs().type(g).size(hHs(i,o,r));return b()},h=d.className,m=d.cx,p=d.cy,x=bo(d,!0);return m===+m&&p===+p&&i===+i?Lt.createElement("path",QFe({},x,{className:Il("recharts-symbols",h),transform:"translate(".concat(m,", ").concat(p,")"),d:u()})):null};_Ge.registerSymbol=mHs;function D$(s){"@babel/helpers - typeof";return D$=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},D$(s)}function JFe(){return JFe=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var v=p.inactive?d:p.color;return Lt.createElement("li",JFe({className:g,style:h,key:"legend-item-".concat(x)},UD(r.props,p,x)),Lt.createElement(VFe,{width:l,height:l,viewBox:u,style:m},r.renderIcon(p)),Lt.createElement("span",{className:"recharts-legend-item-text",style:{color:v}},y?y(b,p,x):b))})}},{key:"render",value:function(){var r=this.props,a=r.payload,i=r.layout,l=r.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:i==="horizontal"?l:"left"};return Lt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(j.PureComponent);SZ(wGe,"displayName","Legend");SZ(wGe,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var jHs=FCe;function NHs(){this.__data__=new jHs,this.size=0}var kHs=NHs;function SHs(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var CHs=SHs;function AHs(s){return this.__data__.get(s)}var THs=AHs;function EHs(s){return this.__data__.has(s)}var MHs=EHs,LHs=FCe,PHs=cGe,IHs=dGe,RHs=200;function DHs(s,t){var n=this.__data__;if(n instanceof LHs){var r=n.__data__;if(!PHs||r.lengtho))return!1;var d=i.get(s),u=i.get(t);if(d&&u)return d==t&&u==s;var h=-1,m=!0,p=n&rGs?new eGs:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=lWs}var SGe=cWs,dWs=nC,uWs=SGe,hWs=rC,mWs="[object Arguments]",pWs="[object Array]",fWs="[object Boolean]",xWs="[object Date]",gWs="[object Error]",yWs="[object Function]",vWs="[object Map]",bWs="[object Number]",_Ws="[object Object]",wWs="[object RegExp]",jWs="[object Set]",NWs="[object String]",kWs="[object WeakMap]",SWs="[object ArrayBuffer]",CWs="[object DataView]",AWs="[object Float32Array]",TWs="[object Float64Array]",EWs="[object Int8Array]",MWs="[object Int16Array]",LWs="[object Int32Array]",PWs="[object Uint8Array]",IWs="[object Uint8ClampedArray]",RWs="[object Uint16Array]",DWs="[object Uint32Array]",lm={};lm[AWs]=lm[TWs]=lm[EWs]=lm[MWs]=lm[LWs]=lm[PWs]=lm[IWs]=lm[RWs]=lm[DWs]=!0;lm[mWs]=lm[pWs]=lm[SWs]=lm[fWs]=lm[CWs]=lm[xWs]=lm[gWs]=lm[yWs]=lm[vWs]=lm[bWs]=lm[_Ws]=lm[wWs]=lm[jWs]=lm[NWs]=lm[kWs]=!1;function OWs(s){return hWs(s)&&uWs(s.length)&&!!lm[dWs(s)]}var FWs=OWs;function zWs(s){return function(t){return s(t)}}var aPt=zWs,u5e={exports:{}};u5e.exports;(function(s,t){var n=hLt,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})(u5e,u5e.exports);var BWs=u5e.exports,$Ws=FWs,UWs=aPt,Uct=BWs,qct=Uct&&Uct.isTypedArray,qWs=qct?UWs(qct):$Ws,iPt=qWs,VWs=WGs,HWs=NGe,GWs=Db,WWs=rPt,KWs=kGe,YWs=iPt,ZWs=Object.prototype,XWs=ZWs.hasOwnProperty;function QWs(s,t){var n=GWs(s),r=!n&&HWs(s),a=!n&&!r&&WWs(s),i=!n&&!r&&!a&&YWs(s),l=n||r||a||i,o=l?VWs(s.length,String):[],c=o.length;for(var d in s)(t||XWs.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||KWs(d,c)))&&o.push(d);return o}var JWs=QWs,eKs=Object.prototype;function tKs(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||eKs;return s===n}var sKs=tKs;function nKs(s,t){return function(n){return s(t(n))}}var oPt=nKs,rKs=oPt,aKs=rKs(Object.keys,Object),iKs=aKs,oKs=sKs,lKs=iKs,cKs=Object.prototype,dKs=cKs.hasOwnProperty;function uKs(s){if(!oKs(s))return lKs(s);var t=[];for(var n in Object(s))dKs.call(s,n)&&n!="constructor"&&t.push(n);return t}var hKs=uKs,mKs=oGe,pKs=SGe;function fKs(s){return s!=null&&pKs(s.length)&&!mKs(s)}var HJ=fKs,xKs=JWs,gKs=hKs,yKs=HJ;function vKs(s){return yKs(s)?xKs(s):gKs(s)}var tAe=vKs,bKs=RGs,_Ks=HGs,wKs=tAe;function jKs(s){return bKs(s,wKs,_Ks)}var NKs=jKs,Vct=NKs,kKs=1,SKs=Object.prototype,CKs=SKs.hasOwnProperty;function AKs(s,t,n,r,a,i){var l=n&kKs,o=Vct(s),c=o.length,d=Vct(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var m=o[h];if(!(l?m in t:CKs.call(t,m)))return!1}var p=i.get(s),x=i.get(t);if(p&&x)return p==t&&x==s;var y=!0;i.set(s,t),i.set(t,s);for(var g=l;++h-1}var SZs=kZs;function CZs(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=UZs){var d=t?null:BZs(s);if(d)return $Zs(d);l=!1,a=zZs,c=new DZs}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function rXs(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 aXs(s){return s.value}function iXs(s,t){if(Lt.isValidElement(s))return Lt.cloneElement(s,t);if(typeof s=="function")return Lt.createElement(s,t);t.ref;var n=nXs(t,YZs);return Lt.createElement(wGe,n)}var idt=1,iD=function(s){function t(){var n;ZZs(this,t);for(var r=arguments.length,a=new Array(r),i=0;iidt||Math.abs(a.height-this.lastBoundingBox.height)>idt)&&(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?QS({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(r){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,u=a.chartHeight,h,m;if(!r||(r.left===void 0||r.left===null)&&(r.right===void 0||r.right===null))if(l==="center"&&i==="vertical"){var p=this.getBBoxSnapshot();h={left:((d||0)-p.width)/2}}else h=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!r||(r.top===void 0||r.top===null)&&(r.bottom===void 0||r.bottom===null))if(o==="middle"){var x=this.getBBoxSnapshot();m={top:((u||0)-x.height)/2}}else m=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return QS(QS({},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=QS(QS({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Lt.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(p){r.wrapperNode=p}},iXs(i,QS(QS({},this.props),{},{payload:pPt(u,d,aXs)})))}}],[{key:"getWithHeight",value:function(r,a){var i=QS(QS({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&La(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(j.PureComponent);sAe(iD,"displayName","Legend");sAe(iD,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var odt=VJ,oXs=NGe,lXs=Db,ldt=odt?odt.isConcatSpreadable:void 0;function cXs(s){return lXs(s)||oXs(s)||!!(ldt&&s&&s[ldt])}var dXs=cXs,uXs=sPt,hXs=dXs;function gPt(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=hXs),a||(a=[]);++i0&&n(o)?t>1?gPt(o,t-1,n,r,a):uXs(a,o):r||(a[a.length]=o)}return a}var yPt=gPt;function mXs(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 pXs=mXs,fXs=pXs,xXs=fXs(),gXs=xXs,yXs=gXs,vXs=tAe;function bXs(s,t){return s&&yXs(s,t,vXs)}var vPt=bXs,_Xs=HJ;function wXs(s,t){return function(n,r){if(n==null)return n;if(!_Xs(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 DXs=RXs,jPe=hGe,OXs=mGe,FXs=uS,zXs=bPt,BXs=MXs,$Xs=aPt,UXs=DXs,qXs=bq,VXs=Db;function HXs(s,t,n){t.length?t=jPe(t,function(i){return VXs(i)?function(l){return OXs(l,i.length===1?i[0]:i)}:i}):t=[qXs];var r=-1;t=jPe(t,$Xs(FXs));var a=zXs(s,function(i,l,o){var c=jPe(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return BXs(a,function(i,l){return UXs(i,l,n)})}var GXs=HXs;function WXs(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 KXs=WXs,YXs=KXs,ddt=Math.max;function ZXs(s,t,n){return t=ddt(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=ddt(r.length-t,0),l=Array(i);++a0){if(++t>=iQs)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var dQs=cQs,uQs=aQs,hQs=dQs,mQs=hQs(uQs),pQs=mQs,fQs=bq,xQs=XXs,gQs=pQs;function yQs(s,t){return gQs(xQs(s,t,fQs),s+"")}var vQs=yQs,bQs=lGe,_Qs=HJ,wQs=kGe,jQs=y6;function NQs(s,t,n){if(!jQs(n))return!1;var r=typeof t;return(r=="number"?_Qs(n)&&wQs(t,n.length):r=="string"&&t in n)?bQs(n[t],s):!1}var nAe=NQs,kQs=yPt,SQs=GXs,CQs=vQs,hdt=nAe,AQs=CQs(function(s,t){if(s==null)return[];var n=t.length;return n>1&&hdt(s,t[0],t[1])?t=[]:n>2&&hdt(t[0],t[1],t[2])&&(t=[t[0]]),SQs(s,kQs(t,1),[])}),TQs=AQs;const TGe=sd(TQs);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 o7e(){return o7e=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(RH,"-left"),La(n)&&t&&La(t.x)&&n=t.y),"".concat(RH,"-top"),La(r)&&t&&La(t.y)&&ry?Math.max(u,c[r]):Math.max(h,c[r])}function VQs(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 HQs(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=fdt({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=fdt({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=VQs({translateX:u,translateY:h,useTranslate3d:o})):d=UQs,{cssProperties:d,cssClasses:qQs({translateX:u,translateY:h,coordinate:n})}}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 xdt(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 gdt(s){for(var t=1;tydt||Math.abs(r.height-this.state.lastBoundingBox.height)>ydt)&&this.setState({lastBoundingBox:{width:r.width,height:r.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var r,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var r=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,u=a.coordinate,h=a.hasPayload,m=a.isAnimationActive,p=a.offset,x=a.position,y=a.reverseDirection,g=a.useTranslate3d,b=a.viewBox,v=a.wrapperStyle,k=HQs({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:p,position:x,reverseDirection:y,tooltipBox:this.state.lastBoundingBox,useTranslate3d:g,viewBox:b}),C=k.cssClasses,T=k.cssProperties,M=gdt(gdt({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},v);return Lt.createElement("div",{tabIndex:-1,className:C,style:M,ref:function(L){r.wrapperNode=L}},d)}}])}(j.PureComponent),tJs=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},jN={isSsr:tJs(),get:function(t){return jN[t]},set:function(t,n){if(typeof t=="string")jN[t]=n;else{var r=Object.keys(t);r&&r.length&&r.forEach(function(a){jN[a]=t[a]})}}};function z$(s){"@babel/helpers - typeof";return z$=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},z$(s)}function vdt(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 bdt(s){for(var t=1;t0;return Lt.createElement(eJs,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:m,active:i,coordinate:u,hasPayload:M,offset:p,position:g,reverseDirection:b,useTranslate3d:v,viewBox:k,wrapperStyle:C},uJs(d,bdt(bdt({},this.props),{},{payload:T})))}}])}(j.PureComponent);EGe(ff,"displayName","Tooltip");EGe(ff,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!jN.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 hJs=dS,mJs=function(){return hJs.Date.now()},pJs=mJs,fJs=/\s/;function xJs(s){for(var t=s.length;t--&&fJs.test(s.charAt(t)););return t}var gJs=xJs,yJs=gJs,vJs=/^\s+/;function bJs(s){return s&&s.slice(0,yJs(s)+1).replace(vJs,"")}var _Js=bJs,wJs=_Js,_dt=y6,jJs=hq,wdt=NaN,NJs=/^[-+]0x[0-9a-f]+$/i,kJs=/^0b[01]+$/i,SJs=/^0o[0-7]+$/i,CJs=parseInt;function AJs(s){if(typeof s=="number")return s;if(jJs(s))return wdt;if(_dt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=_dt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=wJs(s);var n=kJs.test(s);return n||SJs.test(s)?CJs(s.slice(2),n?2:8):NJs.test(s)?wdt:+s}var SPt=AJs,TJs=y6,kPe=pJs,jdt=SPt,EJs="Expected a function",MJs=Math.max,LJs=Math.min;function PJs(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(EJs);t=jdt(t)||0,TJs(n)&&(u=!!n.leading,h="maxWait"in n,i=h?MJs(jdt(n.maxWait)||0,t):i,m="trailing"in n?!!n.trailing:m);function p(M){var P=r,L=a;return r=a=void 0,d=M,l=s.apply(L,P),l}function x(M){return d=M,o=setTimeout(b,t),u?p(M):l}function y(M){var P=M-c,L=M-d,I=t-P;return h?LJs(I,i-L):I}function g(M){var P=M-c,L=M-d;return c===void 0||P>=t||P<0||h&&L>=i}function b(){var M=kPe();if(g(M))return v(M);o=setTimeout(b,y(M))}function v(M){return o=void 0,m&&r?p(M):(r=a=void 0,l)}function k(){o!==void 0&&clearTimeout(o),d=0,r=c=a=o=void 0}function C(){return o===void 0?l:v(kPe())}function T(){var M=kPe(),P=g(M);if(r=arguments,a=this,c=M,P){if(o===void 0)return x(c);if(h)return clearTimeout(o),o=setTimeout(b,t),p(c)}return o===void 0&&(o=setTimeout(b,t)),l}return T.cancel=k,T.flush=C,T}var IJs=PJs,RJs=IJs,DJs=y6,OJs="Expected a function";function FJs(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(OJs);return DJs(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),RJs(s,t,{leading:r,maxWait:t,trailing:a})}var zJs=FJs;const CPt=sd(zJs);function TZ(s){"@babel/helpers - typeof";return TZ=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},TZ(s)}function Ndt(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 _ne(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(W=CPt(W,y,{trailing:!0,leading:!1}));var G=new ResizeObserver(W),K=T.current.getBoundingClientRect(),ee=K.width,J=K.height;return $(ee,J),G.observe(T.current),function(){G.disconnect()}},[$,y]);var q=j.useMemo(function(){var W=I.containerWidth,G=I.containerHeight;if(W<0||G<0)return null;wN(c8(l)||c8(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),wN(!n||n>0,"The aspect(%s) must be greater than zero.",n);var K=c8(l)?W:l,ee=c8(c)?G:c;n&&n>0&&(K?ee=K/n:ee&&(K=ee*n),m&&ee>m&&(ee=m)),wN(K>0||ee>0,`The width(%s) and height(%s) of chart should be greater than 0, please check the style of container, or the props width(%s) and height(%s), or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the height and width.`,K,ee,l,c,u,h,n);var J=!Array.isArray(p)&&S3(p.type).endsWith("Chart");return Lt.Children.map(p,function(le){return Lt.isValidElement(le)?j.cloneElement(le,_ne({width:K,height:ee},J?{style:_ne({height:"100%",width:"100%",maxHeight:ee,maxWidth:K},le.props.style)}:{})):le})},[n,p,c,m,h,u,I,l]);return Lt.createElement("div",{id:g?"".concat(g):void 0,className:Il("recharts-responsive-container",b),style:_ne(_ne({},C),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:m}),ref:T},q)}),_q=function(t){return null};_q.displayName="Cell";function EZ(s){"@babel/helpers - typeof";return EZ=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},EZ(s)}function Sdt(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 u7e(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||jN.isSsr)return{width:0,height:0};var r=JJs(n),a=JSON.stringify({text:t,copyStyle:r});if(QF.widthCache[a])return QF.widthCache[a];try{var i=document.getElementById(Cdt);i||(i=document.createElement("span"),i.setAttribute("id",Cdt),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=u7e(u7e({},QJs),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return QF.widthCache[a]=c,++QF.cacheCount>XJs&&(QF.cacheCount=0,QF.widthCache={}),c}catch{return{width:0,height:0}}},een=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function MZ(s){"@babel/helpers - typeof";return MZ=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},MZ(s)}function f5e(s,t){return ren(s)||nen(s,t)||sen(s,t)||ten()}function ten(){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 sen(s,t){if(s){if(typeof s=="string")return Adt(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 Adt(s,t)}}function Adt(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 yen(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 Idt(s,t){return wen(s)||_en(s,t)||ben(s,t)||ven()}function ven(){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 ben(s,t){if(s){if(typeof s=="string")return Rdt(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 Rdt(s,t)}}function Rdt(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&arguments[0]!==void 0?arguments[0]:[];return K.reduce(function(ee,J){var le=J.word,ue=J.width,oe=ee[ee.length-1];if(oe&&(a==null||i||oe.width+ue+rJ.width?ee:J})};if(!u)return p;for(var y="…",g=function(K){var ee=h.slice(0,K),J=MPt({breakAll:d,style:c,children:ee+y}).wordsWithComputedWidth,le=m(J),ue=le.length>l||x(le).width>Number(a);return[ue,le]},b=0,v=h.length-1,k=0,C;b<=v&&k<=h.length-1;){var T=Math.floor((b+v)/2),M=T-1,P=g(M),L=Idt(P,2),I=L[0],O=L[1],$=g(T),q=Idt($,1),W=q[0];if(!I&&!W&&(b=T+1),I&&W&&(v=T-1),!I&&W){C=O;break}k++}return C||p},Ddt=function(t){var n=Al(t)?[]:t.toString().split(EPt);return[{words:n}]},Nen=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!jN.isSsr){var c,d,u=MPt({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,m=u.spaceWidth;c=h,d=m}else return Ddt(a);return jen({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return Ddt(a)},Odt="#808080",qD=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.lineHeight,o=l===void 0?"1em":l,c=t.capHeight,d=c===void 0?"0.71em":c,u=t.scaleToFit,h=u===void 0?!1:u,m=t.textAnchor,p=m===void 0?"start":m,x=t.verticalAnchor,y=x===void 0?"end":x,g=t.fill,b=g===void 0?Odt:g,v=Pdt(t,xen),k=j.useMemo(function(){return Nen({breakAll:v.breakAll,children:v.children,maxLines:v.maxLines,scaleToFit:h,style:v.style,width:v.width})},[v.breakAll,v.children,v.maxLines,h,v.style,v.width]),C=v.dx,T=v.dy,M=v.angle,P=v.className,L=v.breakAll,I=Pdt(v,gen);if(!lg(r)||!lg(i))return null;var O=r+(La(C)?C:0),$=i+(La(T)?T:0),q;switch(y){case"start":q=SPe("calc(".concat(d,")"));break;case"middle":q=SPe("calc(".concat((k.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:q=SPe("calc(".concat(k.length-1," * -").concat(o,")"));break}var W=[];if(h){var G=k[0].width,K=v.width;W.push("scale(".concat((La(K)?K/G:1)/G,")"))}return M&&W.push("rotate(".concat(M,", ").concat(O,", ").concat($,")")),W.length&&(I.transform=W.join(" ")),Lt.createElement("text",h7e({},bo(I,!0),{x:O,y:$,className:Il("recharts-text",P),textAnchor:p,fill:b.includes("url")?Odt:b}),k.map(function(ee,J){var le=ee.words.join(L?"":" ");return Lt.createElement("tspan",{x:O,dy:J===0?q:o,key:"".concat(le,"-").concat(J)},le)}))};function fE(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function ken(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function MGe(s){let t,n,r;s.length!==2?(t=fE,n=(o,c)=>fE(s(o),c),r=(o,c)=>s(o)-c):(t=s===fE||s===ken?s:Sen,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 Sen(){return 0}function LPt(s){return s===null?NaN:+s}function*Cen(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const Aen=MGe(fE),GJ=Aen.right;MGe(LPt).center;class Fdt extends Map{constructor(t,n=Men){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(zdt(this,t))}has(t){return super.has(zdt(this,t))}set(t,n){return super.set(Ten(this,t),n)}delete(t){return super.delete(Een(this,t))}}function zdt({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function Ten({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function Een({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function Men(s){return s!==null&&typeof s=="object"?s.valueOf():s}function Len(s=fE){if(s===fE)return PPt;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 PPt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const Pen=Math.sqrt(50),Ien=Math.sqrt(10),Ren=Math.sqrt(2);function x5e(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>=Pen?10:i>=Ien?5:i>=Ren?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 $dt(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function IPt(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?PPt:Len(a);r>n;){if(r-n>600){const c=r-n+1,d=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),m=.5*Math.sqrt(u*h*(c-h)/c)*(d-c/2<0?-1:1),p=Math.max(n,Math.floor(t-d*h/c+m)),x=Math.min(r,Math.floor(t+(c-d)*h/c+m));IPt(s,t,p,x,a)}const i=s[t];let l=n,o=r;for(DH(s,n,t),a(s[r],i)>0&&DH(s,n,r);l0;)--o}a(s[n],i)===0?DH(s,n,o):(++o,DH(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function DH(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function Den(s,t,n){if(s=Float64Array.from(Cen(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return $dt(s);if(t>=1)return Bdt(s);var r,a=(r-1)*t,i=Math.floor(a),l=Bdt(IPt(s,i).subarray(0,i+1)),o=$dt(s.subarray(i+1));return l+(o-l)*(a-i)}}function Oen(s,t,n=LPt){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 Fen(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?jne(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?jne(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=Ben.exec(s))?new lb(t[1],t[2],t[3],1):(t=$en.exec(s))?new lb(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Uen.exec(s))?jne(t[1],t[2],t[3],t[4]):(t=qen.exec(s))?jne(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Ven.exec(s))?Kdt(t[1],t[2]/100,t[3]/100,1):(t=Hen.exec(s))?Kdt(t[1],t[2]/100,t[3]/100,t[4]):Udt.hasOwnProperty(s)?Hdt(Udt[s]):s==="transparent"?new lb(NaN,NaN,NaN,0):null}function Hdt(s){return new lb(s>>16&255,s>>8&255,s&255,1)}function jne(s,t,n,r){return r<=0&&(s=t=n=NaN),new lb(s,t,n,r)}function Ken(s){return s instanceof WJ||(s=RZ(s)),s?(s=s.rgb(),new lb(s.r,s.g,s.b,s.opacity)):new lb}function g7e(s,t,n,r){return arguments.length===1?Ken(s):new lb(s,t,n,r??1)}function lb(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}PGe(lb,g7e,DPt(WJ,{brighter(s){return s=s==null?g5e:Math.pow(g5e,s),new lb(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?PZ:Math.pow(PZ,s),new lb(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new lb(oD(this.r),oD(this.g),oD(this.b),y5e(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:Gdt,formatHex:Gdt,formatHex8:Yen,formatRgb:Wdt,toString:Wdt}));function Gdt(){return`#${d8(this.r)}${d8(this.g)}${d8(this.b)}`}function Yen(){return`#${d8(this.r)}${d8(this.g)}${d8(this.b)}${d8((isNaN(this.opacity)?1:this.opacity)*255)}`}function Wdt(){const s=y5e(this.opacity);return`${s===1?"rgb(":"rgba("}${oD(this.r)}, ${oD(this.g)}, ${oD(this.b)}${s===1?")":`, ${s})`}`}function y5e(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function oD(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function d8(s){return s=oD(s),(s<16?"0":"")+s.toString(16)}function Kdt(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new iN(s,t,n,r)}function OPt(s){if(s instanceof iN)return new iN(s.h,s.s,s.l,s.opacity);if(s instanceof WJ||(s=RZ(s)),!s)return new iN;if(s instanceof iN)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 iN(l,o,c,s.opacity)}function Zen(s,t,n,r){return arguments.length===1?OPt(s):new iN(s,t,n,r??1)}function iN(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}PGe(iN,Zen,DPt(WJ,{brighter(s){return s=s==null?g5e:Math.pow(g5e,s),new iN(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?PZ:Math.pow(PZ,s),new iN(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 lb(CPe(s>=240?s-240:s+120,a,r),CPe(s,a,r),CPe(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new iN(Ydt(this.h),Nne(this.s),Nne(this.l),y5e(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=y5e(this.opacity);return`${s===1?"hsl(":"hsla("}${Ydt(this.h)}, ${Nne(this.s)*100}%, ${Nne(this.l)*100}%${s===1?")":`, ${s})`}`}}));function Ydt(s){return s=(s||0)%360,s<0?s+360:s}function Nne(s){return Math.max(0,Math.min(1,s||0))}function CPe(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 IGe=s=>()=>s;function Xen(s,t){return function(n){return s+n*t}}function Qen(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 Jen(s){return(s=+s)==1?FPt:function(t,n){return n-t?Qen(t,n,s):IGe(isNaN(t)?n:t)}}function FPt(s,t){var n=t-s;return n?Xen(s,n):IGe(isNaN(s)?t:s)}const Zdt=function s(t){var n=Jen(t);function r(a,i){var l=n((a=g7e(a)).r,(i=g7e(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=FPt(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 etn(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:v5e(r,a)})),n=APe.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function utn(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?htn:utn,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),v5e)))(m)))},h.domain=function(m){return arguments.length?(s=Array.from(m,b5e),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=RGe,u()},h.clamp=function(m){return arguments.length?(l=m?!0:Qv,u()):l!==Qv},h.interpolate=function(m){return arguments.length?(n=m,u()):n},h.unknown=function(m){return arguments.length?(i=m,h):i},function(m,p){return r=m,a=p,u()}}function DGe(){return rAe()(Qv,Qv)}function mtn(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function _5e(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 B$(s){return s=_5e(Math.abs(s)),s?s[1]:NaN}function ptn(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 ftn(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var xtn=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function DZ(s){if(!(t=xtn.exec(s)))throw new Error("invalid format: "+s);var t;return new OGe({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]})}DZ.prototype=OGe.prototype;function OGe(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+""}OGe.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 gtn(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 zPt;function ytn(s,t){var n=_5e(s,t);if(!n)return s+"";var r=n[0],a=n[1],i=a-(zPt=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")+_5e(s,Math.max(0,t+i-1))[0]}function Qdt(s,t){var n=_5e(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 Jdt={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:mtn,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)=>Qdt(s*100,t),r:Qdt,s:ytn,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function eut(s){return s}var tut=Array.prototype.map,sut=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function vtn(s){var t=s.grouping===void 0||s.thousands===void 0?eut:ptn(tut.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?eut:ftn(tut.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=DZ(h);var m=h.fill,p=h.align,x=h.sign,y=h.symbol,g=h.zero,b=h.width,v=h.comma,k=h.precision,C=h.trim,T=h.type;T==="n"?(v=!0,T="g"):Jdt[T]||(k===void 0&&(k=12),C=!0,T="g"),(g||m==="0"&&p==="=")&&(g=!0,m="0",p="=");var M=y==="$"?n:y==="#"&&/[boxX]/.test(T)?"0"+T.toLowerCase():"",P=y==="$"?r:/[%p]/.test(T)?l:"",L=Jdt[T],I=/[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 O($){var q=M,W=P,G,K,ee;if(T==="c")W=L($)+W,$="";else{$=+$;var J=$<0||1/$<0;if($=isNaN($)?c:L(Math.abs($),k),C&&($=gtn($)),J&&+$==0&&x!=="+"&&(J=!1),q=(J?x==="("?x:o:x==="-"||x==="("?"":x)+q,W=(T==="s"?sut[8+zPt/3]:"")+W+(J&&x==="("?")":""),I){for(G=-1,K=$.length;++Gee||ee>57){W=(ee===46?a+$.slice(G+1):$.slice(G))+W,$=$.slice(0,G);break}}}v&&!g&&($=t($,1/0));var le=q.length+$.length+W.length,ue=le>1)+q+$+W+ue.slice(le);break;default:$=ue+q+$+W;break}return i($)}return O.toString=function(){return h+""},O}function u(h,m){var p=d((h=DZ(h),h.type="f",h)),x=Math.max(-8,Math.min(8,Math.floor(B$(m)/3)))*3,y=Math.pow(10,-x),g=sut[8+x/3];return function(b){return p(y*b)+g}}return{format:d,formatPrefix:u}}var kne,FGe,BPt;btn({thousands:",",grouping:[3],currency:["$",""]});function btn(s){return kne=vtn(s),FGe=kne.format,BPt=kne.formatPrefix,kne}function _tn(s){return Math.max(0,-B$(Math.abs(s)))}function wtn(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(B$(t)/3)))*3-B$(Math.abs(s)))}function jtn(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,B$(t)-B$(s))+1}function $Pt(s,t,n,r){var a=f7e(s,t,n),i;switch(r=DZ(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=wtn(a,l))&&(r.precision=i),BPt(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=jtn(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=_tn(a))&&(r.precision=i-(r.type==="%")*2);break}}return FGe(r)}function v6(s){var t=s.domain;return s.ticks=function(n){var r=t();return m7e(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return $Pt(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=p7e(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 w5e(){var s=DGe();return s.copy=function(){return KJ(s,w5e())},Zj.apply(s,arguments),v6(s)}function UPt(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,b5e),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return UPt(s).unknown(t)},s=arguments.length?Array.from(s,b5e):[0,1],v6(n)}function qPt(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 Atn(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 aut(s){return(t,n)=>-s(-t,n)}function zGe(s){const t=s(nut,rut),n=t.domain;let r=10,a,i;function l(){return a=Atn(r),i=Ctn(r),n()[0]<0?(a=aut(a),i=aut(i),s(Ntn,ktn)):s(nut,rut),t}return t.base=function(o){return arguments.length?(r=+o,l()):r},t.domain=function(o){return arguments.length?(n(o),l()):n()},t.ticks=o=>{const c=n();let d=c[0],u=c[c.length-1];const h=u0){for(;m<=p;++m)for(x=1;xu)break;b.push(y)}}else for(;m<=p;++m)for(x=r-1;x>=1;--x)if(y=m>0?x/i(-m):x*i(m),!(yu)break;b.push(y)}b.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=DZ(c)).precision==null&&(c.trim=!0),c=FGe(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(qPt(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function VPt(){const s=zGe(rAe()).domain([1,10]);return s.copy=()=>KJ(s,VPt()).base(s.base()),Zj.apply(s,arguments),s}function iut(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function out(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function BGe(s){var t=1,n=s(iut(t),out(t));return n.constant=function(r){return arguments.length?s(iut(t=+r),out(t)):t},v6(n)}function HPt(){var s=BGe(rAe());return s.copy=function(){return KJ(s,HPt()).constant(s.constant())},Zj.apply(s,arguments)}function lut(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function Ttn(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function Etn(s){return s<0?-s*s:s*s}function $Ge(s){var t=s(Qv,Qv),n=1;function r(){return n===1?s(Qv,Qv):n===.5?s(Ttn,Etn):s(lut(n),lut(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},v6(t)}function UGe(){var s=$Ge(rAe());return s.copy=function(){return KJ(s,UGe()).exponent(s.exponent())},Zj.apply(s,arguments),s}function Mtn(){return UGe.apply(null,arguments).exponent(.5)}function cut(s){return Math.sign(s)*s*s}function Ltn(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function GPt(){var s=DGe(),t=[0,1],n=!1,r;function a(i){var l=Ltn(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(cut(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,b5e)).map(cut)),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 GPt(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},Zj.apply(a,arguments),v6(a)}function WPt(){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 KPt().domain([s,t]).range(a).unknown(i)},Zj.apply(v6(l),arguments)}function YPt(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[GJ(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 YPt().domain(s).range(t).unknown(n)},Zj.apply(a,arguments)}const TPe=new Date,EPe=new Date;function bg(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(dbg(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)=>(TPe.setTime(+i),EPe.setTime(+l),s(TPe),s(EPe),Math.floor(n(TPe,EPe))),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 j5e=bg(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);j5e.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?bg(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):j5e);j5e.range;const c3=1e3,vj=c3*60,d3=vj*60,$3=d3*24,qGe=$3*7,dut=$3*30,MPe=$3*365,u8=bg(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*c3)},(s,t)=>(t-s)/c3,s=>s.getUTCSeconds());u8.range;const VGe=bg(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*c3)},(s,t)=>{s.setTime(+s+t*vj)},(s,t)=>(t-s)/vj,s=>s.getMinutes());VGe.range;const HGe=bg(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*vj)},(s,t)=>(t-s)/vj,s=>s.getUTCMinutes());HGe.range;const GGe=bg(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*c3-s.getMinutes()*vj)},(s,t)=>{s.setTime(+s+t*d3)},(s,t)=>(t-s)/d3,s=>s.getHours());GGe.range;const WGe=bg(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*d3)},(s,t)=>(t-s)/d3,s=>s.getUTCHours());WGe.range;const YJ=bg(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*vj)/$3,s=>s.getDate()-1);YJ.range;const aAe=bg(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/$3,s=>s.getUTCDate()-1);aAe.range;const ZPt=bg(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/$3,s=>Math.floor(s/$3));ZPt.range;function TO(s){return bg(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())*vj)/qGe)}const iAe=TO(0),N5e=TO(1),Ptn=TO(2),Itn=TO(3),$$=TO(4),Rtn=TO(5),Dtn=TO(6);iAe.range;N5e.range;Ptn.range;Itn.range;$$.range;Rtn.range;Dtn.range;function EO(s){return bg(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)/qGe)}const oAe=EO(0),k5e=EO(1),Otn=EO(2),Ftn=EO(3),U$=EO(4),ztn=EO(5),Btn=EO(6);oAe.range;k5e.range;Otn.range;Ftn.range;U$.range;ztn.range;Btn.range;const KGe=bg(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());KGe.range;const YGe=bg(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());YGe.range;const U3=bg(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());U3.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:bg(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)});U3.range;const q3=bg(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());q3.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:bg(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)});q3.range;function XPt(s,t,n,r,a,i){const l=[[u8,1,c3],[u8,5,5*c3],[u8,15,15*c3],[u8,30,30*c3],[i,1,vj],[i,5,5*vj],[i,15,15*vj],[i,30,30*vj],[a,1,d3],[a,3,3*d3],[a,6,6*d3],[a,12,12*d3],[r,1,$3],[r,2,2*$3],[n,1,qGe],[t,1,dut],[t,3,3*dut],[s,1,MPe]];function o(d,u,h){const m=ug).right(l,m);if(p===l.length)return s.every(f7e(d/MPe,u/MPe,h));if(p===0)return j5e.every(Math.max(f7e(d,u,h),1));const[x,y]=l[m/l[p-1][2]53)return null;"w"in Ne||(Ne.w=1),"Z"in Ne?(_e=PPe(OH(Ne.y,0,1)),Oe=_e.getUTCDay(),_e=Oe>4||Oe===0?k5e.ceil(_e):k5e(_e),_e=aAe.offset(_e,(Ne.V-1)*7),Ne.y=_e.getUTCFullYear(),Ne.m=_e.getUTCMonth(),Ne.d=_e.getUTCDate()+(Ne.w+6)%7):(_e=LPe(OH(Ne.y,0,1)),Oe=_e.getDay(),_e=Oe>4||Oe===0?N5e.ceil(_e):N5e(_e),_e=YJ.offset(_e,(Ne.V-1)*7),Ne.y=_e.getFullYear(),Ne.m=_e.getMonth(),Ne.d=_e.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),Oe="Z"in Ne?PPe(OH(Ne.y,0,1)).getUTCDay():LPe(OH(Ne.y,0,1)).getDay(),Ne.m=0,Ne.d="W"in Ne?(Ne.w+6)%7+Ne.W*7-(Oe+5)%7:Ne.w+Ne.U*7-(Oe+6)%7);return"Z"in Ne?(Ne.H+=Ne.Z/100|0,Ne.M+=Ne.Z%100,PPe(Ne)):LPe(Ne)}}function L(Le,De,Be,Ne){for(var Ge=0,_e=De.length,Oe=Be.length,Ae,Xe;Ge<_e;){if(Ne>=Oe)return-1;if(Ae=De.charCodeAt(Ge++),Ae===37){if(Ae=De.charAt(Ge++),Xe=T[Ae in uut?De.charAt(Ge++):Ae],!Xe||(Ne=Xe(Le,Be,Ne))<0)return-1}else if(Ae!=Be.charCodeAt(Ne++))return-1}return Ne}function I(Le,De,Be){var Ne=d.exec(De.slice(Be));return Ne?(Le.p=u.get(Ne[0].toLowerCase()),Be+Ne[0].length):-1}function O(Le,De,Be){var Ne=p.exec(De.slice(Be));return Ne?(Le.w=x.get(Ne[0].toLowerCase()),Be+Ne[0].length):-1}function $(Le,De,Be){var Ne=h.exec(De.slice(Be));return Ne?(Le.w=m.get(Ne[0].toLowerCase()),Be+Ne[0].length):-1}function q(Le,De,Be){var Ne=b.exec(De.slice(Be));return Ne?(Le.m=v.get(Ne[0].toLowerCase()),Be+Ne[0].length):-1}function W(Le,De,Be){var Ne=y.exec(De.slice(Be));return Ne?(Le.m=g.get(Ne[0].toLowerCase()),Be+Ne[0].length):-1}function G(Le,De,Be){return L(Le,t,De,Be)}function K(Le,De,Be){return L(Le,n,De,Be)}function ee(Le,De,Be){return L(Le,r,De,Be)}function J(Le){return l[Le.getDay()]}function le(Le){return i[Le.getDay()]}function ue(Le){return c[Le.getMonth()]}function oe(Le){return o[Le.getMonth()]}function ie(Le){return a[+(Le.getHours()>=12)]}function de(Le){return 1+~~(Le.getMonth()/3)}function we(Le){return l[Le.getUTCDay()]}function je(Le){return i[Le.getUTCDay()]}function xe(Le){return c[Le.getUTCMonth()]}function fe(Le){return o[Le.getUTCMonth()]}function Se(Le){return a[+(Le.getUTCHours()>=12)]}function Ee(Le){return 1+~~(Le.getUTCMonth()/3)}return{format:function(Le){var De=M(Le+="",k);return De.toString=function(){return Le},De},parse:function(Le){var De=P(Le+="",!1);return De.toString=function(){return Le},De},utcFormat:function(Le){var De=M(Le+="",C);return De.toString=function(){return Le},De},utcParse:function(Le){var De=P(Le+="",!0);return De.toString=function(){return Le},De}}}var uut={"-":"",_:" ",0:"0"},m0=/^\s*\d+/,Gtn=/^%/,Wtn=/[\\^$*+?|[\]().{}]/g;function Zd(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function Ytn(s,t,n){var r=m0.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function Ztn(s,t,n){var r=m0.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function Xtn(s,t,n){var r=m0.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function Qtn(s,t,n){var r=m0.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function Jtn(s,t,n){var r=m0.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function hut(s,t,n){var r=m0.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function mut(s,t,n){var r=m0.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function esn(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 tsn(s,t,n){var r=m0.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function ssn(s,t,n){var r=m0.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function put(s,t,n){var r=m0.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function nsn(s,t,n){var r=m0.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function fut(s,t,n){var r=m0.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function rsn(s,t,n){var r=m0.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function asn(s,t,n){var r=m0.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function isn(s,t,n){var r=m0.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function osn(s,t,n){var r=m0.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function lsn(s,t,n){var r=Gtn.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function csn(s,t,n){var r=m0.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function dsn(s,t,n){var r=m0.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function xut(s,t){return Zd(s.getDate(),t,2)}function usn(s,t){return Zd(s.getHours(),t,2)}function hsn(s,t){return Zd(s.getHours()%12||12,t,2)}function msn(s,t){return Zd(1+YJ.count(U3(s),s),t,3)}function QPt(s,t){return Zd(s.getMilliseconds(),t,3)}function psn(s,t){return QPt(s,t)+"000"}function fsn(s,t){return Zd(s.getMonth()+1,t,2)}function xsn(s,t){return Zd(s.getMinutes(),t,2)}function gsn(s,t){return Zd(s.getSeconds(),t,2)}function ysn(s){var t=s.getDay();return t===0?7:t}function vsn(s,t){return Zd(iAe.count(U3(s)-1,s),t,2)}function JPt(s){var t=s.getDay();return t>=4||t===0?$$(s):$$.ceil(s)}function bsn(s,t){return s=JPt(s),Zd($$.count(U3(s),s)+(U3(s).getDay()===4),t,2)}function _sn(s){return s.getDay()}function wsn(s,t){return Zd(N5e.count(U3(s)-1,s),t,2)}function jsn(s,t){return Zd(s.getFullYear()%100,t,2)}function Nsn(s,t){return s=JPt(s),Zd(s.getFullYear()%100,t,2)}function ksn(s,t){return Zd(s.getFullYear()%1e4,t,4)}function Ssn(s,t){var n=s.getDay();return s=n>=4||n===0?$$(s):$$.ceil(s),Zd(s.getFullYear()%1e4,t,4)}function Csn(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Zd(t/60|0,"0",2)+Zd(t%60,"0",2)}function gut(s,t){return Zd(s.getUTCDate(),t,2)}function Asn(s,t){return Zd(s.getUTCHours(),t,2)}function Tsn(s,t){return Zd(s.getUTCHours()%12||12,t,2)}function Esn(s,t){return Zd(1+aAe.count(q3(s),s),t,3)}function eIt(s,t){return Zd(s.getUTCMilliseconds(),t,3)}function Msn(s,t){return eIt(s,t)+"000"}function Lsn(s,t){return Zd(s.getUTCMonth()+1,t,2)}function Psn(s,t){return Zd(s.getUTCMinutes(),t,2)}function Isn(s,t){return Zd(s.getUTCSeconds(),t,2)}function Rsn(s){var t=s.getUTCDay();return t===0?7:t}function Dsn(s,t){return Zd(oAe.count(q3(s)-1,s),t,2)}function tIt(s){var t=s.getUTCDay();return t>=4||t===0?U$(s):U$.ceil(s)}function Osn(s,t){return s=tIt(s),Zd(U$.count(q3(s),s)+(q3(s).getUTCDay()===4),t,2)}function Fsn(s){return s.getUTCDay()}function zsn(s,t){return Zd(k5e.count(q3(s)-1,s),t,2)}function Bsn(s,t){return Zd(s.getUTCFullYear()%100,t,2)}function $sn(s,t){return s=tIt(s),Zd(s.getUTCFullYear()%100,t,2)}function Usn(s,t){return Zd(s.getUTCFullYear()%1e4,t,4)}function qsn(s,t){var n=s.getUTCDay();return s=n>=4||n===0?U$(s):U$.ceil(s),Zd(s.getUTCFullYear()%1e4,t,4)}function Vsn(){return"+0000"}function yut(){return"%"}function vut(s){return+s}function but(s){return Math.floor(+s/1e3)}var JF,sIt,nIt;Hsn({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 Hsn(s){return JF=Htn(s),sIt=JF.format,JF.parse,nIt=JF.utcFormat,JF.utcParse,JF}function Gsn(s){return new Date(s)}function Wsn(s){return s instanceof Date?+s:+new Date(+s)}function ZGe(s,t,n,r,a,i,l,o,c,d){var u=DGe(),h=u.invert,m=u.domain,p=d(".%L"),x=d(":%S"),y=d("%I:%M"),g=d("%I %p"),b=d("%a %d"),v=d("%b %d"),k=d("%B"),C=d("%Y");function T(M){return(c(M)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>Den(s,i/r))},n.copy=function(){return oIt(t).domain(s)},aC.apply(n,arguments)}function cAe(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=Qv,u,h=!1,m;function p(y){return isNaN(y=+y)?m:(y=.5+((y=+u(y))-i)*(r*yt}var uIt=enn,tnn=dAe,snn=uIt,nnn=bq;function rnn(s){return s&&s.length?tnn(s,nnn,snn):void 0}var ann=rnn;const ST=sd(ann);function inn(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};Yi.decimalPlaces=Yi.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*dm;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};Yi.dividedBy=Yi.div=function(s){return C3(this,new this.constructor(s))};Yi.dividedToIntegerBy=Yi.idiv=function(s){var t=this,n=t.constructor;return kh(C3(t,new n(s),0,1),n.precision)};Yi.equals=Yi.eq=function(s){return!this.cmp(s)};Yi.exponent=function(){return Tx(this)};Yi.greaterThan=Yi.gt=function(s){return this.cmp(s)>0};Yi.greaterThanOrEqualTo=Yi.gte=function(s){return this.cmp(s)>=0};Yi.isInteger=Yi.isint=function(){return this.e>this.d.length-2};Yi.isNegative=Yi.isneg=function(){return this.s<0};Yi.isPositive=Yi.ispos=function(){return this.s>0};Yi.isZero=function(){return this.s===0};Yi.lessThan=Yi.lt=function(s){return this.cmp(s)<0};Yi.lessThanOrEqualTo=Yi.lte=function(s){return this.cmp(s)<1};Yi.logarithm=Yi.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(O_))throw Error(zj+"NaN");if(n.s<1)throw Error(zj+(n.s?"NaN":"-Infinity"));return n.eq(O_)?new r(0):(Hm=!1,t=C3(OZ(n,i),OZ(s,i),i),Hm=!0,kh(t,a))};Yi.minus=Yi.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?xIt(t,s):pIt(t,(s.s=-s.s,s))};Yi.modulo=Yi.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(zj+"NaN");return n.s?(Hm=!1,t=C3(n,s,0,1).times(s),Hm=!0,n.minus(t)):kh(new r(n),a)};Yi.naturalExponential=Yi.exp=function(){return fIt(this)};Yi.naturalLogarithm=Yi.ln=function(){return OZ(this)};Yi.negated=Yi.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};Yi.plus=Yi.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?pIt(t,s):xIt(t,(s.s=-s.s,s))};Yi.precision=Yi.sd=function(s){var t,n,r,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(lD+s);if(t=Tx(a)+1,r=a.d.length-1,n=r*dm+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};Yi.squareRoot=Yi.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(zj+"NaN")}for(s=Tx(o),Hm=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=w5(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=Nq((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(C3(o,i,l+2)).times(.5),w5(i.d).slice(0,l)===(t=w5(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(kh(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return Hm=!0,kh(r,n)};Yi.times=Yi.mul=function(s){var t,n,r,a,i,l,o,c,d,u=this,h=u.constructor,m=u.d,p=(s=new h(s)).d;if(!u.s||!s.s)return new h(0);for(s.s*=u.s,n=u.e+s.e,c=m.length,d=p.length,c=0;){for(t=0,a=c+r;a>r;)o=i[a]+p[r]*m[a-r-1]+t,i[a--]=o%Gg|0,t=o/Gg|0;i[a]=(i[a]+t)%Gg|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,Hm?kh(s,h.precision):s};Yi.toDecimalPlaces=Yi.todp=function(s,t){var n=this,r=n.constructor;return n=new r(n),s===void 0?n:(J5(s,0,jq),t===void 0?t=r.rounding:J5(t,0,8),kh(n,s+Tx(n)+1,t))};Yi.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=HD(r,!0):(J5(s,0,jq),t===void 0?t=a.rounding:J5(t,0,8),r=kh(new a(r),s+1,t),n=HD(r,!0,s+1)),n};Yi.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?HD(a):(J5(s,0,jq),t===void 0?t=i.rounding:J5(t,0,8),r=kh(new i(a),s+Tx(a)+1,t),n=HD(r.abs(),!1,s+Tx(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};Yi.toInteger=Yi.toint=function(){var s=this,t=s.constructor;return kh(new t(s),Tx(s)+1,t.rounding)};Yi.toNumber=function(){return+this};Yi.toPower=Yi.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(O_);if(o=new c(o),!o.s){if(s.s<1)throw Error(zj+"Infinity");return o}if(o.eq(O_))return o;if(r=c.precision,s.eq(O_))return kh(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=mIt){for(a=new c(O_),t=Math.ceil(r/dm+4),Hm=!1;n%2&&(a=a.times(o),jut(a.d,t)),n=Nq(n/2),n!==0;)o=o.times(o),jut(o.d,t);return Hm=!0,s.s<0?new c(O_).div(a):kh(a,r)}}else if(i<0)throw Error(zj+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,Hm=!1,a=s.times(OZ(o,r+d)),Hm=!0,a=fIt(a),a.s=i,a};Yi.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=Tx(a),r=HD(a,n<=i.toExpNeg||n>=i.toExpPos)):(J5(s,1,jq),t===void 0?t=i.rounding:J5(t,0,8),a=kh(new i(a),s,t),n=Tx(a),r=HD(a,s<=n||n<=i.toExpNeg,s)),r};Yi.toSignificantDigits=Yi.tosd=function(s,t){var n=this,r=n.constructor;return s===void 0?(s=r.precision,t=r.rounding):(J5(s,1,jq),t===void 0?t=r.rounding:J5(t,0,8)),kh(new r(n),s,t)};Yi.toString=Yi.valueOf=Yi.val=Yi.toJSON=Yi[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=Tx(s),n=s.constructor;return HD(s,t<=n.toExpNeg||t>=n.toExpPos)};function pIt(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)),Hm?kh(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/dm),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)/Gg|0,c[i]%=Gg;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,Hm?kh(t,h):t}function J5(s,t,n){if(s!==~~s||sn)throw Error(lD+s)}function w5(s){var t,n,r,a=s.length-1,i="",l=s[0];if(a>0){for(i+=l,t=1;tl?1:-1;else for(o=c=0;oa[o]?1:-1;break}return c}function n(r,a,i){for(var l=0;i--;)r[i]-=l,l=r[i]1;)r.shift()}return function(r,a,i,l){var o,c,d,u,h,m,p,x,y,g,b,v,k,C,T,M,P,L,I=r.constructor,O=r.s==a.s?1:-1,$=r.d,q=a.d;if(!r.s)return new I(r);if(!a.s)throw Error(zj+"Division by zero");for(c=r.e-a.e,P=q.length,T=$.length,p=new I(O),x=p.d=[],d=0;q[d]==($[d]||0);)++d;if(q[d]>($[d]||0)&&--c,i==null?v=i=I.precision:l?v=i+(Tx(r)-Tx(a))+1:v=i,v<0)return new I(0);if(v=v/dm+2|0,d=0,P==1)for(u=0,q=q[0],v++;(d1&&(q=s(q,u),$=s($,u),P=q.length,T=$.length),C=P,y=$.slice(0,P),g=y.length;g=Gg/2&&++M;do u=0,o=t(q,y,P,g),o<0?(b=y[0],P!=g&&(b=b*Gg+(y[1]||0)),u=b/M|0,u>1?(u>=Gg&&(u=Gg-1),h=s(q,u),m=h.length,g=y.length,o=t(h,y,m,g),o==1&&(u--,n(h,P16)throw Error(JGe+Tx(s));if(!s.s)return new u(O_);for(t==null?(Hm=!1,o=h):o=t,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(II(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(O_),u.precision=o;;){if(a=kh(a.times(s),o),n=n.times(++c),l=i.plus(C3(a,n,o)),w5(l.d).slice(0,o)===w5(i.d).slice(0,o)){for(;d--;)i=kh(i.times(i),o);return u.precision=h,t==null?(Hm=!0,kh(i,h)):i}i=l}}function Tx(s){for(var t=s.e*dm,n=s.d[0];n>=10;n/=10)t++;return t}function IPe(s,t,n){if(t>s.LN10.sd())throw Hm=!0,n&&(s.precision=n),Error(zj+"LN10 precision limit exceeded");return kh(new s(s.LN10),t)}function gA(s){for(var t="";s--;)t+="0";return t}function OZ(s,t){var n,r,a,i,l,o,c,d,u,h=1,m=10,p=s,x=p.d,y=p.constructor,g=y.precision;if(p.s<1)throw Error(zj+(p.s?"NaN":"-Infinity"));if(p.eq(O_))return new y(0);if(t==null?(Hm=!1,d=g):d=t,p.eq(10))return t==null&&(Hm=!0),IPe(y,d);if(d+=m,y.precision=d,n=w5(x),r=n.charAt(0),i=Tx(p),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)p=p.times(s),n=w5(p.d),r=n.charAt(0),h++;i=Tx(p),r>1?(p=new y("0."+n),i++):p=new y(r+"."+n.slice(1))}else return c=IPe(y,d+2,g).times(i+""),p=OZ(new y(r+"."+n.slice(1)),d-m).plus(c),y.precision=g,t==null?(Hm=!0,kh(p,g)):p;for(o=l=p=C3(p.minus(O_),p.plus(O_),d),u=kh(p.times(p),d),a=3;;){if(l=kh(l.times(u),d),c=o.plus(C3(l,new y(a),d)),w5(c.d).slice(0,d)===w5(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(IPe(y,d+2,g).times(i+""))),o=C3(o,new y(h),d),y.precision=g,t==null?(Hm=!0,kh(o,g)):o;o=c,a+=2}}function wut(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=Nq(n/dm),s.d=[],r=(n+1)%dm,n<0&&(r+=dm),rS5e||s.e<-S5e))throw Error(JGe+n)}else s.s=0,s.e=0,s.d=[0];return s}function kh(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+=dm,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/dm),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=dm,a=r-dm+l}if(n!==void 0&&(i=II(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/II(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=Tx(s),h.length=1,t=t-i-1,h[0]=II(10,(dm-t%dm)%dm),s.e=Nq(-t/dm)||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=II(10,dm-r),h[u]=a>0?(d/II(10,l-a)%II(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==Gg&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=Gg)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(Hm&&(s.e>S5e||s.e<-S5e))throw Error(JGe+Tx(s));return s}function xIt(s,t){var n,r,a,i,l,o,c,d,u,h,m=s.constructor,p=m.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new m(s),Hm?kh(t,p):t;if(c=s.d,h=t.d,r=t.e,d=s.e,c=c.slice(),l=d-r,l){for(u=l<0,u?(n=c,l=-l,o=h.length):(n=h,r=d,o=c.length),a=Math.max(Math.ceil(p/dm),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)+gA(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+gA(-a-1)+i,n&&(r=n-l)>0&&(i+=gA(r))):a>=l?(i+=gA(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+gA(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=gA(r))),s.s<0?"-"+i:i}function jut(s,t){if(s.length>t)return s.length=t,!0}function gIt(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(lD+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 wut(l,i.toString())}else if(typeof i!="string")throw Error(lD+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,Cnn.test(i))wut(l,i);else throw Error(lD+i)}if(a.prototype=Yi,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=gIt,a.config=a.set=Ann,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(lD+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(lD+n+": "+r);return this}var eWe=gIt(Snn);O_=new eWe(1);const th=eWe;function Tnn(s){return Pnn(s)||Lnn(s)||Mnn(s)||Enn()}function Enn(){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 Mnn(s,t){if(s){if(typeof s=="string")return b7e(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 b7e(s,t)}}function Lnn(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function Pnn(s){if(Array.isArray(s))return b7e(s)}function b7e(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,Nut(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 Knn(s){if(Array.isArray(s))return s}function wIt(s){var t=FZ(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function jIt(s,t,n){if(s.lte(0))return new th(0);var r=mAe.getDigitCount(s.toNumber()),a=new th(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new th(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new th(Math.ceil(c))}function Ynn(s,t,n){var r=1,a=new th(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new th(10).pow(mAe.getDigitCount(s)-1),a=new th(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new th(Math.floor(s)))}else s===0?a=new th(Math.floor((t-1)/2)):n||(a=new th(Math.floor(s)));var l=Math.floor((t-1)/2),o=Onn(Dnn(function(c){return a.add(new th(c-l).mul(r)).toNumber()}),_7e);return o(0,t)}function NIt(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 th(0),tickMin:new th(0),tickMax:new th(0)};var i=jIt(new th(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new th(0):(l=new th(s).add(t).div(2),l=l.sub(new th(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new th(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?NIt(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new th(o).mul(i)),tickMax:l.add(new th(c).mul(i))})}function Znn(s){var t=FZ(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=wIt([n,r]),c=FZ(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(j7e(_7e(0,a-1).map(function(){return 1/0}))):[].concat(j7e(_7e(0,a-1).map(function(){return-1/0})),[u]);return n>r?w7e(h):h}if(d===u)return Ynn(d,a,i);var m=NIt(d,u,l,i),p=m.step,x=m.tickMin,y=m.tickMax,g=mAe.rangeStep(x,y.add(new th(.1).mul(p)),p);return n>r?w7e(g):g}function Xnn(s,t){var n=FZ(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=wIt([r,a]),o=FZ(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=jIt(new th(d).sub(c).div(u-1),i,0),m=[].concat(j7e(mAe.rangeStep(new th(c),new th(d).sub(new th(.99).mul(h)),h)),[d]);return r>a?w7e(m):m}var Qnn=bIt(Znn),Jnn=bIt(Xnn),ern="Invariant failed";function GD(s,t){throw new Error(ern)}var trn=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function q$(s){"@babel/helpers - typeof";return q$=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},q$(s)}function C5e(){return C5e=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 lrn(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 crn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function drn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:[],a=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,l=-1,o=(n=r==null?void 0:r.length)!==null&&n!==void 0?n:0;if(o<=1)return 0;if(i&&i.axisType==="angleAxis"&&Math.abs(Math.abs(i.range[1]-i.range[0])-360)<=1e-6)for(var c=i.range,d=0;d0?a[d-1].coordinate:a[o-1].coordinate,h=a[d].coordinate,m=d>=o-1?a[0].coordinate:a[d+1].coordinate,p=void 0;if(Zv(h-u)!==Zv(m-h)){var x=[];if(Zv(m-h)===Zv(c[1]-c[0])){p=m;var y=h+c[1]-c[0];x[0]=Math.min(y,(y+u)/2),x[1]=Math.max(y,(y+u)/2)}else{p=u;var g=m+c[1]-c[0];x[0]=Math.min(h,(g+h)/2),x[1]=Math.max(h,(g+h)/2)}var b=[Math.min(h,(p+h)/2),Math.max(h,(p+h)/2)];if(t>b[0]&&t<=b[1]||t>=x[0]&&t<=x[1]){l=a[d].index;break}}else{var v=Math.min(u,m),k=Math.max(u,m);if(t>(v+h)/2&&t<=(k+h)/2){l=a[d].index;break}}}else for(var C=0;C0&&C(r[C].coordinate+r[C-1].coordinate)/2&&t<=(r[C].coordinate+r[C+1].coordinate)/2||C===o-1&&t>(r[C].coordinate+r[C-1].coordinate)/2){l=r[C].index;break}return l},tWe=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?hf(hf({},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},Crn=function(t){var n=t.barSize,r=t.totalSize,a=t.stackGroups,i=a===void 0?{}:a;if(!i)return{};for(var l={},o=Object.keys(i),c=0,d=o.length;c=0});if(b&&b.length){var v=b[0].type.defaultProps,k=v!==void 0?hf(hf({},v),b[0].props):b[0].props,C=k.barSize,T=k[g];l[T]||(l[T]=[]);var M=Al(C)?n:C;l[T].push({item:b[0],stackList:b.slice(1),barSize:Al(M)?void 0:Xv(M,r,0)})}}return l},Arn=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=Xv(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var m=!1,p=a/c,x=l.reduce(function(C,T){return C+T.barSize||0},0);x+=(c-1)*d,x>=a&&(x-=(c-1)*d,d=0),x>=a&&p>0&&(m=!0,p*=.9,x=c*p);var y=(a-x)/2>>0,g={offset:y-d,size:0};u=l.reduce(function(C,T){var M={item:T.item,position:{offset:g.offset+g.size+d,size:m?p:T.barSize}},P=[].concat(Cut(C),[M]);return g=P[P.length-1].position,T.stackList&&T.stackList.length&&T.stackList.forEach(function(L){P.push({item:L,position:g})}),P},h)}else{var b=Xv(r,a,0,!0);a-2*b-(c-1)*d<=0&&(d=0);var v=(a-2*b-(c-1)*d)/c;v>1&&(v>>=0);var k=o===+o?Math.min(v,o):v;u=l.reduce(function(C,T,M){var P=[].concat(Cut(C),[{item:T.item,position:{offset:b+(v+d)*M+(v-k)/2,size:k}}]);return T.stackList&&T.stackList.length&&T.stackList.forEach(function(L){P.push({item:L,position:P[P.length-1].position})}),P},h)}return u},Trn=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=AIt({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,m=u.height,p=d.align,x=d.verticalAlign,y=d.layout;if((y==="vertical"||y==="horizontal"&&x==="middle")&&p!=="center"&&La(t[p]))return hf(hf({},t),{},Lz({},p,t[p]+(h||0)));if((y==="horizontal"||y==="vertical"&&p==="center")&&x!=="middle"&&La(t[x]))return hf(hf({},t),{},Lz({},x,t[x]+(m||0)))}return t},Ern=function(t,n,r){return Al(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},TIt=function(t,n,r,a,i){var l=n.props.children,o=Z_(l,ZJ).filter(function(d){return Ern(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=Zf(u,r);if(Al(h))return d;var m=Array.isArray(h)?[uAe(h),ST(h)]:[h,h],p=c.reduce(function(x,y){var g=Zf(u,y,0),b=m[0]-Math.abs(Array.isArray(g)?g[0]:g),v=m[1]+Math.abs(Array.isArray(g)?g[1]:g);return[Math.min(b,x[0]),Math.max(v,x[1])]},[1/0,-1/0]);return[Math.min(p[0],d[0]),Math.max(p[1],d[1])]},[1/0,-1/0])}return null},Mrn=function(t,n,r,a,i){var l=n.map(function(o){return TIt(t,o,r,i,a)}).filter(function(o){return!Al(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},EIt=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&TIt(t,c,d,a)||tY(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!gq(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}})},RPe=new WeakMap,Sne=function(t,n){if(typeof n!="function")return t;RPe.has(t)||RPe.set(t,new WeakMap);var r=RPe.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},PIt=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:LZ(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:w5e(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:eY(),realScaleType:"point"}:i==="category"?{scale:LZ(),realScaleType:"band"}:{scale:w5e(),realScaleType:"linear"};if($D(a)){var c="scale".concat(XCe(a));return{scale:(_ut[c]||eY)(),realScaleType:_ut[c]?c:"point"}}return nl(a)?{scale:a}:{scale:eY(),realScaleType:"point"}},Tut=1e-4,IIt=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])-Tut,l=Math.max(a[0],a[1])+Tut,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},Lrn=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])}},Rrn=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)}},Drn={sign:Irn,expand:tHs,none:R$,silhouette:sHs,wiggle:nHs,positive:Rrn},Orn=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=Drn[r],l=eHs().keys(a).value(function(o,c){return+Zf(o,c,0)}).order(XFe).offset(i);return l(t)},Frn=function(t,n,r,a,i,l){if(!t)return null;var o=l?n.reverse():n,c={},d=o.reduce(function(h,m){var p,x=(p=m.type)!==null&&p!==void 0&&p.defaultProps?hf(hf({},m.type.defaultProps),m.props):m.props,y=x.stackId,g=x.hide;if(g)return h;var b=x[r],v=h[b]||{hasStack:!1,stackGroups:{}};if(lg(y)){var k=v.stackGroups[y]||{numericAxisId:r,cateAxisId:a,items:[]};k.items.push(m),v.hasStack=!0,v.stackGroups[y]=k}else v.stackGroups[AO("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[m]};return hf(hf({},h),{},Lz({},b,v))},c),u={};return Object.keys(d).reduce(function(h,m){var p=d[m];if(p.hasStack){var x={};p.stackGroups=Object.keys(p.stackGroups).reduce(function(y,g){var b=p.stackGroups[g];return hf(hf({},y),{},Lz({},g,{numericAxisId:r,cateAxisId:a,items:b.items,stackedData:Orn(t,b.items,i)}))},x)}return hf(hf({},h),{},Lz({},m,p))},u)},RIt=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=Qnn(d,i,o);return t.domain([uAe(u),ST(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),m=Jnn(h,i,o);return{niceTicks:m}}return null};function T5e(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&&!Al(a[t.dataKey])){var o=t5e(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=Zf(a,Al(l)?t.dataKey:l);return Al(c)?null:t.scale(c)}var Eut=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=Zf(l,n.dataKey,n.domain[o]);return Al(c)?null:n.scale(c)-i/2+a},zrn=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]},Brn=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?hf(hf({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(lg(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},$rn=function(t){return t.reduce(function(n,r){return[uAe(r.concat([n[0]]).filter(La)),ST(r.concat([n[1]]).filter(La))]},[1/0,-1/0])},DIt=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=$rn(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})},Mut=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Lut=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,C7e=function(t,n,r){if(nl(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(La(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(Mut.test(t[0])){var i=+Mut.exec(t[0])[1];a[0]=n[0]-i}else nl(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(La(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(Lut.test(t[1])){var l=+Lut.exec(t[1])[1];a[1]=n[1]+l}else nl(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},E5e=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=TGe(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},Zrn=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=Xv(t.cx,l,l/2),h=Xv(t.cy,o,o/2),m=zIt(l,o,r),p=Xv(t.innerRadius,m,0),x=Xv(t.outerRadius,m,m*.8),y=Object.keys(n);return y.reduce(function(g,b){var v=n[b],k=v.domain,C=v.reversed,T;if(Al(v.range))a==="angleAxis"?T=[c,d]:a==="radiusAxis"&&(T=[p,x]),C&&(T=[T[1],T[0]]);else{T=v.range;var M=T,P=Vrn(M,2);c=P[0],d=P[1]}var L=PIt(v,i),I=L.realScaleType,O=L.scale;O.domain(k).range(T),IIt(O);var $=RIt(O,g4(g4({},v),{},{realScaleType:I})),q=g4(g4(g4({},v),$),{},{range:T,radius:x,realScaleType:I,scale:O,cx:u,cy:h,innerRadius:p,outerRadius:x,startAngle:c,endAngle:d});return g4(g4({},g),{},FIt({},b,q))},{})},Xrn=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))},Qrn=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=Xrn({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:Yrn(d),angleInRadian:d}},Jrn=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}},ean=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},Dut=function(t,n){var r=t.x,a=t.y,i=Qrn({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=Jrn(n),h=u.startAngle,m=u.endAngle,p=o,x;if(h<=m){for(;p>m;)p-=360;for(;p=h&&p<=m}else{for(;p>h;)p-=360;for(;p=m&&p<=h}return x?g4(g4({},n),{},{radius:l,angle:ean(p,n)}):null},BIt=function(t){return!j.isValidElement(t)&&!nl(t)&&typeof t!="boolean"?t.className:""};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)}var tan=["offset"];function san(s){return ian(s)||aan(s)||ran(s)||nan()}function nan(){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 ran(s,t){if(s){if(typeof s=="string")return A7e(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 A7e(s,t)}}function aan(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function ian(s){if(Array.isArray(s))return A7e(s)}function A7e(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 lan(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Out(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 Vx(s){for(var t=1;t=0?1:-1,k,C;a==="insideStart"?(k=p+v*l,C=y):a==="insideEnd"?(k=x-v*l,C=!y):a==="end"&&(k=x+v*l,C=y),C=b<=0?C:!C;var T=qh(d,u,g,k),M=qh(d,u,g,k+(C?1:-1)*359),P="M".concat(T.x,",").concat(T.y,` A`).concat(g,",").concat(g,",0,1,").concat(C?0:1,`, `).concat(M.x,",").concat(M.y),L=Al(t.id)?AO("recharts-radial-line-"):t.id;return Lt.createElement("text",qZ({},r,{dominantBaseline:"central",className:Il("recharts-radial-bar-label",o)}),Lt.createElement("defs",null,Lt.createElement("path",{id:L,d:P})),Lt.createElement("textPath",{xlinkHref:"#".concat(L)},n))},fan=function(t){var n=t.viewBox,r=t.offset,a=t.position,i=n,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,u=i.startAngle,h=i.endAngle,m=(u+h)/2;if(a==="outside"){var p=qh(l,o,d+r,m),x=p.x,y=p.y;return{x,y,textAnchor:x>=l?"start":"end",verticalAnchor:"middle"}}if(a==="center")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"middle"};if(a==="centerTop")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"start"};if(a==="centerBottom")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"end"};var g=(c+d)/2,b=qh(l,o,g,m),v=b.x,k=b.y;return{x:v,y:k,textAnchor:"middle",verticalAnchor:"middle"}},xan=function(t){var n=t.viewBox,r=t.parentViewBox,a=t.offset,i=t.position,l=n,o=l.x,c=l.y,d=l.width,u=l.height,h=u>=0?1:-1,m=h*a,p=h>0?"end":"start",x=h>0?"start":"end",y=d>=0?1:-1,g=y*a,b=y>0?"end":"start",v=y>0?"start":"end";if(i==="top"){var k={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:p};return Vx(Vx({},k),r?{height:Math.max(c-r.y,0),width:d}:{})}if(i==="bottom"){var C={x:o+d/2,y:c+u+m,textAnchor:"middle",verticalAnchor:x};return Vx(Vx({},C),r?{height:Math.max(r.y+r.height-(c+u),0),width:d}:{})}if(i==="left"){var T={x:o-g,y:c+u/2,textAnchor:b,verticalAnchor:"middle"};return Vx(Vx({},T),r?{width:Math.max(T.x-r.x,0),height:u}:{})}if(i==="right"){var M={x:o+d+g,y:c+u/2,textAnchor:v,verticalAnchor:"middle"};return Vx(Vx({},M),r?{width:Math.max(r.x+r.width-M.x,0),height:u}:{})}var P=r?{width:d,height:u}:{};return i==="insideLeft"?Vx({x:o+g,y:c+u/2,textAnchor:v,verticalAnchor:"middle"},P):i==="insideRight"?Vx({x:o+d-g,y:c+u/2,textAnchor:b,verticalAnchor:"middle"},P):i==="insideTop"?Vx({x:o+d/2,y:c+m,textAnchor:"middle",verticalAnchor:x},P):i==="insideBottom"?Vx({x:o+d/2,y:c+u-m,textAnchor:"middle",verticalAnchor:p},P):i==="insideTopLeft"?Vx({x:o+g,y:c+m,textAnchor:v,verticalAnchor:x},P):i==="insideTopRight"?Vx({x:o+d-g,y:c+m,textAnchor:b,verticalAnchor:x},P):i==="insideBottomLeft"?Vx({x:o+g,y:c+u-m,textAnchor:v,verticalAnchor:p},P):i==="insideBottomRight"?Vx({x:o+d-g,y:c+u-m,textAnchor:b,verticalAnchor:p},P):mq(i)&&(La(i.x)||c8(i.x))&&(La(i.y)||c8(i.y))?Vx({x:o+Xv(i.x,d),y:c+Xv(i.y,u),textAnchor:"end",verticalAnchor:"end"},P):Vx({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},P)},gan=function(t){return"cx"in t&&La(t.cx)};function Qg(s){var t=s.offset,n=t===void 0?5:t,r=oan(s,tan),a=Vx({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||Al(o)&&Al(c)&&!j.isValidElement(d)&&!nl(d))return null;if(j.isValidElement(d))return j.cloneElement(d,a);var p;if(nl(d)){if(p=j.createElement(d,a),j.isValidElement(p))return p}else p=han(a);var x=gan(i),y=bo(a,!0);if(x&&(l==="insideStart"||l==="insideEnd"||l==="end"))return pan(a,p,y);var g=x?fan(a):xan(a);return Lt.createElement(qD,qZ({className:Il("recharts-label",h)},y,g,{breakAll:m}),p)}Qg.displayName="Label";var $It=function(t){var n=t.cx,r=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,u=t.outerRadius,h=t.x,m=t.y,p=t.top,x=t.left,y=t.width,g=t.height,b=t.clockWise,v=t.labelViewBox;if(v)return v;if(La(y)&&La(g)){if(La(h)&&La(m))return{x:h,y:m,width:y,height:g};if(La(p)&&La(x))return{x:p,y:x,width:y,height:g}}return La(h)&&La(m)?{x:h,y:m,width:0,height:0}:La(n)&&La(r)?{cx:n,cy:r,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:b}:t.viewBox?t.viewBox:{}},yan=function(t,n){return t?t===!0?Lt.createElement(Qg,{key:"label-implicit",viewBox:n}):lg(t)?Lt.createElement(Qg,{key:"label-implicit",viewBox:n,value:t}):j.isValidElement(t)?t.type===Qg?j.cloneElement(t,{key:"label-implicit",viewBox:n}):Lt.createElement(Qg,{key:"label-implicit",content:t,viewBox:n}):nl(t)?Lt.createElement(Qg,{key:"label-implicit",content:t,viewBox:n}):mq(t)?Lt.createElement(Qg,qZ({viewBox:n},t,{key:"label-implicit"})):null:null},van=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=$It(t),l=Z_(a,Qg).map(function(c,d){return j.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=yan(t.label,n||i);return[o].concat(san(l))};Qg.parseViewBox=$It;Qg.renderCallByParent=van;function ban(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var _an=ban;const wan=sd(_an);function VZ(s){"@babel/helpers - typeof";return VZ=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},VZ(s)}var jan=["valueAccessor"],Nan=["data","dataKey","clockWise","id","textBreakAll"];function kan(s){return Tan(s)||Aan(s)||Can(s)||San()}function San(){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 Can(s,t){if(s){if(typeof s=="string")return T7e(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 T7e(s,t)}}function Aan(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Tan(s){if(Array.isArray(s))return T7e(s)}function T7e(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 Pan(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 Ian=function(t){return Array.isArray(t.value)?wan(t.value):t.value};function $5(s){var t=s.valueAccessor,n=t===void 0?Ian:t,r=But(s,jan),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=But(r,Nan);return!a||!a.length?null:Lt.createElement(qc,{className:"recharts-label-list"},a.map(function(u,h){var m=Al(i)?n(u,h):Zf(u&&u.payload,i),p=Al(o)?{}:{id:"".concat(o,"-").concat(h)};return Lt.createElement(Qg,L5e({},bo(u,!0),d,p,{parentViewBox:u.parentViewBox,value:m,textBreakAll:c,viewBox:Qg.parseViewBox(Al(l)?u:zut(zut({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}$5.displayName="LabelList";function Ran(s,t){return s?s===!0?Lt.createElement($5,{key:"labelList-implicit",data:t}):Lt.isValidElement(s)||nl(s)?Lt.createElement($5,{key:"labelList-implicit",data:t,content:s}):mq(s)?Lt.createElement($5,L5e({data:t},s,{key:"labelList-implicit"})):null:null}function Dan(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=Z_(r,$5).map(function(l,o){return j.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=Ran(s.label,t);return[i].concat(kan(a))}$5.renderCallByParent=Dan;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 E7e(){return E7e=Object.assign?Object.assign.bind():function(s){for(var t=1;t180),",").concat(+(l>d),`, `).concat(h.x,",").concat(h.y,` `);if(a>0){var p=qh(n,r,a,l),x=qh(n,r,a,d);m+="L ".concat(x.x,",").concat(x.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(p.x,",").concat(p.y," Z")}else m+="L ".concat(n,",").concat(r," Z");return m},$an=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=Cne({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),p=m.circleTangency,x=m.lineTangency,y=m.theta,g=Cne({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),b=g.circleTangency,v=g.lineTangency,k=g.theta,C=c?Math.abs(d-u):Math.abs(d-u)-y-k;if(C<0)return o?"M ".concat(x.x,",").concat(x.y,` a`).concat(l,",").concat(l,",0,0,1,").concat(l*2,`,0 a`).concat(l,",").concat(l,",0,0,1,").concat(-l*2,`,0 `):UIt({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var T="M ".concat(x.x,",").concat(x.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(p.x,",").concat(p.y,` A`).concat(i,",").concat(i,",0,").concat(+(C>180),",").concat(+(h<0),",").concat(b.x,",").concat(b.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(v.x,",").concat(v.y,` `);if(a>0){var M=Cne({cx:n,cy:r,radius:a,angle:d,sign:h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),P=M.circleTangency,L=M.lineTangency,I=M.theta,O=Cne({cx:n,cy:r,radius:a,angle:u,sign:-h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),$=O.circleTangency,q=O.lineTangency,W=O.theta,G=c?Math.abs(d-u):Math.abs(d-u)-I-W;if(G<0&&l===0)return"".concat(T,"L").concat(n,",").concat(r,"Z");T+="L".concat(q.x,",").concat(q.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(P.x,",").concat(P.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(L.x,",").concat(L.y,"Z")}else T+="L".concat(n,",").concat(r,"Z");return T},Uan={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},qIt=function(t){var n=Uut(Uut({},Uan),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?g=$an({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(y,x/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):g=UIt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),Lt.createElement("path",E7e({},bo(n,!0),{className:p,d:g,role:"img"}))};function GZ(s){"@babel/helpers - typeof";return GZ=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},GZ(s)}function M7e(){return M7e=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 nin(s,t){return kq(s.getTime(),t.getTime())}function Zut(s,t,n){if(s.size!==t.size)return!1;for(var r={},a=s.entries(),i=0,l,o;(l=a.next())&&!l.done;){for(var c=t.entries(),d=!1,u=0;(o=c.next())&&!o.done;){var h=l.value,m=h[0],p=h[1],x=o.value,y=x[0],g=x[1];!d&&!r[u]&&(d=n.equals(m,y,i,u,s,t,n)&&n.equals(p,g,m,y,s,t,n))&&(r[u]=!0),u++}if(!d)return!1;i++}return!0}function rin(s,t,n){var r=Yut(s),a=r.length;if(Yut(t).length!==a)return!1;for(var i;a-- >0;)if(i=r[a],i===KIt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!WIt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n))return!1;return!0}function UH(s,t,n){var r=Wut(s),a=r.length;if(Wut(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=r[a],i===KIt&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!WIt(t,i)||!n.equals(s[i],t[i],i,i,s,t,n)||(l=Kut(s,i),o=Kut(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function ain(s,t){return kq(s.valueOf(),t.valueOf())}function iin(s,t){return s.source===t.source&&s.flags===t.flags}function Xut(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 oin(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 lin="[object Arguments]",cin="[object Boolean]",din="[object Date]",uin="[object Map]",hin="[object Number]",min="[object Object]",pin="[object RegExp]",fin="[object Set]",xin="[object String]",gin=Array.isArray,Qut=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,Jut=Object.assign,yin=Object.prototype.toString.call.bind(Object.prototype.toString);function vin(s){var t=s.areArraysEqual,n=s.areDatesEqual,r=s.areMapsEqual,a=s.areObjectsEqual,i=s.arePrimitiveWrappersEqual,l=s.areRegExpsEqual,o=s.areSetsEqual,c=s.areTypedArraysEqual;return function(u,h,m){if(u===h)return!0;if(u==null||h==null||typeof u!="object"||typeof h!="object")return u!==u&&h!==h;var p=u.constructor;if(p!==h.constructor)return!1;if(p===Object)return a(u,h,m);if(gin(u))return t(u,h,m);if(Qut!=null&&Qut(u))return c(u,h,m);if(p===Date)return n(u,h,m);if(p===RegExp)return l(u,h,m);if(p===Map)return r(u,h,m);if(p===Set)return o(u,h,m);var x=yin(u);return x===din?n(u,h,m):x===pin?l(u,h,m):x===uin?r(u,h,m):x===fin?o(u,h,m):x===min?typeof u.then!="function"&&typeof h.then!="function"&&a(u,h,m):x===lin?a(u,h,m):x===cin||x===hin||x===xin?i(u,h,m):!1}}function bin(s){var t=s.circular,n=s.createCustomConfig,r=s.strict,a={areArraysEqual:r?UH:sin,areDatesEqual:nin,areMapsEqual:r?Gut(Zut,UH):Zut,areObjectsEqual:r?UH:rin,arePrimitiveWrappersEqual:ain,areRegExpsEqual:iin,areSetsEqual:r?Gut(Xut,UH):Xut,areTypedArraysEqual:r?UH:oin};if(n&&(a=Jut({},a,n(a))),t){var i=Tne(a.areArraysEqual),l=Tne(a.areMapsEqual),o=Tne(a.areObjectsEqual),c=Tne(a.areSetsEqual);a=Jut({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function _in(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function win(s){var t=s.circular,n=s.comparator,r=s.createState,a=s.equals,i=s.strict;if(r)return function(c,d){var u=r(),h=u.cache,m=h===void 0?t?new WeakMap:void 0:h,p=u.meta;return n(c,d,{cache:m,equals:a,meta:p,strict:i})};if(t)return function(c,d){return n(c,d,{cache:new WeakMap,equals:a,meta:void 0,strict:i})};var l={cache:void 0,equals:a,meta:void 0,strict:i};return function(c,d){return n(c,d,l)}}var jin=_6();_6({strict:!0});_6({circular:!0});_6({circular:!0,strict:!0});_6({createInternalComparator:function(){return kq}});_6({strict:!0,createInternalComparator:function(){return kq}});_6({circular:!0,createInternalComparator:function(){return kq}});_6({circular:!0,createInternalComparator:function(){return kq},strict:!0});function _6(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=bin(s),c=vin(o),d=r?r(c):_in(c);return win({circular:n,comparator:c,createState:a,equals:d,strict:l})}function Nin(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function eht(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):Nin(a)};requestAnimationFrame(r)}function L7e(s){"@babel/helpers - typeof";return L7e=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},L7e(s)}function kin(s){return Tin(s)||Ain(s)||Cin(s)||Sin()}function Sin(){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 Cin(s,t){if(s){if(typeof s=="string")return tht(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 tht(s,t)}}function tht(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1?1:b<0?0:b},y=function(b){for(var v=b>1?1:b,k=v,C=0;C<8;++C){var T=h(k)-v,M=p(k);if(Math.abs(T-v)0&&arguments[0]!==void 0?arguments[0]:{},n=t.stiff,r=n===void 0?100:n,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(u,h,m){var p=-(u-h)*r,x=m*i,y=m+(p-x)*o/1e3,g=m*o/1e3+u;return Math.abs(g-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 ion(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 DPe(s){return don(s)||con(s)||lon(s)||oon()}function oon(){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 lon(s,t){if(s){if(typeof s=="string")return O7e(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 O7e(s,t)}}function con(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function don(s){if(Array.isArray(s))return O7e(s)}function O7e(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 R5e(s){return R5e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},R5e(s)}var MN=function(s){fon(n,s);var t=xon(n);function n(r,a){var i;uon(this,n),i=t.call(this,r,a);var l=i.props,o=l.isActive,c=l.attributeName,d=l.from,u=l.to,h=l.steps,m=l.children,p=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(B7e(i)),i.changeStyle=i.changeStyle.bind(B7e(i)),!o||p<=0)return i.state={style:{}},typeof m=="function"&&(i.state={style:u}),z7e(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof m=="function")return i.state={style:d},z7e(i);i.state={style:c?VG({},c,d):d}}else i.state={style:{}};return i}return mon(n,[{key:"componentDidMount",value:function(){var a=this.props,i=a.isActive,l=a.canBegin;this.mounted=!0,!(!i||!l)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(a){var i=this.props,l=i.isActive,o=i.canBegin,c=i.attributeName,d=i.shouldReAnimate,u=i.to,h=i.from,m=this.state.style;if(o){if(!l){var p={style:c?VG({},c,u):u};this.state&&m&&(c&&m[c]!==u||!c&&m!==u)&&this.setState(p);return}if(!(jin(a.to,u)&&a.canBegin&&a.isActive)){var x=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var y=x||d?h:a.to;if(this.state&&m){var g={style:c?VG({},c,y):y};(c&&m[c]!==y||!c&&m!==y)&&this.setState(g)}this.runAnimation(j2(j2({},this.props),{},{from:y,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var a=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),a&&a()}},{key:"handleStyleChange",value:function(a){this.changeStyle(a)}},{key:"changeStyle",value:function(a){this.mounted&&this.setState({style:a})}},{key:"runJSAnimation",value:function(a){var i=this,l=a.from,o=a.to,c=a.duration,d=a.easing,u=a.begin,h=a.onAnimationEnd,m=a.onAnimationStart,p=non(l,o,Gin(d),c,this.changeStyle),x=function(){i.stopJSAnimation=p()};this.manager.start([m,u,x,c,h])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],u=d.style,h=d.duration,m=h===void 0?0:h,p=function(y,g,b){if(b===0)return y;var v=g.duration,k=g.easing,C=k===void 0?"ease":k,T=g.style,M=g.properties,P=g.onAnimationEnd,L=b>0?l[b-1]:g,I=M||Object.keys(T);if(typeof C=="function"||C==="spring")return[].concat(DPe(y),[i.runJSAnimation.bind(i,{from:L.style,to:T,duration:v,easing:C}),v]);var O=rht(I,v,C),$=j2(j2(j2({},L.style),T),{},{transition:O});return[].concat(DPe(y),[$,v,P]).filter(Iin)};return this.manager.start([c].concat(DPe(l.reduce(p,[u,Math.max(m,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=Ein());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,u=a.onAnimationStart,h=a.onAnimationEnd,m=a.steps,p=a.children,x=this.manager;if(this.unSubscribe=x.subscribe(this.handleStyleChange),typeof d=="function"||typeof p=="function"||d==="spring"){this.runJSAnimation(a);return}if(m.length>1){this.runStepAnimation(a);return}var y=o?VG({},o,c):c,g=rht(Object.keys(y),l,d);x.start([u,i,j2(j2({},y),{},{transition:g}),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=aon(a,ron),d=j.Children.count(i),u=this.state.style;if(typeof i=="function")return i(u);if(!o||d===0||l<=0)return i;var h=function(p){var x=p.props,y=x.style,g=y===void 0?{}:y,b=x.className,v=j.cloneElement(p,j2(j2({},c),{},{style:j2(j2({},g),u),className:b}));return v};return d===1?h(j.Children.only(i)):Lt.createElement("div",null,j.Children.map(i,function(m){return h(m)}))}}]),n}(j.PureComponent);MN.displayName="Animate";MN.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};MN.propTypes={from:Nu.oneOfType([Nu.object,Nu.string]),to:Nu.oneOfType([Nu.object,Nu.string]),attributeName:Nu.string,duration:Nu.number,begin:Nu.number,easing:Nu.oneOfType([Nu.string,Nu.func]),steps:Nu.arrayOf(Nu.shape({duration:Nu.number.isRequired,style:Nu.object.isRequired,easing:Nu.oneOfType([Nu.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),Nu.func]),properties:Nu.arrayOf("string"),onAnimationEnd:Nu.func})),children:Nu.oneOfType([Nu.node,Nu.func]),isActive:Nu.bool,canBegin:Nu.bool,onAnimationEnd:Nu.func,shouldReAnimate:Nu.bool,onAnimationStart:Nu.func,onAnimationReStart:Nu.func};function YZ(s){"@babel/helpers - typeof";return YZ=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},YZ(s)}function D5e(){return D5e=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0?1:-1,c=r>=0?1:-1,d=a>=0&&r>=0||a<0&&r<0?1:0,u;if(l>0&&i instanceof Array){for(var h=[0,0,0,0],m=0,p=4;ml?l:i[m];u="M".concat(t,",").concat(n+o*h[0]),h[0]>0&&(u+="A ".concat(h[0],",").concat(h[0],",0,0,").concat(d,",").concat(t+c*h[0],",").concat(n)),u+="L ".concat(t+r-c*h[1],",").concat(n),h[1]>0&&(u+="A ".concat(h[1],",").concat(h[1],",0,0,").concat(d,`, `).concat(t+r,",").concat(n+o*h[1])),u+="L ".concat(t+r,",").concat(n+a-o*h[2]),h[2]>0&&(u+="A ".concat(h[2],",").concat(h[2],",0,0,").concat(d,`, `).concat(t+r-c*h[2],",").concat(n+a)),u+="L ".concat(t+c*h[3],",").concat(n+a),h[3]>0&&(u+="A ".concat(h[3],",").concat(h[3],",0,0,").concat(d,`, `).concat(t,",").concat(n+a-o*h[3])),u+="Z"}else if(l>0&&i===+i&&i>0){var x=Math.min(l,i);u="M ".concat(t,",").concat(n+o*x,` A `).concat(x,",").concat(x,",0,0,").concat(d,",").concat(t+c*x,",").concat(n,` L `).concat(t+r-c*x,",").concat(n,` A `).concat(x,",").concat(x,",0,0,").concat(d,",").concat(t+r,",").concat(n+o*x,` L `).concat(t+r,",").concat(n+a-o*x,` A `).concat(x,",").concat(x,",0,0,").concat(d,",").concat(t+r-c*x,",").concat(n+a,` L `).concat(t+c*x,",").concat(n+a,` A `).concat(x,",").concat(x,",0,0,").concat(d,",").concat(t,",").concat(n+a-o*x," Z")}else u="M ".concat(t,",").concat(n," h ").concat(r," v ").concat(a," h ").concat(-r," Z");return u},Son=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},Con={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},sWe=function(t){var n=hht(hht({},Con),t),r=j.useRef(),a=j.useState(-1),i=yon(a,2),l=i[0],o=i[1];j.useEffect(function(){if(r.current&&r.current.getTotalLength)try{var C=r.current.getTotalLength();C&&o(C)}catch{}},[]);var c=n.x,d=n.y,u=n.width,h=n.height,m=n.radius,p=n.className,x=n.animationEasing,y=n.animationDuration,g=n.animationBegin,b=n.isAnimationActive,v=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var k=Il("recharts-rectangle",p);return v?Lt.createElement(MN,{canBegin:l>0,from:{width:u,height:h,x:c,y:d},to:{width:u,height:h,x:c,y:d},duration:y,animationEasing:x,isActive:v},function(C){var T=C.width,M=C.height,P=C.x,L=C.y;return Lt.createElement(MN,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:g,duration:y,isActive:b,easing:x},Lt.createElement("path",D5e({},bo(n,!0),{className:k,d:mht(P,L,T,M,m),ref:r})))}):Lt.createElement("path",D5e({},bo(n,!0),{className:k,d:mht(c,d,u,h,m)}))},Aon=["points","className","baseLinePoints","connectNulls"];function x9(){return x9=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function 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 pht(s){return Ion(s)||Pon(s)||Lon(s)||Mon()}function Mon(){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 Lon(s,t){if(s){if(typeof s=="string")return $7e(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 $7e(s,t)}}function Pon(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Ion(s){if(Array.isArray(s))return $7e(s)}function $7e(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){fht(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),fht(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},nY=function(t,n){var r=Ron(t);n&&(r=[r.reduce(function(i,l){return[].concat(pht(i),pht(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},Don=function(t,n,r){var a=nY(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(nY(n.reverse(),r).slice(1))},Oon=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=Ton(t,Aon);if(!n||!n.length)return null;var o=Il("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=Don(n,a,i);return Lt.createElement("g",{className:o},Lt.createElement("path",x9({},bo(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Lt.createElement("path",x9({},bo(l,!0),{fill:"none",d:nY(n,i)})):null,c?Lt.createElement("path",x9({},bo(l,!0),{fill:"none",d:nY(a,i)})):null)}var u=nY(n,i);return Lt.createElement("path",x9({},bo(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function U7e(){return U7e=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 Von(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 Hon=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},Gon=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.top,o=l===void 0?0:l,c=t.left,d=c===void 0?0:c,u=t.width,h=u===void 0?0:u,m=t.height,p=m===void 0?0:m,x=t.className,y=qon(t,Fon),g=zon({x:r,y:i,top:o,left:d,width:h,height:p},y);return!La(r)||!La(i)||!La(h)||!La(p)||!La(o)||!La(d)?null:Lt.createElement("path",q7e({},bo(g,!0),{className:Il("recharts-cross",x),d:Hon(r,i,h,p,o,d)}))},Won=dAe,Kon=uIt,Yon=uS;function Zon(s,t){return s&&s.length?Won(s,Yon(t),Kon):void 0}var Xon=Zon;const Qon=sd(Xon);var Jon=dAe,eln=uS,tln=hIt;function sln(s,t){return s&&s.length?Jon(s,eln(t),tln):void 0}var nln=sln;const rln=sd(nln);var aln=["cx","cy","angle","ticks","axisLine"],iln=["ticks","tick","angle","tickFormatter","stroke"];function H$(s){"@babel/helpers - typeof";return H$=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},H$(s)}function rY(){return rY=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 oln(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 lln(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function vht(s,t){for(var n=0;nwht?l=a==="outer"?"start":"end":i<-wht?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=mM(mM({},bo(this.props,!1)),{},{fill:"none"},bo(o,!1));if(c==="circle")return Lt.createElement(XJ,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 qh(a,i,l,m.coordinate)});return Lt.createElement(Oon,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=bo(this.props,!1),h=bo(l,!1),m=mM(mM({},u),{},{fill:"none"},bo(o,!1)),p=i.map(function(x,y){var g=r.getTickLineCoord(x),b=r.getTickTextAnchor(x),v=mM(mM(mM({textAnchor:b},u),{},{stroke:"none",fill:d},h),{},{index:y,payload:x,x:g.x2,y:g.y2});return Lt.createElement(qc,WI({className:Il("recharts-polar-angle-axis-tick",BIt(l)),key:"tick-".concat(x.coordinate)},UD(r.props,x,y)),o&&Lt.createElement("line",WI({className:"recharts-polar-angle-axis-tick-line"},m,g)),l&&t.renderTickItem(l,v,c?c(x.value,y):x.value))});return Lt.createElement(qc,{className:"recharts-polar-angle-axis-ticks"},p)}},{key:"render",value:function(){var r=this.props,a=r.ticks,i=r.radius,l=r.axisLine;return i<=0||!a||!a.length?null:Lt.createElement(qc,{className:Il("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return Lt.isValidElement(r)?l=Lt.cloneElement(r,a):nl(r)?l=r(a):l=Lt.createElement(qD,WI({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(j.PureComponent);xAe(gAe,"displayName","PolarAngleAxis");xAe(gAe,"axisType","angleAxis");xAe(gAe,"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 jln=oPt,Nln=jln(Object.getPrototypeOf,Object),kln=Nln,Sln=nC,Cln=kln,Aln=rC,Tln="[object Object]",Eln=Function.prototype,Mln=Object.prototype,a8t=Eln.toString,Lln=Mln.hasOwnProperty,Pln=a8t.call(Object);function Iln(s){if(!Aln(s)||Sln(s)!=Tln)return!1;var t=Cln(s);if(t===null)return!0;var n=Lln.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&a8t.call(n)==Pln}var Rln=Iln;const Dln=sd(Rln);var Oln=nC,Fln=rC,zln="[object Boolean]";function Bln(s){return s===!0||s===!1||Fln(s)&&Oln(s)==zln}var $ln=Bln;const Uln=sd($ln);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 z5e(){return z5e=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:x,isActive:b},function(k){var C=k.upperWidth,T=k.lowerWidth,M=k.height,P=k.x,L=k.y;return Lt.createElement(MN,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:g,duration:y,easing:x},Lt.createElement("path",z5e({},bo(n,!0),{className:v,d:Sht(P,L,C,T,M),ref:r})))}):Lt.createElement("g",null,Lt.createElement("path",z5e({},bo(n,!0),{className:v,d:Sht(c,d,u,h,m)})))},Jln=["option","shapeType","propTransformer","activeClassName","isActive"];function QZ(s){"@babel/helpers - typeof";return QZ=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},QZ(s)}function ecn(s,t){if(s==null)return{};var n=tcn(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 tcn(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 Cht(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 B5e(s){for(var t=1;t0?Y_(k,"paddingAngle",0):0;if(T){var P=rg(T.endAngle-T.startAngle,k.endAngle-k.startAngle),L=Fh(Fh({},k),{},{startAngle:v+M,endAngle:v+P(y)+M});g.push(L),v=L.endAngle}else{var I=k.endAngle,O=k.startAngle,$=rg(0,I-O),q=$(y),W=Fh(Fh({},k),{},{startAngle:v+M,endAngle:v+q+M});g.push(W),v=W.endAngle}}),Lt.createElement(qc,null,r.renderSectorsStatically(g))})}},{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||!VD(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var r=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,u=a.cy,h=a.innerRadius,m=a.outerRadius,p=a.isAnimationActive,x=this.state.isAnimationFinished;if(i||!l||!l.length||!La(d)||!La(u)||!La(h)||!La(m))return null;var y=Il("recharts-pie",o);return Lt.createElement(qc,{tabIndex:this.props.rootTabIndex,className:y,ref:function(b){r.pieRef=b}},this.renderSectors(),c&&this.renderLabels(l),Qg.renderCallByParent(this.props,null,!1),(!p||x)&&$5.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return a.prevIsAnimationActive!==r.isAnimationActive?{prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:[],isAnimationFinished:!0}:r.isAnimationActive&&r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:r.sectors!==a.curSectors?{curSectors:r.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(r,a){return r>a?"start":r=360?v:v-1)*c,C=g-v*p-k,T=a.reduce(function(L,I){var O=Zf(I,b,0);return L+(La(O)?O:0)},0),M;if(T>0){var P;M=a.map(function(L,I){var O=Zf(L,b,0),$=Zf(L,u,I),q=(La(O)?O:0)/T,W;I?W=P.endAngle+Zv(y)*c*(O!==0?1:0):W=l;var G=W+Zv(y)*((O!==0?p:0)+q*C),K=(W+G)/2,ee=(x.innerRadius+x.outerRadius)/2,J=[{name:$,value:O,payload:L,dataKey:b,type:m}],le=qh(x.cx,x.cy,ee,K);return P=Fh(Fh(Fh({percent:q,cornerRadius:i,name:$,tooltipPayload:J,midAngle:K,middleRadius:ee,tooltipPosition:le},L),x),{},{value:Zf(L,b),startAngle:W,endAngle:G,payload:L,paddingAngle:Zv(y)*c}),P})}return Fh(Fh({},x),{},{sectors:M,data:a})});var wcn=Math.ceil,jcn=Math.max;function Ncn(s,t,n,r){for(var a=-1,i=jcn(wcn((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var kcn=Ncn,Scn=SPt,Mht=1/0,Ccn=17976931348623157e292;function Acn(s){if(!s)return s===0?s:0;if(s=Scn(s),s===Mht||s===-Mht){var t=s<0?-1:1;return t*Ccn}return s===s?s:0}var c8t=Acn,Tcn=kcn,Ecn=nAe,OPe=c8t;function Mcn(s){return function(t,n,r){return r&&typeof r!="number"&&Ecn(t,n,r)&&(n=r=void 0),t=OPe(t),n===void 0?(n=t,t=0):n=OPe(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),p_(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()}),p_(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),p_(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),p_(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),p_(r,"handleSlideDragStart",function(a){var i=Dht(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 Hcn(t,s),$cn(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(r){var a=r.startX,i=r.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,u=d.length-1,h=Math.min(a,i),m=Math.max(a,i),p=t.getIndexInRange(l,h),x=t.getIndexInRange(l,m);return{startIndex:p-p%c,endIndex:x===u?u:x-x%c}}},{key:"getTextOfTick",value:function(r){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=Zf(i[r],o,r);return nl(l)?l(c,r):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(r){var a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,u=c.width,h=c.travellerWidth,m=c.startIndex,p=c.endIndex,x=c.onChange,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 g=this.getIndex({startX:l+y,endX:o+y});(g.startIndex!==m||g.endIndex!==p)&&x&&x(g),this.setState({startX:l+y,endX:o+y,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=Dht(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:r,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(r){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],u=this.props,h=u.x,m=u.width,p=u.travellerWidth,x=u.onChange,y=u.gap,g=u.data,b={startX:this.state.startX,endX:this.state.endX},v=r.pageX-i;v>0?v=Math.min(v,h+m-p-d):v<0&&(v=Math.max(v,h-d)),b[l]=d+v;var k=this.getIndex(b),C=k.startIndex,T=k.endIndex,M=function(){var L=g.length-1;return l==="startX"&&(o>c?C%y===0:T%y===0)||oc?T%y===0:C%y===0)||o>c&&T===L};this.setState(p_(p_({},l,d+v),"brushMoveStartX",r.pageX),function(){x&&M()&&x(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 p=o[m];a==="startX"&&p>=d||a==="endX"&&p<=c||this.setState(p_({},a,p),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.fill,d=r.stroke;return Lt.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.data,d=r.children,u=r.padding,h=j.Children.only(d);return h?Lt.cloneElement(h,{x:a,y:i,width:l,height:o,margin:u,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(r,a){var i,l,o=this,c=this.props,d=c.y,u=c.travellerWidth,h=c.height,m=c.traveller,p=c.ariaLabel,x=c.data,y=c.startIndex,g=c.endIndex,b=Math.max(r,this.props.x),v=FPe(FPe({},bo(this.props,!1)),{},{x:b,y:d,width:u,height:h}),k=p||"Min value: ".concat((i=x[y])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=x[g])===null||l===void 0?void 0:l.name);return Lt.createElement(qc,{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,v))}},{key:"renderSlide",value:function(r,a){var i=this.props,l=i.y,o=i.height,c=i.stroke,d=i.travellerWidth,u=Math.min(r,a)+d,h=Math.max(Math.abs(a-r)-d,0);return Lt.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:u,y:l,width:h,height:o})}},{key:"renderText",value:function(){var r=this.props,a=r.startIndex,i=r.endIndex,l=r.y,o=r.height,c=r.travellerWidth,d=r.stroke,u=this.state,h=u.startX,m=u.endX,p=5,x={pointerEvents:"none",fill:d};return Lt.createElement(qc,{className:"recharts-brush-texts"},Lt.createElement(qD,q5e({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,m)-p,y:l+o/2},x),this.getTextOfTick(a)),Lt.createElement(qD,q5e({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,m)+c+p,y:l+o/2},x),this.getTextOfTick(i)))}},{key:"render",value:function(){var r=this.props,a=r.data,i=r.className,l=r.children,o=r.x,c=r.y,d=r.width,u=r.height,h=r.alwaysShowText,m=this.state,p=m.startX,x=m.endX,y=m.isTextActive,g=m.isSlideMoving,b=m.isTravellerMoving,v=m.isTravellerFocused;if(!a||!a.length||!La(o)||!La(c)||!La(d)||!La(u)||d<=0||u<=0)return null;var k=Il("recharts-brush",i),C=Lt.Children.count(l)===1,T=zcn("userSelect","none");return Lt.createElement(qc,{className:k,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:T},this.renderBackground(),C&&this.renderPanorama(),this.renderSlide(p,x),this.renderTravellerLayer(p,"startX"),this.renderTravellerLayer(x,"endX"),(y||g||b||v||h)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(r){var a=r.x,i=r.y,l=r.width,o=r.height,c=r.stroke,d=Math.floor(i+o/2)-1;return Lt.createElement(Lt.Fragment,null,Lt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),Lt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),Lt.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 Lt.isValidElement(r)?i=Lt.cloneElement(r,a):nl(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 FPe({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?Wcn({data:i,width:l,x:o,travellerWidth:c,startIndex:u,endIndex:h}):{scale:null,scaleValues:null});if(a.scale&&(l!==a.prevWidth||o!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([o,o+l-c]);var m=a.scale.domain().map(function(p){return a.scale(p)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(r.startIndex),endX:a.scale(r.endIndex),scaleValues:m}}return null}},{key:"getIndexInRange",value:function(r,a){for(var i=r.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);r[c]>a?o=c:l=c}return a>=r[o]?o:l}}])}(j.PureComponent);p_(Y$,"displayName","Brush");p_(Y$,"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 Kcn=AGe;function Ycn(s,t){var n;return Kcn(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var Zcn=Ycn,Xcn=JLt,Qcn=uS,Jcn=Zcn,edn=Db,tdn=nAe;function sdn(s,t,n){var r=edn(s)?Xcn:Jcn;return n&&tdn(s,t,n)&&(t=void 0),r(s,Qcn(t))}var ndn=sdn;const rdn=sd(ndn);var U5=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},Oht=_Pt;function adn(s,t,n){t=="__proto__"&&Oht?Oht(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var idn=adn,odn=idn,ldn=vPt,cdn=uS;function ddn(s,t){var n={};return t=cdn(t),ldn(s,function(r,a,i){odn(n,a,t(r,a,i))}),n}var udn=ddn;const hdn=sd(udn);function mdn(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 Edn(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 Mdn(s,t){var n=s.x,r=s.y,a=Tdn(s,kdn),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 qH(qH(qH(qH(qH({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:m,name:t.name,radius:t.radius})}function zht(s){return Lt.createElement(i8t,K7e({shapeType:"rectangle",propTransformer:Mdn,activeClassName:"recharts-active-bar"},s))}var Ldn=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=La(r)||pqs(r);return i?t(r,a):(i||GD(),n)}},Pdn=["value","background"],p8t;function Z$(s){"@babel/helpers - typeof";return Z$=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},Z$(s)}function Idn(s,t){if(s==null)return{};var n=Rdn(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 Rdn(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 H5e(){return H5e=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(K)0&&Math.abs(G)0&&(W=Math.min((je||0)-(G[xe-1]||0),W))}),Number.isFinite(W)){var K=W/q,ee=y.layout==="vertical"?r.height:r.width;if(y.padding==="gap"&&(P=K*ee/2),y.padding==="no-gap"){var J=Xv(t.barCategoryGap,K*ee),le=K*ee/2;P=le-J-(le-J)/ee*J}}}a==="xAxis"?L=[r.left+(k.left||0)+(P||0),r.left+r.width-(k.right||0)-(P||0)]:a==="yAxis"?L=c==="horizontal"?[r.top+r.height-(k.bottom||0),r.top+(k.top||0)]:[r.top+(k.top||0)+(P||0),r.top+r.height-(k.bottom||0)-(P||0)]:L=y.range,T&&(L=[L[1],L[0]]);var ue=PIt(y,i,m),oe=ue.scale,ie=ue.realScaleType;oe.domain(b).range(L),IIt(oe);var de=RIt(oe,X2(X2({},y),{},{realScaleType:ie}));a==="xAxis"?($=g==="top"&&!C||g==="bottom"&&C,I=r.left,O=h[M]-$*y.height):a==="yAxis"&&($=g==="left"&&!C||g==="right"&&C,I=h[M]-$*y.width,O=r.top);var we=X2(X2(X2({},y),de),{},{realScaleType:ie,x:I,y:O,scale:oe,width:a==="xAxis"?r.width:y.width,height:a==="yAxis"?r.height:y.height});return we.bandSize=E5e(we,de),!y.hide&&a==="xAxis"?h[M]+=($?-1:1)*we.height:y.hide||(h[M]+=($?-1:1)*we.width),X2(X2({},p),{},bAe({},x,we))},{})},y8t=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)}},Gdn=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return y8t({x:n,y:r},{x:a,y:i})},v8t=function(){function s(t){qdn(this,s),this.scale=t}return Vdn(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)}}])}();bAe(v8t,"EPS",1e-4);var rWe=function(t){var n=Object.keys(t).reduce(function(r,a){return X2(X2({},r),{},bAe({},a,v8t.create(t[a])))},{});return X2(X2({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return hdn(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return m8t(a,function(i,l){return n[l].isInRange(i)})}})};function Wdn(s){return(s%180+180)%180}var Kdn=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=Wdn(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var Jdn=Qdn,eun=c8t;function tun(s){var t=eun(s),n=t%1;return t===t?n?t-n:t:0}var sun=tun,nun=mPt,run=uS,aun=sun,iun=Math.max;function oun(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:aun(n);return a<0&&(a=iun(r+a,0)),nun(s,run(t),a)}var lun=oun,cun=Jdn,dun=lun,uun=cun(dun),hun=uun;const mun=sd(hun);var pun=yUs(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("")}),aWe=j.createContext(void 0),iWe=j.createContext(void 0),b8t=j.createContext(void 0),_8t=j.createContext({}),w8t=j.createContext(void 0),j8t=j.createContext(0),N8t=j.createContext(0),Vht=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=pun(i);return Lt.createElement(aWe.Provider,{value:r},Lt.createElement(iWe.Provider,{value:a},Lt.createElement(_8t.Provider,{value:i},Lt.createElement(b8t.Provider,{value:u},Lt.createElement(w8t.Provider,{value:l},Lt.createElement(j8t.Provider,{value:d},Lt.createElement(N8t.Provider,{value:c},o)))))))},fun=function(){return j.useContext(w8t)},k8t=function(t){var n=j.useContext(aWe);n==null&&GD();var r=n[t];return r==null&&GD(),r},xun=function(){var t=j.useContext(aWe);return EA(t)},gun=function(){var t=j.useContext(iWe),n=mun(t,function(r){return m8t(r.domain,Number.isFinite)});return n||EA(t)},S8t=function(t){var n=j.useContext(iWe);n==null&&GD();var r=n[t];return r==null&&GD(),r},yun=function(){var t=j.useContext(b8t);return t},vun=function(){return j.useContext(_8t)},oWe=function(){return j.useContext(N8t)},lWe=function(){return j.useContext(j8t)};function X$(s){"@babel/helpers - typeof";return X$=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},X$(s)}function bun(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function _un(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 shn(s,t){return P8t(s,t+1)}function nhn(s,t,n,r,a){for(var i=(r||[]).slice(),l=t.start,o=t.end,c=0,d=1,u=l,h=function(){var x=r==null?void 0:r[c];if(x===void 0)return{v:P8t(r,d)};var y=c,g,b=function(){return g===void 0&&(g=n(x,y)),g},v=x.coordinate,k=c===0||Z5e(s,v,b,u,o);k||(c=0,u=l,d+=1),k&&(u=v+s*(b()/2+a),c+=d)},m;d<=i.length;)if(m=h(),m)return m.v;return[]}function nX(s){"@babel/helpers - typeof";return nX=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},nX(s)}function Qht(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function Uy(s){for(var t=1;t0?p.coordinate-g*s:p.coordinate})}else i[m]=p=Uy(Uy({},p),{},{tickCoord:p.coordinate});var b=Z5e(s,p.tickCoord,y,o,c);b&&(c=p.tickCoord-s*(y()/2+a),i[m]=Uy(Uy({},p),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function lhn(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=Uy(Uy({},u),{},{tickCoord:m>0?u.coordinate-m*s:u.coordinate});var p=Z5e(s,u.tickCoord,function(){return h},c,d);p&&(d=u.tickCoord-s*(h/2+a),l[o-1]=Uy(Uy({},u),{},{isShow:!0}))}for(var x=i?o-1:o,y=function(v){var k=l[v],C,T=function(){return C===void 0&&(C=n(k,v)),C};if(v===0){var M=s*(k.coordinate-s*T()/2-c);l[v]=k=Uy(Uy({},k),{},{tickCoord:M<0?k.coordinate-M*s:k.coordinate})}else l[v]=k=Uy(Uy({},k),{},{tickCoord:k.coordinate});var P=Z5e(s,k.tickCoord,T,c,d);P&&(c=k.tickCoord+s*(T()/2+a),l[v]=Uy(Uy({},k),{},{isShow:!0}))},g=0;g=2?Zv(a[1].coordinate-a[0].coordinate):1,b=thn(i,g,p);return c==="equidistantPreserveStart"?nhn(g,b,y,a,l):(c==="preserveStart"||c==="preserveStartEnd"?m=lhn(g,b,y,a,l,c==="preserveStartEnd"):m=ohn(g,b,y,a,l),m.filter(function(v){return v.isShow}))}var chn=["viewBox"],dhn=["viewBox"],uhn=["ticks"];function eU(s){"@babel/helpers - typeof";return eU=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},eU(s)}function y9(){return y9=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 hhn(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 mhn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function emt(s,t){for(var n=0;n0?c(this.props):c(p)),l<=0||o<=0||!x||!x.length?null:Lt.createElement(qc,{className:Il("recharts-cartesian-axis",d),ref:function(g){r.layerReference=g}},i&&this.renderAxisLine(),this.renderTicks(x,this.state.fontSize,this.state.letterSpacing),Qg.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=Il(a.className,"recharts-cartesian-axis-tick-value");return Lt.isValidElement(r)?l=Lt.cloneElement(r,qx(qx({},a),{},{className:o})):nl(r)?l=r(qx(qx({},a),{},{className:o})):l=Lt.createElement(qD,y9({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(j.Component);hWe(Sq,"displayName","CartesianAxis");hWe(Sq,"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 bhn=["x1","y1","x2","y2","key"],_hn=["offset"];function WD(s){"@babel/helpers - typeof";return WD=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},WD(s)}function tmt(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 Gy(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function khn(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 Shn=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 Lt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function D8t(s,t){var n;if(Lt.isValidElement(s))n=Lt.cloneElement(s,t);else if(nl(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=smt(t,bhn),d=bo(c,!1);d.offset;var u=smt(d,_hn);n=Lt.createElement("line",h8({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function Chn(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=Gy(Gy({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return D8t(a,d)});return Lt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function Ahn(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=Gy(Gy({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return D8t(a,d)});return Lt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function Thn(s){var t=s.horizontalFill,n=s.fillOpacity,r=s.x,a=s.y,i=s.width,l=s.height,o=s.horizontalPoints,c=s.horizontal,d=c===void 0?!0:c;if(!d||!t||!t.length)return null;var u=o.map(function(m){return Math.round(m+a-a)}).sort(function(m,p){return m-p});a!==u[0]&&u.unshift(0);var h=u.map(function(m,p){var x=!u[p+1],y=x?a+l-m:u[p+1]-m;if(y<=0)return null;var g=p%t.length;return Lt.createElement("rect",{key:"react-".concat(p),y:m,x:r,height:y,width:i,stroke:"none",fill:t[g],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return Lt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function Ehn(s){var t=s.vertical,n=t===void 0?!0:t,r=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!n||!r||!r.length)return null;var u=d.map(function(m){return Math.round(m+i-i)}).sort(function(m,p){return m-p});i!==u[0]&&u.unshift(0);var h=u.map(function(m,p){var x=!u[p+1],y=x?i+o-m:u[p+1]-m;if(y<=0)return null;var g=p%r.length;return Lt.createElement("rect",{key:"react-".concat(p),x:m,y:l,width:y,height:c,stroke:"none",fill:r[g],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Lt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var Mhn=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return LIt(uWe(Gy(Gy(Gy({},Sq.defaultProps),r),{},{ticks:u3(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},Lhn=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return LIt(uWe(Gy(Gy(Gy({},Sq.defaultProps),r),{},{ticks:u3(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},e7={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function KD(s){var t,n,r,a,i,l,o=oWe(),c=lWe(),d=vun(),u=Gy(Gy({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:e7.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:e7.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:e7.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:e7.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:e7.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:e7.verticalFill,x:La(s.x)?s.x:d.left,y:La(s.y)?s.y:d.top,width:La(s.width)?s.width:d.width,height:La(s.height)?s.height:d.height}),h=u.x,m=u.y,p=u.width,x=u.height,y=u.syncWithTicks,g=u.horizontalValues,b=u.verticalValues,v=xun(),k=gun();if(!La(p)||p<=0||!La(x)||x<=0||!La(h)||h!==+h||!La(m)||m!==+m)return null;var C=u.verticalCoordinatesGenerator||Mhn,T=u.horizontalCoordinatesGenerator||Lhn,M=u.horizontalPoints,P=u.verticalPoints;if((!M||!M.length)&&nl(T)){var L=g&&g.length,I=T({yAxis:k?Gy(Gy({},k),{},{ticks:L?g:k.ticks}):void 0,width:o,height:c,offset:d},L?!0:y);wN(Array.isArray(I),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(WD(I),"]")),Array.isArray(I)&&(M=I)}if((!P||!P.length)&&nl(C)){var O=b&&b.length,$=C({xAxis:v?Gy(Gy({},v),{},{ticks:O?b:v.ticks}):void 0,width:o,height:c,offset:d},O?!0:y);wN(Array.isArray($),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(WD($),"]")),Array.isArray($)&&(P=$)}return Lt.createElement("g",{className:"recharts-cartesian-grid"},Lt.createElement(Shn,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),Lt.createElement(Chn,h8({},u,{offset:d,horizontalPoints:M,xAxis:v,yAxis:k})),Lt.createElement(Ahn,h8({},u,{offset:d,verticalPoints:P,xAxis:v,yAxis:k})),Lt.createElement(Thn,h8({},u,{horizontalPoints:M})),Lt.createElement(Ehn,h8({},u,{verticalPoints:P})))}KD.displayName="CartesianGrid";var Phn=["type","layout","connectNulls","ref"],Ihn=["key"];function tU(s){"@babel/helpers - typeof";return tU=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},tU(s)}function nmt(s,t){if(s==null)return{};var n=Rhn(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 Rhn(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 aY(){return aY=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);nh){p=[].concat(t7(c.slice(0,x)),[h-y]);break}var g=p.length%2===0?[0,m]:[m];return[].concat(t7(t.repeat(c,u)),t7(p),g).map(function(b){return"".concat(b,"px")}).join(", ")}),Q2(n,"id",AO("recharts-line-")),Q2(n,"pathRef",function(l){n.mainCurve=l}),Q2(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),Q2(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return Hhn(t,s),$hn(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=Z_(u,ZJ);if(!h)return null;var m=function(y,g){return{x:y.x,y:y.y,value:y.value,errorVal:Zf(y.payload,g)}},p={clipPath:r?"url(#clipPath-".concat(a,")"):null};return Lt.createElement(qc,p,h.map(function(x){return Lt.cloneElement(x,{key:"bar-".concat(x.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:m})}))}},{key:"renderDots",value:function(r,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,u=o.dataKey,h=bo(this.props,!1),m=bo(c,!0),p=d.map(function(y,g){var b=d_(d_(d_({key:"dot-".concat(g),r:3},h),m),{},{index:g,cx:y.x,cy:y.y,value:y.value,dataKey:u,payload:y.payload,points:d});return t.renderDotItem(c,b)}),x={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Lt.createElement(qc,aY({className:"recharts-line-dots",key:"dots"},x),p)}},{key:"renderCurveStatically",value:function(r,a,i,l){var o=this.props,c=o.type,d=o.layout,u=o.connectNulls;o.ref;var h=nmt(o,Phn),m=d_(d_(d_({},bo(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 Lt.createElement(cD,aY({},m,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(r,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,u=l.animationBegin,h=l.animationDuration,m=l.animationEasing,p=l.animationId,x=l.animateNewValues,y=l.width,g=l.height,b=this.state,v=b.prevPoints,k=b.totalLength;return Lt.createElement(MN,{begin:u,duration:h,isActive:d,easing:m,from:{t:0},to:{t:1},key:"line-".concat(p),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(C){var T=C.t;if(v){var M=v.length/o.length,P=o.map(function(q,W){var G=Math.floor(W*M);if(v[G]){var K=v[G],ee=rg(K.x,q.x),J=rg(K.y,q.y);return d_(d_({},q),{},{x:ee(T),y:J(T)})}if(x){var le=rg(y*2,q.x),ue=rg(g/2,q.y);return d_(d_({},q),{},{x:le(T),y:ue(T)})}return d_(d_({},q),{},{x:q.x,y:q.y})});return i.renderCurveStatically(P,r,a)}var L=rg(0,k),I=L(T),O;if(c){var $="".concat(c).split(/[,\s]+/gim).map(function(q){return parseFloat(q)});O=i.getStrokeDasharray(I,k,$)}else O=i.generateSimpleStrokeDasharray(k,I);return i.renderCurveStatically(o,r,a,{strokeDasharray:O})})}},{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||!VD(d,l))?this.renderCurveWithAnimation(r,a):this.renderCurveStatically(l,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,u=a.yAxis,h=a.top,m=a.left,p=a.width,x=a.height,y=a.isAnimationActive,g=a.id;if(i||!o||!o.length)return null;var b=this.state.isAnimationFinished,v=o.length===1,k=Il("recharts-line",c),C=d&&d.allowDataOverflow,T=u&&u.allowDataOverflow,M=C||T,P=Al(g)?this.id:g,L=(r=bo(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},I=L.r,O=I===void 0?3:I,$=L.strokeWidth,q=$===void 0?2:$,W=NLt(l)?l:{},G=W.clipDot,K=G===void 0?!0:G,ee=O*2+q;return Lt.createElement(qc,{className:k},C||T?Lt.createElement("defs",null,Lt.createElement("clipPath",{id:"clipPath-".concat(P)},Lt.createElement("rect",{x:C?m:m-p/2,y:T?h:h-x/2,width:C?p:p*2,height:T?x:x*2})),!K&&Lt.createElement("clipPath",{id:"clipPath-dots-".concat(P)},Lt.createElement("rect",{x:m-ee/2,y:h-ee/2,width:p+ee,height:x+ee}))):null,!v&&this.renderCurve(M,P),this.renderErrorBar(M,P),(v||l)&&this.renderDots(M,K,P),(!y||b)&&$5.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(t7(r),[0]):r,l=[],o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Yhn(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 m8(){return m8=Object.assign?Object.assign.bind():function(s){for(var t=1;t0||!VD(u,l)||!VD(h,o))?this.renderAreaWithAnimation(r,a):this.renderAreaStatically(l,o,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.top,u=a.left,h=a.xAxis,m=a.yAxis,p=a.width,x=a.height,y=a.isAnimationActive,g=a.id;if(i||!o||!o.length)return null;var b=this.state.isAnimationFinished,v=o.length===1,k=Il("recharts-area",c),C=h&&h.allowDataOverflow,T=m&&m.allowDataOverflow,M=C||T,P=Al(g)?this.id:g,L=(r=bo(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},I=L.r,O=I===void 0?3:I,$=L.strokeWidth,q=$===void 0?2:$,W=NLt(l)?l:{},G=W.clipDot,K=G===void 0?!0:G,ee=O*2+q;return Lt.createElement(qc,{className:k},C||T?Lt.createElement("defs",null,Lt.createElement("clipPath",{id:"clipPath-".concat(P)},Lt.createElement("rect",{x:C?u:u-p/2,y:T?d:d-x/2,width:C?p:p*2,height:T?x:x*2})),!K&&Lt.createElement("clipPath",{id:"clipPath-dots-".concat(P)},Lt.createElement("rect",{x:u-ee/2,y:d-ee/2,width:p+ee,height:x+ee}))):null,v?null:this.renderArea(M,P),(l||v)&&this.renderDots(M,K,P),(!y||b)&&$5.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curPoints:r.points,curBaseLine:r.baseLine,prevPoints:a.curPoints,prevBaseLine:a.curBaseLine}:r.points!==a.curPoints||r.baseLine!==a.curBaseLine?{curPoints:r.points,curBaseLine:r.baseLine}:null}}])}(j.PureComponent);z8t=Nb;j5(Nb,"displayName","Area");j5(Nb,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!jN.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});j5(Nb,"getBaseValue",function(s,t,n,r){var a=s.layout,i=s.baseValue,l=t.props.baseValue,o=l??i;if(La(o)&&typeof o=="number")return o;var c=a==="horizontal"?r:n,d=c.scale.domain();if(c.type==="number"){var u=Math.max(d[0],d[1]),h=Math.min(d[0],d[1]);return o==="dataMin"?h:o==="dataMax"||u<0?u:Math.max(Math.min(d[0],d[1]),0)}return o==="dataMin"?d[0]:o==="dataMax"?d[1]:d[0]});j5(Nb,"getComposedData",function(s){var t=s.props,n=s.item,r=s.xAxis,a=s.yAxis,i=s.xAxisTicks,l=s.yAxisTicks,o=s.bandSize,c=s.dataKey,d=s.stackedData,u=s.dataStartIndex,h=s.displayedData,m=s.offset,p=t.layout,x=d&&d.length,y=z8t.getBaseValue(t,n,r,a),g=p==="horizontal",b=!1,v=h.map(function(C,T){var M;x?M=d[u+T]:(M=Zf(C,c),Array.isArray(M)?b=!0:M=[y,M]);var P=M[1]==null||x&&Zf(C,c)==null;return g?{x:T5e({axis:r,ticks:i,bandSize:o,entry:C,index:T}),y:P?null:a.scale(M[1]),value:M,payload:C}:{x:P?null:r.scale(M[1]),y:T5e({axis:a,ticks:l,bandSize:o,entry:C,index:T}),value:M,payload:C}}),k;return x||b?k=v.map(function(C){var T=Array.isArray(C.value)?C.value[0]:null;return g?{x:C.x,y:T!=null&&C.y!=null?a.scale(T):null}:{x:T!=null?r.scale(T):null,y:C.y}}):k=g?a.scale(y):r.scale(y),nA({points:v,baseLine:k,layout:p,isRange:b},m)});j5(Nb,"renderDotItem",function(s,t){var n;if(Lt.isValidElement(s))n=Lt.cloneElement(s,t);else if(nl(s))n=s(t);else{var r=Il("recharts-area-dot",typeof s!="boolean"?s.className:""),a=t.key,i=B8t(t,Khn);n=Lt.createElement(XJ,m8({},i,{key:a,className:r}))}return n});function nU(s){"@babel/helpers - typeof";return nU=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},nU(s)}function nmn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function rmn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Vmn(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 Hmn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Gmn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&La(a)&&La(i)?t.slice(a,i+1):[]};function sRt(s){return s==="number"?[0,"auto"]:void 0}var p9e=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=kAe(n,t);return r<0||!i||!i.length||r>=o.length?null:i.reduce(function(c,d){var u,h=(u=d.props.data)!==null&&u!==void 0?u:n;h&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=r&&(h=h.slice(t.dataStartIndex,t.dataEndIndex+1));var m;if(l.dataKey&&!l.allowDuplicatedCategory){var p=h===void 0?o:h;m=t5e(p,l.dataKey,a)}else m=h&&h[r]||o[r];return m?[].concat(iU(c),[OIt(d,m)]):c},[])},mmt=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=rpn(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=Srn(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,m=p9e(t,n,u,h),p=apn(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:m,activeCoordinate:p}}return null},ipn=function(t,n){var r=n.axes,a=n.graphicalItems,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,m=t.stackOffset,p=MIt(u,i);return r.reduce(function(x,y){var g,b=y.type.defaultProps!==void 0?qr(qr({},y.type.defaultProps),y.props):y.props,v=b.type,k=b.dataKey,C=b.allowDataOverflow,T=b.allowDuplicatedCategory,M=b.scale,P=b.ticks,L=b.includeHidden,I=b[l];if(x[I])return x;var O=kAe(t.data,{graphicalItems:a.filter(function(de){var we,je=l in de.props?de.props[l]:(we=de.type.defaultProps)===null||we===void 0?void 0:we[l];return je===I}),dataStartIndex:c,dataEndIndex:d}),$=O.length,q,W,G;Lmn(b.domain,C,v)&&(q=C7e(b.domain,null,C),p&&(v==="number"||M!=="auto")&&(G=tY(O,k,"category")));var K=sRt(v);if(!q||q.length===0){var ee,J=(ee=b.domain)!==null&&ee!==void 0?ee:K;if(k){if(q=tY(O,k,v),v==="category"&&p){var le=xqs(q);T&&le?(W=q,q=U5e(0,$)):T||(q=Put(J,q,y).reduce(function(de,we){return de.indexOf(we)>=0?de:[].concat(iU(de),[we])},[]))}else if(v==="category")T?q=q.filter(function(de){return de!==""&&!Al(de)}):q=Put(J,q,y).reduce(function(de,we){return de.indexOf(we)>=0||we===""||Al(we)?de:[].concat(iU(de),[we])},[]);else if(v==="number"){var ue=Mrn(O,a.filter(function(de){var we,je,xe=l in de.props?de.props[l]:(we=de.type.defaultProps)===null||we===void 0?void 0:we[l],fe="hide"in de.props?de.props.hide:(je=de.type.defaultProps)===null||je===void 0?void 0:je.hide;return xe===I&&(L||!fe)}),k,i,u);ue&&(q=ue)}p&&(v==="number"||M!=="auto")&&(G=tY(O,k,"category"))}else p?q=U5e(0,$):o&&o[I]&&o[I].hasStack&&v==="number"?q=m==="expand"?[0,1]:DIt(o[I].stackGroups,c,d):q=EIt(O,a.filter(function(de){var we=l in de.props?de.props[l]:de.type.defaultProps[l],je="hide"in de.props?de.props.hide:de.type.defaultProps.hide;return we===I&&(L||!je)}),v,u,!0);if(v==="number")q=u9e(h,q,I,i,P),J&&(q=C7e(J,q,C));else if(v==="category"&&J){var oe=J,ie=q.every(function(de){return oe.indexOf(de)>=0});ie&&(q=oe)}}return qr(qr({},x),{},sl({},I,qr(qr({},b),{},{axisType:i,domain:q,categoricalDomain:G,duplicateDomain:W,originalDomain:(g=b.domain)!==null&&g!==void 0?g:K,isCategorical:p,layout:u})))},{})},opn=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=kAe(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),p=m.length,x=MIt(u,i),y=-1;return r.reduce(function(g,b){var v=b.type.defaultProps!==void 0?qr(qr({},b.type.defaultProps),b.props):b.props,k=v[l],C=sRt("number");if(!g[k]){y++;var T;return x?T=U5e(0,p):o&&o[k]&&o[k].hasStack?(T=DIt(o[k].stackGroups,c,d),T=u9e(h,T,k,i)):(T=C7e(C,EIt(m,r.filter(function(M){var P,L,I=l in M.props?M.props[l]:(P=M.type.defaultProps)===null||P===void 0?void 0:P[l],O="hide"in M.props?M.props.hide:(L=M.type.defaultProps)===null||L===void 0?void 0:L.hide;return I===k&&!O}),"number",u),a.defaultProps.allowDataOverflow),T=u9e(h,T,k,i)),qr(qr({},g),{},sl({},k,qr(qr({axisType:i},a.defaultProps),{},{hide:!0,orientation:Y_(spn,"".concat(i,".").concat(y%2),null),domain:T,originalDomain:C,isCategorical:x,layout:u})))}return g},{})},lpn=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=Z_(u,i),p={};return m&&m.length?p=ipn(t,{axes:m,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(p=opn(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),p},cpn=function(t){var n=EA(t),r=u3(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:TGe(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:E5e(n,r)}},pmt=function(t){var n=t.children,r=t.defaultShowTooltip,a=T_(n,Y$),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}},dpn=function(t){return!t||!t.length?!1:t.some(function(n){var r=S3(n&&n.type);return r&&r.indexOf("Bar")>=0})},fmt=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"}},upn=function(t,n){var r=t.props,a=t.graphicalItems,i=t.xAxisMap,l=i===void 0?{}:i,o=t.yAxisMap,c=o===void 0?{}:o,d=r.width,u=r.height,h=r.children,m=r.margin||{},p=T_(h,Y$),x=T_(h,iD),y=Object.keys(c).reduce(function(T,M){var P=c[M],L=P.orientation;return!P.mirror&&!P.hide?qr(qr({},T),{},sl({},L,T[L]+P.width)):T},{left:m.left||0,right:m.right||0}),g=Object.keys(l).reduce(function(T,M){var P=l[M],L=P.orientation;return!P.mirror&&!P.hide?qr(qr({},T),{},sl({},L,Y_(T,"".concat(L))+P.height)):T},{top:m.top||0,bottom:m.bottom||0}),b=qr(qr({},g),y),v=b.bottom;p&&(b.bottom+=p.props.height||Y$.defaultProps.height),x&&n&&(b=Trn(b,a,r,n));var k=d-b.left-b.right,C=u-b.top-b.bottom;return qr(qr({brushBottom:v},b),{},{width:Math.max(k,0),height:Math.max(C,0)})},hpn=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},SAe=function(t){var n=t.chartName,r=t.GraphicalChild,a=t.defaultTooltipEventType,i=a===void 0?"axis":a,l=t.validateTooltipEventTypes,o=l===void 0?["axis"]:l,c=t.axisComponents,d=t.legendContent,u=t.formatAxisMap,h=t.defaultProps,m=function(b,v){var k=v.graphicalItems,C=v.stackGroups,T=v.offset,M=v.updateId,P=v.dataStartIndex,L=v.dataEndIndex,I=b.barSize,O=b.layout,$=b.barGap,q=b.barCategoryGap,W=b.maxBarSize,G=fmt(O),K=G.numericAxisName,ee=G.cateAxisName,J=dpn(k),le=[];return k.forEach(function(ue,oe){var ie=kAe(b.data,{graphicalItems:[ue],dataStartIndex:P,dataEndIndex:L}),de=ue.type.defaultProps!==void 0?qr(qr({},ue.type.defaultProps),ue.props):ue.props,we=de.dataKey,je=de.maxBarSize,xe=de["".concat(K,"Id")],fe=de["".concat(ee,"Id")],Se={},Ee=c.reduce(function(Ye,nt){var rt=v["".concat(nt.axisType,"Map")],Fe=de["".concat(nt.axisType,"Id")];rt&&rt[Fe]||nt.axisType==="zAxis"||GD();var dt=rt[Fe];return qr(qr({},Ye),{},sl(sl({},nt.axisType,dt),"".concat(nt.axisType,"Ticks"),u3(dt)))},Se),Le=Ee[ee],De=Ee["".concat(ee,"Ticks")],Be=C&&C[xe]&&C[xe].hasStack&&Brn(ue,C[xe].stackGroups),Ne=S3(ue.type).indexOf("Bar")>=0,Ge=E5e(Le,De),_e=[],Oe=J&&Crn({barSize:I,stackGroups:C,totalSize:hpn(Ee,ee)});if(Ne){var Ae,Xe,Ue=Al(je)?W:je,Ze=(Ae=(Xe=E5e(Le,De,!0))!==null&&Xe!==void 0?Xe:Ue)!==null&&Ae!==void 0?Ae:0;_e=Arn({barGap:$,barCategoryGap:q,bandSize:Ze!==Ge?Ze:Ge,sizeList:Oe[fe],maxBarSize:Ue}),Ze!==Ge&&(_e=_e.map(function(Ye){return qr(qr({},Ye),{},{position:qr(qr({},Ye.position),{},{offset:Ye.position.offset-Ze/2})})}))}var Qe=ue&&ue.type&&ue.type.getComposedData;Qe&&le.push({props:qr(qr({},Qe(qr(qr({},Ee),{},{displayedData:ie,props:b,dataKey:we,item:ue,bandSize:Ge,barPosition:_e,offset:T,stackedData:Be,layout:O,dataStartIndex:P,dataEndIndex:L}))),{},sl(sl(sl({key:ue.key||"item-".concat(oe)},K,Ee[K]),ee,Ee[ee]),"animationId",M)),childIndex:Aqs(ue,b.children),item:ue})}),le},p=function(b,v){var k=b.props,C=b.dataStartIndex,T=b.dataEndIndex,M=b.updateId;if(!Cct({props:k}))return null;var P=k.children,L=k.layout,I=k.stackOffset,O=k.data,$=k.reverseStackOrder,q=fmt(L),W=q.numericAxisName,G=q.cateAxisName,K=Z_(P,r),ee=Frn(O,K,"".concat(W,"Id"),"".concat(G,"Id"),I,$),J=c.reduce(function(de,we){var je="".concat(we.axisType,"Map");return qr(qr({},de),{},sl({},je,lpn(k,qr(qr({},we),{},{graphicalItems:K,stackGroups:we.axisType===W&&ee,dataStartIndex:C,dataEndIndex:T}))))},{}),le=upn(qr(qr({},J),{},{props:k,graphicalItems:K}),v==null?void 0:v.legendBBox);Object.keys(J).forEach(function(de){J[de]=u(k,J[de],le,de.replace("Map",""),n)});var ue=J["".concat(G,"Map")],oe=cpn(ue),ie=m(k,qr(qr({},J),{},{dataStartIndex:C,dataEndIndex:T,updateId:M,graphicalItems:K,stackGroups:ee,offset:le}));return qr(qr({formattedGraphicalItems:ie,graphicalItems:K,offset:le,stackGroups:ee},oe),J)},x=function(g){function b(v){var k,C,T;return Hmn(this,b),T=Kmn(this,b,[v]),sl(T,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),sl(T,"accessibilityManager",new Mmn),sl(T,"handleLegendBBoxUpdate",function(M){if(M){var P=T.state,L=P.dataStartIndex,I=P.dataEndIndex,O=P.updateId;T.setState(qr({legendBBox:M},p({props:T.props,dataStartIndex:L,dataEndIndex:I,updateId:O},qr(qr({},T.state),{},{legendBBox:M}))))}}),sl(T,"handleReceiveSyncEvent",function(M,P,L){if(T.props.syncId===M){if(L===T.eventEmitterSymbol&&typeof T.props.syncMethod!="function")return;T.applySyncEvent(P)}}),sl(T,"handleBrushChange",function(M){var P=M.startIndex,L=M.endIndex;if(P!==T.state.dataStartIndex||L!==T.state.dataEndIndex){var I=T.state.updateId;T.setState(function(){return qr({dataStartIndex:P,dataEndIndex:L},p({props:T.props,dataStartIndex:P,dataEndIndex:L,updateId:I},T.state))}),T.triggerSyncEvent({dataStartIndex:P,dataEndIndex:L})}}),sl(T,"handleMouseEnter",function(M){var P=T.getMouseInfo(M);if(P){var L=qr(qr({},P),{},{isTooltipActive:!0});T.setState(L),T.triggerSyncEvent(L);var I=T.props.onMouseEnter;nl(I)&&I(L,M)}}),sl(T,"triggeredAfterMouseMove",function(M){var P=T.getMouseInfo(M),L=P?qr(qr({},P),{},{isTooltipActive:!0}):{isTooltipActive:!1};T.setState(L),T.triggerSyncEvent(L);var I=T.props.onMouseMove;nl(I)&&I(L,M)}),sl(T,"handleItemMouseEnter",function(M){T.setState(function(){return{isTooltipActive:!0,activeItem:M,activePayload:M.tooltipPayload,activeCoordinate:M.tooltipPosition||{x:M.cx,y:M.cy}}})}),sl(T,"handleItemMouseLeave",function(){T.setState(function(){return{isTooltipActive:!1}})}),sl(T,"handleMouseMove",function(M){M.persist(),T.throttleTriggeredAfterMouseMove(M)}),sl(T,"handleMouseLeave",function(M){T.throttleTriggeredAfterMouseMove.cancel();var P={isTooltipActive:!1};T.setState(P),T.triggerSyncEvent(P);var L=T.props.onMouseLeave;nl(L)&&L(P,M)}),sl(T,"handleOuterEvent",function(M){var P=Cqs(M),L=Y_(T.props,"".concat(P));if(P&&nl(L)){var I,O;/.*touch.*/i.test(P)?O=T.getMouseInfo(M.changedTouches[0]):O=T.getMouseInfo(M),L((I=O)!==null&&I!==void 0?I:{},M)}}),sl(T,"handleClick",function(M){var P=T.getMouseInfo(M);if(P){var L=qr(qr({},P),{},{isTooltipActive:!0});T.setState(L),T.triggerSyncEvent(L);var I=T.props.onClick;nl(I)&&I(L,M)}}),sl(T,"handleMouseDown",function(M){var P=T.props.onMouseDown;if(nl(P)){var L=T.getMouseInfo(M);P(L,M)}}),sl(T,"handleMouseUp",function(M){var P=T.props.onMouseUp;if(nl(P)){var L=T.getMouseInfo(M);P(L,M)}}),sl(T,"handleTouchMove",function(M){M.changedTouches!=null&&M.changedTouches.length>0&&T.throttleTriggeredAfterMouseMove(M.changedTouches[0])}),sl(T,"handleTouchStart",function(M){M.changedTouches!=null&&M.changedTouches.length>0&&T.handleMouseDown(M.changedTouches[0])}),sl(T,"handleTouchEnd",function(M){M.changedTouches!=null&&M.changedTouches.length>0&&T.handleMouseUp(M.changedTouches[0])}),sl(T,"handleDoubleClick",function(M){var P=T.props.onDoubleClick;if(nl(P)){var L=T.getMouseInfo(M);P(L,M)}}),sl(T,"handleContextMenu",function(M){var P=T.props.onContextMenu;if(nl(P)){var L=T.getMouseInfo(M);P(L,M)}}),sl(T,"triggerSyncEvent",function(M){T.props.syncId!==void 0&&BPe.emit($Pe,T.props.syncId,M,T.eventEmitterSymbol)}),sl(T,"applySyncEvent",function(M){var P=T.props,L=P.layout,I=P.syncMethod,O=T.state.updateId,$=M.dataStartIndex,q=M.dataEndIndex;if(M.dataStartIndex!==void 0||M.dataEndIndex!==void 0)T.setState(qr({dataStartIndex:$,dataEndIndex:q},p({props:T.props,dataStartIndex:$,dataEndIndex:q,updateId:O},T.state)));else if(M.activeTooltipIndex!==void 0){var W=M.chartX,G=M.chartY,K=M.activeTooltipIndex,ee=T.state,J=ee.offset,le=ee.tooltipTicks;if(!J)return;if(typeof I=="function")K=I(le,M);else if(I==="value"){K=-1;for(var ue=0;ue=0){var Be,Ne;if(W.dataKey&&!W.allowDuplicatedCategory){var Ge=typeof W.dataKey=="function"?De:"payload.".concat(W.dataKey.toString());Be=t5e(ue,Ge,K),Ne=oe&&ie&&t5e(ie,Ge,K)}else Be=ue==null?void 0:ue[G],Ne=oe&&ie&&ie[G];if(fe||xe){var _e=M.props.activeIndex!==void 0?M.props.activeIndex:G;return[j.cloneElement(M,qr(qr(qr({},I.props),Ee),{},{activeIndex:_e})),null,null]}if(!Al(Be))return[Le].concat(iU(T.renderActivePoints({item:I,activePoint:Be,basePoint:Ne,childIndex:G,isRange:oe})))}else{var Oe,Ae=(Oe=T.getItemByXY(T.state.activeCoordinate))!==null&&Oe!==void 0?Oe:{graphicalItem:Le},Xe=Ae.graphicalItem,Ue=Xe.item,Ze=Ue===void 0?M:Ue,Qe=Xe.childIndex,Ye=qr(qr(qr({},I.props),Ee),{},{activeIndex:Qe});return[j.cloneElement(Ze,Ye),null,null]}return oe?[Le,null,null]:[Le,null]}),sl(T,"renderCustomized",function(M,P,L){return j.cloneElement(M,qr(qr({key:"recharts-customized-".concat(L)},T.props),T.state))}),sl(T,"renderMap",{CartesianGrid:{handler:Mne,once:!0},ReferenceArea:{handler:T.renderReferenceElement},ReferenceLine:{handler:Mne},ReferenceDot:{handler:T.renderReferenceElement},XAxis:{handler:Mne},YAxis:{handler:Mne},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=v.id)!==null&&k!==void 0?k:AO("recharts"),"-clip"),T.throttleTriggeredAfterMouseMove=CPt(T.triggeredAfterMouseMove,(C=v.throttleDelay)!==null&&C!==void 0?C:1e3/60),T.state={},T}return Xmn(b,g),Wmn(b,[{key:"componentDidMount",value:function(){var k,C;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(k=this.props.margin.left)!==null&&k!==void 0?k:0,top:(C=this.props.margin.top)!==null&&C!==void 0?C:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var k=this.props,C=k.children,T=k.data,M=k.height,P=k.layout,L=T_(C,ff);if(L){var I=L.props.defaultIndex;if(!(typeof I!="number"||I<0||I>this.state.tooltipTicks.length-1)){var O=this.state.tooltipTicks[I]&&this.state.tooltipTicks[I].value,$=p9e(this.state,T,I,O),q=this.state.tooltipTicks[I].coordinate,W=(this.state.offset.top+M)/2,G=P==="horizontal",K=G?{x:q,y:W}:{y:q,x:W},ee=this.state.formattedGraphicalItems.find(function(le){var ue=le.item;return ue.type.name==="Scatter"});ee&&(K=qr(qr({},K),ee.props.points[I].tooltipPosition),$=ee.props.points[I].tooltipPayload);var J={activeTooltipIndex:I,isTooltipActive:!0,activeLabel:O,activePayload:$,activeCoordinate:K};this.setState(J),this.renderCursor(L),this.accessibilityManager.setIndex(I)}}}},{key:"getSnapshotBeforeUpdate",value:function(k,C){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==C.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,M;this.accessibilityManager.setDetails({offset:{left:(T=this.props.margin.left)!==null&&T!==void 0?T:0,top:(M=this.props.margin.top)!==null&&M!==void 0?M:0}})}return null}},{key:"componentDidUpdate",value:function(k){UFe([T_(k.children,ff)],[T_(this.props.children,ff)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var k=T_(this.props.children,ff);if(k&&typeof k.props.shared=="boolean"){var C=k.props.shared?"axis":"item";return o.indexOf(C)>=0?C:i}return i}},{key:"getMouseInfo",value:function(k){if(!this.container)return null;var C=this.container,T=C.getBoundingClientRect(),M=een(T),P={chartX:Math.round(k.pageX-M.left),chartY:Math.round(k.pageY-M.top)},L=T.width/C.offsetWidth||1,I=this.inRange(P.chartX,P.chartY,L);if(!I)return null;var O=this.state,$=O.xAxisMap,q=O.yAxisMap,W=this.getTooltipEventType(),G=mmt(this.state,this.props.data,this.props.layout,I);if(W!=="axis"&&$&&q){var K=EA($).scale,ee=EA(q).scale,J=K&&K.invert?K.invert(P.chartX):null,le=ee&&ee.invert?ee.invert(P.chartY):null;return qr(qr({},P),{},{xValue:J,yValue:le},G)}return G?qr(qr({},P),G):null}},{key:"inRange",value:function(k,C){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,M=this.props.layout,P=k/T,L=C/T;if(M==="horizontal"||M==="vertical"){var I=this.state.offset,O=P>=I.left&&P<=I.left+I.width&&L>=I.top&&L<=I.top+I.height;return O?{x:P,y:L}:null}var $=this.state,q=$.angleAxisMap,W=$.radiusAxisMap;if(q&&W){var G=EA(q);return Dut({x:P,y:L},G)}return null}},{key:"parseEventsOfWrapper",value:function(){var k=this.props.children,C=this.getTooltipEventType(),T=T_(k,ff),M={};T&&C==="axis"&&(T.props.trigger==="click"?M={onClick:this.handleClick}:M={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var P=s5e(this.props,this.handleOuterEvent);return qr(qr({},P),M)}},{key:"addListener",value:function(){BPe.on($Pe,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){BPe.removeListener($Pe,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(k,C,T){for(var M=this.state.formattedGraphicalItems,P=0,L=M.length;P{const{data:v,error:k}=await U.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(k)throw k;return v}}),{data:r}=mt({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:v,error:k}=await U.from("profiles").select("id, name, email");if(k)throw k;return v}});if(n)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."});const a=t||[],i=new Map((r||[]).map(v=>[v.id,v])),l=a.reduce((v,k)=>v+(k.sent_count||0),0),o=a.reduce((v,k)=>v+(k.open_count||0),0),c=a.reduce((v,k)=>v+(k.click_count||0),0),d=a.reduce((v,k)=>v+(k.bounce_count||0),0),u=a.reduce((v,k)=>v+(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",p=[{label:"Campaigns Sent",value:a.length,icon:Dr,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:Bn,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:ma,color:"text-blue-600"},{label:"Avg Click Rate",value:`${m}%`,icon:ag,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:hd,color:"text-orange-600"},{label:"Complaints",value:u,icon:kl,color:"text-destructive"}],x=new Map;a.forEach(v=>{var T,M;const k=v.user_id,C=x.get(k)||{name:((T=i.get(k))==null?void 0:T.name)||((M=i.get(k))==null?void 0:M.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};C.campaigns++,C.sent+=v.sent_count||0,C.opens+=v.open_count||0,C.clicks+=v.click_count||0,x.set(k,C)});const y=[...x.entries()].map(([v,k])=>({id:v,...k,openRate:k.sent>0?+(k.opens/k.sent*100).toFixed(1):0})).sort((v,k)=>k.sent-v.sent),g=y.slice(0,6).map(v=>({name:v.name,value:v.sent})),b=a.map(v=>{var k;return{name:v.name.length>20?v.name.slice(0,20)+"…":v.name,agent:((k=i.get(v.user_id))==null?void 0:k.name)||"Unknown",openRate:v.sent_count>0?+(v.open_count/v.sent_count*100).toFixed(1):0,clickRate:v.sent_count>0?+(v.click_count/v.sent_count*100).toFixed(1):0,sent:v.sent_count,date:v.sent_at?Bs(new Date(v.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Dr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No campaigns sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Campaign analytics will appear here after the first send."})]})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:p.map(v=>e.jsx(be,{children:e.jsxs(Re,{className:"p-4 text-center",children:[e.jsx(v.icon,{className:`h-5 w-5 mx-auto mb-1 ${v.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:v.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v.label})]})},v.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Re,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(CAe,{data:b,children:[e.jsx(p1,{dataKey:"date",fontSize:11}),e.jsx(f1,{fontSize:11,unit:"%"}),e.jsx(ff,{formatter:v=>`${v}%`}),e.jsx(Bj,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(Bj,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Re,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(pWe,{children:[e.jsx($N,{data:g,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:v,percent:k})=>`${v} (${(k*100).toFixed(0)}%)`,fontSize:11,children:g.map((v,k)=>e.jsx(_q,{fill:xmt[k%xmt.length]},k))}),e.jsx(ff,{})]})})})})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Re,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(mWe,{data:b,children:[e.jsx(p1,{dataKey:"date",fontSize:11}),e.jsx(f1,{fontSize:11}),e.jsx(ff,{}),e.jsx(MO,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Agent Performance"})}),e.jsx(Re,{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(v=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:v.name}),e.jsx("td",{className:"py-2.5 text-center",children:v.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:v.sent}),e.jsx("td",{className:"py-2.5 text-center",children:v.opens}),e.jsx("td",{className:"py-2.5 text-center",children:v.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(qe,{variant:"outline",children:[v.openRate,"%"]})})]},v.id))})]})})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Re,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((v,k)=>{const C=v.sent_count>0?v.open_count/v.sent_count:0;return(k.sent_count>0?k.open_count/k.sent_count:0)-C}).slice(0,10).map((v,k)=>{const C=v.sent_count>0?(v.open_count/v.sent_count*100).toFixed(1):"0.0",T=v.sent_count>0?(v.click_count/v.sent_count*100).toFixed(1):"0.0",M=i.get(v.user_id);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted/30 cursor-pointer",onClick:()=>s(`/admin/email-campaigns/${v.id}`),children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",k+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(M==null?void 0:M.name)||"Unknown"," · ",v.sent_at?Bs(new Date(v.sent_at),"MMM d, yyyy"):""," · ",v.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(ma,{className:"h-3 w-3"})," ",C,"%"]}),e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(ag,{className:"h-3 w-3"})," ",T,"%"]})]})]},v.id)})})})]})]})})}const ppn=()=>{const{toast:s}=pi(),[t,n]=j.useState(!0),[r,a]=j.useState([]),[i,l]=j.useState([]),[o,c]=j.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});j.useEffect(()=>{d()},[]);const d=async()=>{try{n(!0);const u=new Date;u.setDate(u.getDate()-30);const h=u.toISOString(),{data:m}=await U.from("website_apps").select("slug, name").order("sort_order"),p=[];let x=0;for(;;){const{data:T,error:M}=await U.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(x,x+999);if(M)throw M;if(p.push(...T||[]),!T||T.length<1e3)break;x+=1e3}const y=[];for(x=0;;){const{data:T,error:M}=await U.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",h).order("created_at",{ascending:!1}).range(x,x+999);if(M)throw M;if(y.push(...T||[]),!T||T.length<1e3||(x+=1e3,x>2e4))break}const g=new Map;for(const T of m||[])g.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 p){const M=g.get(T.app_slug);M&&(M.installs+=1,T.enabled&&(M.enabled+=1))}for(const T of y){const M=g.get(T.app_slug);M&&(T.event_type==="impression"?M.impressions+=1:T.event_type==="expand"?M.expands+=1:T.event_type==="cta_click"?M.cta_clicks+=1:T.event_type==="lead_capture"&&(M.lead_captures+=1))}const b=new Map;for(const T of p){if(!T.enabled)continue;const M=b.get(T.user_id)||{user_id:T.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};M.apps_enabled.includes(T.app_slug)||M.apps_enabled.push(T.app_slug),b.set(T.user_id,M)}for(const T of y){const M=b.get(T.user_id);M&&(M.events_30d+=1,T.event_type==="lead_capture"&&(M.leads_30d+=1))}const v=Array.from(b.keys());if(v.length>0){const{data:T}=await U.from("profiles").select("id, name, email").in("id",v);for(const M of T||[]){const P=b.get(M.id);P&&(P.name=M.name,P.email=M.email)}}const k=Array.from(g.values()),C=Array.from(b.values()).sort((T,M)=>M.events_30d-T.events_30d);a(k),l(C),c({installs:k.reduce((T,M)=>T+M.enabled,0),activeAgents:C.length,impressions30d:k.reduce((T,M)=>T+M.impressions,0),leads30d:k.reduce((T,M)=>T+M.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(be,{children:e.jsx(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(Ql,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(ma,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(on,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"App Performance (last 30 days)"})}),e.jsx(Re,{children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"App"}),e.jsx(Tt,{className:"text-right",children:"Installs"}),e.jsx(Tt,{className:"text-right",children:"Enabled"}),e.jsx(Tt,{className:"text-right",children:"Impressions"}),e.jsx(Tt,{className:"text-right",children:"Expands"}),e.jsx(Tt,{className:"text-right",children:"CTA Clicks"}),e.jsx(Tt,{className:"text-right",children:"Leads"}),e.jsx(Tt,{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(xt,{className:"font-medium",children:u.app_name}),e.jsx(xt,{className:"text-right",children:u.installs}),e.jsx(xt,{className:"text-right",children:u.enabled}),e.jsx(xt,{className:"text-right",children:u.impressions}),e.jsx(xt,{className:"text-right",children:u.expands}),e.jsx(xt,{className:"text-right",children:u.cta_clicks}),e.jsx(xt,{className:"text-right font-semibold",children:u.lead_captures}),e.jsx(xt,{className:"text-right text-muted-foreground",children:h==="—"?"—":`${h}%`})]},u.app_slug)}),r.length===0&&e.jsx(un,{children:e.jsx(xt,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Re,{children:[e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Apps Enabled"}),e.jsx(Tt,{className:"text-right",children:"Events (30d)"}),e.jsx(Tt,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(za,{children:[i.slice(0,100).map(u=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:u.name||"—"}),e.jsx(xt,{className:"text-muted-foreground",children:u.email||"—"}),e.jsx(xt,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:u.apps_enabled.map(h=>e.jsx(qe,{variant:"secondary",className:"text-xs",children:h},h))})}),e.jsx(xt,{className:"text-right",children:u.events_30d}),e.jsx(xt,{className:"text-right font-semibold",children:u.leads_30d})]},u.user_id)),i.length===0&&e.jsx(un,{children:e.jsx(xt,{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."]})]})]})]})},fpn=()=>{const[s,t]=j.useState([]),[n,r]=j.useState([]),[a,i]=j.useState({}),[l,o]=j.useState(!0);j.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:h},{data:m}]=await Promise.all([U.rpc("get_extension_usage_summary"),U.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),p=h||[],x=m||[];t(p),r(x);const y=Array.from(new Set(x.map(g=>g.user_id)));if(y.length){const{data:g}=await U.from("profiles").select("id, name, email").in("id",y),b={};(g||[]).forEach(v=>{b[v.id]={name:v.name,email:v.email}}),i(b)}}finally{o(!1)}},d=s.reduce((h,m)=>({users:h.users+1,contacts:h.contacts+Number(m.contacts_saved||0),listings:h.listings+Number(m.listings_imported||0),activities:h.activities+Number(m.activities_logged||0),events:h.events+Number(m.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(be,{children:e.jsx(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(IR,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(Sl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(ia,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(ro,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Users by Extension Activity"})}),e.jsx(Re,{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(Tt,{children:"User"}),e.jsx(Tt,{className:"text-right",children:"Total"}),e.jsx(Tt,{className:"text-right",children:"Contacts"}),e.jsx(Tt,{className:"text-right",children:"Listings"}),e.jsx(Tt,{className:"text-right",children:"Activities"}),e.jsx(Tt,{children:"First Used"}),e.jsx(Tt,{children:"Last Used"})]})}),e.jsx(za,{children:s.map(h=>e.jsxs(un,{children:[e.jsxs(xt,{children:[e.jsx("div",{className:"font-medium",children:h.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]}),e.jsx(xt,{className:"text-right font-medium",children:h.total_events}),e.jsx(xt,{className:"text-right",children:h.contacts_saved}),e.jsx(xt,{className:"text-right",children:h.listings_imported}),e.jsx(xt,{className:"text-right",children:h.activities_logged}),e.jsx(xt,{className:"text-xs text-muted-foreground",children:h.first_event_at?Bs(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(xt,{className:"text-xs text-muted-foreground",children:h.last_event_at?Bs(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Recent Activity"})}),e.jsx(Re,{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(qe,{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:Bs(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},xpn=()=>e.jsx(Vs,{title:"Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Analytics & Activity"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Platform-wide usage statistics and user activity"})]}),e.jsxs(fa,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"analytics",children:"Analytics"}),e.jsx(ss,{value:"website-apps",children:"Website Apps"}),e.jsx(ss,{value:"extension",children:"Chrome Extension"}),e.jsx(ss,{value:"content",children:"Content"}),e.jsx(ss,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(ss,{value:"activity",children:"Activity"}),e.jsx(ss,{value:"shares",children:"Shares"})]}),e.jsx(ns,{value:"analytics",className:"space-y-4",children:e.jsx(Pzs,{})}),e.jsx(ns,{value:"website-apps",className:"space-y-4",children:e.jsx(ppn,{})}),e.jsx(ns,{value:"extension",className:"space-y-4",children:e.jsx(fpn,{})}),e.jsx(ns,{value:"content",className:"space-y-4",children:e.jsx(Rzs,{})}),e.jsx(ns,{value:"email-campaigns",className:"space-y-4",children:e.jsx(mpn,{})}),e.jsx(ns,{value:"activity",className:"space-y-4",children:e.jsx(Lzs,{})}),e.jsx(ns,{value:"shares",className:"space-y-4",children:e.jsx(uLt,{})})]})]})});function gpn(){const s=as(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState([]),[p,x]=j.useState([]),[y,g]=j.useState([]),[b,v]=j.useState(!1),[k,C]=j.useState(null),[T,M]=j.useState(""),{data:P,isLoading:L}=mt({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:Ne,error:Ge}=await U.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Ge)throw Ge;return Ne}}),{data:I}=mt({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:Ne,error:Ge}=await U.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Ge)throw Ge;return Ne}}),{data:O}=mt({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:Ne,error:Ge}=await U.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 U.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Ge)throw Ge;return Ne}}),{data:q,isLoading:W}=mt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:Ne,error:Ge}=await U.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([]),x([]),g([]),a(null),M("")},K=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||""),M("");const Ge=(I==null?void 0:I.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 _e=(O==null?void 0:O.filter(Ae=>Ae.resource_id===Ne.id))||[];x(_e.map(Ae=>({id:Ae.id,title:Ae.title,video_url:Ae.video_url,sort_order:Ae.sort_order})));const Oe=($==null?void 0:$.filter(Ae=>Ae.resource_id===Ne.id))||[];g(Oe.map(Ae=>({id:Ae.id,title:Ae.title,canva_share_link:Ae.canva_share_link,sort_order:Ae.sort_order}))),n(!0)},ee=Ne=>{var _e;const Ge=(_e=Ne.target.files)==null?void 0:_e[0];Ge&&(c(Ge),u(URL.createObjectURL(Ge)))},J=()=>{m([...h,{name:"",file_url:"",sort_order:h.length}])},le=Ne=>{m(h.filter((Ge,_e)=>_e!==Ne))},ue=(Ne,Ge,_e)=>{const Oe=[...h];if(Ge==="file"&&_e instanceof File){const Ae=_e.name.replace(/\.[^/.]+$/,"");Oe[Ne]={...Oe[Ne],file:_e,file_size:_e.size,name:Oe[Ne].name||Ae}}else Oe[Ne]={...Oe[Ne],[Ge]:_e};m(Oe)},oe=()=>{x([...p,{title:"",video_url:"",sort_order:p.length}])},ie=Ne=>{x(p.filter((Ge,_e)=>_e!==Ne))},de=(Ne,Ge,_e)=>{const Oe=[...p];Ge==="file"&&_e instanceof File?Oe[Ne]={...Oe[Ne],file:_e}:Oe[Ne]={...Oe[Ne],[Ge]:_e},x(Oe)},we=()=>{g([...y,{title:"",canva_share_link:"",sort_order:y.length}])},je=Ne=>{g(y.filter((Ge,_e)=>_e!==Ne))},xe=(Ne,Ge,_e)=>{const Oe=[...y];Oe[Ne]={...Oe[Ne],[Ge]:_e},g(Oe)},fe=async(Ne,Ge)=>{try{const _e=await U.functions.invoke("bunny-upload",{body:{action:"create",title:Ne.name}});if(_e.error)throw _e.error;const{videoId:Oe,uploadUrl:Ae,libraryId:Xe}=_e.data,Ue=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Oe,libraryId:Xe}});if(Ue.error)throw Ue.error;const{uploadUrl:Ze,apiKey:Qe}=Ue.data,Ye=new XMLHttpRequest;return Ye.open("PUT",Ze,!0),Ye.setRequestHeader("AccessKey",Qe),Ye.upload.onprogress=nt=>{if(nt.lengthComputable){const rt=Math.round(nt.loaded/nt.total*100),Fe=[...p];Fe[Ge]={...Fe[Ge],uploadProgress:rt},x(Fe)}},await new Promise((nt,rt)=>{Ye.onload=()=>Ye.status>=200&&Ye.status<300?nt():rt(new Error("Upload failed")),Ye.onerror=()=>rt(new Error("Upload failed")),Ye.send(Ne)}),`https://iframe.mediadelivery.net/embed/${Xe}/${Oe}`}catch(_e){throw console.error("Bunny upload error:",_e),_e}},Se=vt({mutationFn:async Ne=>{const{data:Ge,error:_e}=await U.from("brokerage_resource_categories").insert({name:Ne,sort_order:(q==null?void 0:q.length)||0}).select().single();if(_e)throw _e;return Ge},onSuccess:Ne=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:Ne.id}),M(""),re.success("Category created")},onError:Ne=>{re.error("Failed to create category: "+Ne.message)}}),Ee=vt({mutationFn:async()=>{v(!0);let Ne=(r==null?void 0:r.preview_image_url)||null;if(o){const Oe=o.name.split(".").pop(),Ae=`${Date.now()}.${Oe}`,{error:Xe}=await U.storage.from("brokerage-resources").upload(`previews/${Ae}`,o);if(Xe)throw Xe;const{data:Ue}=U.storage.from("brokerage-resources").getPublicUrl(`previews/${Ae}`);Ne=Ue.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 _e;if(r){const{error:Oe}=await U.from("brokerage_resources").update(Ge).eq("id",r.id);if(Oe)throw Oe;_e=r.id;const Ae=(I==null?void 0:I.filter(dt=>dt.resource_id===r.id).map(dt=>dt.id))||[],Xe=h.filter(dt=>dt.id).map(dt=>dt.id),Ue=Ae.filter(dt=>!Xe.includes(dt));Ue.length>0&&await U.from("brokerage_resource_pdfs").delete().in("id",Ue);const Ze=(O==null?void 0:O.filter(dt=>dt.resource_id===r.id).map(dt=>dt.id))||[],Qe=p.filter(dt=>dt.id).map(dt=>dt.id),Ye=Ze.filter(dt=>!Qe.includes(dt));Ye.length>0&&await U.from("brokerage_resource_videos").delete().in("id",Ye);const nt=($==null?void 0:$.filter(dt=>dt.resource_id===r.id).map(dt=>dt.id))||[],rt=y.filter(dt=>dt.id).map(dt=>dt.id),Fe=nt.filter(dt=>!rt.includes(dt));Fe.length>0&&await U.from("brokerage_resource_links").delete().in("id",Fe)}else{const{data:Oe,error:Ae}=await U.from("brokerage_resources").insert(Ge).select().single();if(Ae)throw Ae;_e=Oe.id}for(let Oe=0;Oe{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),re.success(r?"Resource updated":"Resource created"),n(!1),G(),v(!1)},onError:Ne=>{re.error("Failed to save resource: "+Ne.message),v(!1)}}),Le=vt({mutationFn:async Ne=>{const{error:Ge}=await U.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"]}),re.success("Resource deleted")},onError:Ne=>{re.error("Failed to delete: "+Ne.message)}}),De=Ne=>{if(Ne.preventDefault(),!i.title){re.error("Please enter a title");return}Ee.mutate()},Be=Ne=>{const Ge=(I==null?void 0:I.filter(Ae=>Ae.resource_id===Ne).length)||0,_e=(O==null?void 0:O.filter(Ae=>Ae.resource_id===Ne).length)||0,Oe=($==null?void 0:$.filter(Ae=>Ae.resource_id===Ne).length)||0;return{pdfCount:Ge,videoCount:_e,linkCount:Oe}};return e.jsx(Vs,{title:"Brokerage Resources Management",description:"Create and manage resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:(P==null?void 0:P.length)||0})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:(P==null?void 0:P.filter(Ne=>Ne.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{G(),n(!0)},children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Content"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:L?e.jsx(un,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(P==null?void 0:P.length)===0?e.jsx(un,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):P==null?void 0:P.map(Ne=>{const{pdfCount:Ge,videoCount:_e,linkCount:Oe}=Be(Ne.id),Ae=q==null?void 0:q.find(Xe=>Xe.id===Ne.category_id);return e.jsxs(un,{children:[e.jsx(xt,{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(kx,{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(xt,{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(xt,{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($r,{className:"h-3.5 w-3.5"}),Ge]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"}),_e]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(vc,{className:"h-3.5 w-3.5"}),Oe]})]})}),e.jsx(xt,{children:Bs(new Date(Ne.publish_date),"MMM d, yyyy")}),e.jsx(xt,{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(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{const Xe=(I==null?void 0:I.filter(Qe=>Qe.resource_id===Ne.id))||[],Ue=(O==null?void 0:O.filter(Qe=>Qe.resource_id===Ne.id))||[],Ze=($==null?void 0:$.filter(Qe=>Qe.resource_id===Ne.id))||[];C({...Ne,pdfs:Xe,videos:Ue,links:Ze})},children:e.jsx(ma,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>K(Ne),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Bi("Delete this resource?")&&Le.mutate(Ne.id)},children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})})]},Ne.id)})})]})})}),e.jsx(Fs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:De,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[d?e.jsx("img",{src:d,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):e.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:e.jsx(kx,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(ye,{type:"file",accept:"image/*",onChange:ee})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{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(se,{className:"flex items-center gap-2",children:[e.jsx(wf,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:i.category_id,onValueChange:Ne=>l({...i,category_id:Ne}),children:[e.jsx(gs,{className:"flex-1",children:e.jsx(bs,{placeholder:"Select a category"})}),e.jsx(ys,{children:q==null?void 0:q.map(Ne=>e.jsx(Je,{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(dr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Or create new category...",value:T,onChange:Ne=>M(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(Js,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Kj,{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(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{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(se,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Mn,{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(se,{className:"flex items-center gap-2",children:[e.jsx($r,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:J,children:[e.jsx(Js,{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(ye,{placeholder:"PDF Name",value:Ne.name,onChange:_e=>ue(Ge,"name",_e.target.value),className:"flex-1"}),e.jsx(ye,{type:"file",accept:".pdf",onChange:_e=>{var Ae;const Oe=(Ae=_e.target.files)==null?void 0:Ae[0];Oe&&ue(Ge,"file",Oe)},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:()=>le(Ge),children:e.jsx(dr,{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(se,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-4 w-4"}),"Videos (",p.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:oe,children:[e.jsx(Js,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),p.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(ye,{placeholder:"Video Title",value:Ne.title,onChange:_e=>de(Ge,"title",_e.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>ie(Ge),children:e.jsx(dr,{className:"h-4 w-4"})})]}),e.jsx(ye,{type:"file",accept:"video/*",onChange:_e=>{var Ae;const Oe=(Ae=_e.target.files)==null?void 0:Ae[0];Oe&&de(Ge,"file",Oe)}}),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(se,{className:"flex items-center gap-2",children:[e.jsx(vc,{className:"h-4 w-4"}),"Canva Links (",y.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:we,children:[e.jsx(Js,{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(ye,{placeholder:"Link Title",value:Ne.title,onChange:_e=>xe(Ge,"title",_e.target.value),className:"flex-1"}),e.jsx(ye,{placeholder:"Canva Share Link",value:Ne.canva_share_link,onChange:_e=>xe(Ge,"canva_share_link",_e.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>je(Ge),children:e.jsx(dr,{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:Ee.isPending||b,children:Ee.isPending||b?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(Fs,{open:!!k,onOpenChange:()=>C(null),children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{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($r,{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(Zr,{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(vc,{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 nRt=[{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 ypn(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[x,y]=j.useState(""),[g,b]=j.useState(""),[v,k]=j.useState(""),[C,T]=j.useState(""),[M,P]=j.useState("Learn More"),[L,I]=j.useState("top"),[O,$]=j.useState(""),[q,W]=j.useState(!0),[G,K]=j.useState(""),[ee,J]=j.useState("");j.useEffect(()=>{le()},[]);const le=async()=>{try{const{data:Se,error:Ee}=await U.from("dashboard_banners").select("*").order("placement").order("sort_order");if(Ee)throw Ee;t(Se||[])}catch(Se){re.error("Failed to load banners: "+Se.message)}finally{r(!1)}},ue=()=>{y(""),b(""),k(""),T(""),P("Learn More"),I("top"),$(""),W(!0),K(""),J(""),d(null)},oe=Se=>{d(Se),y(Se.title),b(Se.description||""),k(Se.image_url),T(Se.link_url||""),P(Se.link_text||"Learn More"),I(Se.placement),$(Se.section_after||""),W(Se.is_active),K(Se.start_date?Bs(new Date(Se.start_date),"yyyy-MM-dd'T'HH:mm"):""),J(Se.end_date?Bs(new Date(Se.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},ie=async Se=>{var Le;const Ee=(Le=Se.target.files)==null?void 0:Le[0];if(Ee){h(!0);try{const De=Ee.name.split(".").pop(),Be=`${Date.now()}.${De}`,{error:Ne}=await U.storage.from("banner-images").upload(Be,Ee);if(Ne)throw Ne;const{data:{publicUrl:Ge}}=U.storage.from("banner-images").getPublicUrl(Be);k(Ge),re.success("Image uploaded successfully")}catch(De){re.error("Failed to upload image: "+De.message)}finally{h(!1)}}},de=async()=>{if(!x.trim()||!v){re.error("Please fill in required fields (title and image)");return}p(!0);try{const Se={title:x.trim(),description:g.trim()||null,image_url:v,link_url:C.trim()||null,link_text:M.trim()||"Learn More",placement:L,section_after:L==="between"?O:null,is_active:q,start_date:G?new Date(G).toISOString():null,end_date:ee?new Date(ee).toISOString():null};if(c){const{error:Ee}=await U.from("dashboard_banners").update(Se).eq("id",c.id);if(Ee)throw Ee;re.success("Banner updated successfully")}else{const Ee=s.filter(De=>De.placement===L).length,{error:Le}=await U.from("dashboard_banners").insert({...Se,sort_order:Ee});if(Le)throw Le;re.success("Banner created successfully")}i(!1),ue(),le()}catch(Se){re.error("Failed to save banner: "+Se.message)}finally{p(!1)}},we=async()=>{if(c)try{const{error:Se}=await U.from("dashboard_banners").delete().eq("id",c.id);if(Se)throw Se;re.success("Banner deleted successfully"),o(!1),d(null),le()}catch(Se){re.error("Failed to delete banner: "+Se.message)}},je=async Se=>{try{const{error:Ee}=await U.from("dashboard_banners").update({is_active:!Se.is_active}).eq("id",Se.id);if(Ee)throw Ee;re.success(Se.is_active?"Banner deactivated":"Banner activated"),le()}catch(Ee){re.error("Failed to update banner: "+Ee.message)}},xe=s.filter(Se=>Se.placement==="top"),fe=s.filter(Se=>Se.placement==="between");return n?e.jsx(Vs,{title:"Dashboard Management",children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):e.jsxs(Vs,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ac,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(fr,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(Fs,{open:a&&L==="top",onOpenChange:Se=>{Se||ue(),i(Se),Se&&I("top")},children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ue(),I("top")},children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(kr,{children:"Configure the banner's content and display settings"})]}),e.jsx(gmt,{title:x,setTitle:y,description:g,setDescription:b,imageUrl:v,linkUrl:C,setLinkUrl:T,linkText:M,setLinkText:P,placement:L,setPlacement:I,sectionAfter:O,setSectionAfter:$,isActive:q,setIsActive:W,startDate:G,setStartDate:K,endDate:ee,setEndDate:J,handleImageUpload:ie,uploading:u,showPlacementOptions:!1}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ue()},children:"Cancel"}),e.jsx(B,{onClick:de,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Re,{children:xe.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:xe.map(Se=>e.jsx(ymt,{banner:Se,onEdit:()=>oe(Se),onDelete:()=>{d(Se),o(!0)},onToggleActive:()=>je(Se)},Se.id))})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ac,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(fr,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(Fs,{open:a&&L==="between",onOpenChange:Se=>{Se||ue(),i(Se),Se&&I("between")},children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ue(),I("between")},children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(kr,{children:"Configure where this banner appears between sections"})]}),e.jsx(gmt,{title:x,setTitle:y,description:g,setDescription:b,imageUrl:v,linkUrl:C,setLinkUrl:T,linkText:M,setLinkText:P,placement:L,setPlacement:I,sectionAfter:O,setSectionAfter:$,isActive:q,setIsActive:W,startDate:G,setStartDate:K,endDate:ee,setEndDate:J,handleImageUpload:ie,uploading:u,showPlacementOptions:!0}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ue()},children:"Cancel"}),e.jsx(B,{onClick:de,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Re,{children:fe.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No section banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:fe.map(Se=>e.jsx(ymt,{banner:Se,onEdit:()=>oe(Se),onDelete:()=>{d(Se),o(!0)},onToggleActive:()=>je(Se),showSection:!0},Se.id))})})]})]}),e.jsx(Fs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Delete Banner"}),e.jsxs(kr,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:we,children:"Delete"})]})]})})]})}function gmt({title:s,setTitle:t,description:n,setDescription:r,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:u,sectionAfter:h,setSectionAfter:m,isActive:p,setIsActive:x,startDate:y,setStartDate:g,endDate:b,setEndDate:v,handleImageUpload:k,uploading:C,showPlacementOptions:T}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",placeholder:"Banner headline...",value:s,onChange:M=>t(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ds,{id:"description",placeholder:"Optional banner description...",value:n,onChange:M=>r(M.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(ye,{type:"file",accept:"image/*",onChange:k,disabled:C,className:"flex-1"}),C&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),a&&e.jsx("div",{className:"mt-2 relative rounded-lg overflow-hidden border",children:e.jsx("img",{src:a,alt:"Preview",className:"w-full h-40 object-cover"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(ye,{id:"linkUrl",placeholder:"https://...",value:i,onChange:M=>l(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"linkText",children:"Button Text"}),e.jsx(ye,{id:"linkText",placeholder:"Learn More",value:o,onChange:M=>c(M.target.value)})]})]}),T&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Placement"}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select section placement..."})}),e.jsx(ys,{children:nRt.map(M=>e.jsx(Je,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(ye,{id:"startDate",type:"datetime-local",value:y,onChange:M=>g(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(ye,{id:"endDate",type:"datetime-local",value:b,onChange:M=>v(M.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(Mn,{id:"isActive",checked:p,onCheckedChange:x}),e.jsx(se,{htmlFor:"isActive",children:"Active"})]})})]})}function ymt({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=nRt.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=j.useState(null);return j.useEffect(()=>{(async()=>{const{count:u}=await U.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(u??0)})()},[s.id]),e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[e.jsx(Fp,{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(qe,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(qe,{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(lu,{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(ma,{className:"h-4 w-4"}):e.jsx(n0,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})]})}const Lne={open:{label:"Open",icon:Vr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Yd,color:"bg-blue-500"},resolved:{label:"Resolved",icon:To,color:"bg-green-500"},closed:{label:"Closed",icon:Rd,color:"bg-muted-foreground"}},vmt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function vpn(){var L,I;const{user:s}=Ns(),t=as(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState([]),[c,d]=j.useState("all"),[u,h]=j.useState("all"),[m,p]=j.useState(!1),{data:x=[],isLoading:y}=mt({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let O=U.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(O=O.eq("status",c)),u!=="all"&&(O=O.eq("category",u));const{data:$,error:q}=await O;if(q)throw q;return $}}),{data:g=[]}=mt({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:O,error:$}=await U.from("user_roles").select("user_id").eq("role","admin");if($)throw $;const q=O.map(le=>le.user_id),{data:W,error:G}=await U.from("profiles").select("id, name, email").in("id",q);if(G)throw G;const{data:K,error:ee}=await U.from("support_notification_settings").select("user_id, receive_notifications");if(ee)throw ee;const J=new Map((K==null?void 0:K.map(le=>[le.user_id,le.receive_notifications]))||[]);return W.map(le=>({...le,receives_notifications:J.get(le.id)||!1}))}}),{data:b=[]}=mt({queryKey:["admin-ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:O,error:$}=await U.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if($)throw $;return O},enabled:!!n}),v=vt({mutationFn:async({userId:O,enabled:$})=>{const{data:q}=await U.from("support_notification_settings").select("id").eq("user_id",O).maybeSingle();if(q){const{error:W}=await U.from("support_notification_settings").update({receive_notifications:$}).eq("user_id",O);if(W)throw W}else{const{error:W}=await U.from("support_notification_settings").insert({user_id:O,receive_notifications:$});if(W)throw W}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),re.success("Notification settings updated")},onError:()=>{re.error("Failed to update settings")}}),k=vt({mutationFn:async({ticketId:O,status:$})=>{const{error:q}=await U.from("support_tickets").update({status:$}).eq("id",O);if(q)throw q},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),n&&r({...n,status:n.status}),re.success("Status updated")},onError:()=>{re.error("Failed to update status")}}),C=vt({mutationFn:async({ticketId:O,assignedTo:$})=>{const{error:q}=await U.from("support_tickets").update({assigned_to:$}).eq("id",O);if(q)throw q},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),re.success("Ticket assigned")},onError:()=>{re.error("Failed to assign ticket")}}),T=vt({mutationFn:async({content:O,attachments:$})=>{var W,G;if(!n||!s)throw new Error("Missing data");const{error:q}=await U.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:O,is_admin_reply:!0,attachments:$});if(q)throw q;try{await U.functions.invoke("support-reply-notify",{body:{ticketId:n.id,ticketSubject:n.subject,replyContent:O,userEmail:(W=n.profiles)==null?void 0:W.email,userName:(G=n.profiles)==null?void 0:G.name}})}catch(K){console.error("Failed to send reply notification:",K)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",n==null?void 0:n.id]}),i(""),o([]),re.success("Reply sent!")},onError:()=>{re.error("Failed to send reply")}}),M=()=>{!a.trim()&&l.length===0||T.mutate({content:a,attachments:l})};j.useEffect(()=>{const O=U.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{U.removeChannel(O)}},[t]);const P=x.filter(O=>O.status==="open").length;return n?(Lne[n.status].icon,e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(_a,{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(qe,{variant:"secondary",children:vmt[n.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((L=n.profiles)==null?void 0:L.name)||"Unknown"," (",(I=n.profiles)==null?void 0:I.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm",children:"Status"})}),e.jsx(Re,{children:e.jsxs(vs,{value:n.status,onValueChange:O=>{k.mutate({ticketId:n.id,status:O}),r({...n,status:O})},children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"open",children:"Open"}),e.jsx(Je,{value:"in_progress",children:"In Progress"}),e.jsx(Je,{value:"resolved",children:"Resolved"}),e.jsx(Je,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm",children:"Assigned To"})}),e.jsx(Re,{children:e.jsxs(vs,{value:n.assigned_to||"unassigned",onValueChange:O=>{const $=O==="unassigned"?null:O;C.mutate({ticketId:n.id,assignedTo:$}),r({...n,assigned_to:$})},children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Unassigned"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"unassigned",children:"Unassigned"}),g.map(O=>e.jsx(Je,{value:O.id,children:O.name},O.id))]})]})})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(fr,{children:["Created on ",Bs(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Re,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Conversation"})}),e.jsxs(Re,{children:[e.jsx(lo,{className:"h-[300px] pr-4",children:b.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:b.map(O=>{var $,q;return e.jsxs("div",{className:`p-4 rounded-lg ${O.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:O.is_admin_reply?`${(($=O.profiles)==null?void 0:$.name)||"Admin"} (Support)`:((q=O.profiles)==null?void 0:q.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Bs(new Date(O.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:O.content}),O.attachments&&O.attachments.length>0&&e.jsx(PMt,{attachments:O.attachments})]},O.id)})})}),e.jsx(Xl,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ds,{placeholder:"Type your reply...",value:a,onChange:O=>i(O.target.value),className:"min-h-[80px]"}),e.jsx(B,{onClick:M,disabled:!a.trim()&&l.length===0||T.isPending,className:"self-end",children:e.jsx(Dr,{className:"h-4 w-4"})})]}),e.jsx(LMt,{value:l,onChange:o,disabled:T.isPending})]})]})]})]})})):e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Support Tickets"}),e.jsxs("p",{className:"text-muted-foreground",children:["Manage support requests from agents",P>0&&e.jsxs(qe,{variant:"destructive",className:"ml-2",children:[P," open"]})]})]}),e.jsxs(Fs,{open:m,onOpenChange:p,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(ic,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Email Notification Settings"}),e.jsx(kr,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:g.map(O=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Eo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:O.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:O.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[O.receives_notifications?e.jsx(Nx,{className:"h-4 w-4 text-primary"}):e.jsx(L5,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Mn,{checked:O.receives_notifications,onCheckedChange:$=>v.mutate({userId:O.id,enabled:$})})]})]},O.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(fa,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(xa,{children:[e.jsx(ss,{value:"all",children:"All"}),e.jsx(ss,{value:"open",children:"Open"}),e.jsx(ss,{value:"in_progress",children:"In Progress"}),e.jsx(ss,{value:"resolved",children:"Resolved"}),e.jsx(ss,{value:"closed",children:"Closed"})]})}),e.jsxs(vs,{value:u,onValueChange:h,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"All Categories"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Categories"}),e.jsx(Je,{value:"general",children:"General Support"}),e.jsx(Je,{value:"technology",children:"Technology Support"}),e.jsx(Je,{value:"crm",children:"CRM Support"}),e.jsx(Je,{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..."}):x.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"text-center py-12",children:[e.jsx(Yd,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets found"}),e.jsx("p",{className:"text-muted-foreground",children:"No support tickets match the current filters."})]})}):e.jsx("div",{className:"space-y-3",children:x.map(O=>{var q,W;const $=Lne[O.status].icon;return e.jsx(be,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(O),children:e.jsx(Re,{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:O.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(qe,{variant:"outline",className:"text-xs",children:vmt[O.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(q=O.profiles)==null?void 0:q.name," • ",Bs(new Date(O.created_at),"MMM d, yyyy")]}),O.assigned_to&&e.jsxs(qe,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(Eo,{className:"h-3 w-3"}),((W=g.find(G=>G.id===O.assigned_to))==null?void 0:W.name)||"Assigned"]})]})]}),e.jsxs(qe,{className:Lne[O.status].color,children:[e.jsx($,{className:"h-3 w-3 mr-1"}),Lne[O.status].label]})]})})},O.id)})})})]})]})})}const rRt=my.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 bpn({content:s,onChange:t,variables:n}){const r=eHe({extensions:[sHe,hHe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),mHe.configure({types:["heading","paragraph"]}),pHe,rRt],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});j.useEffect(()=>{r&&s!==r.getHTML()&&r.commands.setContent(s)},[s,r]);const a=l=>{r&&r.chain().focus().insertContent(`{{${l.key}}}`).run()},i=()=>{if(!r)return;const l=r.getAttributes("link").href,o=window.prompt("URL",l);if(o!==null){if(o===""){r.chain().focus().extendMarkRange("link").unsetLink().run();return}r.chain().focus().extendMarkRange("link").setLink({href:o}).run()}};return r?e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b bg-muted/30",children:[e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBold().run(),className:r.isActive("bold")?"bg-muted":"",children:e.jsx(BT,{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(KT,{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(ug,{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(kj,{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(ER,{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(TR,{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(MR,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:i,className:r.isActive("link")?"bg-muted":"",children:e.jsx(vc,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleCodeBlock().run(),className:r.isActive("codeBlock")?"bg-muted":"",children:e.jsx(qT,{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(aE,{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(eE,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(hz,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(xd,{align:"end",className:"w-64",children:n.map(l=>e.jsxs(wa,{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(QVe,{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(qe,{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 _pn(){const s=as(),[t,n]=j.useState(null),[r,a]=j.useState(null),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(!0),[p,x]=j.useState("visual"),{data:y,isLoading:g}=mt({queryKey:["email-templates"],queryFn:async()=>{const{data:T,error:M}=await U.from("email_templates").select("*").order("name");if(M)throw M;return T.map(P=>({...P,available_variables:P.available_variables||[]}))}}),b=vt({mutationFn:async T=>{const{error:M}=await U.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(M)throw M},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),re.success("Email template updated successfully"),n(null)},onError:T=>{re.error("Failed to update template: "+T.message)}}),v=T=>{n(T),l(T.subject),c(T.body_html),u(T.description||""),m(T.is_active),x("visual")},k=()=>{t&&b.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},C=(T,M)=>{let P=T;return M.forEach(L=>{const I=`{{${L.key}}}`,O=`[${L.label}]`;P=P.replace(new RegExp(I.replace(/[{}]/g,"\\$&"),"g"),O)}),P};return t?e.jsxs(Vs,{title:"Edit Email Template",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(B,{variant:"ghost",onClick:()=>n(null),children:[e.jsx(_a,{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(ma,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{onClick:k,disabled:b.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),b.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"}),t.name]}),e.jsxs(fr,{className:"mt-1",children:["Template slug: ",e.jsx("code",{className:"bg-muted px-1 rounded",children:t.slug})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{htmlFor:"active-toggle",children:"Active"}),e.jsx(Mn,{id:"active-toggle",checked:h,onCheckedChange:m})]})]})}),e.jsxs(Re,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ds,{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(se,{htmlFor:"subject",children:"Email Subject"}),e.jsx(ye,{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(se,{children:"Email Body"}),e.jsx(fa,{value:p,onValueChange:T=>x(T),children:e.jsxs(xa,{className:"h-8",children:[e.jsxs(ss,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(Cj,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(ss,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(qT,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),p==="visual"?e.jsx(bpn,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Ds,{value:o,onChange:T=>c(T.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(Fs,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Email Preview"}),e.jsxs(kr,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:C(o,t.available_variables)}})})]})})]}):e.jsx(Vs,{title:"Email Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Email Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and customize system email templates"})]}),g?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((T,M)=>e.jsx(be,{children:e.jsxs(Ft,{children:[e.jsx(gn,{className:"h-5 w-48"}),e.jsx(gn,{className:"h-4 w-96"})]})},M))}):e.jsx("div",{className:"grid gap-4",children:y==null?void 0:y.map(T=>e.jsxs(be,{className:"hover:shadow-md transition-shadow",children:[e.jsx(Ft,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-lg",children:[e.jsx(on,{className:"h-5 w-5 text-muted-foreground"}),T.name,!T.is_active&&e.jsx(qe,{variant:"secondary",children:"Inactive"})]}),e.jsx(fr,{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(ma,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{size:"sm",onClick:()=>v(T),children:[e.jsx(kp,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Re,{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(M=>e.jsx(qe,{variant:"outline",className:"font-mono text-xs",children:`{{${M.key}}}`},M.key))})]})]})})]},T.id))}),e.jsx(Fs,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(kr,{children:["Subject: ",r==null?void 0:r.subject.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),r&&e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:C(r.body_html,r.available_variables)}})})]})})]})})}function wpn(){const s=as(),[t,n]=j.useState("templates"),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[p,x]=j.useState({name:"",description:"",icon:"📧"}),{data:y=[]}=mt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:O,error:$}=await U.from("email_template_categories").select("*").order("sort_order");if($)throw $;return O}}),{data:g=[],isLoading:b}=mt({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:O,error:$}=await U.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if($)throw $;return O}}),v=vt({mutationFn:async O=>{const $={title:O.title,subject:O.subject,body:O.body,description:O.description||null,tone:O.tone||null,category_id:O.category_id||null,is_active:O.is_active};if(O.id){const{error:q}=await U.from("agent_email_templates").update($).eq("id",O.id);if(q)throw q}else{const{error:q}=await U.from("agent_email_templates").insert($);if(q)throw q}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),re.success(r?"Template updated":"Template created")},onError:()=>re.error("Failed to save template")}),k=vt({mutationFn:async O=>{const{error:$}=await U.from("agent_email_templates").delete().eq("id",O);if($)throw $},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),re.success("Template deleted")}}),C=vt({mutationFn:async O=>{const $={name:O.name,description:O.description||null,icon:O.icon};if(O.id){const{error:q}=await U.from("email_template_categories").update($).eq("id",O.id);if(q)throw q}else{const q=y.length>0?Math.max(...y.map(G=>G.sort_order))+1:0,{error:W}=await U.from("email_template_categories").insert({...$,sort_order:q});if(W)throw W}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),u(!1),re.success(i?"Category updated":"Category created")},onError:()=>re.error("Failed to save category")}),T=vt({mutationFn:async O=>{const{error:$}=await U.from("email_template_categories").delete().eq("id",O);if($)throw $},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),re.success("Category deleted")}}),M=()=>{a(null),m({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},P=O=>{a(O),m({title:O.title,subject:O.subject,body:O.body,description:O.description||"",tone:O.tone||"",category_id:O.category_id||"",is_active:O.is_active}),c(!0)},L=()=>{l(null),x({name:"",description:"",icon:"📧"}),u(!0)},I=O=>{l(O),x({name:O.name,description:O.description||"",icon:O.icon}),u(!0)};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(oh,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(fa,{value:t,onValueChange:n,children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"templates",className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"})," Templates"]}),e.jsxs(ss,{value:"categories",className:"gap-2",children:[e.jsx(ny,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(ns,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:M,className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Template"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:b?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin mx-auto"})})}):g.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):g.map(O=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:O.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:O.subject})]})}),e.jsx(xt,{className:"hidden md:table-cell",children:O.category?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[O.category.icon," ",O.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(xt,{className:"hidden md:table-cell",children:O.tone?e.jsx(qe,{variant:"secondary",children:O.tone}):"—"}),e.jsx(xt,{children:e.jsx(qe,{variant:O.is_active?"default":"secondary",children:O.is_active?"Active":"Inactive"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>P(O),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:async()=>{await Bi("Delete this template?")&&k.mutate(O.id)},children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},O.id))})]})})})]}),e.jsxs(ns,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:L,className:"gap-2",children:[e.jsx(Js,{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(O=>e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:O.icon})," ",O.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>I(O),children:e.jsx(Za,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:async()=>{await Bi("Delete this category?")&&T.mutate(O.id)},children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Re,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:O.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[g.filter($=>$.category_id===O.id).length," templates"]})]})]},O.id))})]})]}),e.jsx(Fs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:r?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:h.title,onChange:O=>m($=>({...$,title:O.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Category"}),e.jsxs(vs,{value:h.category_id,onValueChange:O=>m($=>({...$,category_id:O})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select category"})}),e.jsx(ys,{children:y.map(O=>e.jsxs(Je,{value:O.id,children:[O.icon," ",O.name]},O.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Subject Line"}),e.jsx(ye,{value:h.subject,onChange:O=>m($=>({...$,subject:O.target.value})),placeholder:"e.g. Hey {{first_name}}, just checking in!"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}",", ","{{full_name}}"," for merge variables"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email Body"}),e.jsx(Ds,{value:h.body,onChange:O=>m($=>({...$,body:O.target.value})),rows:12,placeholder:"Write your email template...",className:"resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description (internal)"}),e.jsx(ye,{value:h.description,onChange:O=>m($=>({...$,description:O.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Tone"}),e.jsx(ye,{value:h.tone,onChange:O=>m($=>({...$,tone:O.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{checked:h.is_active,onCheckedChange:O=>m($=>({...$,is_active:O}))}),e.jsx(se,{children:"Active"})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>v.mutate({...h,id:r==null?void 0:r.id}),disabled:v.isPending||!h.title||!h.subject||!h.body,children:[v.isPending&&e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(Fs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"sm:max-w-[450px]",children:[e.jsx($s,{children:e.jsx(zs,{children:i?"Edit Category":"New Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-[60px_1fr] gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Icon"}),e.jsx(ye,{value:p.icon,onChange:O=>x($=>({...$,icon:O.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Name"}),e.jsx(ye,{value:p.name,onChange:O=>x($=>({...$,name:O.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(ye,{value:p.description,onChange:O=>x($=>({...$,description:O.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>C.mutate({...p,id:i==null?void 0:i.id}),disabled:C.isPending||!p.name,children:[C.isPending&&e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const jpn=({brokerageId:s})=>{var ea,_s;const{toast:t}=pi(),n=Hn(),[r,a]=j.useState([]),[i,l]=j.useState(!0),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(new Set),[p,x]=j.useState(!1),[y,g]=j.useState({}),[b,v]=j.useState(!1),[k,C]=j.useState(!1),[T,M]=j.useState({email:"",name:"",password:"",phone:""}),[P,L]=j.useState(!1),[I,O]=j.useState(null),[$,q]=j.useState(!1),[W,G]=j.useState(!1),[K,ee]=j.useState(!1),[J,le]=j.useState(""),[ue,oe]=j.useState(!1),[ie,de]=j.useState([]),[we,je]=j.useState(!1),[xe,fe]=j.useState(!1),[Se,Ee]=j.useState(null),[Le,De]=j.useState({name:"",phone:"",email:""}),[Be,Ne]=j.useState(!1),[Ge,_e]=j.useState(!1),[Oe,Ae]=j.useState(null),[Xe,Ue]=j.useState("asc"),[Ze,Qe]=j.useState(!1),[Ye,nt]=j.useState(null),[rt,Fe]=j.useState(!1),[dt,Dt]=j.useState(null),[pt,zt]=j.useState(""),[Gt,qs]=j.useState(!1),[As,Bt]=j.useState(null);j.useEffect(()=>{Is(),At()},[s]);const At=async()=>{try{const{data:We,error:it}=await U.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(it)throw it;de((We==null?void 0:We.map(gt=>gt.user_id))||[])}catch(We){console.error("Error loading brokerage managers:",We)}},Is=async()=>{try{l(!0);const{data:We,error:it}=await U.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(it)throw it;const gt=We.agents||[];if(a(gt),gt.length>0){const St=gt.map(ts=>ts.id),{data:Ht}=await U.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",St);if(Ht&&Ht.length>0){const ts=Ht.map(Zs=>Zs.assistant_id),{data:Ms}=await U.from("profiles").select("id, name, email").in("id",ts),js={};for(const Zs of Ht){const Tn=Ms==null?void 0:Ms.find(vn=>vn.id===Zs.assistant_id);Tn&&(js[Zs.agent_id]={name:Tn.name||"",email:Tn.email||""})}g(js)}else g({})}}catch(We){console.error("Error loading agents:",We),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},jt=async()=>{if(!T.email||!T.name||!T.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}C(!0);try{const{data:{session:We}}=await U.auth.getSession(),it=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${We==null?void 0:We.access_token}`},body:JSON.stringify({...T,brokerageId:s})}),gt=await it.json();if(!it.ok)throw new Error(gt.error||"Failed to create agent");t({title:"Success",description:`Agent ${T.email} created successfully`}),M({email:"",name:"",password:"",phone:""}),v(!1),Is()}catch(We){console.error("Error creating agent:",We),t({title:"Error",description:We.message||"Failed to create agent",variant:"destructive"})}finally{C(!1)}},Qs=async We=>{try{const{data:{session:it}}=await U.auth.getSession(),gt=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:We})}),St=await gt.json();if(!gt.ok)throw new Error(St.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"})}},cn=async(We,it)=>{try{const{error:gt}=await U.functions.invoke("send-password-reset",{body:{email:We,redirectTo:window.location.origin}});if(gt)throw gt;t({title:"Password Reset Sent",description:`Password reset email sent to ${it}`})}catch(gt){console.error("Error sending password reset:",gt),t({title:"Error",description:gt.message||"Failed to send password reset email",variant:"destructive"})}},qt=We=>{O(We),L(!0)},Gs=We=>{Ee(We),De({name:We.name,phone:We.phone||"",email:We.email}),fe(!0)},Ls=async()=>{if(!Se)return;if(!Le.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const We=Le.email.trim().toLowerCase()!==Se.email.toLowerCase();Ne(!0);try{if(We){if(!Le.email.trim())throw new Error("Email is required");_e(!0);const{data:{session:gt}}=await U.auth.getSession(),St=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${gt==null?void 0:gt.access_token}`},body:JSON.stringify({agentId:Se.id,newEmail:Le.email.trim(),brokerageId:s})}),Ht=await St.json();if(_e(!1),!St.ok)throw new Error(Ht.error||"Failed to update email")}const{error:it}=await U.from("profiles").update({name:Le.name.trim(),phone:Le.phone.trim()||null}).eq("id",Se.id);if(it)throw it;t({title:"Success",description:"Agent profile updated successfully"}),fe(!1),Ee(null),Is()}catch(it){console.error("Error updating agent:",it),t({title:"Error",description:it.message||"Failed to update agent",variant:"destructive"})}finally{Ne(!1),_e(!1)}},sn=async()=>{if(!J){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}oe(!0);try{const{data:{session:We}}=await U.auth.getSession(),it=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${We==null?void 0:We.access_token}`},body:JSON.stringify({userId:J,role:"brokerage_manager",action:"add",brokerageId:s})}),gt=await it.json();if(!it.ok)throw new Error(gt.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),ee(!1),le(""),At()}catch(We){console.error("Error adding brokerage manager:",We),t({title:"Error",description:We.message||"Failed to add brokerage manager",variant:"destructive"})}finally{oe(!1)}},Hs=async We=>{try{const{data:{session:it}}=await U.auth.getSession(),gt=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:We,role:"brokerage_manager",action:"remove",brokerageId:s})}),St=await gt.json();if(!gt.ok)throw new Error(St.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"})}},nn=We=>ie.includes(We),tn=We=>{Dt(We),zt(""),Fe(!0)},_n=async()=>{if(!(!dt||!pt)){if(pt.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}qs(!0);try{const{data:{session:We}}=await U.auth.getSession(),it=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${We==null?void 0:We.access_token}`},body:JSON.stringify({agentId:dt.id,brokerageId:s,action:"set_password",newPassword:pt})}),gt=await it.json();if(!it.ok)throw new Error(gt.error||"Failed to set password");t({title:"Success",description:`Password set for ${dt.name}`}),Fe(!1),Dt(null),zt("")}catch(We){console.error("Error setting password:",We),t({title:"Error",description:We.message||"Failed to set password",variant:"destructive"})}finally{qs(!1)}}},Cn=async We=>{Bt(We.id);try{const{data:{session:it}}=await U.auth.getSession(),gt=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:We.id,brokerageId:s,action:"claim_account"})}),St=await gt.json();if(!gt.ok)throw new Error(St.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${We.name}`}),Is()}catch(it){console.error("Error claiming account:",it),t({title:"Error",description:it.message||"Failed to claim account",variant:"destructive"})}finally{Bt(null)}},Un=async()=>{if(I){q(!0);try{const{data:{session:We}}=await U.auth.getSession(),it=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${We==null?void 0:We.access_token}`},body:JSON.stringify({userId:I.id,brokerageId:s})}),gt=await it.json();if(!it.ok)throw new Error(gt.error||"Failed to remove agent");t({title:"Success",description:`${I.name} has been removed from your brokerage`}),L(!1),O(null),Is()}catch(We){console.error("Error removing agent:",We),t({title:"Error",description:We.message||"Failed to remove agent",variant:"destructive"})}finally{q(!1)}}},Kr=We=>{const it=We.trim().split(" ");return it.length>1?it[it.length-1].toLowerCase():We.toLowerCase()},jr=We=>{Oe===We?Ue(Xe==="asc"?"desc":"asc"):(Ae(We),Ue("asc"))},Xs=We=>Oe!==We?e.jsx(_x,{className:"ml-1 h-4 w-4"}):Xe==="asc"?e.jsx(Gm,{className:"ml-1 h-4 w-4"}):e.jsx(tx,{className:"ml-1 h-4 w-4"}),Ba=r.filter(We=>{if(d==="active"&&!We.claimed||d==="pending"&&We.claimed)return!1;if(!o)return!0;const it=o.toLowerCase();return We.name.toLowerCase().includes(it)||We.email.toLowerCase().includes(it)}),Hr=[...Ba].sort((We,it)=>{if(!Oe)return 0;let gt=0;return Oe==="name"?gt=Kr(We.name).localeCompare(Kr(it.name)):Oe==="status"&&(gt=We.claimed===it.claimed?0:We.claimed?-1:1),Xe==="asc"?gt:-gt});Ba.filter(We=>We.claimed&&!nn(We.id));const mr=We=>{m(it=>{const gt=new Set(it);return gt.has(We)?gt.delete(We):gt.add(We),gt})},pr=()=>{h.size===Hr.length?m(new Set):m(new Set(Hr.map(We=>We.id)))},rn=()=>{m(new Set)},Jn=async()=>{const We=Array.from(h);if(We.length===0)return;x(!0);let it=0,gt=0;try{const{data:{session:St}}=await U.auth.getSession();for(const Ht of We)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${St==null?void 0:St.access_token}`},body:JSON.stringify({userId:Ht})})).ok?it++:gt++}catch{gt++}it>0?t({title:"Success",description:`Welcome emails sent to ${it} agent${it>1?"s":""}${gt>0?` (${gt} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),rn()}catch(St){console.error("Error bulk sending welcome emails:",St),t({title:"Error",description:St.message||"Failed to send welcome emails",variant:"destructive"})}finally{x(!1)}};return i?e.jsx(be,{children:e.jsx(Re,{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(be,{children:[e.jsx(Ft,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Agents"}),e.jsx(fr,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>ee(!0),children:[e.jsx(_f,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(B,{variant:"outline",onClick:()=>G(!0),children:[e.jsx(pN,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(B,{onClick:()=>v(!0),children:[e.jsx(Sl,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Re,{children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-4 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:o,onChange:We=>c(We.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:d,onValueChange:We=>u(We),children:[e.jsx(gs,{className:"w-[160px]",children:e.jsx(bs,{placeholder:"Filter by status"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Agents"}),e.jsx(Je,{value:"active",children:"Active"}),e.jsx(Je,{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(gt=>h.has(gt.id)&>.email).map(gt=>({email:gt.email,name:gt.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(it)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:it}})},disabled:p,children:[e.jsx(jh,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:Jn,disabled:p,children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),p?"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(Tt,{className:"w-[40px]",children:e.jsx(wi,{checked:Hr.length>0&&h.size===Hr.length,onCheckedChange:pr,"aria-label":"Select all"})}),e.jsx(Tt,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>jr("name"),children:["Name (Last)",Xs("name")]})}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>jr("status"),children:["Status",Xs("status")]})}),e.jsx(Tt,{children:"Actions"})]})}),e.jsx(za,{children:Hr.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):Hr.map(We=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsx(wi,{checked:h.has(We.id),onCheckedChange:()=>mr(We.id),"aria-label":`Select ${We.name}`})}),e.jsx(xt,{className:"font-medium",children:We.name}),e.jsx(xt,{children:We.email}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[We.claimed?e.jsx(qe,{variant:"default",children:"Active"}):e.jsx(qe,{variant:"secondary",children:"Pending"}),nn(We.id)&&e.jsxs(qe,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(a0,{className:"mr-1 h-3 w-3"}),"Manager"]}),y[We.id]&&e.jsxs(qe,{variant:"outline",className:"text-xs",children:[e.jsx(Bn,{className:"mr-1 h-3 w-3"}),"Asst: ",y[We.id].name||y[We.id].email]})]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{nt(We),Qe(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(bf,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Gs(We),title:"Edit agent",children:e.jsx(Za,{className:"h-4 w-4"})}),!We.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Qs(We.id),title:"Resend welcome email",children:e.jsx(on,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Cn(We),title:"Claim account for agent",disabled:As===We.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(bN,{className:"h-4 w-4"})})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>tn(We),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(du,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>cn(We.email,We.name),title:"Send password reset email",children:e.jsx(b3,{className:"h-4 w-4"})}),nn(We.id)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Hs(We.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(_f,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>qt(We),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},We.id))})]})})]})]}),e.jsx(Fs,{open:b,onOpenChange:v,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Add New Agent"}),e.jsx(kr,{children:"Create a new agent account. They'll receive an email to set up their account."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",value:T.name,onChange:We=>M({...T,name:We.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",value:T.email,onChange:We=>M({...T,email:We.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(ye,{id:"phone",type:"tel",value:T.phone,onChange:We=>M({...T,phone:We.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"password",children:"Temporary Password"}),e.jsx(ye,{id:"password",type:"password",value:T.password,onChange:We=>M({...T,password:We.target.value}),placeholder:"Temporary password"})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(B,{onClick:jt,disabled:k,children:k?"Creating...":"Create Agent"})]})]})}),e.jsx(Fs,{open:P,onOpenChange:L,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Remove Agent"}),e.jsxs(kr,{children:["Are you sure you want to remove ",e.jsx("strong",{children:I==null?void 0:I.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>L(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Un,disabled:$,children:$?"Removing...":"Remove Agent"})]})]})}),e.jsx(IMt,{open:W,onOpenChange:G,fixedBrokerageId:s,onSuccess:Is}),e.jsx(Fs,{open:K,onOpenChange:ee,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Add Brokerage Manager"}),e.jsx(kr,{children:"Promote an existing active agent to brokerage manager. They will be able to manage agents and view analytics."})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{children:[e.jsx(se,{children:"Select Agent"}),e.jsxs(lc,{open:we,onOpenChange:je,children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":we,className:"w-full justify-between",children:[J?((ea=r.find(We=>We.id===J))==null?void 0:ea.name)+" ("+((_s=r.find(We=>We.id===J))==null?void 0:_s.email)+")":"Select an agent to promote...",e.jsx(fb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Jl,{className:"w-full p-0",align:"start",children:e.jsxs(Sb,{children:[e.jsx(Cb,{placeholder:"Search by name or email..."}),e.jsxs(Ab,{className:"max-h-[200px]",children:[e.jsx(Tb,{children:"No eligible agents found."}),e.jsx(Eb,{children:r.filter(We=>!nn(We.id)).map(We=>e.jsxs(Yy,{value:`${We.name} ${We.email}`,onSelect:()=>{le(We.id),je(!1)},children:[e.jsx(da,{className:`mr-2 h-4 w-4 ${J===We.id?"opacity-100":"opacity-0"}`}),We.name," (",We.email,")"]},We.id))})]})]})})]}),r.filter(We=>!nn(We.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>ee(!1),children:"Cancel"}),e.jsx(B,{onClick:sn,disabled:ue||!J,children:ue?"Adding...":"Add as Manager"})]})]})}),e.jsx(Fs,{open:xe,onOpenChange:fe,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Edit Agent"}),e.jsxs(kr,{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(se,{htmlFor:"edit-name",children:"Name"}),e.jsx(ye,{id:"edit-name",value:Le.name,onChange:We=>De({...Le,name:We.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"edit-email",children:"Email"}),e.jsx(ye,{id:"edit-email",type:"email",value:Le.email,onChange:We=>De({...Le,email:We.target.value}),placeholder:"agent@example.com"}),Le.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(se,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(ye,{id:"edit-phone",type:"tel",value:Le.phone,onChange:We=>De({...Le,phone:We.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>fe(!1),children:"Cancel"}),e.jsx(B,{onClick:Ls,disabled:Be||Ge,children:Ge?"Updating email...":Be?"Saving...":"Save Changes"})]})]})}),Ye&&e.jsx(RMt,{open:Ze,onOpenChange:We=>{Qe(We),We||nt(null)},userId:Ye.id,userName:Ye.name}),e.jsx(Fs,{open:rt,onOpenChange:Fe,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Set Password"}),e.jsxs(kr,{children:["Set a new password for ",dt==null?void 0:dt.name,". They will be able to log in with this password immediately."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"new-password",children:"New Password"}),e.jsx(ye,{id:"new-password",type:"password",value:pt,onChange:We=>zt(We.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(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>Fe(!1),children:"Cancel"}),e.jsx(B,{onClick:_n,disabled:Gt||!pt||pt.length<6,children:Gt?"Setting...":"Set Password"})]})]})})]})},Npn={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},kpn={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},Spn=s=>{switch(s){case"academy_video":return e.jsx(Zr,{className:"h-4 w-4"});case"template":return e.jsx($r,{className:"h-4 w-4"});case"toolbox":return e.jsx($r,{className:"h-4 w-4"});case"newsletter":return e.jsx(V_,{className:"h-4 w-4"});case"social_swag":return e.jsx(yn,{className:"h-4 w-4"});case"event":return e.jsx(ra,{className:"h-4 w-4"});default:return e.jsx(Tr,{className:"h-4 w-4"})}},Cpn=({brokerageId:s})=>{const{toast:t}=pi(),[n,r]=j.useState([]),[a,i]=j.useState([]),[l,o]=j.useState([]),[c,d]=j.useState(!0),[u,h]=j.useState(null);j.useEffect(()=>{m()},[s]);const m=async()=>{try{d(!0);const{data:y,error:g}=await U.from("profiles").select("id, name, email").eq("brokerage_id",s);if(g)throw g;const b=y.map($=>$.id),v=new Map(y.map($=>[$.id,$]));if(b.length===0){r([]),i([]),o([]);return}const{data:k,error:C}=await U.from("activity_logs").select("*").in("user_id",b).order("launched_at",{ascending:!1});if(C)throw C;const T=k.map($=>{var q,W;return{id:$.id,user_id:$.user_id,app_name:$.app_name,launched_at:$.launched_at,user_name:((q=v.get($.user_id))==null?void 0:q.name)||"Unknown",user_email:((W=v.get($.user_id))==null?void 0:W.email)||"Unknown"}});r(T);const{data:M,error:P}=await U.from("content_engagement_logs").select("*").in("user_id",b).order("created_at",{ascending:!1});if(P)throw P;const L=(M||[]).map($=>{var q,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:((q=v.get($.user_id))==null?void 0:q.name)||"Unknown",user_email:((W=v.get($.user_id))==null?void 0:W.email)||"Unknown"}});i(L);const I=new Map;y.forEach($=>{I.set($.id,{user_id:$.id,user_name:$.name,user_email:$.email,app_launches:0,content_views:0,last_activity:""})}),T.forEach($=>{const q=I.get($.user_id);q&&(q.app_launches++,(!q.last_activity||new Date($.launched_at)>new Date(q.last_activity))&&(q.last_activity=$.launched_at))}),L.forEach($=>{const q=I.get($.user_id);q&&(q.content_views++,(!q.last_activity||new Date($.created_at)>new Date(q.last_activity))&&(q.last_activity=$.created_at))});const O=Array.from(I.values()).filter($=>$.app_launches>0||$.content_views>0).sort(($,q)=>new Date(q.last_activity).getTime()-new Date($.last_activity).getTime());o(O)}catch(y){console.error("Error loading activity:",y),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},p=y=>n.filter(g=>g.user_id===y),x=y=>a.filter(g=>g.user_id===y);return c?e.jsx(be,{children:e.jsx(Re,{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(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Agent Activity"}),e.jsx(fr,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Re,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"App Launches"}),e.jsx(Tt,{className:"text-center",children:"Content Views"}),e.jsx(Tt,{children:"Last Active"})]})}),e.jsx(za,{children:l.length===0?e.jsx(un,{children:e.jsx(xt,{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(xt,{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(xt,{className:"text-center",children:e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(fd,{className:"h-3 w-3"}),y.app_launches]})}),e.jsx(xt,{className:"text-center",children:e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx($r,{className:"h-3 w-3"}),y.content_views]})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:y.last_activity&&oc(new Date(y.last_activity),{addSuffix:!0})})]},y.user_id))})]})})})]}),e.jsx(Fs,{open:!!u,onOpenChange:y=>!y&&h(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs($s,{children:[e.jsxs(zs,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(kr,{children:u==null?void 0:u.email})]}),e.jsxs(fa,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(xa,{className:"grid w-full grid-cols-2",children:[e.jsx(ss,{value:"content",children:"Content Engagement"}),e.jsx(ss,{value:"apps",children:"App Launches"})]}),e.jsx(ns,{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(Tt,{children:"Resource"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Action"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(za,{children:u&&x(u.id).length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&x(u.id).map(y=>e.jsxs(un,{children:[e.jsx(xt,{className:"max-w-[200px] truncate font-medium",children:y.resource_title}),e.jsx(xt,{children:e.jsxs(qe,{variant:"outline",className:"gap-1",children:[Spn(y.resource_type),Npn[y.resource_type]||y.resource_type]})}),e.jsx(xt,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:kpn[y.action_type]||y.action_type})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:oc(new Date(y.created_at),{addSuffix:!0})})]},y.id))})]})})}),e.jsx(ns,{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(Tt,{children:"App"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(za,{children:u&&p(u.id).length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&p(u.id).map(y=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsx(qe,{variant:"outline",children:y.app_name})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:oc(new Date(y.launched_at),{addSuffix:!0})})]},y.id))})]})})})]})]})})]})},Apn=({brokerageId:s})=>{const{toast:t}=pi(),[n,r]=j.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=j.useState(!0);j.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await U.from("profiles").select("id").eq("brokerage_id",s);if(c)throw c;const d=o.map(T=>T.id),u=d.length;if(d.length===0){i(!1);return}const{data:h,error:m}=await U.from("profiles").select("id, email").in("id",d);if(m)throw m;const{count:p}=await U.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),x=p||0,y=u-x,{count:g}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),b=new Date;b.setDate(b.getDate()-7);const{count:v}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",b.toISOString()),k=new Date;k.setMonth(k.getMonth()-1);const{count:C}=await U.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",k.toISOString());r({totalAgents:u,activeAgents:x,pendingAgents:y,totalLaunches:g||0,launchesThisWeek:v||0,launchesThisMonth:C||0})}catch(o){console.error("Error loading analytics:",o),t({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{i(!1)}};return a?e.jsx(be,{children:e.jsx(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(To,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(Vr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(vf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"This Week"}),e.jsx(vf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"This Month"}),e.jsx(vf,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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"})]})]})]})},Tpn=({brokerageId:s})=>{const[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState({description:"",maxUses:""});j.useEffect(()=>{h()},[s]);const h=async()=>{try{const{data:b,error:v}=await U.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(v)throw v;n(b||[])}catch(b){console.error("Error loading invite codes:",b),re.error("Failed to load invite links")}finally{a(!1)}},m=()=>Math.random().toString(36).substring(2,8).toUpperCase(),p=async()=>{l(!0);try{const b=m(),{error:v}=await U.from("invite_codes").insert({code:b,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(v)throw v;re.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(b){console.error("Error creating invite code:",b),re.error("Failed to create invite link")}finally{l(!1)}},x=async b=>{try{const{error:v}=await U.from("invite_codes").delete().eq("id",b);if(v)throw v;re.success("Invite link deleted"),n(t.filter(k=>k.id!==b))}catch(v){console.error("Error deleting invite code:",v),re.error("Failed to delete invite link")}},y=async(b,v)=>{try{const{error:k}=await U.from("invite_codes").update({is_active:!v}).eq("id",b);if(k)throw k;n(t.map(C=>C.id===b?{...C,is_active:!v}:C)),re.success(`Invite link ${v?"deactivated":"activated"}`)}catch(k){console.error("Error toggling invite code:",k),re.error("Failed to update invite link")}},g=b=>{const v=`${window.location.origin}/join?code=${b}`;navigator.clipboard.writeText(v),re.success("Link copied to clipboard!")};return r?e.jsx(be,{children:e.jsx(Re,{className:"flex items-center justify-center py-8",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(vc,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(fr,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(Fs,{open:o,onOpenChange:c,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Create Invite Link"}),e.jsx(kr,{children:"Create a new invite link for agents to join your brokerage"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description (optional)"}),e.jsx(ye,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:b=>u({...d,description:b.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(ye,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:b=>u({...d,maxUses:b.target.value})})]}),e.jsx(B,{onClick:p,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Re,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(vc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No invite links yet"}),e.jsx("p",{className:"text-sm",children:"Create one to start inviting agents"})]}):e.jsx("div",{className:"space-y-3",children:t.map(b=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"text-sm font-mono bg-muted px-2 py-0.5 rounded",children:b.code}),e.jsx(qe,{variant:b.is_active?"default":"secondary",children:b.is_active?"Active":"Inactive"})]}),b.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:b.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[b.uses_count," uses",b.max_uses&&` / ${b.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>g(b.code),title:"Copy link",children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>y(b.id,b.is_active),title:b.is_active?"Deactivate":"Activate",children:b.is_active?"Disable":"Enable"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>x(b.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(Rn,{className:"h-4 w-4"})})]})]},b.id))})})]})},Epn=({open:s,onOpenChange:t,referralCode:n,brokerageId:r,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=j.useState(""),[d,u]=j.useState([]),[h,m]=j.useState(""),[p,x]=j.useState(!1),y=C=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(C),g=()=>{const C=o.trim().toLowerCase();if(C&&y(C)&&!d.includes(C)){if(d.length>=10){re.error("Maximum 10 emails per invite");return}u([...d,C]),c("")}else C&&!y(C)?re.error("Please enter a valid email address"):d.includes(C)&&re.error("Email already added")},b=C=>{u(d.filter(T=>T!==C))},v=C=>{(C.key==="Enter"||C.key===",")&&(C.preventDefault(),g())},k=async()=>{if(d.length===0){re.error("Please add at least one email address");return}x(!0);try{const{data:C,error:T}=await U.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;C.successCount===C.totalCount?re.success(`${C.successCount} invite${C.successCount>1?"s":""} sent successfully!`):re.warning(`${C.successCount} of ${C.totalCount} invites sent. Some failed.`),u([]),m(""),t(!1),l==null||l()}catch(C){console.error("Error sending invites:",C),re.error("Failed to send invites. Please try again.")}finally{x(!1)}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[550px]",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(kr,{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(zo,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:"Earn $25/month for each referral!"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When they sign up and stay for 30 days, you save on your membership forever."})]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:C=>c(C.target.value),onKeyDown:v,onBlur:g}),e.jsx(B,{type:"button",variant:"secondary",onClick:g,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(C=>e.jsxs(qe,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[C,e.jsx("button",{type:"button",onClick:()=>b(C),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(dr,{className:"h-3 w-3"})})]},C))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(Ds,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:h,onChange:C=>m(C.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[h.length,"/500 characters"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(yn,{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||p,children:p?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent mr-2"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},Mpn=({brokerageId:s,refreshTrigger:t})=>{const[n,r]=j.useState([]),[a,i]=j.useState(!0);j.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await U.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;r(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(qe,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(To,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(qe,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(Rd,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Vr,{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(on,{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 ",Bs(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},Lpn=()=>{const{brokerageId:s,user:t}=Ns(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState([]),[u,h]=j.useState(!0),[m,p]=j.useState(!1),[x,y]=j.useState(0);j.useEffect(()=>{s&&g()},[s]);const g=async()=>{try{const[M,P]=await Promise.all([U.from("brokerages").select("name").eq("id",s).single(),t?U.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);M.data&&i(M.data.name),P.data&&o(P.data.name||"A LevelUp Member");const{data:L}=await U.from("referral_codes").select("code").eq("brokerage_id",s).single();if(L)r(L.code);else{const O=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await U.from("referral_codes").insert({brokerage_id:s,code:O}),r(O)}const{data:I}=await U.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",s).order("created_at",{ascending:!1});d(I||[])}catch(M){console.error("Error fetching referral data:",M)}finally{h(!1)}},b=()=>{const M=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(M),re.success("Referral link copied to clipboard!")},v=c.filter(M=>M.status==="qualified").length,k=c.filter(M=>M.status==="pending").length,C=v*25,T=Math.max(0,Math.ceil((299-C)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(be,{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(zo,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold",children:"Referral Rewards Program"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Earn $25/month off your membership for every broker you refer"})]})]}),e.jsx("div",{className:"mt-4 bg-background/80 rounded-lg p-4 border",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-3xl font-bold text-primary",children:["$",C]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),C>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(To,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),T>0&&C<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"})]}),C>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(yn,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Re,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs(B,{onClick:()=>p(!0),className:"w-full",size:"lg",children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(B,{onClick:b,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(ja,{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(Od,{className:"h-5 w-5 mx-auto text-green-600 mb-1"}),e.jsxs("p",{className:"text-2xl font-bold text-green-700 dark:text-green-400",children:["$",C]}),e.jsx("p",{className:"text-xs text-green-600 dark:text-green-500",children:"Monthly Savings"})]}),e.jsxs("div",{className:"text-center p-4 bg-primary/5 rounded-lg border border-primary/20",children:[e.jsx(Bn,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified Referrals"})]}),e.jsxs("div",{className:"text-center p-4 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-900",children:[e.jsx(Vr,{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(Mpn,{brokerageId:s,refreshTrigger:x}),c.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Your Referrals"}),c.slice(0,5).map(M=>{var P,L;return e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsx("span",{className:"text-sm truncate",children:((P=M.referred_brokerage)==null?void 0:P.name)||((L=M.referred_user)==null?void 0:L.email)||"Pending setup"}),e.jsxs(qe,{variant:M.status==="qualified"?"default":M.status==="pending"?"secondary":"destructive",className:M.status==="qualified"?"bg-green-600":"",children:[M.status==="qualified"&&e.jsx(To,{className:"h-3 w-3 mr-1"}),M.status]})]},M.id)})]})]})]}),e.jsx(Epn,{open:m,onOpenChange:p,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>y(M=>M+1)})]})},Ppn=({brokerageId:s})=>{const t=Hn(),{teams:n,isLoading:r}=SO(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(M=>M.id),{data:h}=await U.from("team_members").select("team_id, user_id, role").in("team_id",u);if(!h||h.length===0)return n.map(M=>({team_id:M.id,team_name:M.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const m=h.map(M=>M.user_id),p=h.filter(M=>M.role==="team_leader").map(M=>M.user_id),{data:x}=await U.from("profiles").select("id, name, avatar_url").in("id",p),y=new Map((x||[]).map(M=>[M.id,M])),{data:g}=await U.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",m),{data:b}=await U.from("deal_pipeline").select("owner_user_id").in("owner_user_id",m),{data:v}=await U.from("agent_videos").select("owner_user_id").in("owner_user_id",m).eq("is_deleted",!1),k=new Map;(g||[]).forEach(M=>{k.set(M.owner_user_id,(k.get(M.owner_user_id)||0)+1)});const C=new Map;(b||[]).forEach(M=>{C.set(M.owner_user_id,(C.get(M.owner_user_id)||0)+1)});const T=new Map;return(v||[]).forEach(M=>{T.set(M.owner_user_id,(T.get(M.owner_user_id)||0)+1)}),n.map(M=>{const P=h.filter(G=>G.team_id===M.id),L=P.find(G=>G.role==="team_leader"),I=L?y.get(L.user_id):null,O=P.map(G=>G.user_id),$=O.reduce((G,K)=>G+(k.get(K)||0),0),q=O.reduce((G,K)=>G+(C.get(K)||0),0),W=O.reduce((G,K)=>G+(T.get(K)||0),0);return{team_id:M.id,team_name:M.name,member_count:P.length,leader_name:(I==null?void 0:I.name)||null,leader_avatar:(I==null?void 0:I.avatar_url)||null,total_contacts:$,total_deals:q,total_videos:W}})},enabled:n.length>0});if(r||i)return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(u=>e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(gn,{className:"h-5 w-32"})}),e.jsx(Re,{children:e.jsx(gn,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Bn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create teams to organize your agents and track their performance."}),e.jsx(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(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Bn,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(Bn,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(DR,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(kx,{className:"h-4 w-4"})," Total Deals"]}),e.jsx("p",{className:"text-2xl font-bold",children:d.toLocaleString()})]})})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:(a||[]).map(u=>e.jsxs(be,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ut,{className:"text-lg",children:u.team_name}),e.jsxs(qe,{variant:"secondary",children:[u.member_count," members"]})]}),u.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(Ra,{className:"h-6 w-6",children:[e.jsx(Fi,{src:u.leader_avatar||""}),e.jsx(Da,{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(sy,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(Re,{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 →"})})]})},Ipn=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=Ns(),o=Hn(),{toast:c}=pi(),[d,u]=j.useState(""),[h,m]=j.useState(!0),p=i||(a.length>0?a[0].id:n);j.useEffect(()=>{if(!s||!t&&!r){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),p?x():a.length===0&&!n&&m(!1)},[s,t,r,p,o,a,i]);const x=async()=>{if(!p){m(!1);return}try{const{data:y,error:g}=await U.from("brokerages").select("name").eq("id",p).single();if(g)throw g;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(Vs,{title:"Manage Brokerages",description:"Loading brokerage information...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):p?e.jsx(Vs,{title:d||"Manage Brokerages",description:"Brokerage Management Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(vs,{value:i||"",onValueChange:l,children:[e.jsxs(gs,{className:"w-[280px]",children:[e.jsx(Ni,{className:"mr-2 h-4 w-4"}),e.jsx(bs,{placeholder:"Select brokerage"})]}),e.jsx(ys,{children:a.map(y=>e.jsx(Je,{value:y.id,children:y.name},y.id))})]})]}),e.jsxs(fa,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(xa,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(ss,{value:"agents",children:"Agents"}),e.jsx(ss,{value:"teams",children:"Teams"}),e.jsx(ss,{value:"invite",children:"Invite Links"}),e.jsx(ss,{value:"referrals",children:"Referrals"}),e.jsx(ss,{value:"leaderboard",children:"Leaderboard"}),e.jsx(ss,{value:"activity",children:"Activity"}),e.jsx(ss,{value:"analytics",children:"Analytics"}),e.jsx(ss,{value:"shares",children:"Shares"})]}),e.jsx(ns,{value:"agents",className:"space-y-4",children:e.jsx(jpn,{brokerageId:p})}),e.jsx(ns,{value:"teams",className:"space-y-4",children:e.jsx(Ppn,{brokerageId:p})}),e.jsx(ns,{value:"invite",className:"space-y-4",children:e.jsx(Tpn,{brokerageId:p})}),e.jsx(ns,{value:"referrals",className:"space-y-4",children:e.jsx(Lpn,{})}),e.jsx(ns,{value:"leaderboard",className:"space-y-4",children:e.jsx(gEt,{brokerageId:p,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(ns,{value:"activity",className:"space-y-4",children:e.jsx(Cpn,{brokerageId:p})}),e.jsx(ns,{value:"analytics",className:"space-y-4",children:e.jsx(Apn,{brokerageId:p})}),e.jsx(ns,{value:"shares",className:"space-y-4",children:e.jsx(uLt,{brokerageOnly:!0,brokerageId:p})})]})]})}):e.jsx(Vs,{title:"Manage Brokerages",description:"Brokerage Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ni,{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 Rpn({brokerageId:s,canManage:t}){const{user:n}=Ns(),[r,a]=j.useState([]),[i,l]=j.useState(!0),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,x]=j.useState(!1),[y,g]=j.useState(""),[b,v]=j.useState(""),[k,C]=j.useState(!1),T=async()=>{try{const{data:O,error:$}=await U.from("brokerage_announcements").select("*").eq("brokerage_id",s).order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1});if($)throw $;const q=O;if(q&&q.length>0){const W=[...new Set(q.map(J=>J.created_by))],{data:G}=await U.from("profiles").select("id, name, avatar_url").in("id",W),K=new Map((G==null?void 0:G.map(J=>[J.id,J]))||[]),ee=q.map(J=>({...J,author:K.get(J.created_by)||{name:"Unknown",avatar_url:null}}));a(ee)}else a([])}catch(O){console.error("Error fetching announcements:",O)}finally{l(!1)}};j.useEffect(()=>{T()},[s]);const M=()=>{g(""),v(""),C(!1),u(null)},P=O=>{O?(u(O),g(O.title),v(O.content),C(O.is_pinned)):M(),c(!0)},L=async()=>{if(!y.trim()||!b.trim()){re.error("Please fill in all fields");return}x(!0);try{if(d){const{error:O}=await U.from("brokerage_announcements").update({title:y.trim(),content:b.trim(),is_pinned:k,pinned_at:k?new Date().toISOString():null}).eq("id",d.id);if(O)throw O;re.success("Announcement updated")}else{const{error:O}=await U.from("brokerage_announcements").insert({brokerage_id:s,created_by:n==null?void 0:n.id,title:y.trim(),content:b.trim(),is_pinned:k,pinned_at:k?new Date().toISOString():null});if(O)throw O;re.success("Announcement created")}c(!1),M(),T()}catch(O){console.error("Error saving announcement:",O),re.error("Failed to save announcement")}finally{x(!1)}},I=async()=>{if(h)try{const{error:O}=await U.from("brokerage_announcements").delete().eq("id",h);if(O)throw O;re.success("Announcement deleted"),T()}catch(O){console.error("Error deleting announcement:",O),re.error("Failed to delete announcement")}finally{m(null)}};return i?e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(jh,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(jh,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>P(),className:"gap-1",children:[e.jsx(Js,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Re,{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(O=>{var $,q,W,G;return e.jsx("div",{className:`p-4 rounded-lg border ${O.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:[O.is_pinned&&e.jsx(JT,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:O.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:O.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(Ra,{className:"h-5 w-5",children:[e.jsx(Fi,{src:(($=O.author)==null?void 0:$.avatar_url)||void 0}),e.jsx(Da,{className:"text-[10px]",children:((W=(q=O.author)==null?void 0:q.name)==null?void 0:W.charAt(0))||"?"})]}),e.jsx("span",{children:(G=O.author)==null?void 0:G.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Bs(new Date(O.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>P(O),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>m(O.id),children:e.jsx(Rn,{className:"h-4 w-4"})})]})]})},O.id)})})})]}),e.jsx(Fs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",value:y,onChange:O=>g(O.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"content",children:"Content"}),e.jsx(Ds,{id:"content",value:b,onChange:O=>v(O.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(Mn,{id:"pinned",checked:k,onCheckedChange:C}),e.jsxs(se,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(JT,{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:L,disabled:p,children:p?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Nl,{open:!!h,onOpenChange:()=>m(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete Announcement"}),e.jsx(xl,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:I,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function Dpn({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=Q4e(),{user:a}=Ns(),[i,l]=j.useState([]),[o,c]=j.useState(!0),[d,u]=j.useState(""),[h,m]=j.useState(new Set);j.useEffect(()=>{(async()=>{try{const{data:y,error:g}=await U.from("profiles").select("id, name, email, phone, avatar_url, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("brokerage_id",s).order("name");if(g)throw g;if(l(y||[]),y&&y.length>0){const b=y.map(k=>k.id),{data:v}=await U.from("agent_assistant_assignments").select("agent_id").in("agent_id",b);v&&m(new Set(v.map(k=>k.agent_id)))}}catch(y){console.error("Error fetching agents:",y)}finally{c(!1)}})()},[s]);const p=i.filter(x=>{var y,g;return x.name.toLowerCase().includes(d.toLowerCase())||x.email.toLowerCase().includes(d.toLowerCase())||((y=x.title)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))||((g=x.areas_served)==null?void 0:g.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Re,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:[1,2,3,4].map(x=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},x))})})]}):e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5 text-primary"}),"Agent Roster",e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["(",i.length,")"]})]}),e.jsxs("div",{className:"relative w-full sm:w-64",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:d,onChange:x=>u(x.target.value),className:"pl-9"})]})]}),e.jsx(Re,{children:p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:d?"No agents match your search":"No agents in this brokerage yet"}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:p.map(x=>e.jsx(Opn,{agent:x,hasAssistant:h.has(x.id),canImpersonate:t&&x.id!==(a==null?void 0:a.id),onImpersonate:()=>n(x.id,"/my-brokerage"),impersonationLoading:r},x.id))})})]})}function Opn({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(Ra,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(Fi,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(Da,{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(qe,{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(oi,{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(Cu,{children:[e.jsx(Au,{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($R,{className:"h-4 w-4"})})}),e.jsxs(ou,{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(pa,{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(on,{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(ry,{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(vm,{className:"h-4 w-4"})})})]})]})}function Fpn({brokerageId:s}){const[t,n]=j.useState([]),[r,a]=j.useState(!0);if(j.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await U.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),a(!1);return}const u=c.map(y=>y.id),{data:h,error:m}=await U.from("agent_attendance_stats").select("user_id, total_points").in("user_id",u).order("total_points",{ascending:!1});if(m)throw m;const p=new Map(c.map(y=>[y.id,y])),x=(h||[]).filter(y=>y.total_points>0).map(y=>{const g=p.get(y.user_id);return{user_id:y.user_id,total_points:y.total_points,name:(g==null?void 0:g.name)||"Unknown",avatar_url:(g==null?void 0:g.avatar_url)||null}});n(x)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ll,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Re,{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(_3,{className:Et("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ll,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Re,{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:Et("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(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:o.avatar_url||void 0}),e.jsx(Da,{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 zpn({brokerageId:s}){const t=Hn(),[n,r]=j.useState([]),[a,i]=j.useState(!0);j.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await U.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),i(!1);return}const u=c.map(y=>y.id),h=new Map(c.map(y=>[y.id,y])),{data:m,error:p}=await U.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",u).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(p)throw p;const x=(m||[]).map(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(x)}catch(c){console.error("Error fetching listings:",c)}finally{i(!1)}})()},[s]);const l=o=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(o);return a?e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ia,{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(Js,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Re,{children:[n.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(ia,{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(Js,{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(ia,{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"})]})]})]})}const Bpn={primary_color:"",secondary_color:"",accent_color:"",logo_url:"",logo_dark_url:"",icon_mark_url:"",heading_font:"",body_font:"",legal_name:"",license_number:"",license_state:"",compliance_line:""};function $pn({brokerageId:s,canManage:t}){const{user:n}=Ns(),{toast:r}=pi(),{data:a,isLoading:i}=T6s(s),l=E6s(s),[o,c]=j.useState({...Bpn}),[d,u]=j.useState({show_equal_housing:!1,show_realtor_logo:!1,lock_colors:!1,lock_logo:!1}),[h,m]=j.useState(null),p={logo_url:j.useRef(null),logo_dark_url:j.useRef(null),icon_mark_url:j.useRef(null)};j.useEffect(()=>{a&&(c({primary_color:a.primary_color||"",secondary_color:a.secondary_color||"",accent_color:a.accent_color||"",logo_url:a.logo_url||"",logo_dark_url:a.logo_dark_url||"",icon_mark_url:a.icon_mark_url||"",heading_font:a.heading_font||"",body_font:a.body_font||"",legal_name:a.legal_name||"",license_number:a.license_number||"",license_state:a.license_state||"",compliance_line:a.compliance_line||""}),u({show_equal_housing:!!a.show_equal_housing,show_realtor_logo:!!a.show_realtor_logo,lock_colors:!!a.lock_colors,lock_logo:!!a.lock_logo}))},[a]);const x=(v,k)=>c(C=>({...C,[v]:k})),y=async(v,k)=>{if(n){m(v);try{const C=await fEt(n.id,k,`brokerage-${v}`);x(v,C),r({title:"Image uploaded"})}catch(C){r({title:"Upload failed",description:C.message,variant:"destructive"})}finally{m(null)}}},g=async()=>{try{await l.mutateAsync({...Object.fromEntries(Object.entries(o).map(([v,k])=>[v,k||null])),...d}),r({title:"Brokerage brand saved",description:"Agents in this brokerage now inherit these settings."})}catch(v){r({title:"Could not save",description:v.message,variant:"destructive"})}},b=(v,k)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:k}),e.jsxs("div",{className:"flex items-center gap-3",children:[o[v]&&e.jsx("img",{src:o[v],alt:k,className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:p[v],type:"file",accept:"image/*",className:"hidden",onChange:C=>{var T;return((T=C.target.files)==null?void 0:T[0])&&y(v,C.target.files[0])}}),e.jsxs(B,{type:"button",variant:"outline",disabled:!t||h===v,onClick:()=>{var C;return(C=p[v].current)==null?void 0:C.click()},children:[h===v?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ja,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload"})]}),o[v]&&t&&e.jsx(B,{type:"button",variant:"ghost",onClick:()=>x(v,""),children:"Remove"})]})]});return e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Ni,{className:"h-5 w-5"}),"Brokerage Brand"]}),e.jsx(fr,{children:t?"Every agent in this brokerage inherits these colors, logos and disclaimer wherever they leave their own brand blank — including AI-generated marketing through the LevelUp connector.":"These are your brokerage brand settings. Only a brokerage manager can change them."})]}),e.jsx(Re,{className:"space-y-6",children:i?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["primary_color","Primary color","#2a4c64"],["secondary_color","Secondary color","#1c1c1c"],["accent_color","Accent color","#B8965A"]].map(([v,k,C])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:k}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{type:"color",className:"h-10 w-14 p-1",disabled:!t,value:o[v]||C,onChange:T=>x(v,T.target.value)}),e.jsx(ye,{disabled:!t,value:o[v],placeholder:C,onChange:T=>x(v,T.target.value)})]})]},v))}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[b("logo_url","Logo (light background)"),b("logo_dark_url","Logo (dark background)"),b("icon_mark_url","Icon mark")]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Heading font"}),e.jsx(ye,{disabled:!t,value:o.heading_font,placeholder:"Playfair Display",onChange:v=>x("heading_font",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Body font"}),e.jsx(ye,{disabled:!t,value:o.body_font,placeholder:"Inter",onChange:v=>x("body_font",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Legal brokerage name"}),e.jsx(ye,{disabled:!t,value:o.legal_name,placeholder:"Acme Realty, Inc.",onChange:v=>x("legal_name",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Brokerage license #"}),e.jsx(ye,{disabled:!t,value:o.license_number,placeholder:"DRE #01234567",onChange:v=>x("license_number",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"License state"}),e.jsx(ye,{disabled:!t,value:o.license_state,placeholder:"CA",onChange:v=>x("license_state",v.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Required disclaimer / compliance line"}),e.jsx(Ds,{disabled:!t,rows:2,value:o.compliance_line,placeholder:"Each office independently owned and operated. Information deemed reliable but not guaranteed.",onChange:v=>x("compliance_line",v.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Included in every brand kit so AI-generated marketing carries it automatically."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[["show_equal_housing","Include Equal Housing logo"],["show_realtor_logo","Include REALTOR® logo"],["lock_colors","Lock colors (agents cannot override)"],["lock_logo","Lock logo (agents cannot override)"]].map(([v,k])=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx(se,{className:"text-sm font-normal",children:k}),e.jsx(Mn,{disabled:!t,checked:d[v],onCheckedChange:C=>u(T=>({...T,[v]:C}))})]},v))}),t&&e.jsxs(B,{onClick:g,disabled:l.isPending,children:[l.isPending?e.jsx(Wt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"mr-2 h-4 w-4"}),"Save brokerage brand"]})]})})]})}function Upn(){const{user:s,isAdmin:t,isBrokerageManager:n}=Ns(),r=Hn(),[a,i]=j.useState(!0),[l,o]=j.useState(null),[c,d]=j.useState(""),[u,h]=j.useState(0),[m,p]=j.useState(!1),[x,y]=j.useState(!1);return j.useEffect(()=>{(async()=>{if(s)try{const{data:b}=await U.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(b!=null&&b.brokerage_id)){i(!1);return}o(b.brokerage_id);const{data:v}=await U.from("brokerages").select("name").eq("id",b.brokerage_id).maybeSingle();v&&d(v.name);const{count:k}=await U.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",b.brokerage_id);if(h(k||0),t)p(!0),y(!0);else if(n){const{data:C}=await U.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",b.brokerage_id).maybeSingle();p(!!C),y(!!C)}}catch(b){console.error("Error fetching brokerage info:",b)}finally{i(!1)}})()},[s,t,n]),a?e.jsx(Vs,{title:"My Brokerage",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):l?e.jsx(Vs,{title:c||"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 bg-muted/50 rounded-lg px-4 py-2",children:[e.jsx(Bn,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[u," ",u===1?"Agent":"Agents"]})]}),x&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>r("/brokerage-content"),children:[e.jsx(Op,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(B,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(ia,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx($pn,{brokerageId:l,canManage:m}),e.jsx(Rpn,{brokerageId:l,canManage:m}),e.jsx(Dpn,{brokerageId:l,canManage:m}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(Fpn,{brokerageId:l}),e.jsx(zpn,{brokerageId:l})]})]})}):e.jsx(Vs,{title:"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ni,{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 qpn(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 Vpn(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 bmt={video:{icon:fd,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:$r,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:Rc,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ra,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:Ac,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function Hpn({item:s,canManage:t}){const[n,r]=j.useState(!1),[a,i]=j.useState(null),l=jks(),o=Hn(),c=bmt[s.content_type]||bmt.link,d=c.icon,u=j.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?qpn(s.url):null,[s]);j.useEffect(()=>{u||!s.url||s.content_type!=="video"||!Vpn(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(x=>x.ok?x.json():null).then(x=>{x!=null&&x.thumbnail_url&&i(x.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,u]);const h=u||a,m=()=>{o(`/brokerage-content/${s.id}`)},p=async()=>{try{await l.mutateAsync(s.id),re.success("Content deleted")}catch{re.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(be,{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(Re,{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(qe,{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(qe,{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:["📅 ",Bs(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",Bs(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,onClick:x=>x.stopPropagation(),children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(W0,{className:"h-4 w-4"})})}),e.jsx(xd,{align:"end",children:e.jsxs(wa,{onClick:x=>{x.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Nl,{open:n,onOpenChange:r,children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete Content"}),e.jsxs(xl,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:p,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Gpn(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 _mt=[{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 Wpn({brokerageId:s,categories:t}){var de;const{user:n}=Ns(),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(""),[d,u]=j.useState("📁"),[h,m]=j.useState(!1);j.useRef(null);const[p,x]=j.useState("video"),[y,g]=j.useState(""),[b,v]=j.useState(""),[k,C]=j.useState(""),[T,M]=j.useState(""),[P,L]=j.useState(""),[I,O]=j.useState(""),[$,q]=j.useState(""),W=wks(),G=Nks(s),K=kks(),ee=Sks(s),J=()=>{x("video"),g(""),v(""),C(""),M(""),L(""),O(""),q("")},le=async(we,je)=>{var fe;const xe=(fe=we.target.files)==null?void 0:fe[0];if(xe){m(!0);try{const Se=xe.name.split(".").pop(),Ee=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${Se}`,{error:Le}=await U.storage.from("brokerage-content").upload(Ee,xe);if(Le)throw Le;const{data:{publicUrl:De}}=U.storage.from("brokerage-content").getPublicUrl(Ee);je==="file"?(M(De),p==="graphic"&&!P&&L(De)):L(De),re.success("File uploaded")}catch(Se){re.error(Se.message||"Upload failed")}finally{m(!1)}}},ue=async()=>{if(!y.trim()){re.error("Title is required");return}if(n)try{await W.mutateAsync({brokerage_id:s,category_id:$||null,content_type:p,title:y.trim(),description:b.trim()||null,url:k.trim()||null,file_url:T.trim()||null,thumbnail_url:P.trim()||null,event_date:I?new Date(I).toISOString():null,created_by:n.id}),re.success("Content added!"),J(),a(!1)}catch(we){re.error(we.message||"Failed to add content")}},oe=async()=>{if(o.trim())try{await G.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),re.success("Category created")}catch(we){re.error(we.message||"Failed to create category")}},ie=async()=>{try{await ee.mutateAsync(),re.success("Default categories created")}catch{re.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Fs,{open:r,onOpenChange:a,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Add Brokerage Content"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Content Type"}),e.jsxs(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:_mt.map(we=>e.jsx(Je,{value:we.value,children:we.label},we.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(de=_mt.find(we=>we.value===p))==null?void 0:de.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Category"}),e.jsxs(vs,{value:$,onValueChange:q,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select category (optional)"})}),e.jsx(ys,{children:t.map(we=>e.jsxs(Je,{value:we.id,children:[we.icon," ",we.name]},we.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Title *"}),e.jsx(ye,{value:y,onChange:we=>g(we.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{value:b,onChange:we=>v(we.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:p==="video"?"Video URL":p==="graphic"?"Canva / Image URL":p==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(ye,{value:k,onChange:we=>{const je=we.target.value;if(C(je),p==="video"&&!P){const xe=Gpn(je);xe&&L(xe)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:p==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"file",accept:p==="pdf"?".pdf,.doc,.docx":"image/*",onChange:we=>le(we,"file"),disabled:h}),h&&e.jsx(Wt,{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(se,{children:"Thumbnail Image (optional)"}),e.jsx(ye,{type:"file",accept:"image/*",onChange:we=>le(we,"thumbnail"),disabled:h}),P&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:P,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>L(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx(dr,{className:"h-3 w-3"})})]})]}),p==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Event Date & Time"}),e.jsx(ye,{type:"datetime-local",value:I,onChange:we=>O(we.target.value)})]}),e.jsxs(B,{onClick:ue,disabled:W.isPending||!y.trim(),className:"w-full",children:[W.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(Fs,{open:i,onOpenChange:l,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",children:[e.jsx(ic,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(Os,{className:"max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{children:"Manage Categories"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[t.length===0&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No categories yet"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ie,disabled:ee.isPending,children:[ee.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(we=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[we.icon," ",we.name]}),!we.is_default&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await K.mutateAsync(we.id),re.success("Category deleted")},children:e.jsx(dr,{className:"h-4 w-4"})})]},we.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(ye,{value:d,onChange:we=>u(we.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(ye,{value:o,onChange:we=>c(we.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:we=>we.key==="Enter"&&oe()}),e.jsx(B,{size:"sm",onClick:oe,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function Kpn(){const{user:s,isAdmin:t,isBrokerageManager:n}=Ns(),[r,a]=j.useState(!0),[i,l]=j.useState(null),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,x]=j.useState("");j.useEffect(()=>{(async()=>{if(s)try{const{data:C}=await U.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(C!=null&&C.brokerage_id)){a(!1);return}l(C.brokerage_id);const{data:T}=await U.from("brokerages").select("name").eq("id",C.brokerage_id).maybeSingle();if(T&&c(T.name),t)u(!0);else if(n){const{data:M}=await U.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",C.brokerage_id).maybeSingle();u(!!M)}}catch(C){console.error("Error fetching brokerage info:",C)}finally{a(!1)}})()},[s,t,n]);const{data:y=[]}=vks(i),{data:g=[],isLoading:b}=bks(i,h),v=j.useMemo(()=>{if(!p.trim())return g;const k=p.toLowerCase();return g.filter(C=>{var T;return C.title.toLowerCase().includes(k)||((T=C.description)==null?void 0:T.toLowerCase().includes(k))||C.content_type.toLowerCase().includes(k)})},[g,p]);return r?e.jsx(Vs,{title:"Brokerage Content",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):i?e.jsx(Vs,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(Wpn,{brokerageId:i,categories:y}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search content...",value:p,onChange:k=>x(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))]})]}),b?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):v.length===0?e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(ny,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:p.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:p.trim()?"Try a different search term or category.":d?"Add your first piece of content above.":"Your brokerage hasn't added content yet."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(k=>e.jsx(Hpn,{item:k,canManage:d},k.id))})]})}):e.jsx(Vs,{title:"Brokerage Content",description:"Content Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ni,{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 wmt={video:{icon:fd,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:$r,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:Rc,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ra,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:Ac,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function Ypn(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 Zpn(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function Xpn(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function Qpn(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function Jpn(){const{contentId:s}=$i(),{data:t,isLoading:n}=mt({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:u}=await U.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(u)throw u;return d},enabled:!!s});if(n)return e.jsx(Vs,{title:"Brokerage Content",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!t)return e.jsx(Vs,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ni,{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(Yn,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=wmt[t.content_type]||wmt.link,a=r.icon,i=t.url||t.file_url,l=i&&Zpn(i)?Ypn(i):null,o=i&&Xpn(i)?Qpn(i):null,c=l||o;return e.jsx(Vs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(Yn,{to:"/brokerage-content",children:[e.jsx(_a,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(qe,{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(qe,{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 ",Bs(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(be,{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(be,{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(be,{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(be,{children:e.jsx(Re,{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(be,{children:e.jsxs(Re,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(ra,{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:Bs(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(ii,{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 nSe={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 efn(s="open"){const{user:t}=Ns();return mt({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let n=U.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, avatar_url)").order("created_at",{ascending:!1});if(s==="open")n=n.eq("status","open");else if(s==="mine")n=n.eq("requester_user_id",t.id);else if(s==="filled")n=n.in("status",["filled","completed"]);else if(s==="my_claims"){const{data:i}=await U.from("brokerage_help_claims").select("request_id").eq("claimant_user_id",t.id),l=(i||[]).map(o=>o.request_id);if(l.length===0)return[];n=n.in("id",l)}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function tfn(s){return mt({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, phone, avatar_url)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function sfn(s){return mt({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("brokerage_help_claims").select("*, claimant:profiles!brokerage_help_claims_claimant_user_id_fkey(name, email, phone, avatar_url)").eq("request_id",s).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function nfn(){const s=as(),{user:t,brokerageId:n}=Ns();return vt({mutationFn:async r=>{if(!t||!n)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await U.from("brokerage_help_requests").insert({...r,brokerage_id:n,requester_user_id:t.id}).select().single();if(i)throw i;try{await U.functions.invoke("brokerage-help-notify",{body:{request_id:a.id}})}catch(l){console.warn("notify failed (non-blocking):",l)}return a},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function rfn(){const s=as(),{user:t}=Ns();return vt({mutationFn:async({request_id:n,note:r})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await U.from("brokerage_help_claims").insert({request_id:n,claimant_user_id:t.id,note:r}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function afn(){const s=as();return vt({mutationFn:async({claim_id:t,request_id:n,claimant_user_id:r})=>{const{error:a}=await U.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await U.from("brokerage_help_requests").update({status:"filled",assigned_user_id:r}).eq("id",n);if(i)throw i;try{await U.functions.invoke("brokerage-help-claim-decision",{body:{claim_id:t}})}catch(l){console.warn("claim decision notify failed:",l)}},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-request",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function ifn(){const s=as();return vt({mutationFn:async({claim_id:t})=>{const{error:n}=await U.from("brokerage_help_claims").update({status:"declined",responded_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]})}})}function ofn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("brokerage_help_requests").update({status:"cancelled"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function lfn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("brokerage_help_requests").update({status:"completed"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function cfn(){const{user:s,brokerageId:t}=Ns(),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 U.from("brokerage_help_notification_prefs").select("*").eq("user_id",s.id).eq("brokerage_id",t).maybeSingle();if(l)throw l;return i},enabled:!!s&&!!t}),a=vt({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await U.from("brokerage_help_notification_prefs").upsert({user_id:s.id,brokerage_id:t,email_enabled:i},{onConflict:"user_id,brokerage_id"});if(l)throw l},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-help-prefs"]})}});return{...r,setEmailEnabled:a.mutate,isSaving:a.isPending}}function dfn(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 ufn(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 hfn({req:s,onClick:t}){var i;const n=nSe[s.request_type],r=dfn(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(be,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Re,{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(qe,{variant:"secondary",className:"text-xs",children:[n.emoji," ",n.label]}),s.status!=="open"&&e.jsx(qe,{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(Vr,{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(oi,{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(Od,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:ufn(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 mfn(){var c;const s=Hn(),{brokerageId:t}=Ns(),[n,r]=j.useState("open"),{data:a=[],isLoading:i}=efn(n),l=cfn(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(Vs,{title:"Help Board",description:"Ask a teammate to cover an open house, showing, or shift.",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx(fa,{value:n,onValueChange:d=>r(d),children:e.jsxs(xa,{children:[e.jsx(ss,{value:"open",children:"Open"}),e.jsx(ss,{value:"mine",children:"My Posts"}),e.jsx(ss,{value:"my_claims",children:"My Claims"}),e.jsx(ss,{value:"filled",children:"Filled"})]})}),e.jsxs(B,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(be,{className:"bg-muted/30 border-dashed",children:e.jsxs(Re,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(Nx,{className:"h-4 w-4 text-primary"}):e.jsx(L5,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email-notif",className:"text-sm font-medium cursor-pointer",children:"Email me when teammates post new help requests"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can still browse the board either way."})]})]}),e.jsx(Mn,{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(be,{className:"bg-muted/30 border-dashed",children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(tN,{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(hfn,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(Vs,{title:"Help Board",description:"Brokerage Help Board",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(tN,{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 pfn(){const s=Hn(),{toast:t}=pi(),n=nfn(),[r,a]=j.useState("open_house"),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(""),[y,g]=j.useState(""),[b,v]=j.useState(""),[k,C]=j.useState(""),[T,M]=j.useState(""),[P,L]=j.useState(""),[I,O]=j.useState("goodwill"),[$,q]=j.useState(""),[W,G]=j.useState(""),K=r==="open_house"||r==="showing_coverage",ee=r!=="general",J=(ue,oe)=>!ue||!oe?null:`${ue}T${oe}:00`,le=async ue=>{if(ue.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const oe=J(d,h),ie=J(d,p);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:oe,event_end_at:ie,address:K&&y.trim()||null,city:K&&b.trim()||null,state:K&&k.trim()||null,zip:K&&T.trim()||null,mls_number:P.trim()||null,compensation_type:I,compensation_amount:$?Number($):null,compensation_notes:W.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(oe){t({title:"Could not post",description:(oe==null?void 0:oe.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(Vs,{title:"Post a Help Request",description:"Ask a teammate to cover for you",children:e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(_a,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:le,children:e.jsx(be,{children:e.jsxs(Re,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(nSe).map(ue=>{const oe=nSe[ue],ie=ue===r;return e.jsxs("button",{type:"button",onClick:()=>a(ue),className:`text-left p-3 rounded-lg border-2 transition ${ie?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:oe.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:oe.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:oe.description})]},ue)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:i,onChange:ue=>l(ue.target.value),placeholder:r==="open_house"?"Open house at 123 Oak St — Sat 1-3pm":"Quick description",maxLength:120,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Details"}),e.jsx(Ds,{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})]}),ee&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"date",children:"Date"}),e.jsx(ye,{id:"date",type:"date",value:d,onChange:ue=>u(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"start",children:"Start"}),e.jsx(ye,{id:"start",type:"time",value:h,onChange:ue=>m(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"end",children:"End"}),e.jsx(ye,{id:"end",type:"time",value:p,onChange:ue=>x(ue.target.value)})]})]}),K&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"address",children:"Address"}),e.jsx(ye,{id:"address",value:y,onChange:ue=>g(ue.target.value),placeholder:"123 Oak St"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(ye,{id:"city",value:b,onChange:ue=>v(ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:k,onChange:ue=>C(ue.target.value.toUpperCase()),maxLength:2})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zip",children:"Zip"}),e.jsx(ye,{id:"zip",value:T,onChange:ue=>M(ue.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(ye,{id:"mls",value:P,onChange:ue=>L(ue.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(se,{children:"Compensation"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{val:"goodwill",label:"Goodwill",sub:"Pay it forward"},{val:"flat_fee",label:"Flat Fee",sub:"Dollar amount"},{val:"referral_percent",label:"Referral %",sub:"On the deal"}].map(ue=>{const oe=I===ue.val;return e.jsxs("button",{type:"button",onClick:()=>O(ue.val),className:`text-left p-3 rounded-lg border-2 transition ${oe?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:ue.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ue.sub})]},ue.val)})}),I!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"amount",children:I==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(ye,{id:"amount",type:"number",min:"0",step:I==="referral_percent"?"1":"5",value:$,onChange:ue=>q(ue.target.value),placeholder:I==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(ye,{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(Wt,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function ffn(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 qPe(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function xfn(){var P,L,I,O,$,q,W,G;const{id:s}=$i(),t=Hn(),{user:n}=Ns(),{toast:r}=pi(),{data:a,isLoading:i}=tfn(s),{data:l=[]}=sfn(s),o=rfn(),c=afn(),d=ifn(),u=ofn(),h=lfn(),[m,p]=j.useState("");if(i)return e.jsx(Vs,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(Vs,{title:"Not Found",description:"",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(_a,{className:"h-4 w-4"})," Back to board"]}),e.jsx("p",{className:"mt-4 text-muted-foreground",children:"Request not found or you don't have access."})]});const x=nSe[a.request_type],y=ffn(a.event_start_at,a.event_end_at),g=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),b=(n==null?void 0:n.id)===a.requester_user_id,v=l.find(K=>K.claimant_user_id===(n==null?void 0:n.id)),k=l.find(K=>K.status==="accepted"),C=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)",M=async()=>{if(!m.trim()){r({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:m.trim()}),r({title:"You're in!",description:"The requester will review and pick someone."}),p("")}catch(K){r({title:"Could not submit",description:K==null?void 0:K.message,variant:"destructive"})}};return e.jsx(Vs,{title:a.title,description:`${x.emoji} ${x.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(_a,{className:"h-4 w-4"})," Back to board"]}),e.jsx(be,{children:e.jsxs(Re,{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(qe,{variant:"secondary",children:[x.emoji," ",x.label]}),e.jsx(qe,{variant:C?"default":"outline",className:"capitalize",children:a.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(Ra,{className:"h-7 w-7",children:[e.jsx(Fi,{src:((P=a.requester)==null?void 0:P.avatar_url)||void 0}),e.jsx(Da,{children:qPe((L=a.requester)==null?void 0:L.name)})]}),e.jsx("span",{children:((I=a.requester)==null?void 0:I.name)||"Teammate"})]})]}),e.jsx("h1",{className:"text-2xl font-bold",children:a.title}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2",children:[y&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Vr,{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})]})]}),g&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(oi,{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:g})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Od,{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(HT,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"MLS"}),e.jsx("div",{children:a.mls_number})]})]})]}),a.description&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h3",{className:"text-xs uppercase tracking-wide font-semibold text-muted-foreground mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:a.description})]}),a.compensation_notes&&e.jsxs("p",{className:"text-sm text-muted-foreground italic",children:["💰 ",a.compensation_notes]})]})}),!b&&C&&!v&&e.jsx(be,{children:e.jsxs(Re,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Ds,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:m,onChange:K=>p(K.target.value),rows:3,maxLength:400}),e.jsxs(B,{onClick:M,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(Wt,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!b&&v&&e.jsx(be,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Re,{className:"p-4 flex items-center gap-3",children:[e.jsx(da,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",v.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[v.status==="pending"&&"Waiting for the requester to pick.",v.status==="accepted"&&"You're confirmed — see contact info below.",v.status==="declined"&&"They went with someone else this time."]})]})]})}),k&&(b||k.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(be,{className:"border-primary/30",children:e.jsxs(Re,{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(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:((O=k.claimant)==null?void 0:O.avatar_url)||void 0}),e.jsx(Da,{children:qPe(($=k.claimant)==null?void 0:$.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(q=k.claimant)==null?void 0:q.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Covering this request"})]})]}),e.jsxs("div",{className:"space-y-1.5 text-sm",children:[((W=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(on,{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(pa,{className:"h-4 w-4"})," ",k.claimant.phone]})]})]})}),b&&e.jsx(be,{children:e.jsxs(Re,{className:"p-6 space-y-3",children:[e.jsxs("h3",{className:"font-semibold",children:["Interested agents (",l.length,")"]}),l.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No claims yet. Hang tight — your teammates were just notified."}),l.map(K=>{var ee,J,le,ue,oe;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:((ee=K.claimant)==null?void 0:ee.avatar_url)||void 0}),e.jsx(Da,{children:qPe((J=K.claimant)==null?void 0:J.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx("div",{className:"font-medium",children:((le=K.claimant)==null?void 0:le.name)||"Teammate"}),e.jsx(qe,{variant:"outline",className:"capitalize text-xs",children:K.status})]}),K.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',K.note,'"']}),K.status==="pending"&&C&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(B,{size:"sm",onClick:()=>c.mutate({claim_id:K.id,request_id:a.id,claimant_user_id:K.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(da,{className:"h-3.5 w-3.5"})," Pick ",((oe=(ue=K.claimant)==null?void 0:ue.name)==null?void 0:oe.split(" ")[0])||"them"]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:K.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(dr,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},K.id)}),b&&C&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>u.mutate(a.id),disabled:u.isPending,children:"Cancel request"})}),b&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(B,{size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Mark complete"})})]})})]})})}function aRt({onSelect:s,maxHeight:t="460px"}){const[n,r]=j.useState(""),[a,i]=j.useState("all"),{data:l=[],isLoading:o}=mt({queryKey:["newsletter-graphics-picker"],queryFn:async()=>{const{data:u,error:h}=await U.from("newsletter_graphics").select("*").eq("is_active",!0).order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0}).order("created_at",{ascending:!1});if(h)throw h;return u||[]}}),c=j.useMemo(()=>{const u=new Set;return l.forEach(h=>u.add(h.category||"general")),["all",...Array.from(u).sort()]},[l]),d=j.useMemo(()=>{const u=n.trim().toLowerCase();return l.filter(h=>a!=="all"&&h.category!==a?!1:u?h.title.toLowerCase().includes(u)||(h.description||"").toLowerCase().includes(u)||(h.tags||[]).some(m=>m.toLowerCase().includes(u)):!0)},[l,n,a]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{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(Wt,{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(ac,{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(qe,{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 gfn=[{key:"search",label:"Search for Properties",icon:Fr,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:pa,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:on,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:ra,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:ia,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:Od,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:oi,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:zd,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:lu,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function jmt(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function yfn(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function iRt({html:s,onChange:t}){const{user:n}=Ns(),r=j.useRef(null),a=j.useRef(""),i=j.useRef(t);i.current=t;const[l,o]=j.useState("desktop"),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,x]=j.useState(""),y=j.useRef(null),g=()=>{var jt;const At=(jt=r.current)==null?void 0:jt.contentDocument,Is=At==null?void 0:At.getSelection();Is&&Is.rangeCount>0&&(At!=null&&At.body.contains(Is.anchorNode))&&(y.current=Is.getRangeAt(0).cloneRange())},b=()=>{var qt;const At=c.current,Is=(qt=r.current)==null?void 0:qt.contentDocument;if(!At||!Is)return;let jt=h.trim();jt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(jt)&&(jt="https://"+jt),At.setAttribute("href",jt),At.setAttribute("target","_blank");const Qs=p.trim();Qs&&Qs!==(At.textContent||"").trim()&&(At.textContent=Qs);const cn=` `+Is.documentElement.outerHTML;a.current=cn,i.current(cn),u(!1)};j.useEffect(()=>{var jt,Qs;const At=r.current;if(!At||a.current===s)return;const Is=()=>{const cn=At.contentDocument;if(!cn)return;cn.open(),cn.write(s||""),cn.close(),a.current=s;const qt=cn.body;if(!qt)return;qt.setAttribute("contenteditable","true"),qt.style.outline="none",qt.style.minHeight="400px",qt.style.cursor="text";const Gs=()=>{const sn=` `+cn.documentElement.outerHTML;a.current=sn,i.current(sn)};qt.addEventListener("input",Gs),qt.addEventListener("blur",Gs),qt.addEventListener("mouseup",g),qt.addEventListener("keyup",g),cn.addEventListener("selectionchange",g);const Ls=sn=>{var Un;const Hs=sn.target,nn=Hs==null?void 0:Hs.closest("a");if(nn){if(sn.metaKey||sn.ctrlKey||sn.shiftKey)return;sn.preventDefault(),sn.stopPropagation(),c.current=nn,m(nn.getAttribute("href")||""),x((nn.textContent||"").trim()),u(!0);return}const tn=cn.getSelection();if(!tn)return;const _n=(Un=cn.caretRangeFromPoint)==null?void 0:Un.call(cn,sn.clientX,sn.clientY),Cn=_n==null?void 0:_n.startContainer;if(Cn&&Cn.nodeType===Node.TEXT_NODE){const Kr=Cn.textContent||"",jr=_n.startOffset,Xs=Kr.lastIndexOf("[",jr),Ba=Kr.indexOf("]",jr);if(Xs!==-1&&Ba!==-1&&Ba>Xs){const Hr=cn.createRange();Hr.setStart(Cn,Xs),Hr.setEnd(Cn,Ba+1),tn.removeAllRanges(),tn.addRange(Hr),y.current=Hr.cloneRange()}}};qt.addEventListener("click",Ls,!0)};((jt=At.contentDocument)==null?void 0:jt.readyState)==="complete"||(Qs=At.contentDocument)!=null&&Qs.body?Is():At.addEventListener("load",Is,{once:!0})},[s]);const v=(At,Is)=>{var cn;const jt=(cn=r.current)==null?void 0:cn.contentDocument;if(!jt)return;jt.body.focus(),jt.execCommand(At,!1,Is);const Qs=` `+jt.documentElement.outerHTML;a.current=Qs,i.current(Qs)},k=()=>{const At=window.prompt("Enter URL (https://...)");At&&v("createLink",At)},C=(At,Is)=>{var cn;const jt=(cn=r.current)==null?void 0:cn.contentDocument;if(!jt)return;if(jt.body.focus(),Is==="cursor"&&y.current&&jt.body.contains(y.current.startContainer)){const qt=jt.getSelection();if(qt){qt.removeAllRanges(),qt.addRange(y.current),jt.execCommand("insertHTML",!1,At);const Gs=` `+jt.documentElement.outerHTML;a.current=Gs,i.current(Gs);return}}Is==="top"?jt.body.insertAdjacentHTML("afterbegin",At):jt.body.insertAdjacentHTML("beforeend",At);const Qs=` `+jt.documentElement.outerHTML;a.current=Qs,i.current(Qs)},[T,M]=j.useState(!1),[P,L]=j.useState(null),[I,O]=j.useState(""),[$,q]=j.useState(""),[W,G]=j.useState("#406E71"),[K,ee]=j.useState("cursor"),J=At=>{L(At),O(At.defaultText),q(""),M(!0)},le=()=>{if(!P)return;const At=$.trim();if(!P.isForward&&!At)return;let Is=At;if(P.isForward){const qt=At||"",Gs=encodeURIComponent("You should see this newsletter"),Ls=encodeURIComponent(qt?`I thought you'd like this — take a look: ${qt} `:`I thought you'd like this newsletter — take a look! `);Is=`mailto:?subject=${Gs}&body=${Ls}`}else P.hrefPrefix==="tel:"?Is="tel:"+At.replace(/[^0-9+]/g,""):P.hrefPrefix==="mailto:"?Is="mailto:"+At:/^https?:\/\//i.test(At)||(Is="https://"+At);const jt=(I||P.defaultText).replace(/[<>]/g,""),Qs=W||"#406E71",cn=`
${jt}

 

`;C(cn,K),M(!1)},[ue,oe]=j.useState(!1),[ie,de]=j.useState(""),[we,je]=j.useState(""),[xe,fe]=j.useState(""),[Se,Ee]=j.useState("cursor"),Le=(()=>{if(we.trim())return we.trim();const At=jmt(ie);return At?`https://i.ytimg.com/vi/${At}/hqdefault.jpg`:""})(),De=()=>{de(""),je(""),fe(""),oe(!0)},Be=()=>{const At=ie.trim();if(!At)return;let Is=At;/^https?:\/\//i.test(Is)||(Is="https://"+Is);const jt=jmt(Is),Qs=jt?null:yfn(Is);let cn=we.trim();!cn&&jt&&(cn=`https://i.ytimg.com/vi/${jt}/hqdefault.jpg`),!cn&&Qs&&(cn=`https://vumbnail.com/${Qs}.jpg`),cn||(cn="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const qt=(xe||"Watch the video").replace(/[<>]/g,""),Gs=`
${qt}
▶ ${qt}

 

`.trim();C(Gs,Se),oe(!1)},[Ne,Ge]=j.useState(!1),[_e,Oe]=j.useState(""),[Ae,Xe]=j.useState(""),[Ue,Ze]=j.useState("full"),[Qe,Ye]=j.useState("cursor"),[nt,rt]=j.useState(!1),Fe=j.useRef(null),dt=()=>{Oe(""),Xe(""),Ze("full"),Ge(!0)},Dt=async At=>{var Is;if(!n){re.error("You must be signed in to upload images");return}if(At.size>10*1024*1024){re.error("Image must be under 10MB");return}rt(!0);try{const jt=((Is=At.name.split(".").pop())==null?void 0:Is.toLowerCase())||"png",Qs=`${n.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${jt}`,{error:cn}=await U.storage.from("email-assets").upload(Qs,At,{cacheControl:"3600",upsert:!1,contentType:At.type});if(cn)throw cn;const{data:qt}=U.storage.from("email-assets").getPublicUrl(Qs);Oe(qt.publicUrl),re.success("Image uploaded")}catch(jt){re.error(jt.message||"Upload failed")}finally{rt(!1)}},pt=()=>{if(!_e.trim())return;const At=(Ae||"").replace(/[<>"]/g,""),Is=Ue==="half"?280:560,jt=`
${At}

 

`.trim();C(jt,Qe),Ge(!1)},{data:zt,isLoading:Gt}=mt({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&ue,queryFn:async()=>{const{data:At,error:Is}=await U.from("agent_videos").select("id, title, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",n.id).eq("is_deleted",!1).eq("status","ready").not("share_token","is",null).order("created_at",{ascending:!1}).limit(50);if(Is)throw Is;return At||[]}}),qs=At=>{At.share_token&&(de(`https://video.relevelup.com/share/video/${At.share_token}`),je(`https://video.relevelup.com/thumb/${At.share_token}`),fe(At.title||"Watch the video"))},As=l==="mobile"?390:"100%",Bt=l==="mobile"?390:void 0;return e.jsxs("div",{className:"rounded-md border overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b bg-muted/40 px-2 py-1.5 flex-wrap",children:[e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("bold"),title:"Bold",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:()=>v("italic"),title:"Italic",children:e.jsx(KT,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("underline"),title:"Underline",children:e.jsx(dz,{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:()=>v("insertUnorderedList"),title:"Bullet list",children:e.jsx(ug,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("insertOrderedList"),title:"Numbered list",children:e.jsx(kj,{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(vc,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("undo"),title:"Undo",children:e.jsx(aE,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>v("redo"),title:"Redo",children:e.jsx(eE,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(kd,{children:[e.jsx(Sd,{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(lu,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(xd,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(TE,{children:"Insert a call-to-action"}),e.jsx(uy,{}),gfn.map(At=>{const Is=At.icon;return e.jsxs(wa,{onClick:()=>J(At),children:[e.jsx(Is,{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:dt,children:[e.jsx(ac,{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:De,children:[e.jsx(Zr,{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(Az,{type:"single",value:l,onValueChange:At=>At&&o(At),size:"sm",className:"h-7",children:[e.jsx(aD,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(Cj,{className:"h-3.5 w-3.5"})}),e.jsx(aD,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(Jy,{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(lu,{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:As,maxWidth:Bt,height:480,border:l==="mobile"?"1px solid hsl(var(--border))":"none",borderRadius:l==="mobile"?12:0,boxShadow:l==="mobile"?"0 4px 12px rgba(0,0,0,0.08)":"none"}})}),e.jsx(Fs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(ye,{id:"link-edit-text",value:p,onChange:At=>x(At.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(ye,{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(Nr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:b,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(Fs,{open:T,onOpenChange:M,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx($s,{children:e.jsxs(zs,{children:["Insert ",(P==null?void 0:P.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"cta-text",children:"Button text"}),e.jsx(ye,{id:"cta-text",value:I,onChange:At=>O(At.target.value),placeholder:P==null?void 0:P.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"cta-value",children:P==null?void 0:P.helper}),e.jsx(ye,{id:"cta-value",value:$,onChange:At=>q(At.target.value),placeholder:P==null?void 0:P.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{id:"cta-color",type:"color",value:W,onChange:At=>G(At.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(ye,{value:W,onChange:At=>G(At.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Position"}),e.jsxs(ob,{value:K,onValueChange:At=>ee(At),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:"cursor",id:"cta-cursor"}),e.jsxs(se,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(lu,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:"top",id:"cta-top"}),e.jsxs(se,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Gm,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:"bottom",id:"cta-bottom"}),e.jsxs(se,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(tx,{className:"h-3.5 w-3.5"}),"Bottom of newsletter"]})]})]})]}),e.jsx("div",{className:"rounded-md border bg-muted/30 p-4 flex justify-center",children:e.jsx("div",{style:{backgroundColor:W,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:I||(P==null?void 0:P.defaultText)})})]}),e.jsxs(Nr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>M(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:le,disabled:!(P!=null&&P.isForward)&&!$.trim(),children:"Insert Button"})]})]})}),e.jsx(Fs,{open:ue,onOpenChange:oe,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Insert Video Block"})}),e.jsxs(fa,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(xa,{className:"grid w-full grid-cols-3",children:[e.jsx(ss,{value:"library",children:"My Library"}),e.jsx(ss,{value:"url",children:"From URL"}),e.jsx(ss,{value:"record",children:"Record New"})]}),e.jsxs(ns,{value:"library",className:"space-y-3 mt-2",children:[Gt?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(Wt,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!zt||zt.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(Zr,{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:zt.map(At=>{const Is=ie.includes(At.share_token||"___"),jt=At.share_token?`https://video.relevelup.com/thumb/${At.share_token}`:At.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>qs(At),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${Is?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[jt?e.jsx("img",{src:jt,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(Zr,{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(fd,{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(se,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(ye,{id:"vid-title-lib",value:xe,onChange:At=>fe(At.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(ns,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(ye,{id:"vid-url",value:ie,onChange:At=>de(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(se,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(ye,{id:"vid-title",value:xe,onChange:At=>fe(At.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(ye,{id:"vid-thumb",value:we,onChange:At=>je(At.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(ns,{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(Zr,{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(se,{children:"Position"}),e.jsxs(ob,{value:Se,onValueChange:At=>Ee(At),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:"cursor",id:"vid-cursor"}),e.jsxs(se,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(lu,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:"top",id:"vid-top"}),e.jsxs(se,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Gm,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:"bottom",id:"vid-bottom"}),e.jsxs(se,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(tx,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Le&&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:Le,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(Nr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>oe(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:Be,disabled:!ie.trim(),children:"Insert Video"})]})]})}),e.jsx(Fs,{open:Ne,onOpenChange:Ge,children:e.jsxs(Os,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Insert Image"})}),e.jsxs(fa,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(xa,{className:"grid w-full grid-cols-3",children:[e.jsx(ss,{value:"library",children:"Library"}),e.jsx(ss,{value:"upload",children:"Upload"}),e.jsx(ss,{value:"url",children:"From URL"})]}),e.jsx(ns,{value:"library",className:"mt-2",children:e.jsx(aRt,{maxHeight:"380px",onSelect:At=>{Oe(At.image_url),Ae||Xe(At.title)}})}),e.jsxs(ns,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:Fe,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:At=>{var jt;const Is=(jt=At.target.files)==null?void 0:jt[0];Is&&Dt(Is),At.target.value=""}}),_e?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:_e,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:()=>Oe(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var At;return(At=Fe.current)==null?void 0:At.click()},disabled:nt,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:nt?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{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(Ja,{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(ns,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"img-url",children:"Image URL"}),e.jsx(ye,{id:"img-url",value:_e,onChange:At=>Oe(At.target.value),placeholder:"https://..."})]}),_e&&/^https?:\/\//i.test(_e)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:_e,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(se,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(ye,{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(se,{children:"Size"}),e.jsxs(ob,{value:Ue,onValueChange:At=>Ze(At),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:"full",id:"img-full"}),e.jsx(se,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:"half",id:"img-half"}),e.jsx(se,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Position"}),e.jsxs(ob,{value:Qe,onValueChange:At=>Ye(At),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:"cursor",id:"img-cursor"}),e.jsxs(se,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(lu,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:"top",id:"img-top"}),e.jsxs(se,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Gm,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(eh,{value:"bottom",id:"img-bottom"}),e.jsxs(se,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(tx,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>Ge(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:pt,disabled:!_e.trim()||nt,children:"Insert Image"})]})]})})]})}const Nmt="newsletter-content",vfn="inline-images";function bfn(s,t){const n=atob(s),r=new Array(n.length);for(let a=0;a{const{data:L}=await U.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return L}}),T=(C==null?void 0:C.role)==="team_leader",M=(C==null?void 0:C.team_id)??null;j.useEffect(()=>{s&&(d((n==null?void 0:n.title)??""),h((n==null?void 0:n.description)??""),p((n==null?void 0:n.html_content)??jfn()),y((n==null?void 0:n.is_template)??!1),b((n==null?void 0:n.share_scope)??"private"))},[s,n]);const P=async()=>{if(a){if(!c.trim()){re.error("Please enter a title");return}if(!m.trim()){re.error("Newsletter content is empty");return}k(!0);try{const L=await _fn(m);L!==m&&p(L);const I={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:L,is_template:x,share_scope:g,shared_team_id:g==="team"?M:null,shared_brokerage_id:g==="brokerage"?o:null};if(g==="team"&&!M){re.error("You must be a team leader to share with a team"),k(!1);return}if(g==="brokerage"&&!l){re.error("Only brokerage managers can share to a brokerage"),k(!1);return}if(g==="global"&&!i){re.error("Only admins can publish global starter templates"),k(!1);return}let O;if(n!=null&&n.id?{error:O}=await U.from("agent_custom_newsletters").update(I).eq("id",n.id):{error:O}=await U.from("agent_custom_newsletters").insert(I),O)throw O;re.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(L){re.error(L.message||"Failed to save")}finally{k(!1)}}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx($s,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx(zs,{children:n!=null&&n.id?"Edit Newsletter":"Create Newsletter"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"acn-title",children:"Title *"}),e.jsx(ye,{id:"acn-title",value:c,onChange:L=>d(L.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(ye,{id:"acn-desc",value:u,onChange:L=>h(L.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(Mn,{id:"acn-template",checked:x,onCheckedChange:y}),e.jsx(se,{htmlFor:"acn-template",className:"cursor-pointer",children:"Save as reusable template"}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:"Templates can be duplicated and reused for future newsletters"})]}),(T||l||i)&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx(se,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(ob,{value:g,onValueChange:L=>b(L),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(eh,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(se,{htmlFor:"s-private",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Private"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Only you can see this"})]})]}),T&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(eh,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(se,{htmlFor:"s-team",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Share with my team"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"All members of your team can use this"})]})]}),l&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(eh,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(se,{htmlFor:"s-brokerage",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Share with my brokerage"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"All agents in your brokerage can use this"})]})]}),i&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(eh,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(se,{htmlFor:"s-global",className:"cursor-pointer font-normal",children:[e.jsx("span",{className:"font-medium",children:"Global starter template"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Visible to all users as a starter"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"mb-2 block",children:"Content"}),e.jsx(iRt,{html:m,onChange:p})]})]}),e.jsxs(Nr,{className:"px-6 py-3 border-t",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:v,children:"Cancel"}),e.jsxs(B,{onClick:P,disabled:v,children:[v?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),n!=null&&n.id?"Save Changes":"Create"]})]})]})})}function jfn(){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 xWe=/\[[^\]\[<>]{2,80}\]/g,Nfn=/^\[\s*(?:\/?\s*if\b[^\]]*|endif|else|x-apple-[\w-]*|data-[\w-]*|object [^\]]*|cdata[^\]]*)\s*\]$/i;function gWe(s){return!Nfn.test(s)}function kfn(s){return(s.match(xWe)||[]).filter(gWe)}function kmt(s){const t=s.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function Sfn(s){const t=[],n=new RegExp(xWe.source,"g");let r;for(;(r=n.exec(s))!==null;)gWe(r[0])&&t.push({token:r[0],start:r.index});const a=t.reduce((l,o)=>(l[o.token]=(l[o.token]||0)+1,l),{}),i={};return t.map((l,o)=>{const c=l.token.slice(1,-1),d=/^#+$/.test(c);i[l.token]=(i[l.token]||0)+1;const u=t[o+1],h=u?u.token.slice(1,-1):"";let m;return d?m=u&&!/^#+$/.test(h)?`Date · ${kmt(h)}`:`Date ${i[l.token]}`:(m=kmt(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 Cfn({html:s,onChange:t,originalHtml:n}){const r=j.useMemo(()=>Sfn(s),[s]),[a,i]=j.useState({}),[l,o]=j.useState([]),c=j.useRef(null);c.current===null&&s&&(c.current=n??s);const d=j.useRef(!1);j.useEffect(()=>{if(d.current){d.current=!1;return}i({}),o([])},[s]);const u=()=>{const b=new RegExp(xWe.source,"g");let v=0;const k=s.replace(b,C=>{if(!gWe(C))return C;const T=(a[v]||"").trim();return v+=1,T||C});k!==s&&(o(C=>[...C,{html:s,values:a}]),d.current=!0,i({}),t(k))},h=()=>{const b=l[l.length-1];b&&(o(v=>v.slice(0,-1)),d.current=!0,i(b.values),t(b.html))},m=()=>{const b=c.current;!b||b===s||(o([]),d.current=!0,i({}),t(b))},p=l.length>0,x=!!c.current&&c.current!==s,y=e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{type:"button",size:"sm",variant:"outline",onClick:h,disabled:!p,children:[e.jsx(fK,{className:"h-3.5 w-3.5 mr-1"}),"Undo last fill"]}),e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:m,disabled:!x,children:[e.jsx(bm,{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(Rr,{className:"h-4 w-4 text-emerald-600 shrink-0"}),e.jsx("span",{className:"text-muted-foreground",children:"All template fields are filled in. Your name, phone, website and brokerage fill in automatically."})]}),(p||x)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pl-6",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Made a typo?"}),y]})]});const g=r.filter(b=>(a[b.index]||"").trim()).length;return e.jsxs("div",{className:"rounded-xl border border-amber-500/40 bg-amber-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(hd,{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(qe,{variant:"secondary",className:"shrink-0",children:[g,"/",r.length," ready"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-4",children:r.map(b=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:b.label}),e.jsx(ye,{value:a[b.index]||"",placeholder:b.hint,className:"h-10 text-sm",onChange:v=>i(k=>({...k,[b.index]:v.target.value})),onKeyDown:v=>{v.key==="Enter"&&(v.preventDefault(),u())}})]},b.index))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{type:"button",size:"sm",onClick:u,children:[e.jsx(ez,{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 Cq(){var a;const{user:s}=Ns(),{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([U.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),U.from("profiles").select("email, name").eq("id",s.id).maybeSingle()]),o=i.data,c=l.data;return{reply_to_email:((d=o==null?void 0:o.reply_to_email)==null?void 0:d.trim())||((u=c==null?void 0:c.email)==null?void 0:u.trim())||s.email||null,display_name:((h=o==null?void 0:o.display_name)==null?void 0:h.trim())||((m=c==null?void 0:c.name)==null?void 0:m.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:n,settings:t}}function AAe(){const{user:s}=Ns();return mt({queryKey:["verified-sender-check",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{const[t,n]=await Promise.all([U.from("user_verified_senders").select("id, email, status").eq("user_id",s.id),U.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]),r=t.data||[],a=r.filter(l=>l.status==="verified"),i=r.filter(l=>l.status==="pending");return{hasVerifiedSes:a.length>0,hasPendingSes:i.length>0,hasAnySender:r.length>0,hasGmail:!!n.data,verifiedEmails:a.map(l=>l.email),pendingEmails:i.map(l=>l.email)}}})}function TAe({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=Hn();return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{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(po,{className:"h-5 w-5"})}),e.jsx(zs,{children:"Verify your sending email first"})]}),e.jsx(kr,{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(Vr,{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(on,{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(Nr,{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 Aq(){const s=ei();return mt({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(n)throw n;return t},enabled:!!s})}function Afn(s){return mt({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(n)throw n;return t},enabled:!!s})}function yWe(){const s=as(),t=ei();return vt({mutationFn:async({name:n,color:r})=>{const{data:a,error:i}=await U.from("contact_custom_tags").insert({owner_user_id:t,name:n.trim(),color:r||"#6366F1"}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]})}})}function Tfn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("contact_custom_tags").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function Efn(){const s=as();return vt({mutationFn:async({id:t,name:n,color:r})=>{const a={};n!==void 0&&(a.name=n.trim()),r!==void 0&&(a.color=r);const{error:i}=await U.from("contact_custom_tags").update(a).eq("id",t);if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function oRt(){const s=as();return vt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await U.from("contact_custom_tag_assignments").insert({contact_id:t,tag_id:n});if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function Mfn(){const s=as();return vt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await U.from("contact_custom_tag_assignments").delete().eq("contact_id",t).eq("tag_id",n);if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function EAe(){const s=ei();return mt({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags(id, name, color)");if(n)throw n;return t},enabled:!!s})}function vWe(){const{user:s}=Ns();return mt({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function lRt(){const s=as(),{user:t}=Ns();return vt({mutationFn:async({name:n,filters:r,sort_by:a})=>{const{data:i,error:l}=await U.from("contact_smart_lists").insert({owner_user_id:t.id,name:n,filters:r,sort_by:a}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),ba({title:"Smart filter saved"})},onError:n=>{ba({title:"Error saving smart filter",description:n.message,variant:"destructive"})}})}function cRt(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("contact_smart_lists").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),ba({title:"Smart filter deleted"})}})}const Smt=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function Cmt(s,t,n,r){const a=t.name||`${t.first_name||""} ${t.last_name||""}`.trim()||"there",i=new Date,l=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"long",day:"numeric",year:"numeric"}).format(i),o=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric"}).format(i),c=(n==null?void 0:n.name)||"",d=c.split(/\s+/).filter(Boolean).map(p=>p[0]).join("").slice(0,2).toUpperCase(),u=((n==null?void 0:n.website_url)||"").trim(),h=[n==null?void 0:n.return_address_line1,[n==null?void 0:n.return_address_city,n==null?void 0:n.return_address_state].filter(Boolean).join(", "),n==null?void 0:n.return_address_zip].filter(Boolean).join(" · "),m={first_name:t.first_name||"there",last_name:t.last_name||"",name:a,full_name:a,email:t.email||"",phone:t.phone||"",address:t.address||"",city:t.city||"",state:t.state||"",zip:t.zip||t.zip_code||"",agent_name:c,agent_first_name:c.split(" ")[0]||"",agent_initials:d,agent_email:(n==null?void 0:n.email)||"",agent_phone:(n==null?void 0:n.phone)||"",agent_title:(n==null?void 0:n.title)||"",agent_website:u.replace(/^https?:\/\//i,"").replace(/\/$/,""),agent_website_url:u?/^https?:\/\//i.test(u)?u:`https://${u}`:"#",market_city:(n==null?void 0:n.market_city)||t.city||"",brokerage:r||(n==null?void 0:n.brokerage_name)||"",brokerage_address:h,current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(p,x)=>m[x]??`{{${x}}}`)}function Lfn(s,t,n,r){const a=t.trim()?`
${Smt(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${Smt(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function Pfn(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 Ifn=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function Rfn(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=Ifn.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 bWe({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=Ns();Tf();const{isReady:l,settings:o}=Cq(),{data:c}=AAe(),[d,u]=j.useState(!1),h=ei(),{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 U.from("profiles").select("name, email, phone, avatar_url, title, email_signature, use_email_signature, website_url, market_city, brokerage_name, return_address_line1, return_address_city, return_address_state, return_address_zip").eq("id",i.id).maybeSingle();return rn}}),[p,x]=j.useState("visual"),[y,g]=j.useState("all"),[b,v]=j.useState(""),[k,C]=j.useState(""),[T,M]=j.useState(""),[P,L]=j.useState(""),[I,O]=j.useState(!0),[$,q]=j.useState([]),[W,G]=j.useState(null),[K,ee]=j.useState(new Set),[J,le]=j.useState(""),[ue,oe]=j.useState(!1),[ie,de]=j.useState(!1),[we,je]=j.useState(!1),[xe,fe]=j.useState({sent:0,failed:0,total:0,currentName:""}),[Se,Ee]=j.useState(!0),[Le,De]=j.useState(!1),[Be,Ne]=j.useState([]),[Ge,_e]=j.useState(!1),[Oe,Ae]=j.useState(new Set),[Xe,Ue]=j.useState("now"),[Ze,Qe]=j.useState(""),{data:Ye=[]}=Aq(),{data:nt=[]}=EAe(),{data:rt=[]}=vWe(),{data:Fe=[],isLoading:dt}=mt({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const rn=[];let Jn=0;const ea=1e3;for(;;){const{data:_s,error:We}=await U.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(Jn,Jn+ea-1);if(We)throw We;if(!_s||_s.length===0||(rn.push(..._s),_s.length{const{data:rn}=await U.from("ses_suppressed_emails").select("email");return(rn||[]).map(Jn=>Jn.email.toLowerCase())}}),{data:pt}=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 U.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(rn!=null&&rn.brokerage_id))return null;const{data:Jn}=await U.from("brokerages").select("name, city, state").eq("id",rn.brokerage_id).maybeSingle();return Jn}}),{data:zt}=mt({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:rn}=await U.from("lead_sites").select("id, subdomain_slug, mls_provider_id, mls_agent_id, mls_agent_key, is_active").eq("agent_id",h).eq("is_active",!0).not("mls_provider_id","is",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();return rn}}),Gt=!!(zt!=null&&zt.mls_provider_id),qs=(zt==null?void 0:zt.mls_agent_id)||(zt==null?void 0:zt.mls_agent_key)||null,{data:As=[],isLoading:Bt}=mt({queryKey:["newsletter-agent-listings",h,qs],enabled:!!h&&!!qs&&Ge,staleTime:60*1e3,queryFn:async()=>{if(!qs)return[];const{data:rn}=await U.from("mlsgrid_listings").select("listing_key, address, city, state, list_price, bedrooms, bathrooms_total, living_area, photos, standard_status, modification_timestamp").eq("list_agent_mls_id",qs).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return rn||[]}}),{data:At=[],isLoading:Is}=mt({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Ge,staleTime:60*1e3,queryFn:async()=>{const{data:rn}=await U.from("listings").select("id, slug, property_address, city, state, price, bedrooms, bathrooms, square_footage, status, created_at").eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]).order("created_at",{ascending:!1}).limit(30),Jn=rn||[];if(Jn.length===0)return[];const ea=Jn.map(gt=>gt.id),{data:_s}=await U.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",ea),We=new Map,it=new Map;for(const gt of _s||[])gt.is_primary&&!We.has(gt.listing_id)&&We.set(gt.listing_id,gt.photo_url),it.has(gt.listing_id)||it.set(gt.listing_id,gt.photo_url);return Jn.map(gt=>({...gt,_photo:We.get(gt.id)||it.get(gt.id)||""}))}}),{data:jt=!1}=mt({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:rn}=await U.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}}),Qs=j.useMemo(()=>{const rn=new Set(Dt);return Fe.filter(Jn=>Jn.email&&Jn.email.includes("@")&&!rn.has(Jn.email.toLowerCase()))},[Fe,Dt]),cn=j.useMemo(()=>{if($.length===0)return null;const rn=new Set;for(const Jn of nt)$.includes(Jn.tag_id)&&rn.add(Jn.contact_id);return rn},[nt,$]),qt=j.useMemo(()=>rt.find(rn=>rn.id===W)||null,[rt,W]),Gs=j.useMemo(()=>{var rn;if(y==="all")return Qs;if(y==="tags")return cn?Qs.filter(Jn=>cn.has(Jn.id)):[];if(y==="smartlists"){if(!qt)return[];const Jn=(((rn=qt.filters)==null?void 0:rn.search)||"").toLowerCase().trim();return Jn?Qs.filter(ea=>`${ea.first_name||""} ${ea.last_name||""}`.toLowerCase().includes(Jn)||(ea.email||"").toLowerCase().includes(Jn)):Qs}return Qs.filter(Jn=>K.has(Jn.id))},[y,Qs,cn,qt,K]),Ls=j.useMemo(()=>{if(!J.trim())return Qs;const rn=J.toLowerCase();return Qs.filter(Jn=>`${Jn.first_name||""} ${Jn.last_name||""}`.toLowerCase().includes(rn))},[Qs,J]);j.useEffect(()=>{s&&(v(""),C(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),M(`As always, reach out anytime if I can help. Talk soon!`),L(a||""),x("light"),g("all"),q([]),G(null),ee(new Set),le(""),oe(!1),O(!0),Ee(!0),Ne([]),Ue("now"),Qe(""),fe({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const sn=l,Hs=j.useMemo(()=>kfn(P||a||""),[P,a]),nn=!!(b.trim()&&sn&&Gs.length>0&&!ie&&Hs.length===0),tn=rn=>{const Jn=P||a,ea=I&&(m!=null&&m.email_signature)?m.email_signature:null;let _s;return p==="light"?_s=Lfn(Jn,k,T,ea):_s=ea?`${Jn}
${ea}
`:Jn,Se&&(_s+=Pfn(m??null,pt??null,rn.email)),Cmt(_s,rn,m??null,(pt==null?void 0:pt.name)??null)},_n=j.useMemo(()=>tn({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[p,k,T,P,a,I,m,Se,pt]),Cn=j.useMemo(()=>Rfn(b,p==="advanced"||p==="visual"?P:a),[b,p,P,a]),Un=async()=>{De(!0),Ne([]);try{const rn=p==="advanced"||p==="visual"?P:a,{data:Jn,error:ea}=await U.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:rn,currentSubject:b}});if(ea)throw ea;const _s=Jn==null?void 0:Jn.subjects;if(!Array.isArray(_s)||_s.length===0)throw new Error("No subjects returned");Ne(_s)}catch(rn){const Jn=(rn==null?void 0:rn.message)||"Failed to generate subjects";Jn.includes("credits exhausted")||Jn.includes("402")?re.error("AI credits exhausted. Please add credits to your workspace."):Jn.includes("Rate limit")||Jn.includes("429")?re.error("Rate limit hit — try again in a moment."):re.error(Jn)}finally{De(!1)}},Kr=rn=>rn?"$"+Number(rn).toLocaleString("en-US"):"",jr=()=>{var it,gt;if(Oe.size===0){re.error("Pick at least one listing first.");return}const rn=(zt==null?void 0:zt.subdomain_slug)||"",Jn=rn?`https://${rn}.relevelup.com`:"https://relevelup.com",ea=[];for(const St of As){const Ht=`mls:${St.listing_key}`;if(!Oe.has(Ht))continue;const ts=Array.isArray(St.photos)&&St.photos.length>0?typeof St.photos[0]=="string"?St.photos[0]:((it=St.photos[0])==null?void 0:it.MediaURL)||((gt=St.photos[0])==null?void 0:gt.url)||"":"",Ms=St.bedrooms?`${St.bedrooms} bd`:"",js=St.bathrooms_total?`${St.bathrooms_total} ba`:"",Zs=St.living_area?`${Number(St.living_area).toLocaleString()} sqft`:"";ea.push({url:`${Jn}/listings/${St.listing_key}`,photo:ts,price:Kr(St.list_price),addr:`${St.address||""}${St.city?", "+St.city:""}`,stats:[Ms,js,Zs].filter(Boolean).join(" • ")})}for(const St of At){const Ht=`ex:${St.id}`;if(!Oe.has(Ht))continue;const ts=St.bedrooms?`${St.bedrooms} bd`:"",Ms=St.bathrooms?`${St.bathrooms} ba`:"",js=St.square_footage?`${Number(St.square_footage).toLocaleString()} sqft`:"";ea.push({url:`https://listings.relevelup.com/${St.slug||St.id}`,photo:St._photo||"",price:Kr(St.price),addr:`${St.property_address||""}${St.city?", "+St.city:""}`,stats:[ts,Ms,js].filter(Boolean).join(" • ")})}const We=`

Featured Listings

${ea.map(St=>`
${St.photo?`${St.addr}`:""}
${St.price}
${St.addr}
${St.stats}
`.trim()).join(` `)}
`.trim();L(St=>(St||a||"")+` `+We),x("visual"),Ae(new Set),_e(!1),re.success(`Added ${ea.length} listing${ea.length===1?"":"s"} to your newsletter.`)},Xs=()=>tn({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}}"),Ba=()=>Cmt(b,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},m??null,(pt==null?void 0:pt.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}}"),Hr=()=>{if(Hs.length>0){re.error(`Fill in ${Hs.length} template field${Hs.length===1?"":"s"} before sending.`);return}if(nn){if(Xe==="later"){if(!Ze){re.error("Pick a date and time to schedule.");return}const rn=new Date(Ze).getTime();if(Number.isNaN(rn)||rn{if(!(!nn||!i)){je(!1),de(!0),fe({sent:0,failed:0,total:Gs.length,currentName:"Preparing campaign…"});try{const Jn=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,ea=Xs(),_s=Ba(),We=Xe==="later",{data:it,error:gt}=await U.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:_s,body_html:ea,from_email:Jn,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:Gs.length,status:We?"scheduled":"draft",scheduled_at:We?new Date(Ze).toISOString():null}).select("id").single();if(gt)throw gt;fe(Ht=>({...Ht,currentName:"Adding recipients…"}));const St=Gs.map(Ht=>({campaign_id:it.id,contact_id:Ht.id,email:Ht.email,name:[Ht.first_name,Ht.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let Ht=0;Ht({...js,sent:Math.min(Ht+ts.length,St.length)}))}if(We){const{error:Ht}=await U.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:it.id}});if(Ht)throw Ht;re.success(`Newsletter scheduled for ${new Date(Ze).toLocaleString()}.`)}else{const{error:Ht}=await U.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:it.id}});if(Ht)throw Ht;re.success(`Sending to ${Gs.length} contact${Gs.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(rn){console.error("Newsletter send failed:",rn),re.error(`Failed to send: ${rn.message||"Unknown error"}`)}finally{de(!1)}}},pr=rn=>{ee(Jn=>{const ea=new Set(Jn);return ea.has(rn)?ea.delete(rn):ea.add(rn),ea})};return e.jsxs(Fs,{open:s,onOpenChange:rn=>!ie&&t(rn),children:[e.jsxs(Os,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5"})," Send Newsletter"]})}),!sn&&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(po,{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(se,{children:"Subject"}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:Un,disabled:Le,title:"Generate subject lines with AI",children:[Le?e.jsx(Wt,{className:"h-3 w-3 animate-spin"}):e.jsx(yn,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(ye,{value:b,onChange:rn=>v(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,Jn)=>e.jsxs("button",{type:"button",onClick:()=>{v(rn),Ne([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(yn,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),rn]},Jn))]}),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}}"})]})]}),Cn.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(iz,{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:Cn.map((rn,Jn)=>e.jsx("li",{children:rn},Jn))})]}),(Gt||jt)&&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(ia,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:Gt&&jt?"Pick from your live MLS listings or your Listing Exchange listings.":Gt?"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:()=>_e(!0),children:"Choose listings"})]}),e.jsx(Cfn,{html:P||a||"",originalHtml:a||"",onChange:L}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Editing"}),e.jsxs(fa,{value:p,onValueChange:rn=>x(rn),children:[e.jsxs(xa,{className:"grid grid-cols-3 w-full",children:[e.jsxs(ss,{value:"visual",children:[e.jsx(um,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(ss,{value:"light",children:[e.jsx($r,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(ss,{value:"advanced",children:[e.jsx(j4,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(ns,{value:"visual",className:"mt-3",children:e.jsx(iRt,{html:P,onChange:L})}),e.jsxs(ns,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(Ds,{value:k,onChange:rn=>C(rn.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(Ds,{value:T,onChange:rn=>M(rn.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(ns,{value:"advanced",className:"mt-3",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Ds,{value:P,onChange:rn=>L(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(Mn,{checked:I&&!!(m!=null&&m.email_signature),disabled:!(m!=null&&m.email_signature),onCheckedChange:O})]}),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(Mn,{checked:Se,onCheckedChange:Ee})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipients"}),e.jsxs(fa,{value:y,onValueChange:rn=>g(rn),children:[e.jsxs(xa,{className:"grid grid-cols-4 w-full",children:[e.jsxs(ss,{value:"all",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(ss,{value:"tags",children:[e.jsx(wf,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(ss,{value:"smartlists",children:[e.jsx(HW,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(ss,{value:"individual",children:[e.jsx(Eo,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(ns,{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:Qs.length})," contact",Qs.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(ns,{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:Ye.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."}):Ye.map(rn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(wi,{checked:$.includes(rn.id),onCheckedChange:Jn=>q(ea=>Jn?[...ea,rn.id]:ea.filter(_s=>_s!==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(ns,{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(ns,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(ye,{placeholder:"Search contacts...",value:J,onChange:rn=>le(rn.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[K.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>ee(new Set),children:"Clear"})]}),e.jsxs(lo,{className:"h-48 rounded-lg border p-2",children:[dt&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!dt&&Ls.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),Ls.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(wi,{checked:K.has(rn.id),onCheckedChange:()=>pr(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)),Ls.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(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Rr,{className:"h-3 w-3"})," ",Gs.length," recipient",Gs.length===1?"":"s"]}),sn&&e.jsxs(qe,{variant:"outline",className:"gap-1 text-xs",children:["via Mass Email",o!=null&&o.reply_to_email?` (${o.reply_to_email})`:""]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Preview"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>oe(rn=>!rn),children:ue?e.jsxs(e.Fragment,{children:[e.jsx(n0,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(ma,{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:_n,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)."]})]})]}),ie&&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(Wt,{className:"h-4 w-4 animate-spin"}),"Sending to ",xe.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[xe.sent+xe.failed," / ",xe.total]})]}),e.jsx(qi,{value:xe.total?(xe.sent+xe.failed)/xe.total*100:0}),xe.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[xe.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(Vr,{className:"h-4 w-4"})," When to send"]}),e.jsxs(ob,{value:Xe,onValueChange:rn=>Ue(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(eh,{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(eh,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(ym,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),Xe==="later"&&e.jsx(ye,{type:"datetime-local",value:Ze,onChange:rn=>Qe(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:Hs.length>0?`${Hs.length} template field${Hs.length===1?"":"s"} still need${Hs.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:ie,children:"Cancel"}),e.jsx(B,{onClick:Hr,disabled:!nn,children:ie?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):Xe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(ym,{className:"h-4 w-4 mr-1"}),"Schedule for ",Gs.length]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{className:"h-4 w-4 mr-1"}),"Send to ",Gs.length]})})]})]})]})]}),e.jsx(Nl,{open:we,onOpenChange:je,children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:Xe==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(xl,{children:[Xe==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',b,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[Gs.length," contact",Gs.length===1?"":"s"]}),Xe==="later"&&Ze?` for ${new Date(Ze).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:mr,children:Xe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(ym,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{className:"h-4 w-4 mr-1"}),"Send to ",Gs.length]})})]})]})}),e.jsx(Fs,{open:Ge,onOpenChange:_e,children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-5 w-5"})," Choose listings to insert"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick up to 6 listings. They'll be added as an email-safe grid."}),(Bt||Is)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!Bt&&!Is&&As.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."}),As.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:As.map(rn=>{var We,it;const Jn=`mls:${rn.listing_key}`,ea=Oe.has(Jn),_s=Array.isArray(rn.photos)&&rn.photos.length>0?typeof rn.photos[0]=="string"?rn.photos[0]:((We=rn.photos[0])==null?void 0:We.MediaURL)||((it=rn.photos[0])==null?void 0:it.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{Ae(gt=>{const St=new Set(gt);return St.has(Jn)?St.delete(Jn):St.size<6?St.add(Jn):re.error("Max 6 listings per newsletter"),St})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${ea?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[_s&&e.jsx("img",{src:_s,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}`:""]})]}),ea&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Rr,{className:"h-4 w-4"})})]},Jn)})})]}),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 Jn=`ex:${rn.id}`,ea=Oe.has(Jn);return e.jsxs("button",{type:"button",onClick:()=>{Ae(_s=>{const We=new Set(_s);return We.has(Jn)?We.delete(Jn):We.size<6?We.add(Jn):re.error("Max 6 listings per newsletter"),We})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${ea?"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}`:""]})]}),ea&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Rr,{className:"h-4 w-4"})})]},Jn)})})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>_e(!1),children:"Cancel"}),e.jsxs(B,{onClick:jr,disabled:Oe.size===0,children:["Insert ",Oe.size>0?Oe.size:""," listing",Oe.size===1?"":"s"]})]})]})}),e.jsx(TAe,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function Dfn(){const{user:s}=Ns(),t=as(),[n,r]=j.useState("starters"),[a,i]=j.useState(!1),[l,o]=j.useState(null),[c,d]=j.useState(null),[u,h]=j.useState(null),{data:m,isLoading:p}=mt({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:P,error:L}=await U.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(L)throw L;return P||[]}}),x=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),y=(m==null?void 0:m.filter(P=>P.user_id===(s==null?void 0:s.id)&&!P.is_template))??[],g=(m==null?void 0:m.filter(P=>P.user_id===(s==null?void 0:s.id)&&P.is_template))??[],b=(m==null?void 0:m.filter(P=>P.user_id!==(s==null?void 0:s.id)&&P.is_template&&(P.share_scope==="team"||P.share_scope==="brokerage"||P.share_scope==="global")))??[],v=(m==null?void 0:m.filter(P=>P.share_scope==="global"&&P.is_template))??[],k=n==="starters"?v:n==="mine"?y:n==="templates"?g:b.filter(P=>P.share_scope!=="global"),C=async P=>{if(!s)return;const{error:L}=await U.from("agent_custom_newsletters").insert({user_id:s.id,title:`${P.title} (Copy)`,description:P.description,html_content:P.html_content,is_template:!1,share_scope:"private"});if(L){re.error(L.message);return}re.success('Duplicated to "My Newsletters"'),x(),r("mine")},T=async P=>{const{error:L}=await U.from("agent_custom_newsletters").delete().eq("id",P);if(L){re.error(L.message);return}re.success("Deleted"),h(null),x()},M=P=>P.share_scope==="global"?e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(yn,{className:"h-3 w-3"}),"Starter"]}):P.share_scope==="brokerage"?e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Ni,{className:"h-3 w-3"}),"Brokerage"]}):P.share_scope==="team"?e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"}),"Team"]}):e.jsxs(qe,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(du,{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(yn,{className:"h-3.5 w-3.5"}),"Starter Templates (",v.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 (",g.length,")"]}),e.jsxs(B,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",b.filter(P=>P.share_scope!=="global").length,")"]})]}),e.jsxs(B,{onClick:()=>{o(null),i(!0)},children:[e.jsx(Js,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),p&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((P,L)=>e.jsx(gn,{className:"h-48 w-full"},L))}),n==="starters"&&!p&&e.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 text-sm flex items-start gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("span",{children:["Click ",e.jsx("strong",{children:"Use"}),' on any starter to copy it into your "My Newsletters" — then edit, send, or save as your own template.']})]}),!p&&k.length===0&&e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center text-muted-foreground",children:[e.jsx($r,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),n==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),n==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),n==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),n==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!p&&k.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:k.map(P=>{const L=P.user_id===(s==null?void 0:s.id);return e.jsxs(be,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[P.thumbnail_url?e.jsx("img",{src:P.thumbnail_url,alt:P.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full p-3 overflow-hidden pointer-events-none",dangerouslySetInnerHTML:{__html:`
${P.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[P.is_template&&e.jsx(qe,{className:"bg-primary/90",children:"Template"}),M(P)]})]}),e.jsxs(Re,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:P.title}),P.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:P.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",Bs(new Date(P.updated_at||P.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs(B,{size:"sm",onClick:()=>d(P),className:"flex-1 min-w-[80px]",children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),L?e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{o(P),i(!0)},children:e.jsx(Za,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>C(P),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>h(P.id),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>C(P),children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},P.id)})}),e.jsx(wfn,{open:a,onOpenChange:i,initial:l,onSaved:x}),c&&e.jsx(bWe,{open:!!c,onOpenChange:P=>!P&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Nl,{open:!!u,onOpenChange:P=>!P&&h(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete this newsletter?"}),e.jsx(xl,{children:"This cannot be undone."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>u&&T(u),children:"Delete"})]})]})})]})}function Ofn(){const s=Hn(),[t,n]=j.useState(""),[r,a]=j.useState("grid"),[i,l]=j.useState(null),{data:o,isLoading:c}=mt({queryKey:["newsletters"],queryFn:async()=>{const{data:T,error:M}=await U.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(M)throw M;return T}}),{data:d}=mt({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:T}=await U.from("newsletter_likes").select("newsletter_id");return T||[]}}),{data:u}=mt({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:T}=await U.from("newsletter_comments").select("newsletter_id");return T||[]}}),{data:h}=mt({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[T,M,P,L]=await Promise.all([U.from("newsletter_canva_links").select("newsletter_id"),U.from("newsletter_pdfs").select("newsletter_id"),U.from("newsletter_videos").select("newsletter_id"),U.from("newsletter_drive_links").select("newsletter_id")]);return{canva:T.data||[],pdfs:M.data||[],videos:P.data||[],drives:L.data||[]}}}),m=T=>(d==null?void 0:d.filter(M=>M.newsletter_id===T).length)||0,p=T=>(u==null?void 0:u.filter(M=>M.newsletter_id===T).length)||0,x=T=>{var M;return((M=h==null?void 0:h.canva)==null?void 0:M.filter(P=>P.newsletter_id===T).length)||0},y=T=>{var M;return((M=h==null?void 0:h.pdfs)==null?void 0:M.filter(P=>P.newsletter_id===T).length)||0},g=T=>{var M;return((M=h==null?void 0:h.videos)==null?void 0:M.filter(P=>P.newsletter_id===T).length)||0},b=T=>{var M;return((M=h==null?void 0:h.drives)==null?void 0:M.filter(P=>P.newsletter_id===T).length)||0},v=T=>x(T)+y(T)+g(T)+b(T),k=o==null?void 0:o.filter(T=>{var M;return T.title.toLowerCase().includes(t.toLowerCase())||((M=T.description)==null?void 0:M.toLowerCase().includes(t.toLowerCase()))}),C=T=>{s(`/newsletters/${T}`)};return e.jsx(Vs,{title:"Newsletter Content",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Newsletter Content"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Monthly templates, plus newsletters you build yourself"})]}),e.jsxs(fa,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"custom",children:"Build & Send"}),e.jsx(ss,{value:"curated",children:"Curated Monthly"})]}),e.jsx(ns,{value:"custom",className:"mt-2",children:e.jsx(Dfn,{})}),e.jsxs(ns,{value:"curated",className:"space-y-6 mt-2",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{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(r0,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(ug,{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,M)=>e.jsx(be,{children:e.jsxs(Re,{className:"p-0",children:[e.jsx(gn,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(gn,{className:"h-5 w-3/4"}),e.jsx(gn,{className:"h-4 w-full"})]})]})},M))}),!c&&(k==null?void 0:k.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx($r,{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 M=v(T.id),P=x(T.id),L=y(T.id),I=g(T.id);return r==="grid"?e.jsxs(be,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>C(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($r,{className:"h-16 w-16"})})}),e.jsxs(Re,{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(ra,{className:"h-3 w-3"}),Bs(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,"")}),M>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[P>0&&e.jsxs(qe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Ac,{className:"h-3 w-3"})," ",P," Template",P>1?"s":""]}),L>0&&e.jsxs(qe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(ii,{className:"h-3 w-3"})," ",L," PDF",L>1?"s":""]}),I>0&&e.jsxs(qe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(fd,{className:"h-3 w-3"})," ",I," Video",I>1?"s":""]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground pt-1 border-t border-border/50",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mg,{className:"h-3 w-3"})," ",m(T.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yd,{className:"h-3 w-3"})," ",p(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:O=>{O.stopPropagation(),l(T)},children:[e.jsx(Dr,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},T.id):e.jsx(be,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>C(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($r,{className:"h-10 w-10"})})}),e.jsxs(Re,{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(ra,{className:"h-3 w-3"}),Bs(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:[M>0&&e.jsxs("span",{children:[M," resource",M>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mg,{className:"h-3 w-3"})," ",m(T.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yd,{className:"h-3 w-3"})," ",p(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:O=>{O.stopPropagation(),l(T)},children:[e.jsx(Dr,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},T.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(bWe,{open:!!i,onOpenChange:T=>!T&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function Ffn({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(be,{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(Re,{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 zfn(){const{id:s}=$i(),t=Hn(),{user:n}=Ns(),{toast:r}=pi(),a=as(),{trackEngagement:i}=eq(),[l,o]=j.useState(""),[c,d]=j.useState(!1),{data:u,isLoading:h}=mt({queryKey:["newsletter",s],queryFn:async()=>{const{data:P,error:L}=await U.from("newsletter_content").select("*").eq("id",s).single();if(L)throw L;return P},enabled:!!s});j.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:P}=await U.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:p}=mt({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:x}=mt({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:y}=mt({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return P||[]},enabled:!!s}),{data:g}=mt({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_likes").select("*").eq("newsletter_id",s);return P||[]},enabled:!!s}),{data:b}=mt({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:P}=await U.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return P||[]},enabled:!!s}),v=g==null?void 0:g.some(P=>P.user_id===(n==null?void 0:n.id)),k=vt({mutationFn:async()=>{v?await U.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",n==null?void 0:n.id):await U.from("newsletter_likes").insert({newsletter_id:s,user_id:n==null?void 0:n.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),C=vt({mutationFn:async P=>{const{error:L}=await U.from("newsletter_comments").insert({newsletter_id:s,user_id:n==null?void 0:n.id,content:P});if(L)throw L},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),r({title:"Comment added"})}}),T=vt({mutationFn:async P=>{const{error:L}=await U.from("newsletter_comments").delete().eq("id",P);if(L)throw L},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),r({title:"Comment deleted"})}}),M=P=>{if(P.includes("player.mediadelivery.net")||P.includes("iframe.mediadelivery.net")){const L=P.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(L)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${L[1]}/${L[2]}?autoplay=false`,className:"absolute inset-0 w-full h-full rounded-lg",allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})}if(P.includes("youtube.com")||P.includes("youtu.be")){const L=P.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if(L)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${L[1]}`,className:"absolute inset-0 w-full h-full rounded-lg",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}return e.jsxs("a",{href:P,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(fd,{className:"h-4 w-4"})," Watch Video"]})};return h?e.jsx(Vs,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(gn,{className:"h-8 w-32"}),e.jsx(gn,{className:"h-64 w-full"}),e.jsx(gn,{className:"h-32 w-full"})]})}):u?e.jsx(Vs,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(_a,{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:Bs(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(Ffn,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(rq,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs(B,{variant:v?"default":"outline",size:"sm",onClick:()=>k.mutate(),children:[e.jsx(mo,{className:`h-4 w-4 mr-1 ${v?"fill-current":""}`}),(g==null?void 0:g.length)||0," ",(g==null?void 0:g.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(Dr,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(bWe,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),y&&y.length>0&&e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Re,{className:"space-y-2",children:y.map(P=>e.jsxs("a",{href:P.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_canva"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(Ac,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:P.title}),e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},P.id))})]}),m&&m.length>0&&e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Re,{className:"space-y-2",children:m.map(P=>e.jsxs("a",{href:P.drive_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_link"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(Tr,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:P.title})]},P.id))})]}),p&&p.length>0&&e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Re,{className:"space-y-2",children:p.map(P=>e.jsxs("a",{href:P.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_pdf"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx($r,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:P.name}),e.jsx(ii,{className:"h-4 w-4 text-muted-foreground"})]},P.id))})]}),x&&x.length>0&&e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Videos"})}),e.jsx(Re,{className:"space-y-6",children:x.map(P=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:P.title}),M(P.video_url)]},P.id))})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"text-lg",children:["Comments (",(b==null?void 0:b.length)||0,")"]})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ds,{placeholder:"Write a comment...",value:l,onChange:P=>o(P.target.value),className:"flex-1"}),e.jsx(B,{onClick:()=>l.trim()&&C.mutate(l),disabled:!l.trim()||C.isPending,children:e.jsx(Dr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:b==null?void 0:b.map(P=>{var L,I,O;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ra,{className:"h-8 w-8",children:e.jsx(Da,{children:((I=(L=P.profiles)==null?void 0:L.name)==null?void 0:I[0])||"U"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-sm",children:((O=P.profiles)==null?void 0:O.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Bs(new Date(P.created_at),"MMM d, yyyy")}),P.user_id===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>T.mutate(P.id),children:e.jsx(Rn,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:P.content})]})]},P.id)})})]})]})]})}):e.jsx(Vs,{title:"Not Found",description:"",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Newsletter not found"}),e.jsx(B,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function Bfn({rows:s,onChange:t}){const[n,r]=j.useState(null),[a,i]=j.useState(null),l=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},o=h=>{t(s.filter((m,p)=>p!==h))},c=(h,m,p,x)=>{const y=[...s];y[h]={...y[h],columns:y[h].columns.map((g,b)=>b===m?{...g,[p]:x}:g)},t(y)},d=async(h,m,p)=>{var g;const x=(g=p.target.files)==null?void 0:g[0];if(!x)return;const y=`${h}-${m}`;r(y);try{const b=`content-blocks/${Date.now()}-${x.name}`,{error:v}=await U.storage.from("newsletter-content").upload(b,x);if(!v){const{data:k}=U.storage.from("newsletter-content").getPublicUrl(b);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(se,{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(Js,{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(be,{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(dr,{className:"h-4 w-4"})}),e.jsxs(Re,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Fp,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",m+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:h.columns.map((p,x)=>{const y=`${m}-${x}`;return e.jsxs("div",{className:"space-y-2 border border-border/50 rounded-md p-3 bg-muted/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:["Column ",x+1]}),p.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:p.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(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,x),children:e.jsx(dr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(ye,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${y}`,onChange:g=>d(m,x,g)}),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(ac,{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:x}),children:[e.jsx(i1,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(ye,{placeholder:"Title",value:p.title,onChange:g=>c(m,x,"title",g.target.value),className:"h-8 text-sm"}),e.jsx(Ds,{placeholder:"Description",value:p.description,onChange:g=>c(m,x,"description",g.target.value),className:"text-sm min-h-[60px] resize-none"})]},x)})})]})]},m)),e.jsx(Fs,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(Os,{className:"sm:max-w-2xl",children:[e.jsx($s,{children:e.jsx(zs,{children:"Choose a Graphic"})}),e.jsx(aRt,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function $fn(){const{toast:s}=pi(),t=as(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState({title:"",description:"",publish_date:Bs(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=j.useState(null),[u,h]=j.useState(null),[m,p]=j.useState([]),[x,y]=j.useState([]),[g,b]=j.useState([]),[v,k]=j.useState([]),[C,T]=j.useState([]),[M,P]=j.useState(""),[L,I]=j.useState([]),[O,$]=j.useState(!1),{data:q,isLoading:W}=mt({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:Se,error:Ee}=await U.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return Se}}),G=vt({mutationFn:async Se=>{const{data:Ee,error:Le}=await U.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(Le)throw Le;return Ee},onSuccess:async Se=>{await J(Se.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),Se.is_published&&L7s(Se.title,Se.id),oe()},onError:Se=>{s({title:"Error creating newsletter",description:Se.message,variant:"destructive"})}}),K=vt({mutationFn:async Se=>{const{error:Ee}=await U.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(Ee)throw Ee;return Se.id},onSuccess:async Se=>{await J(Se),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),oe()},onError:Se=>{s({title:"Error updating newsletter",description:Se.message,variant:"destructive"})}}),ee=vt({mutationFn:async Se=>{const{error:Ee}=await U.from("newsletter_content").delete().eq("id",Se);if(Ee)throw Ee},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:Se=>{s({title:"Error deleting newsletter",description:Se.message,variant:"destructive"})}}),J=async Se=>{await U.from("newsletter_drive_links").delete().eq("newsletter_id",Se),await U.from("newsletter_pdfs").delete().eq("newsletter_id",Se),await U.from("newsletter_videos").delete().eq("newsletter_id",Se),await U.from("newsletter_canva_links").delete().eq("newsletter_id",Se);for(const Ee of L){const Le=`${Se}/${Date.now()}-${Ee.file.name}`,{error:De}=await U.storage.from("newsletter-content").upload(Le,Ee.file);if(!De){const{data:Be}=U.storage.from("newsletter-content").getPublicUrl(Le);x.push({name:Ee.name,file_url:Be.publicUrl,file_size:Ee.file.size,sort_order:x.length})}}m.length>0&&await U.from("newsletter_drive_links").insert(m.map((Ee,Le)=>({newsletter_id:Se,title:Ee.title,drive_url:Ee.drive_url,sort_order:Le}))),x.length>0&&await U.from("newsletter_pdfs").insert(x.map((Ee,Le)=>({newsletter_id:Se,name:Ee.name,file_url:Ee.file_url,file_size:Ee.file_size||null,sort_order:Le}))),g.length>0&&await U.from("newsletter_videos").insert(g.map((Ee,Le)=>({newsletter_id:Se,title:Ee.title,video_url:Ee.video_url,sort_order:Le}))),v.length>0&&await U.from("newsletter_canva_links").insert(v.map((Ee,Le)=>({newsletter_id:Se,title:Ee.title,canva_share_link:Ee.canva_share_link,sort_order:Le})))},le=async Se=>{i(Se),o({title:Se.title,description:Se.description||"",publish_date:Bs(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||[]),P(Se.html_code||"");const[Ee,Le,De,Be]=await Promise.all([U.from("newsletter_drive_links").select("*").eq("newsletter_id",Se.id).order("sort_order"),U.from("newsletter_pdfs").select("*").eq("newsletter_id",Se.id).order("sort_order"),U.from("newsletter_videos").select("*").eq("newsletter_id",Se.id).order("sort_order"),U.from("newsletter_canva_links").select("*").eq("newsletter_id",Se.id).order("sort_order")]);p(Ee.data||[]),y(Le.data||[]),b(De.data||[]),k(Be.data||[]),I([]),r(!0)},ue=async Se=>{const[Ee,Le,De,Be]=await Promise.all([U.from("newsletter_drive_links").select("*").eq("newsletter_id",Se.id).order("sort_order"),U.from("newsletter_pdfs").select("*").eq("newsletter_id",Se.id).order("sort_order"),U.from("newsletter_videos").select("*").eq("newsletter_id",Se.id).order("sort_order"),U.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:Bs(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(Se.preview_image_url),T(Se.content_blocks||[]),P(Se.html_code||""),p((Ee.data||[]).map(({id:Ne,...Ge})=>Ge)),y((Le.data||[]).map(({id:Ne,...Ge})=>Ge)),b((De.data||[]).map(({id:Ne,...Ge})=>Ge)),k((Be.data||[]).map(({id:Ne,...Ge})=>Ge)),I([]),r(!0)},oe=()=>{r(!1),i(null),o({title:"",description:"",publish_date:Bs(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),p([]),y([]),b([]),k([]),T([]),P(""),I([])},ie=async Se=>{var Le;const Ee=(Le=Se.target.files)==null?void 0:Le[0];Ee&&(d(Ee),h(URL.createObjectURL(Ee)))},de=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}$(!0);let Se=u;if(c){const Ee=`previews/${Date.now()}-${c.name}`,{error:Le}=await U.storage.from("newsletter-content").upload(Ee,c);if(!Le){const{data:De}=U.storage.from("newsletter-content").getPublicUrl(Ee);Se=De.publicUrl}}a?K.mutate({id:a.id,...l,preview_image_url:Se,content_blocks:C,html_code:M||null}):G.mutate({...l,preview_image_url:Se,content_blocks:C,html_code:M||null}),$(!1)},we=()=>p([...m,{title:"",drive_url:"",sort_order:m.length}]),je=()=>b([...g,{title:"",video_url:"",sort_order:g.length}]),xe=()=>k([...v,{title:"",canva_share_link:"",sort_order:v.length}]),fe=Se=>{const Ee=Se.target.files;if(!Ee)return;const Le=Array.from(Ee).map(De=>({file:De,name:De.name.replace(/\.[^/.]+$/,"")}));I([...L,...Le])};return e.jsx(Vs,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{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(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:(q==null?void 0:q.length)||0})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:(q==null?void 0:q.filter(Se=>Se.is_published).length)||0})})]})]}),e.jsxs(Fs,{open:n,onOpenChange:Se=>!Se&&oe(),children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(Js,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:a?"Edit Newsletter":"Add Newsletter"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Title *"}),e.jsx(ye,{value:l.title,onChange:Se=>o({...l,title:Se.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Publish Date"}),e.jsx(ye,{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(se,{children:"Description"}),e.jsx(Kj,{content:l.description,onChange:Se=>o({...l,description:Se}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[u&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:u,alt:"Preview",className:"h-20 w-32 object-cover rounded-md"}),e.jsx(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(dr,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(ye,{type:"file",accept:"image/*",onChange:ie,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(Ja,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{checked:l.is_published,onCheckedChange:Se=>o({...l,is_published:Se})}),e.jsx(se,{children:"Published"})]}),e.jsx(Bfn,{rows:C,onChange:T}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"HTML Code (for agent send)"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:'When provided, agents see a "Send Newsletter" button on this newsletter.'})]}),e.jsx("textarea",{value:M,onChange:Se=>P(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(se,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:xe,children:[e.jsx(Js,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),v.map((Se,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{placeholder:"Link title",value:Se.title,onChange:Le=>{const De=[...v];De[Ee].title=Le.target.value,k(De)},className:"w-1/3"}),e.jsx(ye,{placeholder:"Canva share link",value:Se.canva_share_link,onChange:Le=>{const De=[...v];De[Ee].canva_share_link=Le.target.value,k(De)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>k(v.filter((Le,De)=>De!==Ee)),children:e.jsx(dr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:we,children:[e.jsx(Js,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),m.map((Se,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{placeholder:"Link title",value:Se.title,onChange:Le=>{const De=[...m];De[Ee].title=Le.target.value,p(De)},className:"w-1/3"}),e.jsx(ye,{placeholder:"Google Drive URL",value:Se.drive_url,onChange:Le=>{const De=[...m];De[Ee].drive_url=Le.target.value,p(De)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>p(m.filter((Le,De)=>De!==Ee)),children:e.jsx(dr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(ye,{type:"file",accept:".pdf",multiple:!0,onChange:fe,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(Ja,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),x.map((Se,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx($r,{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(x.filter((Le,De)=>De!==Ee)),children:e.jsx(dr,{className:"h-4 w-4"})})]},`existing-${Ee}`)),L.map((Se,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:Se.name,onChange:Le=>{const De=[...L];De[Ee].name=Le.target.value,I(De)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>I(L.filter((Le,De)=>De!==Ee)),children:e.jsx(dr,{className:"h-4 w-4"})})]},`pending-${Ee}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-base font-medium",children:"Video Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:je,children:[e.jsx(Js,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),g.map((Se,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{placeholder:"Video title",value:Se.title,onChange:Le=>{const De=[...g];De[Ee].title=Le.target.value,b(De)},className:"w-1/3"}),e.jsx(ye,{placeholder:"Video URL",value:Se.video_url,onChange:Le=>{const De=[...g];De[Ee].video_url=Le.target.value,b(De)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>b(g.filter((Le,De)=>De!==Ee)),children:e.jsx(dr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(B,{variant:"outline",onClick:oe,children:"Cancel"}),e.jsx(B,{onClick:de,disabled:O||G.isPending||K.isPending,children:O?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:W?e.jsx(un,{children:e.jsx(xt,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(q==null?void 0:q.length)===0?e.jsx(un,{children:e.jsx(xt,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):q==null?void 0:q.map(Se=>e.jsxs(un,{children:[e.jsx(xt,{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($r,{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(xt,{children:Bs(new Date(Se.publish_date),"MMM d, yyyy")}),e.jsx(xt,{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(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>le(Se),title:"Edit",children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ue(Se),title:"Duplicate",children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:async()=>{await Bi("Are you sure you want to delete this newsletter?")&&ee.mutate(Se.id)},children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},Se.id))})]})})})]})})}const Ufn={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null};function qfn({brokerages:s}){var T;const{toast:t}=pi(),[n,r]=j.useState(Ufn),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(null),[m,p]=j.useState(!1),[x,y]=j.useState(!1),[g,b]=j.useState(null),v=(M,P)=>r(L=>({...L,[M]:P}));j.useEffect(()=>{const M=setTimeout(async()=>{p(!0);try{const{data:P,error:L}=await U.functions.invoke("admin-broadcast-sms",{body:{action:"preview",filters:n,sms_body:a||"Sample message"}});if(L)throw L;h(P)}catch{h(null)}finally{p(!1)}},450);return()=>clearTimeout(M)},[n,a]);const k=async()=>{if(!c||!a.trim()){t({title:"Add a test number and message",variant:"destructive"});return}y(!0);const{data:M,error:P}=await U.functions.invoke("admin-broadcast-sms",{body:{action:"test",to:c,sms_body:a}});if(y(!1),P||M!=null&&M.error){t({title:"Test failed",description:(M==null?void 0:M.error)||(P==null?void 0:P.message),variant:"destructive"});return}t({title:"Test text sent",description:`Sent to ${c}`})},C=async()=>{const M=(u==null?void 0:u.count)||0;if(!(!a.trim()||M===0||!await Bi({title:"Send text broadcast?",description:`This will text ${M} member${M===1?"":"s"} who have a recorded SMS opt-in. Texts cannot be recalled.`,confirmText:"Send broadcast"}))){y(!0),b({total:M,sent:0,failed:0});try{const{data:L,error:I}=await U.functions.invoke("admin-broadcast-sms",{body:{action:"queue",name:l||a.slice(0,60),sms_body:a,filters:n}});if(I||L!=null&&L.error)throw new Error((L==null?void 0:L.error)||(I==null?void 0:I.message));let O=0,$=0,q=L.total,W=0;for(;q>0&&W++<400;){const{data:G,error:K}=await U.functions.invoke("admin-broadcast-sms",{body:{action:"process",broadcast_id:L.broadcast_id,limit:40}});if(K||G!=null&&G.error)throw new Error((G==null?void 0:G.error)||(K==null?void 0:K.message));if(G.deferred){t({title:"Paused for quiet hours",description:G.reason});break}O+=G.sent||0,$+=G.failed||0,q=G.remaining||0,b({total:M,sent:O,failed:$})}t({title:"Broadcast complete",description:`${O} sent${$?`, ${$} failed`:""}.`})}catch(L){t({title:"Broadcast failed",description:L.message,variant:"destructive"})}finally{y(!1)}}};return e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[340px_1fr]",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs(be,{children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(a0,{className:"h-4 w-4"})," SMS Audience"]}),e.jsx(fr,{children:"Only members with a recorded consent date and source are included. Opted-out and undeliverable numbers are always excluded."})]}),e.jsxs(Re,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Account status"}),e.jsxs(vs,{value:n.status,onValueChange:M=>v("status",M),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All members"}),e.jsx(Je,{value:"active",children:"Signed in before"}),e.jsx(Je,{value:"pending",children:"Never signed in"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Billing"}),e.jsxs(vs,{value:n.billing,onValueChange:M=>v("billing",M),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All"}),e.jsx(Je,{value:"trial",children:"On trial"}),e.jsx(Je,{value:"paid",children:"Paid"}),e.jsx(Je,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Je,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Role"}),e.jsxs(vs,{value:n.role,onValueChange:M=>v("role",M),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All roles"}),e.jsx(Je,{value:"user",children:"Agents"}),e.jsx(Je,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(Je,{value:"coach",children:"Coaches"}),e.jsx(Je,{value:"admin",children:"Admins"})]})]})]}),!!(s!=null&&s.length)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Brokerage"}),e.jsxs(vs,{value:n.brokerage,onValueChange:M=>v("brokerage",M),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All brokerages"}),e.jsx(Je,{value:"none",children:"No brokerage"}),s.map(M=>e.jsx(Je,{value:M.id,children:M.name},M.id))]})]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"SMS-eligible members"}),e.jsx("span",{className:"text-lg font-semibold",children:m?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):(u==null?void 0:u.count)??0})]}),(T=u==null?void 0:u.sample)!=null&&T.length?e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["e.g. ",u.sample.slice(0,3).map(M=>M.name||M.phone).join(", ")]}):null]}),u&&!u.quiet_hours_ok&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-xs",children:[e.jsx(Vr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:"Outside the 9:00 AM – 8:00 PM ET sending window. Queued texts will be held and resumed instead of sent now."})]})]})]})}),e.jsx("div",{className:"space-y-4",children:e.jsxs(be,{children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(ro,{className:"h-4 w-4"})," Text message"]}),e.jsxs(fr,{children:["Merge tags: ",e.jsx("code",{children:"{{first_name}}"})," ",e.jsx("code",{children:"{{name}}"}),'. The LevelUp prefix and "Reply STOP to opt out" are added automatically.']})]}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"sms-broadcast-name",className:"text-xs",children:"Internal name"}),e.jsx(ye,{id:"sms-broadcast-name",value:l,onChange:M=>o(M.target.value),placeholder:"August member update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"sms-broadcast-body",className:"text-xs",children:"Message"}),e.jsx(Ds,{id:"sms-broadcast-body",value:a,onChange:M=>i(M.target.value),rows:5,maxLength:480,placeholder:"Hi {{first_name}} — join us Thursday at 11am ET for the LevelUp Live session on listing videos."}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[(u==null?void 0:u.length)??a.length," characters"]}),e.jsxs(qe,{variant:((u==null?void 0:u.segments)??1)>2?"destructive":"secondary",children:[(u==null?void 0:u.segments)??1," segment",((u==null?void 0:u.segments)??1)===1?"":"s"]})]})]}),(u==null?void 0:u.composed)&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"Preview as delivered"}),e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:u.composed})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",style:{minWidth:200},children:[e.jsx(se,{htmlFor:"sms-test-phone",className:"text-xs",children:"Send a test to"}),e.jsx(ye,{id:"sms-test-phone",value:c,onChange:M=>d(M.target.value),placeholder:"(555) 123-4567",type:"tel"})]}),e.jsxs(B,{variant:"outline",onClick:k,disabled:x,children:[x&&e.jsx(Wt,{className:"mr-2 h-4 w-4 animate-spin"})," Send test"]})]}),g&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(qi,{value:g.total?(g.sent+g.failed)/g.total*100:0}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Rr,{className:"h-3 w-3"})," ",g.sent," sent"]}),g.failed>0&&e.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[e.jsx(po,{className:"h-3 w-3"})," ",g.failed," failed"]}),e.jsxs("span",{children:["of ",g.total]})]})]}),e.jsxs(B,{onClick:C,disabled:x||!a.trim()||!(u!=null&&u.count),className:"w-full",children:[x?e.jsx(Wt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"mr-2 h-4 w-4"}),"Send to ",(u==null?void 0:u.count)??0," member",((u==null?void 0:u.count)??0)===1?"":"s"]})]})]})})]})}const VPe={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null,respectOptOut:!0},Vfn=["{{first_name}}","{{name}}","{{email}}"];function Hfn(s){return`${s||'

Your email preview will appear here…

'}`}function Gfn(){var rt;const{toast:s}=pi(),{user:t}=Ns(),n=as(),[r,a]=j.useState("filters"),[i,l]=j.useState([]),[o,c]=j.useState(""),[d,u]=j.useState([]),[h,m]=j.useState(!1),[p,x]=j.useState(""),[y,g]=j.useState(!1),[b,v]=j.useState(VPe),[k,C]=j.useState(null),[T,M]=j.useState(!1),[P,L]=j.useState(""),[I,O]=j.useState(""),[$,q]=j.useState(""),[W,G]=j.useState(""),[K,ee]=j.useState("rich"),[J,le]=j.useState(""),[ue,oe]=j.useState(""),[ie,de]=j.useState(""),[we,je]=j.useState(!1),[xe,fe]=j.useState(null),Se=K==="rich"?J:ue;j.useEffect(()=>{t!=null&&t.email&&(q(Fe=>Fe||t.email),G(Fe=>Fe||t.email),de(Fe=>Fe||t.email))},[t==null?void 0:t.email]);const{data:Ee}=mt({queryKey:["broadcast-brokerages"],queryFn:async()=>{const{data:Fe}=await U.from("brokerages").select("id, name").order("name");return Fe||[]}}),{data:Le}=mt({queryKey:["admin-broadcasts"],queryFn:async()=>{const{data:Fe,error:dt}=await U.from("admin_broadcasts").select("*").order("created_at",{ascending:!1}).limit(30);if(dt)throw dt;return Fe}}),{data:De}=mt({queryKey:["admin-broadcast-templates"],queryFn:async()=>{const{data:Fe,error:dt}=await U.from("admin_broadcast_templates").select("*").order("updated_at",{ascending:!1});if(dt)throw dt;return Fe}}),Be=async Fe=>{M(!0);try{const{data:dt,error:Dt}=await U.functions.invoke("admin-broadcast",{body:{action:"preview",filters:Fe}});if(Dt)throw Dt;if(dt!=null&&dt.error)throw new Error(dt.error);C(dt)}catch(dt){s({title:"Could not load audience",description:dt.message,variant:"destructive"})}finally{M(!1)}};j.useEffect(()=>{if(r!=="filters")return;const Fe=setTimeout(()=>Be(b),400);return()=>clearTimeout(Fe)},[b,r]),j.useEffect(()=>{if(r!=="manual")return;const Fe=setTimeout(async()=>{m(!0);try{const{data:dt,error:Dt}=await U.functions.invoke("admin-broadcast",{body:{action:"search_members",query:o}});if(Dt)throw Dt;u((dt==null?void 0:dt.members)||[])}catch{u([])}finally{m(!1)}},350);return()=>clearTimeout(Fe)},[o,r]);const Ne=(Fe,dt)=>v(Dt=>({...Dt,[Fe]:dt})),Ge=r==="manual"?i.length:(k==null?void 0:k.count)||0,_e=()=>r==="manual"?{recipient_mode:"manual",manual_emails:i.map(Fe=>Fe.email)}:{recipient_mode:"filters",filters:b},Oe=Fe=>l(dt=>dt.some(Dt=>Dt.email.toLowerCase()===Fe.email.toLowerCase())?dt.filter(Dt=>Dt.email.toLowerCase()!==Fe.email.toLowerCase()):[...dt,Fe]),Ae=async()=>{const Fe=(p||P||I).trim();if(!Fe||!Se.trim()){s({title:"Add a template name and content first",variant:"destructive"});return}g(!0);try{const{error:dt}=await U.from("admin_broadcast_templates").insert({created_by:t.id,name:Fe,subject:I,body_html:Se,editor_mode:K,from_email:$||null,reply_to_email:W||null,filters:b});if(dt)throw dt;x(""),s({title:"Template saved",description:`"${Fe}" is available for future sends.`}),n.invalidateQueries({queryKey:["admin-broadcast-templates"]})}catch(dt){s({title:"Could not save template",description:dt.message,variant:"destructive"})}finally{g(!1)}},Xe=Fe=>{L(Fe.name||""),O(Fe.subject||""),Fe.from_email&&q(Fe.from_email),Fe.reply_to_email&&G(Fe.reply_to_email);const dt=Fe.editor_mode==="html"?"html":"rich";ee(dt),dt==="html"?oe(Fe.body_html||""):le(Fe.body_html||""),Fe.filters&&Object.keys(Fe.filters).length&&v({...VPe,...Fe.filters}),s({title:"Template loaded",description:"Edit and send when ready."})},Ue=async Fe=>{if(!await Bi(`Delete template "${Fe.name}"?`))return;const{error:dt}=await U.from("admin_broadcast_templates").delete().eq("id",Fe.id);if(dt){s({title:"Delete failed",description:dt.message,variant:"destructive"});return}n.invalidateQueries({queryKey:["admin-broadcast-templates"]})},Ze=j.useMemo(()=>!!I.trim()&&!!Se.trim()&&!!$.trim()&&Ge>0,[I,Se,$,Ge]),Qe=async()=>{if(!ie||!I.trim()||!Se.trim()){s({title:"Add a subject, content and test address first",variant:"destructive"});return}try{const{data:Fe,error:dt}=await U.functions.invoke("admin-broadcast",{body:{action:"test",to:ie,subject:I,html:Se,from_email:$,reply_to:W||void 0}});if(dt)throw dt;if(Fe!=null&&Fe.error)throw new Error(Fe.error);s({title:"Test sent",description:`Check ${ie}`})}catch(Fe){s({title:"Test failed",description:Fe.message,variant:"destructive"})}},Ye=async()=>{const Fe=Ge;if(await Bi({title:"Send this broadcast?",description:`"${I}" will be emailed to ${Fe} member${Fe===1?"":"s"}. Sent emails can't be recalled.`,confirmText:"Send broadcast",cancelText:"Cancel",destructive:!1})){je(!0),fe({total:Fe,sent:0,failed:0});try{const{data:Dt,error:pt}=await U.functions.invoke("admin-broadcast",{body:{action:"queue",name:P||I,subject:I,html:Se,from_email:$,reply_to:W||void 0,..._e()}});if(pt)throw pt;if(Dt!=null&&Dt.error)throw new Error(Dt.error);let zt=0,Gt=0,qs=Dt.total,As=0;for(;qs>0;){const{data:Bt,error:At}=await U.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:Dt.broadcast_id,limit:40}});if(At)throw At;if(Bt!=null&&Bt.error)throw new Error(Bt.error);if(zt+=Bt.sent,Gt+=Bt.failed,qs=Bt.remaining,fe({total:Dt.total,sent:zt,failed:Gt}),Bt.throttled){const Is=Math.min(Math.max(Number(Bt.retry_after_ms)||15e3,5e3),45e3);await new Promise(jt=>setTimeout(jt,Is));continue}if(Bt.sent===0&&Bt.failed===0){if(++As>=3)break;await new Promise(Is=>setTimeout(Is,5e3))}else As=0}s({title:"Broadcast complete",description:`${zt} sent${Gt?`, ${Gt} failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(Dt){s({title:"Send failed",description:Dt.message,variant:"destructive"})}finally{je(!1)}}},nt=async Fe=>{je(!0);try{const{data:dt,error:Dt}=await U.functions.invoke("admin-broadcast",{body:{action:"retry_failed",broadcast_id:Fe}});if(Dt)throw Dt;if(dt!=null&&dt.error)throw new Error(dt.error);let pt=0,zt=0,Gt=dt.requeued,qs=0;for(fe({total:Gt,sent:0,failed:0});Gt>0;){const{data:As,error:Bt}=await U.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:Fe,limit:25}});if(Bt)throw Bt;if(As!=null&&As.error)throw new Error(As.error);if(pt+=As.sent,zt+=As.failed,Gt=As.remaining,fe({total:dt.requeued,sent:pt,failed:zt}),As.throttled){await new Promise(At=>setTimeout(At,Math.min(Math.max(Number(As.retry_after_ms)||15e3,5e3),45e3)));continue}if(As.sent===0&&As.failed===0){if(++qs>=3)break;await new Promise(At=>setTimeout(At,5e3))}else qs=0}s({title:"Retry complete",description:`${pt} sent${zt?`, ${zt} still failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(dt){s({title:"Retry failed",description:dt.message,variant:"destructive"})}finally{je(!1)}};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(oh,{title:"Member Broadcasts",description:"Send a one-off email to a filtered slice of LevelUp members"}),e.jsxs(fa,{defaultValue:"compose",className:"space-y-6",children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"compose",className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"})," Compose"]}),e.jsxs(ss,{value:"sms",className:"gap-2",children:[e.jsx(ro,{className:"h-4 w-4"})," Text (SMS)"]}),e.jsxs(ss,{value:"templates",className:"gap-2",children:[e.jsx(q_,{className:"h-4 w-4"})," Templates"]}),e.jsxs(ss,{value:"history",className:"gap-2",children:[e.jsx(GT,{className:"h-4 w-4"})," History"]})]}),e.jsx(ns,{value:"sms",className:"space-y-6",children:e.jsx(qfn,{brokerages:Ee})}),e.jsx(ns,{value:"compose",className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[340px_1fr]",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs(be,{className:"overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-primary/90 to-primary p-5 text-primary-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm opacity-90",children:[e.jsx(Bn,{className:"h-4 w-4"})," Audience"]}),e.jsxs("div",{className:"mt-2 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-4xl font-bold",children:r==="manual"?i.length:T?"—":(k==null?void 0:k.count)??0}),e.jsx("span",{className:"text-sm opacity-90",children:r==="manual"?"members selected":"members match"})]})]}),e.jsxs(Re,{className:"space-y-4 pt-5",children:[e.jsx(fa,{value:r,onValueChange:Fe=>a(Fe),children:e.jsxs(xa,{className:"grid w-full grid-cols-2",children:[e.jsxs(ss,{value:"filters",className:"gap-1.5 text-xs",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"})," Filters"]}),e.jsxs(ss,{value:"manual",className:"gap-1.5 text-xs",children:[e.jsx(Sl,{className:"h-3.5 w-3.5"})," Individuals"]})]})}),r==="manual"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Find members"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:o,onChange:Fe=>c(Fe.target.value),placeholder:"Search by name or email",className:"pl-8"})]})]}),i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:i.map(Fe=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx("span",{className:"max-w-[150px] truncate",children:Fe.name||Fe.email}),e.jsx("button",{type:"button",onClick:()=>Oe(Fe),"aria-label":`Remove ${Fe.email}`,children:e.jsx(dr,{className:"h-3 w-3"})})]},Fe.email))}),e.jsx("div",{className:"max-h-72 space-y-1 overflow-y-auto rounded-lg border p-1",children:h?e.jsx("p",{className:"p-3 text-xs text-muted-foreground",children:"Searching…"}):d.length===0?e.jsx("p",{className:"p-3 text-xs text-muted-foreground",children:"No members found."}):d.map(Fe=>{const dt=i.some(Dt=>Dt.email.toLowerCase()===Fe.email.toLowerCase());return e.jsxs("button",{type:"button",onClick:()=>Oe(Fe),className:`flex w-full items-center justify-between rounded-md px-2.5 py-2 text-left text-xs hover:bg-muted ${dt?"bg-muted":""}`,children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate font-medium",children:Fe.name||"Member"}),e.jsx("span",{className:"block truncate text-muted-foreground",children:Fe.email})]}),dt&&e.jsx(Rr,{className:"h-4 w-4 shrink-0 text-primary"})]},Fe.id)})})]}),r==="filters"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Account status"}),e.jsxs(vs,{value:b.status,onValueChange:Fe=>Ne("status",Fe),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All members"}),e.jsx(Je,{value:"active",children:"Active (signed in)"}),e.jsx(Je,{value:"pending",children:"Pending (never signed in)"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Membership"}),e.jsxs(vs,{value:b.billing,onValueChange:Fe=>Ne("billing",Fe),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"Any membership"}),e.jsx(Je,{value:"trial",children:"On trial"}),e.jsx(Je,{value:"paid",children:"Paid subscribers"}),e.jsx(Je,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Je,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Role"}),e.jsxs(vs,{value:b.role,onValueChange:Fe=>Ne("role",Fe),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"Any role"}),e.jsx(Je,{value:"user",children:"Members"}),e.jsx(Je,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(Je,{value:"coach",children:"Coaches"}),e.jsx(Je,{value:"assistant",children:"Assistants"}),e.jsx(Je,{value:"admin",children:"Admins"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Brokerage"}),e.jsxs(vs,{value:b.brokerage,onValueChange:Fe=>Ne("brokerage",Fe),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{className:"max-h-72",children:[e.jsx(Je,{value:"all",children:"All brokerages"}),e.jsx(Je,{value:"none",children:"No brokerage"}),(Ee||[]).map(Fe=>e.jsx(Je,{value:Fe.id,children:Fe.name},Fe.id))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Joined within"}),e.jsxs(vs,{value:b.joinedWithinDays?String(b.joinedWithinDays):"all",onValueChange:Fe=>Ne("joinedWithinDays",Fe==="all"?null:Number(Fe)),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"Any time"}),e.jsx(Je,{value:"30",children:"Last 30 days"}),e.jsx(Je,{value:"60",children:"Last 60 days"}),e.jsx(Je,{value:"90",children:"Last 90 days"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Respect opt-outs"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip members who opted out of updates"})]}),e.jsx(Mn,{checked:b.respectOptOut,onCheckedChange:Fe=>Ne("respectOptOut",Fe)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(VPe),children:"Reset"}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>Be(b),disabled:T,children:[T?e.jsx(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ki,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),(rt=k==null?void 0:k.sample)!=null&&rt.length?e.jsxs("div",{className:"rounded-lg bg-muted/40 p-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Sample recipients"}),e.jsx("div",{className:"space-y-1",children:k.sample.map(Fe=>e.jsxs("p",{className:"truncate text-xs",children:[e.jsx("span",{className:"font-medium",children:Fe.name||"Member"})," ",e.jsx("span",{className:"text-muted-foreground",children:Fe.email})]},Fe.email))})]}):null]})]})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsxs(Ft,{className:"pb-4",children:[e.jsx(Ut,{className:"text-base",children:"Message"}),e.jsxs(fr,{children:["Personalize with merge tags: ",Vfn.join(" ")]})]}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Internal name"}),e.jsx(ye,{value:P,onChange:Fe=>L(Fe.target.value),placeholder:"August product update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Subject line"}),e.jsx(ye,{value:I,onChange:Fe=>O(Fe.target.value),placeholder:"Big news for LevelUp members"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"From (must be a verified sender)"}),e.jsx(ye,{value:$,onChange:Fe=>q(Fe.target.value),placeholder:"hello@relevelup.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Reply-to"}),e.jsx(ye,{value:W,onChange:Fe=>G(Fe.target.value),placeholder:"support@relevelup.com"})]})]}),e.jsxs(fa,{value:K,onValueChange:Fe=>ee(Fe),children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"rich",className:"gap-2",children:[e.jsx(yn,{className:"h-3.5 w-3.5"})," Rich text"]}),e.jsxs(ss,{value:"html",className:"gap-2",children:[e.jsx(qT,{className:"h-3.5 w-3.5"})," Paste HTML"]})]}),e.jsx(ns,{value:"rich",className:"mt-3",children:e.jsx(Kj,{content:J,onChange:le,minHeight:"320px",placeholder:"Write your message…"})}),e.jsxs(ns,{value:"html",className:"mt-3 space-y-2",children:[e.jsx(Ds,{value:ue,onChange:Fe=>oe(Fe.target.value),placeholder:"…paste your full email HTML here…",className:"min-h-[320px] font-mono text-xs"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste full HTML from Canva, Beefree, Mailchimp, etc. It is sent exactly as written (merge tags still work)."})]})]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(ma,{className:"h-4 w-4"})," Preview"]}),e.jsx(qe,{variant:"secondary",children:K==="html"?"Raw HTML":"Rich text"})]}),e.jsx(Re,{children:e.jsx("iframe",{title:"Email preview",srcDoc:Hfn(Se),className:"h-[420px] w-full rounded-lg border bg-white"})})]}),e.jsx(be,{children:e.jsxs(Re,{className:"space-y-4 pt-6",children:[xe&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:[xe.sent+xe.failed," of ",xe.total," processed"]}),e.jsxs("span",{className:"text-muted-foreground",children:[xe.sent," sent",xe.failed?` • ${xe.failed} failed`:""]})]}),e.jsx(qi,{value:xe.total?(xe.sent+xe.failed)/xe.total*100:0})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Send a test to"}),e.jsx(ye,{value:ie,onChange:Fe=>de(Fe.target.value),className:"w-64"})]}),e.jsx(B,{variant:"outline",onClick:Qe,disabled:we,children:"Send test"}),e.jsx("div",{className:"flex-1"}),e.jsxs(B,{onClick:Ye,disabled:!Ze||we,size:"lg",className:"gap-2",children:[we?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"}),we?"Sending…":`Send to ${Ge} member${Ge===1?"":"s"}`]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 border-t pt-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Save as template"}),e.jsx(ye,{value:p,onChange:Fe=>x(Fe.target.value),placeholder:P||I||"Template name",className:"w-64"})]}),e.jsxs(B,{variant:"outline",className:"gap-2",onClick:Ae,disabled:y,children:[y?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx($T,{className:"h-4 w-4"}),"Save template"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saves the subject, content, sender and current filters for reuse later."})]})]})})]})]})}),e.jsx(ns,{value:"templates",className:"space-y-3",children:(De||[]).length===0?e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(q_,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No saved templates yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Compose an email, then use "Save template" to reuse it for future sends.'})]})}):(De||[]).map(Fe=>e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children:Fe.name}),e.jsx(qe,{variant:"secondary",className:"text-xs",children:Fe.editor_mode==="html"?"Raw HTML":"Rich text"})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",Fe.subject||"—"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Updated ",Bs(new Date(Fe.updated_at),"MMM d, yyyy h:mm a")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",className:"gap-2",onClick:()=>Xe(Fe),children:[e.jsx(Jo,{className:"h-3.5 w-3.5"})," Use template"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Ue(Fe),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]})},Fe.id))}),e.jsx(ns,{value:"history",className:"space-y-3",children:(Le||[]).length===0?e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(on,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No broadcasts sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your sent member emails will show up here."})]})}):(Le||[]).map(Fe=>e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children:Fe.name}),e.jsxs(qe,{variant:Fe.status==="sent"?"default":Fe.status==="sending"?"secondary":"outline",className:"gap-1 text-xs",children:[Fe.status==="sent"?e.jsx(Rr,{className:"h-3 w-3"}):e.jsx(po,{className:"h-3 w-3"}),Fe.status]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",Fe.subject]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Bs(new Date(Fe.created_at),"MMM d, yyyy h:mm a")," • from ",Fe.from_email]})]}),e.jsxs("div",{className:"flex gap-6 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:Fe.total_recipients}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:Fe.sent_count}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sent"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:Fe.failed_count}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Failed"})]}),Fe.failed_count>0&&e.jsx("div",{className:"flex items-center",children:e.jsx(B,{size:"sm",variant:"outline",disabled:we,onClick:()=>nt(Fe.id),children:"Retry failed"})})]})]})},Fe.id))})]})]})})}const Wfn=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function Kfn(){const s=as(),t=j.useRef(null),[n,r]=j.useState(""),[a,i]=j.useState("all"),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),{data:x=[],isLoading:y}=mt({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:$,error:q}=await U.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if(q)throw q;return $||[]}}),g=j.useMemo(()=>{const $=new Set(Wfn);return x.forEach(q=>$.add(q.category)),Array.from($).sort()},[x]),b=j.useMemo(()=>{const $=n.trim().toLowerCase();return x.filter(q=>a!=="all"&&q.category!==a?!1:$?q.title.toLowerCase().includes($)||(q.description||"").toLowerCase().includes($)||q.tags.some(W=>W.toLowerCase().includes($)):!0)},[x,n,a]),v=()=>{p({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},k=()=>{v(),d(!0)},C=$=>{o($),p({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 q;if(!$.type.startsWith("image/")){re.error("Please choose an image file");return}if($.size>15*1024*1024){re.error("Image must be under 15MB");return}h(!0);try{const W=((q=$.name.split(".").pop())==null?void 0:q.toLowerCase())||"png",G=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${W}`,{error:K}=await U.storage.from("newsletter-content").upload(G,$,{cacheControl:"31536000",upsert:!1,contentType:$.type});if(K)throw K;const{data:ee}=U.storage.from("newsletter-content").getPublicUrl(G);p(J=>({...J,image_url:ee.publicUrl,title:J.title||$.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),re.success("Uploaded")}catch(W){re.error(W.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},M=vt({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),q={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 U.from("newsletter_graphics").update(q).eq("id",l.id);if(G)throw G}else{const{data:G}=await U.auth.getUser(),{error:K}=await U.from("newsletter_graphics").insert({...q,created_by:(W=G.user)==null?void 0:W.id});if(K)throw K}},onSuccess:()=>{re.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),v()},onError:$=>re.error($.message||"Save failed")}),P=vt({mutationFn:async $=>{const{error:q}=await U.from("newsletter_graphics").delete().eq("id",$);if(q)throw q},onSuccess:()=>{re.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:$=>re.error($.message||"Delete failed")}),L=async $=>{const{error:q}=await U.from("newsletter_graphics").update({is_active:!$.is_active}).eq("id",$.id);q?re.error(q.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},I=async $=>{const{error:q}=await U.from("newsletter_graphics").update({is_featured:!$.is_featured}).eq("id",$.id);q?re.error(q.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},O=$=>{navigator.clipboard.writeText($),re.success("URL copied")};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(oh,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(be,{children:e.jsxs(Re,{className:"p-4 flex flex-col md:flex-row gap-3 md:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:n,onChange:$=>r($.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(vs,{value:a,onValueChange:i,children:[e.jsx(gs,{className:"w-full md:w-56",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All categories"}),g.map($=>e.jsx(Je,{value:$,children:$},$))]})]}),e.jsxs(B,{onClick:k,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(a1,{className:"h-4 w-4"})," Add Graphic"]})]})}),y?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-16 text-center",children:[e.jsx(ac,{className:"h-10 w-10 mx-auto mb-3 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:x.length===0?"No graphics uploaded yet — add your first one to get started.":"No graphics match your filters."}),x.length===0&&e.jsxs(B,{onClick:k,className:"gap-1.5",children:[e.jsx(a1,{className:"h-4 w-4"})," Upload First Graphic"]})]})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:b.map($=>e.jsxs(be,{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(qe,{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(qe,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(Re,{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(q=>e.jsx(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:q},q))}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>C($),title:"Edit",children:e.jsx(Za,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I($),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:()=>O($.image_url),title:"Copy URL",children:e.jsx(ja,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{checked:$.is_active,onCheckedChange:()=>L($)}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:async()=>{await Bi(`Delete "${$.title}"?`)&&P.mutate($.id)},children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]})]})]},$.id))})]}),e.jsx(Fs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:$=>{var W;const q=(W=$.target.files)==null?void 0:W[0];q&&T(q)}}),m.image_url?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border bg-muted/30 mt-1.5",children:[e.jsx("img",{src:m.image_url,alt:"Preview",className:"w-full max-h-64 object-contain"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>p($=>({...$,image_url:""})),children:e.jsx(dr,{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(Wt,{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(Ja,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"Click to upload image"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"PNG, JPG, WEBP, GIF · up to 15MB"})]})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"g-title",children:"Title *"}),e.jsx(ye,{id:"g-title",value:m.title,onChange:$=>p(q=>({...q,title:$.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"g-desc",children:"Description"}),e.jsx(Ds,{id:"g-desc",value:m.description,onChange:$=>p(q=>({...q,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(se,{children:"Category"}),e.jsxs(vs,{value:m.category,onValueChange:$=>p(q=>({...q,category:$})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:g.map($=>e.jsx(Je,{value:$,children:$},$))})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(ye,{id:"g-tags",value:m.tags,onChange:$=>p(q=>({...q,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(Mn,{checked:m.is_featured,onCheckedChange:$=>p(q=>({...q,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(Mn,{checked:m.is_active,onCheckedChange:$=>p(q=>({...q,is_active:$}))})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>M.mutate(),disabled:M.isPending,children:[M.isPending&&e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const Amt={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 Yfn(){const{user:s}=Ns(),{toast:t}=pi(),n=Hn(),r=as(),[a,i]=j.useState(""),[l,o]=j.useState("popular"),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState(""),[x,y]=j.useState(!1),{data:g=[],isLoading:b}=mt({queryKey:["wishlist-items",l,x],queryFn:async()=>{let M=U.from("wishlist_items").select("*");x&&s&&(M=M.eq("user_id",s.id)),l==="latest"?M=M.order("created_at",{ascending:!1}):l==="popular"?M=M.order("vote_count",{ascending:!1}):l==="trending"&&(M=M.order("vote_count",{ascending:!1}));const{data:P,error:L}=await M;if(L)throw L;const I=[...new Set((P==null?void 0:P.map(ee=>ee.user_id))||[])],{data:O}=await U.from("profiles").select("id, name").in("id",I),$=new Map((O==null?void 0:O.map(ee=>[ee.id,ee]))||[]);let q=[];if(s){const{data:ee}=await U.from("wishlist_votes").select("item_id").eq("user_id",s.id);q=(ee==null?void 0:ee.map(J=>J.item_id))||[]}const W=(P==null?void 0:P.map(ee=>ee.id))||[],{data:G}=await U.from("wishlist_comments").select("item_id").in("item_id",W),K=new Map;return G==null||G.forEach(ee=>{K.set(ee.item_id,(K.get(ee.item_id)||0)+1)}),P==null?void 0:P.map(ee=>{const J=$.get(ee.user_id),le=(J==null?void 0:J.name)||"Unknown";return{...ee,user_name:le,user_initials:le.split(" ").map(ue=>ue[0]).join("").toUpperCase().slice(0,2),has_voted:q.includes(ee.id),comment_count:K.get(ee.id)||0}})}}),v=vt({mutationFn:async({title:M,description:P})=>{const{error:L}=await U.from("wishlist_items").insert({user_id:s.id,title:M,description:P});if(L)throw L},onSuccess:()=>{r.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),h(""),p(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:M=>{t({title:"Error",description:M.message,variant:"destructive"})}}),k=vt({mutationFn:async({itemId:M,hasVoted:P})=>{if(P){const{error:L}=await U.from("wishlist_votes").delete().eq("item_id",M).eq("user_id",s.id);if(L)throw L;return{itemId:M,wasAdded:!1}}else{const{error:L}=await U.from("wishlist_votes").insert({item_id:M,user_id:s.id});if(L)throw L;return{itemId:M,wasAdded:!0}}},onSuccess:async M=>{if(r.invalidateQueries({queryKey:["wishlist-items"]}),M!=null&&M.wasAdded){const P=g.find(I=>I.id===M.itemId),L=((P==null?void 0:P.vote_count)||0)+1;U.functions.invoke("wishlist-notify",{body:{itemId:M.itemId,voteCount:L}}).catch(console.error)}},onError:M=>{t({title:"Error",description:M.message,variant:"destructive"})}}),C=g.filter(M=>M.title.toLowerCase().includes(a.toLowerCase())||M.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}v.mutate({title:u.trim(),description:m.trim()})};return e.jsx(Vs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(xN,{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(Fs,{open:c,onOpenChange:d,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Submit a New Idea"})}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:M=>h(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ds,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:m,onChange:M=>p(M.target.value),rows:4})]}),e.jsx(B,{onClick:T,className:"w-full",disabled:v.isPending,children:v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Submitting..."]}):"Submit Idea"})]})]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-6",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search ideas...",value:a,onChange:M=>i(M.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(fa,{value:l,onValueChange:M=>o(M),children:e.jsxs(xa,{children:[e.jsx(ss,{value:"popular",children:"Most Popular"}),e.jsx(ss,{value:"latest",children:"Latest"}),e.jsx(ss,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx(B,{variant:x?"default":"outline",size:"sm",onClick:()=>y(!x),children:x?"Show All Ideas":"My Ideas"})}),b?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):C.length===0?e.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[e.jsx(xN,{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(Js,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:C.map(M=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>n(`/wishlist/${M.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:P=>{P.stopPropagation(),k.mutate({itemId:M.id,hasVoted:M.has_voted||!1})},className:Et("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",M.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(Gm,{className:Et("h-4 w-4",M.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:M.vote_count})]}),e.jsx(Ra,{className:"h-10 w-10 bg-primary/20",children:e.jsx(Da,{className:"bg-primary/20 text-primary text-sm font-medium",children:M.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:M.title}),e.jsx(qe,{className:Et("text-xs",Amt[M.status].color),children:Amt[M.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:M.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:M.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(M.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(ro,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:M.comment_count})]})]})},M.id))})]})})}const Tmt={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 Zfn(){const{itemId:s}=$i(),t=Hn(),{user:n}=Ns(),{toast:r}=pi(),a=as(),[i,l]=j.useState(""),{data:o=!1}=mt({queryKey:["user-is-admin",n==null?void 0:n.id],queryFn:async()=>{if(!n)return!1;const{data:g,error:b}=await U.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!b&&!!g},enabled:!!n}),{data:c,isLoading:d}=mt({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:g,error:b}=await U.from("wishlist_items").select("*").eq("id",s).single();if(b)throw b;const{data:v}=await U.from("profiles").select("name").eq("id",g.user_id).single();let k=!1;if(n){const{data:C}=await U.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();k=!!C}return{...g,user_name:(v==null?void 0:v.name)||"Unknown",user_initials:((v==null?void 0:v.name)||"U").split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),has_voted:k}}}),{data:u=[],isLoading:h}=mt({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:g,error:b}=await U.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(b)throw b;const v=[...new Set((g==null?void 0:g.map(T=>T.user_id))||[])],{data:k}=await U.from("profiles").select("id, name").in("id",v),C=new Map((k==null?void 0:k.map(T=>[T.id,T]))||[]);return g==null?void 0:g.map(T=>{const M=C.get(T.user_id),P=(M==null?void 0:M.name)||"Unknown";return{...T,user_name:P,user_initials:P.split(" ").map(L=>L[0]).join("").toUpperCase().slice(0,2)}})}}),m=vt({mutationFn:async g=>{if(g){const{error:b}=await U.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(b)throw b;return{wasAdded:!1}}else{const{error:b}=await U.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(b)throw b;return{wasAdded:!0}}},onSuccess:async g=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),g!=null&&g.wasAdded&&c){const b=(c.vote_count||0)+1;U.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:b}}).catch(console.error)}},onError:g=>{r({title:"Error",description:g.message,variant:"destructive"})}}),p=vt({mutationFn:async g=>{const{error:b}=await U.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:g});if(b)throw b},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:g=>{r({title:"Error",description:g.message,variant:"destructive"})}}),x=vt({mutationFn:async g=>{const{error:b}=await U.from("wishlist_comments").delete().eq("id",g);if(b)throw b},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:g=>{r({title:"Error",description:g.message,variant:"destructive"})}}),y=()=>{i.trim()&&p.mutate(i.trim())};return d?e.jsx(Vs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(gn,{className:"h-8 w-32 mb-6"}),e.jsx(gn,{className:"h-48 w-full mb-6"}),e.jsx(gn,{className:"h-32 w-full"})]})}):c?e.jsx(Vs,{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(_a,{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:Et("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(Gm,{className:Et("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(qe,{className:Et("text-xs",Tmt[c.status].color),children:Tmt[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(Ra,{className:"h-6 w-6",children:e.jsx(Da,{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(Zke,{placeholder:o?"Share your thoughts... Use # to link templates":"Share your thoughts on this idea...",value:i,onChange:l,minHeight:"60px",mentionFormat:"encoded",enableTemplateMentions:o}),e.jsx(B,{onClick:y,disabled:!i.trim()||p.isPending,size:"icon",className:"h-auto",children:p.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(g=>e.jsx(gn,{className:"h-20 w-full"},g))}):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(g=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Ra,{className:"h-8 w-8",children:e.jsx(Da,{className:"bg-primary/20 text-primary text-xs",children:g.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:g.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(g.created_at).toLocaleDateString()})]}),e.jsx(XHe,{content:g.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===g.user_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>x.mutate(g.id),children:e.jsx(Rn,{className:"h-4 w-4"})})]},g.id))})]})]})}):e.jsx(Vs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Item not found"}),e.jsx(B,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const Emt={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"}},Mmt=["open","under_review","planned","in_progress","launched","declined"];function Xfn(){const{toast:s}=pi(),t=Hn(),n=as(),[r,a]=j.useState(""),[i,l]=j.useState("all"),[o,c]=j.useState(!1),[d,u]=j.useState(null),{data:h=[],isLoading:m}=mt({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:b,error:v}=await U.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(v)throw v;const k=[...new Set((b==null?void 0:b.map(I=>I.user_id))||[])],{data:C}=await U.from("profiles").select("id, name, email").in("id",k),T=new Map((C==null?void 0:C.map(I=>[I.id,I]))||[]),M=(b==null?void 0:b.map(I=>I.id))||[],{data:P}=await U.from("wishlist_comments").select("item_id").in("item_id",M),L=new Map;return P==null||P.forEach(I=>{L.set(I.item_id,(L.get(I.item_id)||0)+1)}),b==null?void 0:b.map(I=>{const O=T.get(I.user_id);return{...I,user_name:(O==null?void 0:O.name)||"Unknown",user_email:(O==null?void 0:O.email)||"",comment_count:L.get(I.id)||0}})}}),p=vt({mutationFn:async({itemId:b,status:v})=>{const{error:k}=await U.from("wishlist_items").update({status:v}).eq("id",b);if(k)throw k},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:b=>{s({title:"Error",description:b.message,variant:"destructive"})}}),x=vt({mutationFn:async b=>{const{error:v}=await U.from("wishlist_items").delete().eq("id",b);if(v)throw v},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:b=>{s({title:"Error",description:b.message,variant:"destructive"})}}),y=h.filter(b=>{const v=b.title.toLowerCase().includes(r.toLowerCase())||b.description.toLowerCase().includes(r.toLowerCase())||b.user_name.toLowerCase().includes(r.toLowerCase()),k=i==="all"||b.status===i;return v&&k}),g={total:h.length,open:h.filter(b=>b.status==="open").length,inProgress:h.filter(b=>b.status==="in_progress").length,launched:h.filter(b=>b.status==="launched").length,highVotes:h.filter(b=>b.vote_count>=10).length};return e.jsx(Vs,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(_a,{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:g.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:g.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:g.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:g.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:g.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search ideas, users...",value:r,onChange:b=>a(b.target.value),className:"pl-10"})]}),e.jsxs(vs,{value:i,onValueChange:b=>l(b),children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"Filter by status"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Statuses"}),Mmt.map(b=>e.jsx(Je,{value:b,children:Emt[b].label},b))]})]})]}),m?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(b=>e.jsx(gn,{className:"h-16 w-full"},b))}):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(Tt,{className:"w-[60px]",children:"Votes"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Tt,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(za,{children:y.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):y.map(b=>e.jsxs(un,{className:Et(b.vote_count>=10&&"bg-primary/5"),children:[e.jsx(xt,{children:e.jsx(qe,{variant:b.vote_count>=10?"default":"secondary",children:b.vote_count})}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:b.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:b.description})]})}),e.jsx(xt,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:b.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.user_email})]})}),e.jsx(xt,{className:"hidden sm:table-cell",children:b.comment_count}),e.jsx(xt,{children:e.jsxs(vs,{value:b.status,onValueChange:v=>p.mutate({itemId:b.id,status:v}),children:[e.jsx(gs,{className:"w-[140px] h-8",children:e.jsx(bs,{})}),e.jsx(ys,{children:Mmt.map(v=>e.jsx(Je,{value:v,children:Emt[v].label},v))})]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${b.id}`,"_blank"),children:e.jsx(Tr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(b.id),c(!0)},children:e.jsx(Rn,{className:"h-4 w-4"})})]})})]},b.id))})]})}),e.jsx(Fs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Delete Wishlist Item"})}),e.jsx("p",{className:"text-muted-foreground",children:"Are you sure you want to delete this idea? This will also delete all votes and comments."}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>d&&x.mutate(d),disabled:x.isPending,children:x.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function Qfn(){const{user:s}=Ns(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,x]=j.useState(""),[y,g]=j.useState(""),[b,v]=j.useState(""),[k,C]=j.useState(""),[T,M]=j.useState(""),[P,L]=j.useState(!1),[I,O]=j.useState(""),[$,q]=j.useState("once"),[W,G]=j.useState([]),[K,ee]=j.useState([]),[J,le]=j.useState(!1),[ue,oe]=j.useState(!1),[ie,de]=j.useState([]),[we,je]=j.useState({total:0,dismissed:0});j.useEffect(()=>{xe()},[]);const xe=async()=>{const{data:rt,error:Fe}=await U.from("levelup_briefs").select("*").order("created_at",{ascending:!1});Fe?(re.error("Failed to fetch briefs"),console.error(Fe)):n(rt||[]),a(!1)},fe=()=>{x(""),g(""),v(""),C(""),M(""),L(!1),O(new Date().toISOString().slice(0,16)),q("once"),G([]),ee([]),c(null)},Se=()=>{fe(),l(!0)},Ee=async rt=>{c(rt),x(rt.title),g(rt.description||""),v(rt.video_url||""),C(rt.graphic_url||""),M(rt.graphic_link_url||""),L(rt.is_published),O(rt.publish_date.slice(0,16)),q(rt.show_frequency);const{data:Fe}=await U.from("levelup_brief_links").select("*").eq("brief_id",rt.id).order("sort_order");G((Fe==null?void 0:Fe.map(Dt=>({title:Dt.title,url:Dt.url})))||[]);const{data:dt}=await U.from("levelup_brief_polls").select("*").eq("brief_id",rt.id).order("sort_order");if(dt){const Dt=[];for(const pt of dt){const{data:zt}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",pt.id).order("sort_order");Dt.push({question:pt.question,poll_type:pt.poll_type,options:(zt==null?void 0:zt.map(Gt=>Gt.option_text))||[]})}ee(Dt)}l(!0)},Le=async rt=>{var dt;const Fe=(dt=rt.target.files)==null?void 0:dt[0];if(Fe){le(!0);try{const Dt=await U.functions.invoke("bunny-upload",{body:{action:"create",title:Fe.name.replace(/\.[^/.]+$/,"")}});if(Dt.error)throw Dt.error;const{videoId:pt,libraryId:zt}=Dt.data,Gt=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:pt}});if(Gt.error)throw Gt.error;const{uploadUrl:qs,apiKey:As}=Gt.data,Bt=new XMLHttpRequest;await new Promise((Is,jt)=>{Bt.upload.addEventListener("progress",Qs=>{if(Qs.lengthComputable){const cn=Math.round(Qs.loaded/Qs.total*100);console.log("Upload progress:",cn)}}),Bt.addEventListener("load",()=>{Bt.status>=200&&Bt.status<300?Is():jt(new Error(`Upload failed with status ${Bt.status}`))}),Bt.addEventListener("error",()=>jt(new Error("Upload failed"))),Bt.open("PUT",qs),Bt.setRequestHeader("AccessKey",As),Bt.send(Fe)});const At=`https://player.mediadelivery.net/embed/${zt}/${pt}`;v(At),re.success("Video uploaded successfully! It may take a few minutes to process.")}catch(Dt){console.error("Upload error:",Dt),re.error("Failed to upload video")}finally{le(!1)}}},De=async()=>{if(!p.trim()){re.error("Title is required");return}try{let rt;if(o){const{error:Fe}=await U.from("levelup_briefs").update({title:p,description:y||null,video_url:b||null,graphic_url:k||null,graphic_link_url:T||null,is_published:P,publish_date:I,show_frequency:$}).eq("id",o.id);if(Fe)throw Fe;rt=o.id,await U.from("levelup_brief_links").delete().eq("brief_id",rt);const{data:dt}=await U.from("levelup_brief_polls").select("id").eq("brief_id",rt);if(dt)for(const Dt of dt)await U.from("levelup_brief_poll_options").delete().eq("poll_id",Dt.id);await U.from("levelup_brief_polls").delete().eq("brief_id",rt)}else{const{data:Fe,error:dt}=await U.from("levelup_briefs").insert({title:p,description:y||null,video_url:b||null,graphic_url:k||null,graphic_link_url:T||null,is_published:P,publish_date:I,show_frequency:$,created_by:s==null?void 0:s.id}).select().single();if(dt)throw dt;rt=Fe.id}if(W.length>0){const Fe=W.map((dt,Dt)=>({brief_id:rt,title:dt.title,url:dt.url,sort_order:Dt}));await U.from("levelup_brief_links").insert(Fe)}for(let Fe=0;Fe0){const zt=dt.options.map((Gt,qs)=>({poll_id:Dt.id,option_text:Gt,sort_order:qs}));await U.from("levelup_brief_poll_options").insert(zt)}}re.success(o?"Brief updated":"Brief created"),l(!1),fe(),xe()}catch(rt){console.error("Error saving brief:",rt),re.error("Failed to save brief")}},Be=async rt=>{if(await Bi("Are you sure you want to delete this brief?"))try{const{error:Fe}=await U.from("levelup_briefs").delete().eq("id",rt);if(Fe)throw Fe;re.success("Brief deleted"),xe()}catch(Fe){console.error("Error deleting brief:",Fe),re.error("Failed to delete brief")}},Ne=async rt=>{m(rt);const{count:Fe}=await U.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",rt.id),{count:dt}=await U.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",rt.id).not("dismissed_at","is",null);je({total:Fe||0,dismissed:dt||0});const{data:Dt}=await U.from("levelup_brief_polls").select("*").eq("brief_id",rt.id).order("sort_order");if(Dt){const pt=[];for(const zt of Dt){const{data:Gt}=await U.from("levelup_brief_poll_options").select("*").eq("poll_id",zt.id).order("sort_order"),{data:qs}=await U.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",zt.id),As=[...new Set((qs==null?void 0:qs.map(Qs=>Qs.user_id))||[])];let Bt={};if(As.length>0){const{data:Qs}=await U.from("profiles").select("id, name, email").in("id",As);Qs&&Qs.forEach(cn=>{Bt[cn.id]=cn.name||cn.email||"Unknown"})}const At=(qs||[]).map(Qs=>({optionId:Qs.option_id,userName:Bt[Qs.user_id]||"Unknown",userId:Qs.user_id})),Is={};let jt=0;Gt&&Gt.forEach(Qs=>{const cn=(qs==null?void 0:qs.filter(qt=>qt.option_id===Qs.id).length)||0;Is[Qs.id]=cn,jt+=cn}),pt.push({...zt,options:Gt||[],results:Is,respondents:At,totalResponses:zt.poll_type==="single"?new Set(qs==null?void 0:qs.map(Qs=>Qs.user_id)).size:jt})}de(pt)}u(!0)},Ge=()=>{G([...W,{title:"",url:""}])},_e=(rt,Fe,dt)=>{const Dt=[...W];Dt[rt][Fe]=dt,G(Dt)},Oe=rt=>{G(W.filter((Fe,dt)=>dt!==rt))},Ae=()=>{ee([...K,{question:"",poll_type:"single",options:["",""]}])},Xe=(rt,Fe)=>{const dt=[...K];dt[rt].question=Fe,ee(dt)},Ue=(rt,Fe)=>{const dt=[...K];dt[rt].poll_type=Fe,ee(dt)},Ze=rt=>{const Fe=[...K];Fe[rt].options.push(""),ee(Fe)},Qe=(rt,Fe,dt)=>{const Dt=[...K];Dt[rt].options[Fe]=dt,ee(Dt)},Ye=(rt,Fe)=>{const dt=[...K];dt[rt].options=dt[rt].options.filter((Dt,pt)=>pt!==Fe),ee(dt)},nt=rt=>{ee(K.filter((Fe,dt)=>dt!==rt))};return e.jsxs(Vs,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(B,{onClick:Se,children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Frequency"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:r?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(rt=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:rt.title}),e.jsx(xt,{children:e.jsx(qe,{variant:rt.is_published?"default":"secondary",children:rt.is_published?"Published":"Draft"})}),e.jsx(xt,{className:"capitalize",children:rt.show_frequency.replace("_"," ")}),e.jsx(xt,{children:Bs(new Date(rt.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(xt,{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(ol,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Ee(rt),children:e.jsx(kp,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Be(rt.id),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})})]},rt.id))})]})})})]}),e.jsx(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(fa,{defaultValue:"content",className:"w-full",children:[e.jsxs(xa,{className:"grid w-full grid-cols-4",children:[e.jsx(ss,{value:"content",children:"Content"}),e.jsx(ss,{value:"media",children:"Media"}),e.jsx(ss,{value:"links",children:"Links"}),e.jsx(ss,{value:"polls",children:"Polls"})]}),e.jsxs(ns,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Title *"}),e.jsx(ye,{value:p,onChange:rt=>x(rt.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Kj,{content:y,onChange:rt=>g(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(se,{children:"Publish Date"}),e.jsx(ye,{type:"datetime-local",value:I,onChange:rt=>O(rt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Show Frequency"}),e.jsxs(vs,{value:$,onValueChange:q,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"once",children:"Once (until dismissed)"}),e.jsx(Je,{value:"every_login",children:"Every login"}),e.jsx(Je,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Mn,{checked:P,onCheckedChange:L}),e.jsx(se,{children:"Publish immediately"})]})]}),e.jsxs(ns,{value:"media",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Video (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ye,{type:"file",accept:"video/*",onChange:Le,disabled:J})}),J&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Or paste embed URL"}),e.jsx(ye,{value:b,onChange:rt=>v(rt.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),b&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:b,className:"w-full h-full",allow:"autoplay; fullscreen",allowFullScreen:!0})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Graphic / Image (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ye,{type:"file",accept:"image/*",onChange:async rt=>{var dt;const Fe=(dt=rt.target.files)==null?void 0:dt[0];if(Fe){oe(!0);try{const Dt=Fe.name.split(".").pop(),pt=`brief-graphics/${Date.now()}.${Dt}`,{error:zt}=await U.storage.from("banner-images").upload(pt,Fe,{upsert:!0});if(zt)throw zt;const{data:Gt}=U.storage.from("banner-images").getPublicUrl(pt);C(Gt.publicUrl),re.success("Image uploaded!")}catch(Dt){console.error(Dt),re.error("Failed to upload image")}finally{oe(!1)}}},disabled:ue})}),ue&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Or paste Image URL"}),e.jsx(ye,{value:k,onChange:rt=>C(rt.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Click-through Link (optional)"}),e.jsx(ye,{value:T,onChange:rt=>M(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(ns,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Quick Links"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Ge,children:[e.jsx(Js,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),W.map((rt,Fe)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(ye,{value:rt.title,onChange:dt=>_e(Fe,"title",dt.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(ye,{value:rt.url,onChange:dt=>_e(Fe,"url",dt.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Oe(Fe),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]},Fe)),W.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(ns,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(se,{children:"Polls"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Ae,children:[e.jsx(Js,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),K.map((rt,Fe)=>e.jsx(be,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ye,{value:rt.question,onChange:dt=>Xe(Fe,dt.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(vs,{value:rt.poll_type,onValueChange:dt=>Ue(Fe,dt),children:[e.jsx(gs,{className:"w-32",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"single",children:"Single"}),e.jsx(Je,{value:"multi",children:"Multi-select"})]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>nt(Fe),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[rt.options.map((dt,Dt)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:dt,onChange:pt=>Qe(Fe,Dt,pt.target.value),placeholder:`Option ${Dt+1}`}),rt.options.length>2&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Ye(Fe,Dt),children:e.jsx(Rn,{className:"h-4 w-4 text-muted-foreground"})})]},Dt)),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>Ze(Fe),children:[e.jsx(Js,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},Fe)),K.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls added yet"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:De,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(Fs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx($s,{children:e.jsxs(zs,{children:["Results: ",h==null?void 0:h.title]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Re,{children:e.jsx("p",{className:"text-2xl font-bold",children:we.total})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Re,{children:e.jsx("p",{className:"text-2xl font-bold",children:we.dismissed})})]})]}),ie.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),ie.map(rt=>e.jsxs(be,{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(Fe=>{const dt=rt.results[Fe.id]||0,Dt=rt.totalResponses>0?Math.round(dt/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:Fe.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[dt," (",Dt,"%)"]})]}),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:`${Dt}%`}})}),dt>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(rt.respondents||[]).filter(pt=>pt.optionId===Fe.id).map((pt,zt)=>e.jsx(qe,{variant:"secondary",className:"text-xs font-normal",children:pt.userName},zt))})]},Fe.id)})})]},rt.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const Jfn=()=>{const{user:s}=Ns(),{toast:t}=pi(),n=as(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=j.useState(null),[h,m]=j.useState(""),{data:p=[],isLoading:x}=mt({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:T,error:M}=await U.from("additional_services").select("*").order("publish_date",{ascending:!1});if(M)throw M;return T}}),y=vt({mutationFn:async T=>{let M=T.existingImageUrl;if(T.image){const L=T.image.name.split(".").pop(),I=`${Date.now()}-${Math.random().toString(36).substring(7)}.${L}`,{error:O}=await U.storage.from("service-images").upload(I,T.image);if(O)throw O;const{data:$}=U.storage.from("service-images").getPublicUrl(I);M=$.publicUrl}const P={name:T.item.name,description:T.item.description||null,preview_image_url:M,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:L}=await U.from("additional_services").update(P).eq("id",T.itemId);if(L)throw L}else{const{error:L}=await U.from("additional_services").insert(P);if(L)throw L}},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:i?"Service updated":"Service created"}),a(!1),b()},onError:T=>{t({title:"Error saving service",description:T.message,variant:"destructive"})}}),g=vt({mutationFn:async T=>{const{error:M}=await U.from("additional_services").delete().eq("id",T);if(M)throw M},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"})}}),b=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),l(null)},v=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 P;const M=(P=T.target.files)==null?void 0:P[0];M&&(u(M),m(URL.createObjectURL(M)))},C=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(Vs,{title:"Manage Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(T=>T.is_published).length})})]})]}),e.jsxs(Fs,{open:r,onOpenChange:T=>{a(T),T||b()},children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:C,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name *"}),e.jsx(ye,{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(se,{children:"Description"}),e.jsx(Kj,{content:o.description,onChange:T=>c({...o,description:T}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(ye,{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(se,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{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(Mn,{id:"is_published",checked:o.is_published,onCheckedChange:T=>c({...o,is_published:T})}),e.jsx(se,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(dr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(ac,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(ye,{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(be,{children:e.jsx(Re,{className:"p-0",children:x?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):p.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No services yet. Click "Add Service" to create your first one.'}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{className:"w-16",children:"Preview"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Signup Link"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:p.map(T=>e.jsxs(un,{children:[e.jsx(xt,{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(ac,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(xt,{className:"font-medium",children:T.name}),e.jsx(xt,{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(xt,{children:new Date(T.publish_date).toLocaleDateString()}),e.jsx(xt,{children:e.jsx(qe,{variant:T.is_published?"default":"secondary",children:T.is_published?"Published":"Draft"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>v(T),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{await Bi("Are you sure you want to delete this service?")&&g.mutate(T.id)},children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})})]},T.id))})]})})})]})})};function exn(){const{toast:s}=pi(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});j.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:g,error:b}=await U.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(b)throw b;n(g.coupons||[])}catch(g){console.error("Error fetching coupons:",g),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 g={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?g.percent_off=parseFloat(d.percentOff):(g.amount_off=Math.round(parseFloat(d.amountOff)*100),g.currency="usd"),d.duration==="repeating"&&(g.duration_in_months=parseInt(d.durationInMonths));const{data:b,error:v}=await U.functions.invoke("stripe-manage-coupons",{body:g});if(v)throw v;s({title:"Success",description:"Coupon created successfully"}),c(!1),u({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),h()}catch(g){console.error("Error creating coupon:",g),s({title:"Error",description:g.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},p=async g=>{if(await Bi("Are you sure you want to delete this coupon?"))try{const{error:b}=await U.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:g}});if(b)throw b;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(b){console.error("Error deleting coupon:",b),s({title:"Error",description:b.message||"Failed to delete coupon",variant:"destructive"})}},x=g=>g.percent_off?`${g.percent_off}% off`:g.amount_off?`$${(g.amount_off/100).toFixed(2)} off`:"N/A",y=g=>{switch(g.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${g.duration_in_months} months`;default:return g.duration}};return e.jsx(Vs,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(Fs,{open:o,onOpenChange:c,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Create New Coupon"}),e.jsx(kr,{children:"Create a discount coupon that can be applied to subscriptions"})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Promotion Code (what users will type)"}),e.jsx(ye,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:g=>u({...d,promotionCode:g.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}),className:"font-mono uppercase"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Letters and numbers only. This is the code users enter at checkout."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Coupon Name (internal label)"}),e.jsx(ye,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:g=>u({...d,name:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Discount Type"}),e.jsxs(vs,{value:d.discountType,onValueChange:g=>{const b=g==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:g,duration:b})},children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(QT,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(Je,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(Od,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:g=>u({...d,percentOff:g.target.value})}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Amount Off (USD)"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(ye,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:g=>u({...d,amountOff:g.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Duration"}),e.jsxs(vs,{value:d.duration,onValueChange:g=>u({...d,duration:g}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"once",children:"Once (first payment only)"}),e.jsx(Je,{value:"repeating",children:"Multiple months"}),e.jsxs(Je,{value:"forever",disabled:d.discountType==="amount",children:["Forever ",d.discountType==="amount"&&"(% discounts only)"]})]})]}),d.discountType==="amount"&&e.jsx("p",{className:"text-xs text-muted-foreground",children:'Note: "Forever" duration is only available for percentage-based discounts.'})]}),d.duration==="repeating"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Number of Months"}),e.jsx(ye,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:g=>u({...d,durationInMonths:g.target.value})})]}),e.jsx(B,{onClick:m,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Active Coupons"}),e.jsx(fr,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Re,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Wt,{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(Tt,{children:"Promo Code"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Discount"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Redemptions"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:t.map(g=>{var b;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-mono font-medium",children:((b=g.promotion_codes)==null?void 0:b.length)>0?g.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(xt,{children:g.name||"-"}),e.jsx(xt,{children:x(g)}),e.jsx(xt,{children:y(g)}),e.jsx(xt,{children:g.times_redeemed}),e.jsx(xt,{children:e.jsx(qe,{variant:g.valid?"default":"secondary",children:g.valid?"Active":"Inactive"})}),e.jsx(xt,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>p(g.id),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})})]},g.id)})})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"How to Use Coupons"})}),e.jsxs(Re,{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 HPe={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 txn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),[l,o]=j.useState(null),{data:c,isLoading:d,refetch:u}=mt({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:b,error:v}=await U.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(v)throw v;return b}}),{data:h}=mt({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:b,error:v}=await U.from("brokerages").select("*").order("name");if(v)throw v;return await Promise.all((b||[]).map(async C=>{const{data:T}=await U.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",C.id),{data:M}=await U.from("user_roles").select("user_id").eq("role","brokerage_manager"),P=(M==null?void 0:M.map(O=>O.user_id))||[],L=(T==null?void 0:T.filter(O=>P.includes(O.id)))||[],I=(T==null?void 0:T.length)||0;return{...C,managers:L,agentCount:I}}))}}),{data:m}=mt({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:b,error:v}=await U.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(v)throw v;return b}}),p=b=>{if(b.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(b.brokerage_id&&!b.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(b.is_trial&&b.trial_expires_at)return new Date(b.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(b.subscription_status==="active"||b.subscription_status==="trialing"){const v=HPe[b.subscription_product_id];return{status:(v==null?void 0:v.name)||"Active",badge:b.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return b.subscription_status==="canceled"||b.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},x=c==null?void 0:c.filter(b=>{var k,C;if(!(((k=b.name)==null?void 0:k.toLowerCase().includes(s.toLowerCase()))||((C=b.email)==null?void 0:C.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const T=b.subscription_source||"platform";if(a==="platform"&&T==="local_move_website"||a==="local_move_website"&&T!=="local_move_website")return!1}switch(p(b),n){case"active":return b.subscription_status==="active";case"trialing":return b.subscription_status==="trialing"||b.is_trial&&new Date(b.trial_expires_at)>new Date;case"grandfathered":return b.is_grandfathered;case"brokerage":return b.brokerage_id&&!b.subscription_product_id&&!b.is_grandfathered;case"expired":return b.subscription_status==="canceled"||b.subscription_status==="past_due"||b.is_trial&&new Date(b.trial_expires_at)<=new Date;case"none":return!b.subscription_status||b.subscription_status==="none";default:return!0}}),y={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(b=>b.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(b=>b.subscription_status==="trialing"||b.is_trial&&new Date(b.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(b=>b.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(b=>b.brokerage_id&&!b.subscription_product_id&&!b.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(b=>b.subscription_status==="active"&&b.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(b=>b.subscription_status==="active"&&(b.subscription_product_id==="prod_Tc08MupgoVySDG"||b.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},g=b=>{window.open(`https://dashboard.stripe.com/customers/${b}`,"_blank")};return e.jsx(Vs,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(B,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(Ki,{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(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Users"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:y.totalUsers})]})}),e.jsx(be,{className:"border-green-500/50",children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ty,{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(be,{className:"border-blue-500/50",children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vr,{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(be,{className:"border-purple-500/50",children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sy,{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(be,{className:"border-orange-500/50",children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ni,{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(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bN,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Individual"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:y.individualSubscribers})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ni,{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(fa,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"users",children:"All Users"}),e.jsx(ss,{value:"brokerages",children:"Brokerages"}),e.jsxs(ss,{value:"websites",className:"gap-2",children:[e.jsx(Ql,{className:"h-4 w-4"}),"Website Subscriptions",m&&m.length>0&&e.jsx(qe,{variant:"secondary",className:"ml-1",children:m.length})]})]}),e.jsxs(ns,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:s,onChange:b=>t(b.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:a,onValueChange:b=>i(b),children:[e.jsx(gs,{className:"w-[200px]",children:e.jsx(bs,{placeholder:"Source"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Sources"}),e.jsx(Je,{value:"platform",children:"Platform"}),e.jsx(Je,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(vs,{value:n,onValueChange:b=>r(b),children:[e.jsx(gs,{className:"w-[200px]",children:e.jsx(bs,{placeholder:"Filter by status"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Statuses"}),e.jsx(Je,{value:"active",children:"Active Subscriptions"}),e.jsx(Je,{value:"trialing",children:"Trials"}),e.jsx(Je,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Je,{value:"brokerage",children:"Brokerage Members"}),e.jsx(Je,{value:"expired",children:"Expired/Canceled"}),e.jsx(Je,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Plan"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"End Date"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:d?e.jsx(un,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(x==null?void 0:x.length)===0?e.jsx(un,{children:e.jsx(xt,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):x==null?void 0:x.map(b=>{var C,T;const v=p(b),k=HPe[b.subscription_product_id];return e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.email})]})}),e.jsx(xt,{children:e.jsx(qe,{variant:v.variant,children:v.badge})}),e.jsx(xt,{children:e.jsx("span",{className:"text-sm",children:b.is_grandfathered?"Legacy Access":b.brokerage_id&&!b.subscription_product_id?"Brokerage Subscription":(k==null?void 0:k.name)||v.status})}),e.jsx(xt,{children:(C=b.brokerages)!=null&&C.name?e.jsx("span",{className:"text-sm",children:b.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(xt,{children:b.subscription_end_date?e.jsx("span",{className:"text-sm",children:Bs(new Date(b.subscription_end_date),"MMM d, yyyy")}):b.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Bs(new Date(b.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[b.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>g(b.stripe_customer_id),children:e.jsx(Tr,{className:"h-4 w-4"})}),e.jsxs(Fs,{children:[e.jsx(Io,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",onClick:()=>o(b),children:"Details"})}),e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Subscription Details"}),e.jsxs(kr,{children:[b.name," (",b.email,")"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Status"}),e.jsx(qe,{variant:v.variant,className:"mt-1",children:v.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:b.is_grandfathered?"Grandfathered (Legacy)":b.brokerage_id&&!b.subscription_product_id?"Brokerage Subscription":(k==null?void 0:k.name)||"None"})]}),b.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((T=b.brokerages)==null?void 0:T.name)||"Unknown"})]}),b.subscription_end_date&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Current Period End"}),e.jsx("p",{className:"font-medium",children:Bs(new Date(b.subscription_end_date),"MMMM d, yyyy")})]}),b.trial_expires_at&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trial Expires"}),e.jsx("p",{className:"font-medium",children:Bs(new Date(b.trial_expires_at),"MMMM d, yyyy")})]}),b.stripe_customer_id&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Stripe Customer ID"}),e.jsx("p",{className:"font-mono text-sm",children:b.stripe_customer_id})]})]}),b.stripe_customer_id&&e.jsxs(B,{className:"w-full",onClick:()=>g(b.stripe_customer_id),children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},b.id)})})]})})})]}),e.jsx(ns,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(b=>{var k,C;const v=(k=b.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(be,{children:[e.jsx(Ft,{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(Ni,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:b.name}),e.jsxs(fr,{children:[b.agentCount," agents"]})]})]}),e.jsx(qe,{variant:v?"default":"outline",children:v?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Re,{children:((C=b.managers)==null?void 0:C.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),b.managers.map(T=>{const M=HPe[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:M?e.jsxs("div",{children:[e.jsx(qe,{variant:"default",children:M.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:M.price})]}):e.jsx(qe,{variant:"outline",children:"No Subscription"})})]},T.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},b.id)})})}),e.jsx(ns,{value:"websites",className:"space-y-4",children:e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Ql,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(fr,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Setup Fee"}),e.jsx(Tt,{children:"Monthly"}),e.jsx(Tt,{children:"Next Renewal"}),e.jsx(Tt,{children:"Started"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:m?m.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):m.map(b=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.agent_email})]})}),e.jsx(xt,{children:e.jsx(qe,{variant:b.status==="active"?"default":b.status==="canceled"?"destructive":"outline",children:b.status})}),e.jsx(xt,{children:b.setup_fee_paid?e.jsxs(qe,{variant:"secondary",children:["Paid · $",(b.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(qe,{variant:"outline",children:"Unpaid"})}),e.jsxs(xt,{className:"font-medium",children:["$",(b.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(xt,{children:b.current_period_end?e.jsx("span",{className:"text-sm",children:Bs(new Date(b.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(xt,{children:e.jsx("span",{className:"text-sm",children:Bs(new Date(b.created_at),"MMM d, yyyy")})}),e.jsx(xt,{className:"text-right",children:b.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>g(b.stripe_customer_id),children:e.jsx(Tr,{className:"h-4 w-4"})})})]},b.id)):e.jsx(un,{children:e.jsx(xt,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function sxn(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(""),[l,o]=j.useState("all"),[c,d]=j.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});j.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:x,error:y}=await U.from("referrals").select(` *, referrer_brokerage:brokerages!referrer_brokerage_id(name), referred_brokerage:brokerages!referred_brokerage_id(name), referred_user:profiles!referred_user_id(name, email) `).order("created_at",{ascending:!1});if(y)throw y;t(x||[]);const g=(x==null?void 0:x.filter(k=>k.status==="qualified").length)||0,b=(x==null?void 0:x.filter(k=>k.status==="pending").length)||0,v=(x==null?void 0:x.filter(k=>k.status==="cancelled").length)||0;d({total:(x==null?void 0:x.length)||0,qualified:g,pending:b,cancelled:v,totalDiscounts:g*25})}catch(x){console.error("Error fetching referrals:",x),re.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{re.loading("Processing qualifications...");const{error:x}=await U.functions.invoke("process-referral-qualifications");if(x)throw x;re.dismiss(),re.success("Qualifications processed successfully"),u()}catch(x){re.dismiss(),console.error("Error processing qualifications:",x),re.error("Failed to process qualifications")}},m=s.filter(x=>{var b,v,k,C,T,M;const y=((v=(b=x.referrer_brokerage)==null?void 0:b.name)==null?void 0:v.toLowerCase().includes(a.toLowerCase()))||((C=(k=x.referred_brokerage)==null?void 0:k.name)==null?void 0:C.toLowerCase().includes(a.toLowerCase()))||((M=(T=x.referred_user)==null?void 0:T.email)==null?void 0:M.toLowerCase().includes(a.toLowerCase())),g=l==="all"||x.status===l;return y&&g}),p=x=>{switch(x){case"qualified":return e.jsxs(qe,{className:"bg-green-100 text-green-800",children:[e.jsx(To,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(qe,{variant:"secondary",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(qe,{variant:"destructive",children:[e.jsx(Rd,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(qe,{children:x})}};return e.jsx(Vs,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(B,{onClick:h,variant:"outline",children:[e.jsx(Ki,{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(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Referrals"})]})]})})}),e.jsx(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(To,{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(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vr,{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(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rd,{className:"h-5 w-5 text-red-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.cancelled}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cancelled"})]})]})})}),e.jsx(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Od,{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(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"All Referrals"}),e.jsx(fr,{children:"View and manage all referral relationships"})]}),e.jsxs(Re,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by brokerage or email...",value:a,onChange:x=>i(x.target.value),className:"pl-10"})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"Filter by status"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Statuses"}),e.jsx(Je,{value:"pending",children:"Pending"}),e.jsx(Je,{value:"qualified",children:"Qualified"}),e.jsx(Je,{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(Tt,{children:"Referrer"}),e.jsx(Tt,{children:"Referred"}),e.jsx(Tt,{children:"Signup Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Qualified Date"}),e.jsx(Tt,{children:"Discount"})]})}),e.jsx(za,{children:m.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):m.map(x=>{var y,g,b,v;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:((y=x.referrer_brokerage)==null?void 0:y.name)||"Unknown"}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{children:((g=x.referred_brokerage)==null?void 0:g.name)||((b=x.referred_user)==null?void 0:b.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(v=x.referred_user)==null?void 0:v.email})]})}),e.jsx(xt,{children:Bs(new Date(x.signup_date),"MMM d, yyyy")}),e.jsx(xt,{children:p(x.status)}),e.jsx(xt,{children:x.qualified_date?Bs(new Date(x.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(xt,{children:x.discount_applied?e.jsx(qe,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},x.id)})})]})]})]})]})})}const GPe=[{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"}],nxn=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function rxn(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(null),[c,d]=j.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});j.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:v,error:k}=await U.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(k)throw k;t(v||[])}catch(v){console.error("Error fetching checklist items:",v),re.error("Failed to load checklist items")}finally{r(!1)}},h=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},m=v=>{o(v),d({title:v.title,description:v.description||"",action_type:v.action_type,target_role:v.target_role,is_active:v.is_active}),i(!0)},p=async()=>{if(!c.title.trim()){re.error("Title is required");return}try{if(l){const{error:v}=await U.from("onboarding_checklist_items").update({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active}).eq("id",l.id);if(v)throw v;re.success("Checklist item updated")}else{const v=s.filter(C=>C.target_role===c.target_role).reduce((C,T)=>Math.max(C,T.sort_order),-1),{error:k}=await U.from("onboarding_checklist_items").insert({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active,sort_order:v+1});if(k)throw k;re.success("Checklist item created")}i(!1),u()}catch(v){console.error("Error saving checklist item:",v),re.error("Failed to save checklist item")}},x=async v=>{if(await Bi("Are you sure you want to delete this checklist item?"))try{const{error:k}=await U.from("onboarding_checklist_items").delete().eq("id",v);if(k)throw k;re.success("Checklist item deleted"),u()}catch(k){console.error("Error deleting checklist item:",k),re.error("Failed to delete checklist item")}},y=async v=>{try{const{error:k}=await U.from("onboarding_checklist_items").update({is_active:!v.is_active}).eq("id",v.id);if(k)throw k;re.success(v.is_active?"Item deactivated":"Item activated"),u()}catch(k){console.error("Error toggling item:",k),re.error("Failed to update item")}},g=s.filter(v=>v.target_role==="brokerage_manager"),b=s.filter(v=>v.target_role==="agent");return e.jsxs(Vs,{title:"Onboarding Checklist",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Onboarding Checklist"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage checklist items shown to new users on their dashboard"})]}),e.jsxs(B,{onClick:h,className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Re,{children:g.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(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:g.map((v,k)=>{var C;return e.jsxs(un,{children:[e.jsx(xt,{className:"text-muted-foreground",children:k+1}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v.title}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:v.description})]})}),e.jsx(xt,{children:e.jsx(qe,{variant:"outline",children:((C=GPe.find(T=>T.value===v.action_type))==null?void 0:C.label)||v.action_type})}),e.jsx(xt,{children:e.jsx(Mn,{checked:v.is_active,onCheckedChange:()=>y(v)})}),e.jsx(xt,{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(v),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>x(v.id),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})})]},v.id)})})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Re,{children:b.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(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:b.map((v,k)=>{var C;return e.jsxs(un,{children:[e.jsx(xt,{className:"text-muted-foreground",children:k+1}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v.title}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:v.description})]})}),e.jsx(xt,{children:e.jsx(qe,{variant:"outline",children:((C=GPe.find(T=>T.value===v.action_type))==null?void 0:C.label)||v.action_type})}),e.jsx(xt,{children:e.jsx(Mn,{checked:v.is_active,onCheckedChange:()=>y(v)})}),e.jsx(xt,{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(v),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>x(v.id),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})})]},v.id)})})]})})]})]}),e.jsx(Fs,{open:a,onOpenChange:i,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:l?"Edit Checklist Item":"Add Checklist Item"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:c.title,onChange:v=>d({...c,title:v.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ds,{id:"description",value:c.description,onChange:v=>d({...c,description:v.target.value}),placeholder:"Optional description for the checklist item",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Target Role"}),e.jsxs(vs,{value:c.target_role,onValueChange:v=>d({...c,target_role:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:nxn.map(v=>e.jsx(Je,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Action Type"}),e.jsxs(vs,{value:c.action_type,onValueChange:v=>d({...c,action_type:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:GPe.map(v=>e.jsx(Je,{value:v.value,children:v.label},v.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{id:"is_active",checked:c.is_active,onCheckedChange:v=>d({...c,is_active:v})}),e.jsx(se,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{onClick:p,children:l?"Save Changes":"Create Item"})]})]})})]})}function axn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("name"),[l,o]=j.useState("asc"),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(""),[x,y]=j.useState(""),{data:g}=mt({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:O,error:$}=await U.from("brokerages").select("id, name").order("name");if($)throw $;return O}}),b=async O=>{let q=[],W=0,G=!0;for(;G;){const{data:K,error:ee}=await O(W,W+1e3-1);if(ee)throw ee;K&&K.length>0?(q=[...q,...K],W+=1e3,G=K.length===1e3):G=!1}return q},{data:v,isLoading:k}=mt({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const O=await b((Ee,Le)=>U.from("profiles").select("id, name, email, brokerage_id, created_at").range(Ee,Le)),{data:$}=await U.from("brokerages").select("id, name"),q=new Map(($==null?void 0:$.map(Ee=>[Ee.id,Ee.name]))||[]),[{data:W},{data:G},{data:K},{data:ee},{data:J},{data:le},{data:ue}]=await Promise.all([U.rpc("get_admin_contact_counts"),U.rpc("get_admin_video_counts"),U.rpc("get_admin_popby_counts"),U.rpc("get_admin_listing_counts"),U.rpc("get_admin_deal_counts"),U.rpc("get_admin_portal_counts"),U.rpc("get_admin_sendable_card_counts")]),oe=new Map;W==null||W.forEach(Ee=>oe.set(Ee.owner_user_id,Ee.contact_count));const ie=new Map;G==null||G.forEach(Ee=>ie.set(Ee.owner_user_id,Ee.video_count));const de=new Map;K==null||K.forEach(Ee=>de.set(Ee.owner_user_id,Ee.popby_count));const we=new Map;ee==null||ee.forEach(Ee=>we.set(Ee.agent_id,Ee.listing_count));const je=new Map;J==null||J.forEach(Ee=>je.set(Ee.owner_user_id,Ee.deal_count));const xe=new Map;le==null||le.forEach(Ee=>xe.set(Ee.owner_user_id,{total:Ee.portal_count,active:Ee.active_portal_count}));const fe=new Map;return ue==null||ue.forEach(Ee=>fe.set(Ee.owner_user_id,{total:Ee.card_count,sent:Ee.sent_card_count,views:Ee.total_card_views})),O.map(Ee=>{const Le=xe.get(Ee.id),De=fe.get(Ee.id);return{id:Ee.id,name:Ee.name||"Unknown",email:Ee.email||"",brokerage_id:Ee.brokerage_id,brokerage_name:Ee.brokerage_id&&q.get(Ee.brokerage_id)||null,contact_count:oe.get(Ee.id)||0,video_count:ie.get(Ee.id)||0,popby_count:de.get(Ee.id)||0,listing_count:we.get(Ee.id)||0,deal_count:je.get(Ee.id)||0,portal_count:(Le==null?void 0:Le.total)||0,active_portal_count:(Le==null?void 0:Le.active)||0,card_count:(De==null?void 0:De.total)||0,sent_card_count:(De==null?void 0:De.sent)||0,total_card_views:(De==null?void 0:De.views)||0,created_at:Ee.created_at}})}}),C=j.useMemo(()=>{if(!v)return[];let O=v.filter($=>{const q=s.toLowerCase(),W=!s||$.name.toLowerCase().includes(q)||$.email.toLowerCase().includes(q),G=n==="all"||n==="none"&&!$.brokerage_id||$.brokerage_id===n,K=parseInt(c)||0,ee=parseInt(u)||0,J=parseInt(m)||0,le=parseInt(x)||0,ue=$.contact_count>=K&&$.video_count>=ee&&$.popby_count>=J&&$.listing_count>=le;return W&&G&&ue});return O.sort(($,q)=>{let W=0;return a==="name"?W=$.name.localeCompare(q.name):W=$[a]-q[a],l==="asc"?W:-W}),O},[v,s,n,a,l,c,u,m,x]),T=O=>{a===O?o(l==="asc"?"desc":"asc"):(i(O),o("desc"))},M=()=>{const O=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],$=C.map(ee=>[ee.name,ee.email,ee.brokerage_name||"None",ee.contact_count,ee.video_count,ee.popby_count,ee.listing_count,ee.deal_count,`${ee.portal_count} (${ee.active_portal_count})`,ee.card_count,ee.sent_card_count,ee.total_card_views]),q=[O.join(","),...$.map(ee=>ee.map(J=>`"${J}"`).join(","))].join(` `),W=new Blob([q],{type:"text/csv"}),G=URL.createObjectURL(W),K=document.createElement("a");K.href=G,K.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,K.click(),URL.revokeObjectURL(G)},P=j.useMemo(()=>C.length?C.reduce((O,$)=>({contacts:O.contacts+$.contact_count,videos:O.videos+$.video_count,popbys:O.popbys+$.popby_count,listings:O.listings+$.listing_count,deals:O.deals+$.deal_count,portals:O.portals+$.portal_count,activePortals:O.activePortals+$.active_portal_count,cards:O.cards+$.card_count,sentCards:O.sentCards+$.sent_card_count,cardViews:O.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},[C]),L=j.useMemo(()=>C.length?{portals:C.filter(O=>O.portal_count>0).length,cards:C.filter(O=>O.card_count>0).length}:{portals:0,cards:0},[C]),I=({field:O,children:$})=>e.jsx(Tt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>T(O),children:e.jsxs("div",{className:"flex items-center gap-1",children:[$,e.jsx(_x,{className:`h-3 w-3 ${a===O?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(RN,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(be,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(wj,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Re,{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:L.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:P.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Portals"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:P.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(be,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Re,{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:L.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:P.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Created"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:P.sentCards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Sent"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:P.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(fr,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:M,children:[e.jsx(ii,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-6",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:s,onChange:O=>t(O.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsxs(gs,{children:[e.jsx(Ni,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(bs,{placeholder:"Brokerage"})]}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Brokerages"}),e.jsx(Je,{value:"none",children:"No Brokerage"}),g==null?void 0:g.map(O=>e.jsx(Je,{value:O.id,children:O.name},O.id))]})]})}),e.jsx("div",{children:e.jsx(ye,{type:"number",placeholder:"Min contacts",value:c,onChange:O=>d(O.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(ye,{type:"number",placeholder:"Min videos",value:u,onChange:O=>h(O.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(ye,{type:"number",placeholder:"Min popbys",value:m,onChange:O=>p(O.target.value),min:"0"})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-8 text-sm",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:C.length}),e.jsx("div",{className:"text-muted-foreground",children:"Users"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:P.contacts.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:P.videos.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Videos"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:P.popbys.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Popbys"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:P.listings.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Listings"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:P.deals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{className:"bg-blue-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:P.portals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Portals"})]}),e.jsxs("div",{className:"bg-violet-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:P.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),k?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Wt,{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(I,{field:"name",children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(I,{field:"contact_count",children:"Contacts"}),e.jsx(I,{field:"video_count",children:"Videos"}),e.jsx(I,{field:"popby_count",children:"Popbys"}),e.jsx(I,{field:"listing_count",children:"Listings"}),e.jsx(I,{field:"deal_count",children:"Deals"}),e.jsx(I,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wj,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(I,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(za,{children:C.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):C.map(O=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:O.name}),e.jsx(xt,{className:"text-muted-foreground",children:O.email}),e.jsx(xt,{children:O.brokerage_name?e.jsx(qe,{variant:"secondary",children:O.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(xt,{children:e.jsx(qe,{variant:O.contact_count>0?"default":"outline",children:O.contact_count})}),e.jsx(xt,{children:e.jsx(qe,{variant:O.video_count>0?"default":"outline",children:O.video_count})}),e.jsx(xt,{children:e.jsx(qe,{variant:O.popby_count>0?"default":"outline",children:O.popby_count})}),e.jsx(xt,{children:e.jsx(qe,{variant:O.listing_count>0?"default":"outline",children:O.listing_count})}),e.jsx(xt,{children:e.jsx(qe,{variant:O.deal_count>0?"default":"outline",children:O.deal_count})}),e.jsx(xt,{children:O.portal_count>0?e.jsxs(Cu,{children:[e.jsx(Au,{children:e.jsxs(qe,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[O.portal_count,O.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",O.active_portal_count," active)"]})]})}),e.jsxs(ou,{children:[e.jsxs("p",{children:[O.portal_count," total portals"]}),e.jsxs("p",{children:[O.active_portal_count," currently active"]})]})]}):e.jsx(qe,{variant:"outline",children:"0"})}),e.jsx(xt,{children:O.card_count>0?e.jsxs(Cu,{children:[e.jsx(Au,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(qe,{variant:"default",className:"bg-violet-600 hover:bg-violet-700",children:O.card_count}),O.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx(Dr,{className:"h-3 w-3"}),O.sent_card_count]}),O.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(ma,{className:"h-3 w-3"}),O.total_card_views]})]})}),e.jsxs(ou,{children:[e.jsxs("p",{children:[O.card_count," cards created"]}),e.jsxs("p",{children:[O.sent_card_count," sent"]}),e.jsxs("p",{children:[O.total_card_views," total views"]})]})]}):e.jsx(qe,{variant:"outline",children:"0"})})]},O.id))})]})})]})]})]})})}function ixn(){pi(),as();const[s,t]=j.useState("user-analytics"),{data:n}=mt({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:p,error:x}=await U.from("feature_flags").select("*").order("key");if(x)throw x;return p}}),{data:r,isLoading:a}=mt({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:p,error:x}=await U.from("relationship_types").select("*").order("sort_order");if(x)throw x;return p}}),{data:i,isLoading:l}=mt({queryKey:["admin-action-types"],queryFn:async()=>{const{data:p,error:x}=await U.from("action_types").select("*").order("sort_order");if(x)throw x;return p}}),{data:o,isLoading:c}=mt({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:p,error:x}=await U.from("action_scripts").select("*, action_type:action_types(*)");if(x)throw x;return p}}),{data:d,isLoading:u}=mt({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:p,error:x}=await U.from("touchpoint_plans").select("*").order("name");if(x)throw x;return p}}),{data:h,isLoading:m}=mt({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:p,error:x}=await U.from("popby_items").select("*").is("owner_user_id",null).order("name");if(x)throw x;return p}});return e.jsx(Vs,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(fa,{value:s,onValueChange:t,children:[e.jsxs(xa,{className:"grid w-full grid-cols-9",children:[e.jsxs(ss,{value:"user-analytics",className:"gap-2",children:[e.jsx(ol,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(ss,{value:"relationship-types",className:"gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(ss,{value:"action-types",className:"gap-2",children:[e.jsx(pa,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(ss,{value:"scripts",className:"gap-2",children:[e.jsx($r,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(ss,{value:"video-scripts",className:"gap-2",children:[e.jsx(wh,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(ss,{value:"plans",className:"gap-2",children:[e.jsx(ra,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(ss,{value:"popbys",className:"gap-2",children:[e.jsx(zo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(ss,{value:"settings",className:"gap-2",children:[e.jsx(ic,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(ss,{value:"feature-flags",className:"gap-2",children:[e.jsx(y3,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(ns,{value:"user-analytics",className:"mt-6",children:e.jsx(axn,{})}),e.jsx(ns,{value:"relationship-types",className:"mt-6",children:e.jsx(oxn,{types:r||[],isLoading:a})}),e.jsx(ns,{value:"action-types",className:"mt-6",children:e.jsx(lxn,{types:i||[],isLoading:l})}),e.jsx(ns,{value:"scripts",className:"mt-6",children:e.jsx(cxn,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(ns,{value:"video-scripts",className:"mt-6",children:e.jsx(mxn,{})}),e.jsx(ns,{value:"plans",className:"mt-6",children:e.jsx(dxn,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(ns,{value:"popbys",className:"mt-6",children:e.jsx(hxn,{items:h||[],isLoading:m})}),e.jsx(ns,{value:"settings",className:"mt-6",children:e.jsx(pxn,{})}),e.jsx(ns,{value:"feature-flags",className:"mt-6",children:e.jsx(uxn,{flags:n||[]})})]})]})})}function oxn({types:s,isLoading:t}){const{toast:n}=pi(),r=as(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=vt({mutationFn:async u=>{if(u.id){const{error:h}=await U.from("relationship_types").update({name:u.name,description:u.description,icon:u.icon}).eq("id",u.id);if(h)throw h}else{const{error:h}=await U.from("relationship_types").insert([{name:u.name,description:u.description,icon:u.icon,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-relationship-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await U.from("relationship_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Relationship Types"}),e.jsx(fr,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Re,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{className:"w-12"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:s.map(u=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsx(Fp,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(xt,{className:"font-medium",children:u.name}),e.jsx(xt,{className:"text-muted-foreground",children:u.description}),e.jsx(xt,{children:e.jsx(Mn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(xt,{children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(Za,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Fs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsxs(zs,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ds,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"icon",children:"Icon"}),e.jsx(ye,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(Nr,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function lxn({types:s,isLoading:t}){const{toast:n}=pi(),r=as(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=vt({mutationFn:async u=>{if(u.id){const{error:h}=await U.from("action_types").update({name:u.name,description:u.description,icon:u.icon,color:u.color}).eq("id",u.id);if(h)throw h}else{const{error:h}=await U.from("action_types").insert([{name:u.name,description:u.description,icon:u.icon,color:u.color,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-action-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await U.from("action_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Action Types"}),e.jsx(fr,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Re,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Color"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:s.map(u=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:u.name}),e.jsx(xt,{className:"text-muted-foreground",children:u.description}),e.jsx(xt,{children:u.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:u.color}})}),e.jsx(xt,{children:e.jsx(Mn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(xt,{children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(Za,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(Fs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsxs(zs,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon"),color:h.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ds,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"icon",children:"Icon"}),e.jsx(ye,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"color",children:"Color"}),e.jsx(ye,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(Nr,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function cxn({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=pi(),a=as(),[i,l]=j.useState(null),[o,c]=j.useState(!1),d=vt({mutationFn:async h=>{if(h.id){const{error:m}=await U.from("action_scripts").update({title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:h.active}).eq("id",h.id);if(m)throw m}else{const{error:m}=await U.from("action_scripts").insert([{title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:!0}]);if(m)throw m}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),c(!1),l(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),u=vt({mutationFn:async h=>{const{error:m}=await U.from("action_scripts").delete().eq("id",h);if(m)throw m},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),r({title:"Deleted successfully"})}});return e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Script Library"}),e.jsx(fr,{children:"Create and manage scripts for each action type"})]}),e.jsxs(B,{onClick:()=>{l(null),c(!0)},children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Re,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Tone"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:s.map(h=>{var m;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:h.title}),e.jsx(xt,{children:e.jsx(qe,{variant:"outline",children:((m=h.action_type)==null?void 0:m.name)||"Unknown"})}),e.jsx(xt,{className:"text-muted-foreground",children:h.tone}),e.jsx(xt,{children:e.jsx(qe,{variant:h.active?"default":"secondary",children:h.active?"Active":"Inactive"})}),e.jsxs(xt,{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{l(h),c(!0)},children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(Fs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx($s,{children:e.jsxs(zs,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);d.mutate({id:i==null?void 0:i.id,title:m.get("title"),action_type_id:m.get("action_type_id"),tone:m.get("tone"),script_body:m.get("script_body"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(vs,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select action type"})}),e.jsx(ys,{children:t.map(h=>e.jsx(Je,{value:h.id,children:h.name},h.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(ye,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ds,{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(Nr,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function dxn({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=pi(),i=as(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(!1),[x,y]=j.useState(null),[g,b]=j.useState(null),{data:v}=mt({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:I,error:O}=await U.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(O)throw O;return I},enabled:!!u}),k=vt({mutationFn:async I=>{if(I.id){const{error:O}=await U.from("touchpoint_plans").update({name:I.name,description:I.description,active:I.active}).eq("id",I.id);if(O)throw O}else{const{error:O}=await U.from("touchpoint_plans").insert([{name:I.name,description:I.description,active:!0}]);if(O)throw O}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:I=>{a({title:"Error",description:I.message,variant:"destructive"})}}),C=vt({mutationFn:async I=>{if(I.id){const{error:O}=await U.from("touchpoint_plan_items").update({action_type_id:I.action_type_id,default_script_id:I.default_script_id,notes:I.notes}).eq("id",I.id);if(O)throw O}else{const{error:O}=await U.from("touchpoint_plan_items").insert([{plan_id:I.plan_id,month_number:I.month_number,action_type_id:I.action_type_id,default_script_id:I.default_script_id,notes:I.notes}]);if(O)throw O}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),T=vt({mutationFn:async I=>{const{error:O}=await U.from("touchpoint_plan_items").delete().eq("id",I);if(O)throw O},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),M=vt({mutationFn:async I=>{const{data:O,error:$}=await U.from("action_scripts").insert([{...I,active:!0}]).select().single();if($)throw $;return O},onSuccess:async I=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),x&&await C.mutateAsync({id:x.itemId,plan_id:u,month_number:x.month,action_type_id:x.actionTypeId,default_script_id:I.id}),p(!1),y(null),a({title:"Script created and assigned"})},onError:I=>{a({title:"Error",description:I.message,variant:"destructive"})}}),P=(I,O,$)=>{y({month:I,actionTypeId:O,itemId:$}),p(!0)},L=I=>n.find(O=>O.id===I);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Touchpoint Plans"}),e.jsx(fr,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(B,{onClick:()=>{o(null),d(!0)},children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Re,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(I=>e.jsxs(be,{className:`cursor-pointer transition-colors ${u===I.id?"border-primary":""}`,onClick:()=>h(I.id),children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ut,{className:"text-base",children:I.name}),e.jsx(B,{variant:"ghost",size:"icon",onClick:O=>{O.stopPropagation(),o(I),d(!0)},children:e.jsx(Za,{className:"h-4 w-4"})})]})}),e.jsxs(Re,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:I.description}),e.jsx(qe,{variant:I.active?"default":"secondary",className:"mt-2",children:I.active?"Active":"Inactive"})]})]},I.id))})})]}),u&&e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Plan Schedule"}),e.jsx(fr,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Re,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(I,O)=>O+1).map(I=>{const O=v==null?void 0:v.find(W=>W.month_number===I),$=O!=null&&O.default_script_id?L(O.default_script_id):null,q=n.filter(W=>W.action_type_id===(O==null?void 0:O.action_type_id)&&W.active);return e.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"w-20 font-medium text-sm",children:["Month ",I]}),e.jsxs(vs,{value:(O==null?void 0:O.action_type_id)||"none",onValueChange:W=>{W==="none"&&O?T.mutate(O.id):W!=="none"&&C.mutate({id:O==null?void 0:O.id,plan_id:u,month_number:I,action_type_id:W,default_script_id:null})},children:[e.jsx(gs,{className:"w-40",children:e.jsx(bs,{placeholder:"No action"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No action"}),t.filter(W=>W.active).map(W=>e.jsx(Je,{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))]})]}),O&&e.jsxs(e.Fragment,{children:[e.jsxs(vs,{value:O.default_script_id||"none",onValueChange:W=>{b(null),C.mutate({id:O.id,default_script_id:W==="none"?null:W})},children:[e.jsx(gs,{className:"w-56",children:e.jsx(bs,{placeholder:"Select script"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No default script"}),q.map(W=>e.jsxs(Je,{value:W.id,children:[W.title," ",W.tone&&`(${W.tone})`]},W.id))]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>P(I,O.action_type_id,O.id),children:[e.jsx(Js,{className:"h-3 w-3 mr-1"}),"New Script"]}),$&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>b((g==null?void 0:g.id)===$.id?null:$),children:(g==null?void 0:g.id)===$.id?"Hide":"Preview"})]})]}),g&&(O==null?void 0:O.default_script_id)===g.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(qe,{variant:"outline",children:g.title}),g.tone&&e.jsx(qe,{variant:"secondary",children:g.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:g.script_body})]})]},I)})})})]}),e.jsx(Fs,{open:c,onOpenChange:d,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsxs(zs,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:I=>{I.preventDefault();const O=new FormData(I.currentTarget);k.mutate({id:l==null?void 0:l.id,name:O.get("name"),description:O.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ds,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(Nr,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(Fs,{open:m,onOpenChange:p,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Create New Script"}),e.jsxs(kr,{children:["Create a script for Month ",x==null?void 0:x.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:I=>{I.preventDefault();const O=new FormData(I.currentTarget);M.mutate({title:O.get("title"),action_type_id:x.actionTypeId,tone:O.get("tone"),script_body:O.get("script_body")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_title",children:"Title"}),e.jsx(ye,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_tone",children:"Tone"}),e.jsx(ye,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ds,{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(Nr,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:M.isPending,children:[M.isPending&&e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function uxn({flags:s}){const{toast:t}=pi(),n=as(),r=async(a,i)=>{const{error:l}=await U.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(n.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Feature Flags"}),e.jsx(fr,{children:"Control which features are enabled for members"})]}),e.jsx(Re,{children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Flag"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Notes"}),e.jsx(Tt,{children:"Last Updated"})]})}),e.jsx(za,{children:s.map(a=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-mono text-sm",children:a.key}),e.jsx(xt,{children:e.jsx(Mn,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(xt,{children:e.jsx(ye,{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(xt,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function hxn({items:s,isLoading:t}){const{toast:n}=pi(),r=as(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=vt({mutationFn:async h=>{if(h.id){const{error:m}=await U.from("popby_items").update({name:h.name,description:h.description}).eq("id",h.id);if(m)throw m}else{const{error:m}=await U.from("popby_items").insert([{name:h.name,description:h.description,owner_user_id:null}]);if(m)throw m}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:h=>{n({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await U.from("popby_items").update({is_active:!h.is_active}).eq("id",h.id),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]})},u=async h=>{await U.from("popby_items").delete().eq("id",h),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),n({title:"Deleted successfully"})};return e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Popby Ideas"}),e.jsx(fr,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Re,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Wt,{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(zo,{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(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:s.map(h=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:h.name}),e.jsx(xt,{className:"text-muted-foreground",children:h.description}),e.jsx(xt,{children:e.jsx(Mn,{checked:h.is_active,onCheckedChange:()=>d(h)})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(Fs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsxs(zs,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ds,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(Nr,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function mxn(){var p;const{toast:s}=pi(),t=as(),[n,r]=j.useState(null),[a,i]=j.useState(!1),{data:l,isLoading:o}=mt({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:x,error:y}=await U.from("video_script_categories").select("*").order("sort_order");if(y)throw y;return x}}),{data:c,isLoading:d}=mt({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:x,error:y}=await U.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(y)throw y;return x}}),u=vt({mutationFn:async x=>{var y,g;if(x.id){const{error:b}=await U.from("video_scripts").update({title:x.title,script_text:x.script_text,category_id:x.category_id,tags:((y=x.tags)==null?void 0:y.split(",").map(v=>v.trim()).filter(Boolean))||[]}).eq("id",x.id);if(b)throw b}else{const{error:b}=await U.from("video_scripts").insert([{title:x.title,script_text:x.script_text,category_id:x.category_id||null,tags:((g=x.tags)==null?void 0:g.split(",").map(v=>v.trim()).filter(Boolean))||[]}]);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),r(null),s({title:"Video script saved!"})},onError:x=>s({title:"Error",description:x.message,variant:"destructive"})}),h=async x=>{await U.from("video_scripts").update({is_active:!x.is_active}).eq("id",x.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},m=async x=>{await Bi("Delete this video script?")&&(await U.from("video_scripts").delete().eq("id",x),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Video Scripts"}),e.jsx(fr,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(B,{onClick:()=>{r(null),i(!0)},children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Re,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(za,{children:c==null?void 0:c.map(x=>{var y;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:x.title}),e.jsx(xt,{className:"text-muted-foreground",children:((y=x.category)==null?void 0:y.name)||"Uncategorized"}),e.jsx(xt,{children:e.jsx(Mn,{checked:x.is_active,onCheckedChange:()=>h(x)})}),e.jsxs(xt,{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{r(x),i(!0)},children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>m(x.id),children:e.jsx(Rn,{className:"h-4 w-4"})})]})]},x.id)})})]})}),e.jsx(Fs,{open:a,onOpenChange:i,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx($s,{children:e.jsxs(zs,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:x=>{x.preventDefault();const y=new FormData(x.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(se,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",name:"title",defaultValue:n==null?void 0:n.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"category_id",children:"Category"}),e.jsxs(vs,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select category"})}),e.jsx(ys,{children:l==null?void 0:l.map(x=>e.jsx(Je,{value:x.id,children:x.name},x.id))})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Ds,{id:"script_text",name:"script_text",defaultValue:n==null?void 0:n.script_text,rows:6,required:!0,placeholder:"Enter the teleprompter script..."})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(ye,{id:"tags",name:"tags",defaultValue:((p=n==null?void 0:n.tags)==null?void 0:p.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(Nr,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function pxn(){const{toast:s}=pi(),[t,n]=j.useState(""),[r,a]=j.useState(!0),[i,l]=j.useState(!1);j.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();d!=null&&d.value&&n(d.value)}catch(d){console.error("Error fetching settings:",d)}a(!1)})()},[]);const o=async()=>{l(!0);try{await U.from("settings").upsert({key:"mapbox_public_token",value:t.trim()}),s({title:"Mapbox token saved!"})}catch{s({title:"Error saving token",variant:"destructive"})}l(!1)};return r?e.jsx(be,{children:e.jsx(Re,{className:"flex justify-center py-8",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(oi,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(fr,{children:"Configure the map feature for popbys"})]}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(ye,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(qe,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const fxn=()=>{const[s,t]=j.useState(""),[n,r]=j.useState("grid"),a=Hn(),{data:i=[],isLoading:l}=mt({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await U.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var u;return c.name.toLowerCase().includes(s.toLowerCase())||((u=c.description)==null?void 0:u.toLowerCase().includes(s.toLowerCase()))});return e.jsx(Vs,{title:"Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Additional Services"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Explore our additional services and offerings"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{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(r0,{className:"h-4 w-4"})}),e.jsx(B,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(ug,{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(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsx(gn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(gn,{className:"h-5 w-3/4 mb-2"}),e.jsx(gn,{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(be,{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(yn,{className:"h-8 w-8"})})}),e.jsxs(Re,{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:zY(c.description)})]})]},c.id))})]})})},xxn=()=>{const{serviceId:s}=$i(),t=Hn(),{data:n,isLoading:r}=mt({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await U.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return r?e.jsx(Vs,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(gn,{className:"h-8 w-48"}),e.jsx(gn,{className:"h-64 w-full rounded-lg"}),e.jsx(gn,{className:"h-24 w-full"})]})}):n?e.jsx(Vs,{title:n.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(_a,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(be,{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(yn,{className:"h-16 w-16"})})})}),e.jsx(be,{children:e.jsxs(Re,{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(ra,{className:"h-4 w-4 mr-1"}),"Published ",Bs(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(Vs,{title:"Not Found",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center py-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground mb-4",children:"Service Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"The service you're looking for doesn't exist or has been removed."}),e.jsxs(B,{onClick:()=>t("/additional-services"),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},VH=[{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 gxn(){const[s,t]=j.useState(VH[0].id),n=VH.find(r=>r.id===s)||VH[0];return e.jsx(Vs,{title:"AI Toolkit",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(UT,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"AI Toolkit"}),e.jsx("p",{className:"text-muted-foreground",children:"Powerful AI tools to boost your real estate business"})]})]}),e.jsx("div",{className:"md:hidden",children:e.jsxs(vs,{value:s,onValueChange:t,children:[e.jsx(gs,{className:"w-full",children:e.jsx(bs,{placeholder:"Select a tool"})}),e.jsx(ys,{children:VH.map(r=>e.jsx(Je,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(fa,{value:s,onValueChange:t,className:"w-full",children:e.jsx(xa,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:VH.map(r=>e.jsx(ss,{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 yxn({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 Pne({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:Et("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 vxn({agentName:s,todayDone:t,todayTotal:n,focusLine:r,weekDone:a,weekGoal:i,streak:l,staleCount:o,sphereCount:c,onEditGoal:d,onStaleClick:u,onSphereClick:h}){const m=new Date().getHours(),p=m<12?"Good morning":m<17?"Good afternoon":"Good evening",x=i>0?Math.min(100,Math.round(a/i*100)):0;return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/[0.07] via-card to-card p-5 sm:p-6",children:[e.jsx("div",{className:"pointer-events-none absolute -right-16 -top-16 h-48 w-48 rounded-full bg-primary/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col-reverse items-start gap-5 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-primary",children:[p,s?`, ${s}`:""]}),e.jsx("h2",{className:"mt-1.5 text-xl font-semibold leading-snug sm:text-2xl",children:n===0?"Your day is clear — pick a few people to reconnect with.":t>=n?"Today's list is done. That's how referrals get built.":`${n-t} ${n-t===1?"touch":"touches"} left to stay on track.`}),e.jsxs("p",{className:"mt-2 flex items-start gap-1.5 text-sm text-muted-foreground",children:[e.jsx(yn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),e.jsx("span",{children:r})]})]}),e.jsx(yxn,{done:t,total:n})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Pne,{icon:e.jsx(uu,{className:"h-3.5 w-3.5"}),label:"Weekly goal",value:`${a}/${i}`,hint:`${x}% of your weekly touches`,action:e.jsx("button",{onClick:d,className:"rounded p-0.5 text-muted-foreground transition-colors hover:text-primary","aria-label":"Edit weekly goal",children:e.jsx(ic,{className:"h-3.5 w-3.5"})})}),e.jsx(Pne,{icon:e.jsx(Fd,{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(Pne,{icon:e.jsx(Vr,{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(Pne,{icon:e.jsx(Bn,{className:"h-3.5 w-3.5"}),label:"Your sphere",value:String(c),hint:"People in your database",onClick:h})]})]})}const Lmt="agent-os-onboarding-completed",Ine=[{icon:oy,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:jf,iconColor:"text-white",bgGradient:"from-pink-500 via-rose-500 to-red-500",title:"InnerCircle Home",description:"Your daily command center. See today's action items, track your momentum streak, and get a snapshot of your relationship health—all at a glance.",highlights:["Today's touchpoints and special dates","Momentum stats and streak tracking","Relationship health overview","Quick access to all features"]},{icon:Bn,iconColor:"text-white",bgGradient:"from-blue-500 via-indigo-500 to-purple-500",title:"Contacts",description:"Import and organize your sphere of influence. Tag contacts by relationship type (Top 25, Past Clients, Referral Partners, etc.) to prioritize your outreach.",highlights:["Import contacts via CSV","Tag by relationship type","Track birthdays and home anniversaries","See relationship health scores"]},{icon:Vc,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:zo,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:ol,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"]}],bxn=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(0),[a,i]=j.useState(!1);j.useEffect(()=>{if(!localStorage.getItem(Lmt)){const x=setTimeout(()=>t(!0),500);return()=>clearTimeout(x)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(Lmt,"true"),t(!1)},d=Ine[n],u=d.icon,h=n===Ine.length-1,m=p=>{p||c(),t(p)};return e.jsx(Fs,{open:s,onOpenChange:m,children:e.jsxs(Os,{className:"sm:max-w-lg overflow-hidden p-0 gap-0",children:[e.jsxs("div",{className:`relative bg-gradient-to-br ${d.bgGradient} p-8 pb-12 transition-all duration-500`,children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx("div",{className:"absolute -top-4 -right-4 w-32 h-32 bg-white/10 rounded-full blur-2xl animate-pulse"}),e.jsx("div",{className:"absolute -bottom-8 -left-8 w-40 h-40 bg-white/10 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl"})]}),e.jsxs("div",{className:`relative mx-auto flex h-20 w-20 items-center justify-center transition-all duration-300 ${a?"scale-75 opacity-0":"scale-100 opacity-100"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-white/20 rounded-2xl blur-xl"}),e.jsx("div",{className:"relative flex h-20 w-20 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm border border-white/30 shadow-2xl",children:e.jsx(u,{className:`h-10 w-10 ${d.iconColor} drop-shadow-lg`})})]}),n===0&&e.jsxs("div",{className:"absolute top-4 right-4 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm border border-white/30 text-white text-xs font-medium flex items-center gap-1.5",children:[e.jsx(yn,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs($s,{className:"text-center sm:text-center pb-2",children:[e.jsx(zs,{className:`text-2xl font-bold transition-all duration-300 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.title}),e.jsx(kr,{className:`text-base pt-2 transition-all duration-300 delay-75 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.description})]}),d.highlights&&e.jsx("div",{className:`space-y-2.5 py-4 transition-all duration-300 delay-100 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.highlights.map((p,x)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+x*50}ms`},children:[e.jsx("div",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-gradient-to-br ${d.bgGradient} shadow-sm`,children:e.jsx(da,{className:"h-3.5 w-3.5 text-white"})}),e.jsx("span",{className:"text-sm text-muted-foreground group-hover:text-foreground transition-colors",children:p})]},x))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:Ine.map((p,x)=>e.jsx("button",{onClick:()=>{x!==n&&(i(!0),setTimeout(()=>{r(x),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${x===n?"w-8 bg-gradient-to-r "+d.bgGradient:x{const{user:s}=Ns();return mt({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(n)throw n;return t},enabled:!!s})},wxn=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=jd(new Date,r);await U.from("contact_snoozes").delete().eq("contact_id",n);const{error:i}=await U.from("contact_snoozes").insert({contact_id:n,owner_user_id:t.id,snoozed_until:a.toISOString()});if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),ba({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:n=>{ba({title:"Error snoozing contact",description:n.message,variant:"destructive"})}})},jxn=()=>{const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("contact_snoozes").delete().eq("contact_id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),ba({title:"Snooze cancelled"})},onError:t=>{ba({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},Nxn=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function MAe({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=j.useState(null),l=wxn(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>Bs(jd(new Date,d),"MMM d, yyyy");return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(kr,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:Nxn.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Et("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(ra,{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 kxn={Crown:sy,FileText:$r,Users:Bn,Globe:Ql,Star:Wa,Phone:pa,MessageSquare:ro,PenTool:XT,Video:Zr,Gift:zo};function Sxn({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=Hn(),[c,d]=j.useState("name"),[u,h]=j.useState("asc"),[m,p]=j.useState(null),[x,y]=j.useState(""),g=T=>{c===T?h(M=>M==="asc"?"desc":"asc"):(d(T),h("asc"))},b=j.useMemo(()=>[...s].sort((T,M)=>{var L,I;let P=0;switch(c){case"name":{const O=`${T.contact.first_name} ${T.contact.last_name||""}`.toLowerCase(),$=`${M.contact.first_name} ${M.contact.last_name||""}`.toLowerCase();P=O.localeCompare($);break}case"relationship_type":P=(T.relationshipTypeName||"").localeCompare(M.relationshipTypeName||"");break;case"action_type":P=(((L=T.actionType)==null?void 0:L.name)||"").localeCompare(((I=M.actionType)==null?void 0:I.name)||"");break;case"last_touch":P=(T.monthNumber||0)-(M.monthNumber||0);break}return u==="asc"?P:-P}),[s,c,u]),v=T=>kxn[T||"Phone"]||pa,k=({field:T,children:M})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>g(T),children:[M,c===T?u==="asc"?e.jsx(Gm,{className:"ml-2 h-4 w-4"}):e.jsx(tx,{className:"ml-2 h-4 w-4"}):e.jsx(_x,{className:"ml-2 h-4 w-4 opacity-50"})]}),C=(T,M,P)=>{p(T),y(`${M} ${P||""}`.trim())};return s.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/50",children:[e.jsx(Tt,{className:"w-[180px]",children:e.jsx(k,{field:"name",children:"Contact"})}),e.jsx(Tt,{className:"w-[130px]",children:e.jsx(k,{field:"relationship_type",children:"Type"})}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(k,{field:"action_type",children:"Action"})}),e.jsx(Tt,{className:"w-[130px]",children:"Phone"}),e.jsx(Tt,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(za,{children:b.map((T,M)=>{var q,W,G,K,ee,J;const P=T.isSpecialDate,L=T.specialDateType,I=P?L==="birthday"?Wm:ia:v(((q=T.actionType)==null?void 0:q.icon)||null),O=T.contact.phone,$=T.contact.email;return e.jsxs(un,{className:Et("hover:bg-muted/50 transition-colors",P&&L==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",P&&L==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(xt,{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(xt,{children:T.relationshipTypeName?e.jsx(qe,{variant:"secondary",className:"text-xs",children:T.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(xt,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:P?e.jsx(qe,{className:Et("gap-1",L==="birthday"&&"bg-pink-500 hover:bg-pink-600",L==="anniversary"&&"bg-purple-500 hover:bg-purple-600"),children:L==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(Wm,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(ia,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(I,{className:"h-3 w-3"}),(W=T.actionType)==null?void 0:W.name]})})}),e.jsx(xt,{children:O?e.jsx("span",{className:"text-sm font-mono",children:T.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[O&&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(pa,{className:"h-3.5 w-3.5"})}),O&&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(ro,{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(on,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(T.contact.email,(K=T.script)==null?void 0:K.script_body,(ee=T.script)==null?void 0:ee.email_subject,(J=T.actionType)==null?void 0:J.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(on,{className:"h-3.5 w-3.5"})})),P&&e.jsxs("button",{onClick:()=>{const le=`${T.contact.first_name}${T.contact.last_name?" "+T.contact.last_name:""}`,ue=L==="birthday"?"birthday":"home_anniversary",oe=new URLSearchParams({cardType:ue,contactId:T.contact.id,name:le,...T.contact.address?{address:T.contact.address}:{},...L==="anniversary"&&T.contact.home_anniversary?{date:T.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${oe.toString()}`)},className:Et("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",L==="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 ${L==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(on,{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:()=>C(T.contact.id,T.contact.first_name,T.contact.last_name),title:"Snooze",children:e.jsx(ay,{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 le;return t(T.contact.id,T.actionType.id,(le=T.script)==null?void 0:le.id)},disabled:r,children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${T.contact.id}-${M}`)})})]})}),e.jsx(MAe,{open:!!m,onOpenChange:T=>!T&&p(null),contactId:m||"",contactName:x})]})}function Cxn({onSelect:s}){const{user:t}=Ns(),[n,r]=j.useState("root"),[a,i]=j.useState(null),{data:l=[],isLoading:o}=mt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:b,error:v}=await U.from("email_template_categories").select("*").order("sort_order");if(v)throw v;return b}}),{data:c=[],isLoading:d}=mt({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:b,error:v}=await U.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(v)throw v;return b}}),{data:u=[],isLoading:h}=mt({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:b,error:v}=await U.from("campaign_templates").select("id,name,subject,body_html,is_shared,user_id,updated_at").or(`user_id.eq.${t.id},is_shared.eq.true`).order("updated_at",{ascending:!1});if(v)throw v;return b}}),m=u.filter(b=>b.user_id===(t==null?void 0:t.id)&&!b.is_shared),p=u.filter(b=>b.is_shared),x=l.find(b=>b.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Wt,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const y=b=>{s({title:b.name,subject:b.subject,body:b.body_html})};if(n==="root")return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-1.5",children:"Your templates"}),e.jsxs("button",{onClick:()=>r("my"),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(Eo,{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(Ql,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Shared Library"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p.length," team template",p.length===1?"":"s"]})]})]}),e.jsx(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(b=>e.jsxs("button",{onClick:()=>{i(b.id),r("category")},className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:b.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:b.name}),b.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:b.description})]})]}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},b.id))})]})]});const g=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(Cc,{className:"h-3.5 w-3.5"}),"Back"]});return n==="my"?e.jsxs("div",{className:"space-y-2",children:[g,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Eo,{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(Wt,{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(yn,{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(b=>e.jsxs("button",{onClick:()=>y(b),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:b.subject||"(no subject)"})]},b.id))})})]}):n==="shared"?e.jsxs("div",{className:"space-y-2",children:[g,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Wt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No shared templates yet."}):e.jsx(lo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:p.map(b=>e.jsxs("button",{onClick:()=>y(b),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.name}),e.jsx(qe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Shared"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:b.subject||"(no subject)"})]},b.id))})})]}):e.jsxs("div",{className:"space-y-2",children:[g,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:x==null?void 0:x.icon})," ",x==null?void 0:x.name]}),d?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Wt,{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(b=>e.jsxs("button",{onClick:()=>s(b),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm",children:b.title}),b.tone&&e.jsx(qe,{variant:"secondary",className:"text-[10px] shrink-0",children:b.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:b.subject})]},b.id))})})]})}function LAe(){const{user:s}=Ns(),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 U.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),a=vt({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:u,error:h}=await U.from("contact_intake_pages").insert({user_id:s.id,slug:d.toLowerCase().replace(/[^a-z0-9-]/g,"-")}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),re.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?re.error("That slug is already taken. Try another."):re.error("Failed to create page")}}),i=vt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page");const{error:u}=await U.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",n.id);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),re.success("Page updated!")},onError:()=>re.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 U.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),c=vt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page. Create your Connect page first.");const{data:u,error:h}=await U.from("contact_intake_tokens").insert({contact_id:d,intake_page_id:n.id}).select("token").single();if(h)throw h;return`${window.location.origin}/connect/${n.slug}?t=${u.token}`}});return{intakePage:n,isLoading:r,createPage:a,updatePage:i,submissions:l,loadingSubmissions:o,generateUpdateLink:c}}function dRt({value:s,onChange:t,userId:n,placeholder:r}){const[a,i]=j.useState(!1),[l,o]=j.useState([]),[c,d]=j.useState(!1),[u,h]=j.useState(0),m=j.useRef(null),p=j.useRef(null);j.useEffect(()=>{const y=g=>{m.current&&!m.current.contains(g.target)&&i(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[]),j.useEffect(()=>{p.current&&clearTimeout(p.current);const y=s.trim();if(!n||y.length<1||y.includes("@")&&y.indexOf("@")>0&&/\S+@\S+\.\S+/.test(y)){o([]);return}return p.current=setTimeout(async()=>{d(!0);const g=`%${y}%`,b=U,{data:v,error:k}=await b.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",n).not("email","is",null).or(`first_name.ilike.${g},last_name.ilike.${g},email.ilike.${g}`).order("first_name",{ascending:!0}).limit(8);d(!1),!k&&v&&(o(v),h(0),i(v.length>0))},180),()=>{p.current&&clearTimeout(p.current)}},[s,n]);const x=y=>{y.email&&(t(y.email),i(!1))};return e.jsxs("div",{ref:m,className:"relative",children:[e.jsx(ye,{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(g=>Math.min(g+1,l.length-1))):y.key==="ArrowUp"?(y.preventDefault(),h(g=>Math.max(g-1,0))):y.key==="Enter"?(y.preventDefault(),x(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(Wt,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((y,g)=>{const b=[y.first_name,y.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(g),onClick:()=>x(y),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${g===u?"bg-accent":"bg-popover"}`,children:[e.jsx(Eo,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:b}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:y.email})]})]},y.id)})})]})}function Axn(){const{user:s}=Ns(),{data:t,isLoading:n}=mt({queryKey:["email-signature",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await U.from("profiles").select("email_signature, use_email_signature").eq("id",s.id).maybeSingle();if(i)throw i;return a}}),r=((t==null?void 0:t.email_signature)||"").trim();return{signatureHtml:r,hasSignature:r.length>0,signatureEnabledByDefault:!!(t!=null&&t.use_email_signature)&&r.length>0,isLoading:n}}function Txn(s,t){if(!t||s.includes(t))return s;const n=`
${t}
`;return/<\/body>/i.test(s)?s.replace(/<\/body>/i,`${n}`):`${s}${n}`}function Exn(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 WPe=25*1024*1024,Pmt=Math.floor(6.5*1024*1024),Mxn=750*1024,Bw=50,Lxn=["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 Rne(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function Pxn(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 Ixn(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function bk(s,t){const n=Ixn(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 cw({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=Ns(),h=as(),{isReady:m,settings:p}=Cq(),{data:x}=AAe(),[y,g]=j.useState(!1),{intakePage:b}=LAe(),v=b?`https://contacts.relevelup.com/${b.slug}`:null,k=!!r&&r.length>0,C=m,T=k?r:n?[n]:[],M=T[0],P=k?Math.ceil(T.length/Bw):1,L=k&&T.length>Bw,[I,O]=j.useState((M==null?void 0:M.email)||""),[$,q]=j.useState(a),[W,G]=j.useState(i),[K,ee]=j.useState(!1),[J,le]=j.useState(!1),[ue,oe]=j.useState([]),ie=j.useRef(new Map),[de,we]=j.useState(a),[je,xe]=j.useState(i),[fe,Se]=j.useState("composing"),[Ee,Le]=j.useState(0),[De,Be]=j.useState(0),[Ne,Ge]=j.useState(0),[_e,Oe]=j.useState(0),Ae=j.useRef(!1),Xe=j.useRef(0),[Ue,Ze]=j.useState(!0),{signatureHtml:Qe,hasSignature:Ye,signatureEnabledByDefault:nt}=Axn(),[rt,Fe]=j.useState(!0),[dt,Dt]=j.useState(null);j.useEffect(()=>{s&&Fe(Ye)},[s,Ye]),j.useEffect(()=>{if(s){const tn=/<[a-z][\s\S]*>/i.test(i),_n=tn?Exn(i):i;As.current=tn?{plain:_n,html:i}:null,O((M==null?void 0:M.email)||""),we(a),xe(_n),q(bk(a,M||{first_name:""})),G(bk(_n,M||{first_name:""})),le(!a&&!i),oe([]),ie.current=new Map,Se("composing"),Le(0),Be(0),Ge(0),Oe(0),Ae.current=!1,Xe.current=0,Dt(null)}},[s,M,a,i]);const pt=async tn=>{const _n=tn.target.files;if(!_n)return;const Cn=ue.reduce((jr,Xs)=>jr+Xs.size,0),Un=[];let Kr=Cn;for(const jr of Array.from(_n)){if(!Lxn.includes(jr.type)){re.error(`${jr.name}: Unsupported file type`);continue}if(Kr+jr.size>WPe){re.error(`Total attachments exceed ${Rne(WPe)} limit`);break}try{const Xs=await Pxn(jr);Un.push({name:jr.name,type:jr.type,size:jr.size,data:Xs}),Kr+=jr.size}catch{re.error(`Failed to read ${jr.name}`)}}oe(jr=>[...jr,...Un]),tn.target.value=""},zt=tn=>{const _n=ue[tn];_n&&ie.current.delete(`${_n.name}::${_n.size}`),oe(Cn=>Cn.filter((Un,Kr)=>Kr!==tn))},Gt=async()=>{if(ue.length===0||!u)return{inline:[],paths:[]};const tn=[],_n=[];for(const Cn of ue){const Un=`${Cn.name}::${Cn.size}`,Kr=ie.current.get(Un);if(Kr){_n.push(Kr);continue}if(Cn.size<=Mxn){tn.push(Cn);continue}const jr=Cn.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Xs=`${u.id}/${Date.now()}-${jr}`,Ba=atob(Cn.data),Hr=new Uint8Array(Ba.length);for(let pr=0;pr{if(!/<[a-z][\s\S]*>/i.test(tn)||typeof window>"u")return tn;const _n=tn.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,""),Cn=document.createElement("div");return Cn.innerHTML=_n,(Cn.textContent||Cn.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},As=j.useRef(null),Bt=tn=>{const _n=/<[a-z][\s\S]*>/i.test(tn.body),Cn=_n?qs(tn.body):tn.body;As.current=_n?{plain:Cn,html:tn.body}:null,we(tn.subject),xe(Cn),q(bk(tn.subject,M||{first_name:""})),G(bk(Cn,M||{first_name:""})),le(!1)},At=tn=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(tn)?tn:tn.split(/\n\n+/).map(_n=>`

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

`).join(""),Is=(tn,_n)=>{const Cn="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let Un=tn.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(jr,Xs,Ba,Hr,mr)=>{if(!Hr||/^(mailto:|tel:|#)/i.test(Hr)||Hr.includes("/bulk-email-track")||Hr.includes("/ses-campaign-track"))return jr;const pr=`${Cn}?s=${_n}&t=click&u=${encodeURIComponent(Hr)}`;return``});const Kr=``;return/<\/body>/i.test(Un)?Un=Un.replace(/<\/body>/i,`${Kr}`):Un=`${Un}${Kr}`,Un},jt=async tn=>{if(!(tn!=null&&tn.email))return re.error("Please enter a recipient email"),!1;const _n=tn||{first_name:""},Cn=bk(de,_n),Un=As.current,Kr=Un&&je===Un.plain,jr=bk(Kr?Un.html:je,_n);let Xs=Kr?jr:At(jr);rt&&Qe&&(Xs=Txn(Xs,bk(Qe,_n)));const Ba=u&&tn.id?crypto.randomUUID():null;Ba&&(Xs=Is(Xs,Ba));try{if(u&&tn.email){const pr=new Date(Date.now()-6e5).toISOString(),{data:rn}=await U.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",tn.email).eq("subject",Cn).gte("sent_at",pr).limit(1);if(rn&&rn.length>0)return console.log(`Skipping duplicate send to ${tn.email} (same subject within 10 min)`),re.info(`Skipped ${tn.first_name||tn.email} — already sent this in the last 10 min`),!0}const{inline:Hr,paths:mr}=await Gt();if(C){const pr=(p==null?void 0:p.display_name)||"ReLevelUp",rn=`${pr.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Jn=`${pr} <${rn}>`;let ea=mr[0];if(!ea&&Hr.length>0&&u){const it=Hr[0],gt=it.name.replace(/[^a-zA-Z0-9._-]/g,"_"),St=`${u.id}/${Date.now()}-${gt}`,Ht=atob(it.data),ts=new Uint8Array(Ht.length);for(let js=0;js({name:Jn,type:ea,data:_s})),attachment_paths:mr,skip_signature:!0}});if(rn)throw rn;if(!(pr!=null&&pr.success))throw new Error((pr==null?void 0:pr.error)||"Failed to send")}if(u&&tn.id&&Ba&&(await U.from("bulk_email_sends").insert({id:Ba,user_id:u.id,contact_id:tn.id,contact_email:tn.email,subject:Cn,source:c||(C?"ses_bulk":"sphere_gaps")}),d))try{await U.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:tn.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Cn}`,completed_at:new Date().toISOString()})}catch(pr){console.warn("touch log insert failed",pr)}return!0}catch(Hr){return console.error("Send error:",Hr),re.error("Failed to send to "+tn.first_name+": "+(Hr instanceof Error?Hr.message:"Unknown error")),!1}},Qs=()=>{const tn=Ee*Bw;return T.slice(tn,tn+Bw)},cn=async(tn=0,_n=Ue)=>{if(!$||!W){re.error("Please fill in subject and message");return}ee(!0),Se("sending");let Cn=Math.max(0,Math.min(tn,T.length)),Un=!1;for(;Cnmr+1):Ge(mr=>mr+1),BasetTimeout(mr,150))}if(h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),Un||Ae.current||Cn>=T.length)break;if(!_n){ee(!1),Se("batch_complete");return}if(Oe(0),await new Promise(Ba=>setTimeout(Ba,1500)),Ae.current){Un=!0;break}}ee(!1),Se(Un||Ae.current?"batch_complete":"all_done")},qt=async()=>{if(!$||!W){re.error("Please fill in subject and message");return}if(C&&x&&!x.hasVerifiedSes&&!x.hasGmail){g(!0);return}if(!k){const tn=M||{id:"",first_name:"",last_name:"",email:I.trim()};if(!tn.email){re.error("Please enter a recipient email");return}ee(!0);try{await jt(tn)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),re.success("Email sent successfully!"),t(!1),o==null||o())}finally{ee(!1)}return}Ae.current=!1,Xe.current=0,await cn(0)},Gs=async()=>{Ae.current=!1,Oe(0),await cn(Xe.current,!1)},Ls=async()=>{Ae.current=!1,Ze(!0),Oe(0),await cn(Xe.current,!0)},sn=()=>{if(K){Ae.current=!0;return}t(!1),o==null||o()},Hs=Ee*Bw;Math.min(Hs+Bw,T.length);const nn=k&&T.length>0?Math.round((De+Ne)/T.length*100):0;return e.jsxs(Fs,{open:s,onOpenChange:sn,children:[e.jsxs(Os,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:`h-5 w-5 ${C?"text-orange-500":"text-red-500"}`}),k?`Send to ${T.length} Contacts`:"Compose Email"]}),C?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",p==null?void 0:p.reply_to_email,")"]}):l?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:l})]}):null,k&&fe==="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."]})]}),fe==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Wt,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",Ee+1," of ",P,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[_e," of ",Qs().length," in this batch"]}),Ue&&P>1&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Auto-continuing through all ",P," batches — keep this window open."]})]}),e.jsx(qi,{value:_e/Math.max(Qs().length,1)*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",De+Ne," / ",T.length]}),e.jsxs("span",{children:[De," sent • ",Ne," failed"]})]}),e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Ae.current=!0},children:"Stop Sending"})]}),fe==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Rr,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Sending paused after batch ",Ee+1]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[De," sent, ",Ne," failed so far"]})]}),e.jsx(qi,{value:nn,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[T.length-De-Ne," contacts remaining (",Math.max(P-Ee-1,0)," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:sn,children:"Done for Now"}),e.jsxs(B,{className:"flex-1 gap-2",onClick:Ls,children:[e.jsx(Dr,{className:"h-4 w-4"}),"Resume Sending"]})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full",onClick:Gs,children:["Send just the next ",Math.min(Bw,Math.max(T.length-(De+Ne),0))," contacts"]})]}),fe==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Rr,{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:[De," emails sent successfully",Ne>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Ne," failed"]})]})]}),e.jsx(B,{className:"w-full",onClick:sn,children:"Close"})]}),fe==="composing"&&e.jsxs("div",{className:"space-y-4",children:[J?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($r,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>le(!1),className:"h-7 px-2 text-xs",children:[e.jsx(dr,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(Cxn,{onSelect:Bt})]}):e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>le(!0),children:[e.jsx($r,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(Xl,{}),!k&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"gmail-to",children:"To"}),e.jsx(dRt,{value:I,onChange:O,userId:u==null?void 0:u.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(ye,{id:"gmail-subject",value:$,onChange:tn=>{q(tn.target.value),we(tn.target.value)},placeholder:"Enter subject..."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(qe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{G(tn=>tn+"{{first_name}}"),xe(tn=>tn+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(qe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{G(tn=>tn+"{{last_name}}"),xe(tn=>tn+"{{last_name}}")},children:"{{last_name}}"}),v&&e.jsx(qe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const tn=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${v} `;G(_n=>_n+tn),xe(_n=>_n+tn)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),e.jsx(Ds,{id:"gmail-body",value:W,onChange:tn=>{G(tn.target.value),xe(tn.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:"flex items-center justify-between rounded-md border bg-muted/30 px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium",children:"Include my email signature"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:Ye?"Your saved signature is added to the bottom of this email.":"Add a signature in Profile settings to use this."})]}),e.jsx(Mn,{checked:rt&&Ye,onCheckedChange:Fe,disabled:!Ye})]})]}),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 tn;return(tn=document.getElementById("gmail-attachments"))==null?void 0:tn.click()},disabled:K,children:[e.jsx(ZT,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",Rne(WPe)," 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:pt})]}),ue.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ue.map((tn,_n)=>e.jsxs(qe,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(ZT,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:tn.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",Rne(tn.size),")"]}),e.jsx("button",{type:"button",onClick:()=>zt(_n),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(dr,{className:"h-3 w-3"})})]},_n))}),C&&ue.some(tn=>tn.size>Pmt)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",Rne(Pmt)," 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:()=>{Dt(T[0]||null),Se("reviewing")},disabled:!$||!W,className:"gap-2",children:["Review Emails",e.jsx(Xa,{className:"h-4 w-4"})]}):e.jsxs(B,{onClick:qt,disabled:K||!$||!W||!I.trim(),className:"gap-2",children:[K?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"}),K?"Sending...":"Send Email"]})]})]}),fe==="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."]}),L&&e.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 px-2.5 py-2 space-y-2",children:[e.jsxs("p",{className:"text-xs text-amber-600",children:["📦 ",T.length," contacts will be sent in ",P," batches of up to ",Bw,"."]}),e.jsxs("label",{className:"flex items-start gap-2 text-xs cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5 accent-current",checked:Ue,onChange:tn=>Ze(tn.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Send all batches automatically"}),e.jsx("span",{className:"block text-muted-foreground",children:"Runs straight through every batch — no need to click Continue. Keep this window open; you can stop anytime."})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{children:["Recipients (",T.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:T.map(tn=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(dt==null?void 0:dt.id)===tn.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>Dt(tn),children:[tn.first_name," ",tn.last_name," — ",tn.email]},tn.id))})]}),dt&&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(on,{className:"h-3.5 w-3.5"}),"Preview for ",dt.first_name," ",dt.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:"})," ",dt.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",bk(de,dt)]})]}),e.jsx(Xl,{}),e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:bk(je,dt)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>{Se("composing"),Dt(null)},children:[e.jsx(_a,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(B,{onClick:qt,disabled:K,className:"gap-2",children:[K?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"}),L?`Send First ${Bw}`:`Send to ${T.length}`]})]})]})]}),e.jsx(TAe,{open:y,onOpenChange:g,hasPending:!!(x!=null&&x.hasPendingSes),pendingEmails:x==null?void 0:x.pendingEmails})]})}function Rxn(){const s=Hn(),{data:t}=av(),{data:n}=tq(),r=CJ(),{isGmailConnected:a,gmailEmail:i}=Tf(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(new Set),m=xm(new Date),p=jd(m,30),x=T=>{if(!T)return null;const M=T.split(/[-/T]/);if(M.length<3)return null;const P=parseInt(M[1],10)-1,L=parseInt(M[2],10);return isNaN(P)||isNaN(L)?null:new Date(m.getFullYear(),P,L)},y=j.useMemo(()=>{if(!t)return[];const T=[];for(const M of t){if(M.birthday){const P=x(M.birthday);P&&(pd(P,m)||vb(P,m)&&W_(P,p))&&T.push({contact:M,type:"birthday",date:P,daysUntil:Ky(P,m),dateStr:M.birthday})}if(M.home_anniversary){const P=x(M.home_anniversary);P&&(pd(P,m)||vb(P,m)&&W_(P,p))&&T.push({contact:M,type:"anniversary",date:P,daysUntil:Ky(P,m),dateStr:M.home_anniversary})}if(M.wedding_anniversary){const P=x(M.wedding_anniversary);P&&(pd(P,m)||vb(P,m)&&W_(P,p))&&T.push({contact:M,type:"wedding_anniversary",date:P,daysUntil:Ky(P,m),dateStr:M.wedding_anniversary})}}return T.sort((M,P)=>M.daysUntil-P.daysUntil),T},[t]),g=T=>T==="birthday"?"Birthday":T==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",b=async T=>{const M=(n==null?void 0:n.find(P=>P.name==="Call"))||(n==null?void 0:n[0]);if(M)try{await r.mutateAsync({contactId:T.contact.id,actionTypeId:M.id,notes:`${g(T.type)} outreach`}),h(P=>new Set(P).add(`${T.contact.id}-${T.type}`)),ba({title:"Touch logged!",description:`Logged outreach for ${T.contact.first_name}`})}catch{ba({title:"Error",description:"Failed to log touch",variant:"destructive"})}},v=T=>{const M=`${T.contact.first_name}${T.contact.last_name?" "+T.contact.last_name:""}`,P=T.type==="birthday"?"birthday":T.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",L=new URLSearchParams({cardType:P,contactId:T.contact.id,name:M,...T.contact.address?{address:T.contact.address}:{},...(T.type==="anniversary"||T.type==="wedding_anniversary")&&T.dateStr?{date:T.dateStr}:{}});s(`/mission-control/card-studio?${L.toString()}`)},k=T=>T===0?"Today!":T===1?"Tomorrow":`${T} days`,C=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(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[e.jsx(Vc,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(qe,{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(Re,{className:"space-y-2",children:[y.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Wm,{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,M)=>{var O,$;const P=`${T.contact.id}-${T.type}`,L=u.has(P),I=`${((O=T.contact.first_name)==null?void 0:O[0])||""}${(($=T.contact.last_name)==null?void 0:$[0])||""}`.toUpperCase();return e.jsxs("div",{className:Et("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(Ra,{className:Et("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(Da,{className:Et("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:I})}),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(qe,{variant:"outline",className:Et("text-[10px] shrink-0 whitespace-nowrap",C(T.daysUntil)),children:k(T.daysUntil)})]}),e.jsxs("div",{className:Et("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(Wm,{className:"h-3 w-3"})," Birthday"]}):T.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(mo,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(ia,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Bs(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(pa,{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(ro,{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(on,{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(Zr,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{variant:"ghost",size:"sm",className:Et("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:()=>v(T),children:[e.jsx(yn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx(B,{variant:"ghost",size:"icon",className:Et("h-7 w-7",L&&"text-green-600"),title:"Log a touch",disabled:L||r.isPending,onClick:()=>b(T),children:e.jsx(Rr,{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(ma,{className:"h-3.5 w-3.5"})})]})]},`${P}-${M}`)})]})]}),a&&l&&e.jsx(cw,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function Dxn(s){const[t,n]=j.useState([]),[r,a]=j.useState(!1),{data:i,isLoading:l}=mt({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await U.rpc("cleanup_stale_visitors")}catch{}const{data:u}=await U.from("lead_site_active_visitors").select("*").eq("lead_site_id",s).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!u)return[];const h=u.map(x=>x.contact_id).filter(Boolean);let m={};if(h.length>0){const{data:x}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",h);(x||[]).forEach(y=>{m[y.id]=y})}const p=u.map(x=>x.auth_user_id).filter(Boolean);if(p.length>0){const{data:x}=await U.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",p);(x||[]).forEach(y=>{const g=u.find(b=>b.auth_user_id===y.user_id);g&&!g.contact_id&&y.contact_id&&(g.contact_id=y.contact_id),g&&!m[g.contact_id||""]&&y.name&&(m[g.contact_id||g.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(x=>{var y,g;return{...x,contact_name:m[x.contact_id||x.auth_user_id||""]?`${m[x.contact_id||x.auth_user_id||""].first_name} ${m[x.contact_id||x.auth_user_id||""].last_name||""}`.trim():null,contact_email:((y=m[x.contact_id||x.auth_user_id||""])==null?void 0:y.email)||null,contact_phone:((g=m[x.contact_id||x.auth_user_id||""])==null?void 0:g.phone)||null}})},enabled:!!s,refetchInterval:6e4});j.useEffect(()=>{if(!s)return;const u=U.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},h=>{h.eventType==="INSERT"?n(m=>m.find(x=>x.id===h.new.id)?m:[h.new,...m]):h.eventType==="UPDATE"?n(m=>m.map(p=>p.id===h.new.id?{...p,...h.new}:p)):h.eventType==="DELETE"&&n(m=>m.filter(p=>p.id!==h.old.id))}).subscribe(h=>{h==="SUBSCRIBED"&&a(!0)});return()=>{U.removeChannel(u)}},[s]);const o=r&&t.length>0?Oxn([...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 Oxn(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const Fxn={property_view:{label:"Viewed",icon:ma,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:Sl,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:mo,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function zxn(){const{user:s}=Ns(),t=Hn(),{isGmailConnected:n,gmailEmail:r}=Tf(),{leadSite:a}=h0(),{count:i}=Dxn(a==null?void 0:a.id),[l,o]=j.useState(!1),[c,d]=j.useState(null),{data:u,isLoading:h}=mt({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:b,error:v}=await U.rpc("get_lead_site_activity",{_user_id:s.id});if(v)throw v;return b},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const m=(u.activities||[]).filter(b=>b.visitor_name&&b.visitor_name!=="Site Visitor"),p=m.filter(b=>b.activity_type==="new_lead"),x=(u.activities||[]).filter(b=>b.activity_type==="property_view").length,y=(u.activities||[]).filter(b=>b.activity_type==="saved_listing").length,g=b=>{if(b.visitor_email)if(n){const v=(b.visitor_name||"").split(" ");d({id:b.contact_id||"",first_name:v[0]||"",last_name:v.slice(1).join(" ")||null,email:b.visitor_email}),o(!0)}else window.location.href=`mailto:${b.visitor_email}`};return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 bg-primary/10 rounded-lg",children:e.jsx(Ql,{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(Xa,{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(Sl,{className:"h-4 w-4 text-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-emerald-600 dark:text-emerald-400",children:p.length}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"New Leads"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-blue-500/5 border border-blue-200 dark:border-blue-800",children:[e.jsx(ma,{className:"h-4 w-4 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-blue-600 dark:text-blue-400",children:x}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Views"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-rose-500/5 border border-rose-200 dark:border-rose-800",children:[e.jsx(mo,{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,v)=>{const k=Fxn[b.activity_type],C=k.icon,T=oc(new Date(b.occurred_at),{addSuffix:!0});return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:shadow-sm transition-shadow",children:[e.jsx("div",{className:`p-1.5 rounded-md ${k.bgColor}`,children:e.jsx(C,{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:()=>{b.contact_id&&t(`/mission-control/contacts/${b.contact_id}`)},children:b.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:k.label}),b.mls_number&&e.jsxs("span",{children:["· MLS# ",b.mls_number]}),b.lead_type&&e.jsxs("span",{children:["· ",b.lead_type]}),e.jsxs("span",{children:["· ",T]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[b.visitor_email&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>g(b),children:e.jsx(on,{className:"h-3.5 w-3.5"})}),b.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:${b.visitor_phone}`,children:e.jsx(pa,{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:${b.visitor_phone}`,children:e.jsx(ro,{className:"h-3.5 w-3.5"})})]}),b.contact_id&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${b.contact_id}`),children:e.jsx(Qa,{className:"h-3.5 w-3.5"})})]})]},`${b.activity_type}-${b.occurred_at}-${v}`)}),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(Xa,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(be,{children:e.jsxs(Re,{className:"p-6 text-center",children:[e.jsx(vf,{className:"h-8 w-8 text-muted-foreground/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No actionable website activity yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:x>0?`${x} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs(B,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(Xa,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(cw,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const Imt={Crown:sy,FileText:$r,Users:Bn,Globe:Ql,Star:Wa,Phone:pa,MessageSquare:ro,PenTool:XT,Video:Zr,Gift:zo},Bxn={"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 $xn(){var Dt,pt,zt,Gt,qs,As;const s=Hn(),{user:t}=Ns(),{data:n}=lw(),{data:r}=qCt(),{data:a}=av(),{data:i}=tq(),{data:l}=KCt(),o=gks(),c=jVe(),d=fks(90),u=CJ(),[h,m]=j.useState(null),[p,x]=j.useState(null),[y,g]=j.useState(!1),[b,v]=j.useState(""),[k,C]=j.useState(!1),[T,M]=j.useState(""),[P,L]=j.useState(QNe()),[I,O]=j.useState("cards"),[$,q]=j.useState(!1),[W,G]=j.useState(null),[K,ee]=j.useState(null),[J,le]=j.useState(""),{isGmailConnected:ue,gmailEmail:oe}=Tf(),ie=()=>{const Bt=parseInt(T,10);if(isNaN(Bt)||Bt<1){ba({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}L(Bt),WCt(Bt),C(!1),ba({title:"Goal updated",description:`Weekly touch goal set to ${Bt}`})},de=()=>{M(P.toString()),C(!0)};j.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:At}=await U.from("profiles").select("name").eq("id",t.id).single();At!=null&&At.name&&v(At.name.split(" ")[0])})()},[t==null?void 0:t.id]),j.useEffect(()=>{o.mutate()},[]);const we=xm(new Date),je=jd(we,7),xe=Bt=>{if(!Bt)return null;const At=Bt.split(/[-/T]/);if(At.length<3)return null;const Is=parseInt(At[1],10)-1,jt=parseInt(At[2],10);return isNaN(Is)||isNaN(jt)?null:new Date(we.getFullYear(),Is,jt)},fe=(a==null?void 0:a.filter(Bt=>{const At=xe(Bt.birthday),Is=xe(Bt.home_anniversary);return At&&pd(At,we)||Is&&pd(Is,we)}))||[],Se=(a==null?void 0:a.filter(Bt=>{if(!Bt.birthday&&!Bt.home_anniversary)return!1;const At=Is=>{if(!Is)return!1;const jt=xe(Is);return jt?vb(jt,we)&&W_(jt,je):!1};return At(Bt.birthday)||At(Bt.home_anniversary)}).slice(0,5))||[],Ee=[],Le=(i==null?void 0:i.find(Bt=>Bt.name==="Call"))||(i==null?void 0:i[0]);for(const Bt of fe){const At=xe(Bt.birthday),Is=xe(Bt.home_anniversary),jt=At&&pd(At,we),Qs=Is&&pd(Is,we);jt&&Ee.push({contact:Bt,actionType:Le||{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:((zt=(pt=(Dt=Bt.tags)==null?void 0:Dt[0])==null?void 0:pt.relationship_type)==null?void 0:zt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Qs&&Ee.push({contact:Bt,actionType:Le||{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:((As=(qs=(Gt=Bt.tags)==null?void 0:Gt[0])==null?void 0:qs.relationship_type)==null?void 0:As.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Be=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((Bt,At)=>{var jt,Qs,cn;const Is=i==null?void 0:i[At%((i==null?void 0:i.length)||1)];return Is?{contact:Bt,actionType:Is,planName:"Quick Touch",relationshipTypeName:((cn=(Qs=(jt=Bt.tags)==null?void 0:jt[0])==null?void 0:Qs.relationship_type)==null?void 0:cn.name)||"",monthNumber:0}:null}).filter(Boolean))||[],Ne=[...Ee,...Be],{data:Ge}=sq(7),_e=(Ge||[]).filter(Bt=>pd(new Date(Bt.completed_at),we)).length,Oe=_e+Ne.length,Ae=(a==null?void 0:a.length)??0,Xe=Ee.length>0?`${Ee.length} celebration${Ee.length===1?"":"s"} today — a card or a call goes a long way.`:d.count>0?`${d.count} people haven't heard from you in 90+ days. Start with one.`: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.",Ue=async(Bt,At,Is)=>{await u.mutateAsync({contactId:Bt,actionTypeId:At,scriptUsedId:Is}),g(!1),x(null)},Ze=Bt=>{Bt.script?(x(Bt),g(!0)):Ue(Bt.contact.id,Bt.actionType.id)},Qe=Bt=>Imt[Bt||"Phone"]||pa,Ye=Bt=>Imt[Bt||"Users"]||Bn,nt=(Bt,At)=>Bt.replace(/\{\{FirstName\}\}/g,At.first_name).replace(/\{\{LastName\}\}/g,At.last_name||"").replace(/\{\{AgentName\}\}/g,b||"there"),rt=(Bt,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}`})[Bt]||`Hello ${At}!`,Fe=(Bt,At,Is)=>{const jt=`sms:${Bt}`;if(At&&Is){const Qs=nt(At,Is);return`${jt}?body=${encodeURIComponent(Qs)}`}return jt},dt=(Bt,At,Is,jt,Qs)=>{const cn=`mailto:${Bt}`,qt=[];if(Qs){const Gs=Is||rt(jt||"Email",Qs.first_name);if(qt.push(`subject=${encodeURIComponent(Gs)}`),At){const Ls=nt(At,Qs);qt.push(`body=${encodeURIComponent(Ls)}`)}}return qt.length>0?`${cn}?${qt.join("&")}`:cn};return e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{title:"Mission Control",description:"Your relationship-first contact system",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Mission Control"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(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(wh,{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(Bn,{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(Zr,{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(ic,{className:"h-4 w-4"}),"Plans"]})]})]}),e.jsx(vxn,{agentName:b,todayDone:_e,todayTotal:Oe,focusLine:Xe,weekDone:c.actionsThisWeek,weekGoal:P,streak:c.streak,staleCount:d.count,sphereCount:Ae,onEditGoal:de,onStaleClick:()=>s("/mission-control/contacts?filter=not-touched-90"),onSphereClick:()=>s("/mission-control/contacts")}),e.jsx(zxn,{}),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(Bt=>Bt.active).map(Bt=>{const At=Ye(Bt.icon),Is=(r==null?void 0:r[Bt.id])||0,jt=h===Bt.id,Qs=Bxn[Bt.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{jt?(m(null),s("/mission-control/contacts")):(m(Bt.id),s(`/mission-control/contacts?type=${Bt.id}`))},className:` inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-all ${jt?Qs:"bg-card hover:bg-accent"} `,children:[e.jsx(At,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-medium",children:Bt.name}),e.jsx("span",{className:`rounded-full px-1.5 py-0.5 text-[11px] tabular-nums ${jt?"bg-black/15":"bg-muted text-muted-foreground"}`,children:Is})]},Bt.id)})})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Today in Your InnerCircle"}),l!==void 0&&e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(yn,{className:"h-3 w-3"}),"Plan-based"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 border rounded-lg p-0.5",children:[e.jsx(B,{variant:I==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>O("cards"),title:"Card view",children:e.jsx(r0,{className:"h-4 w-4"})}),e.jsx(B,{variant:I==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>O("table"),title:"Table view",children:e.jsx(ug,{className:"h-4 w-4"})})]})]}),e.jsx(be,{children:e.jsx(Re,{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"})]}):I==="table"?e.jsx(Sxn,{actions:Ne,onMarkComplete:Ue,onViewScript:Ze,isLoading:u.isPending,buildSmsLink:Fe,buildEmailLink:dt,onGmailCompose:ue?Bt=>{G(Bt),q(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[Ne.map((Bt,At)=>{var sn,Hs,nn,tn,_n,Cn,Un;const Is=Bt.isSpecialDate,jt=Bt.specialDateType,Qs=Is?jt==="birthday"?Wm:ia:Qe(((sn=Bt.actionType)==null?void 0:sn.icon)||null),cn=Bt.contact.phone,qt=Bt.contact.email,Gs=Is?jt==="birthday"?"#EC4899":"#8B5CF6":((Hs=Bt.actionType)==null?void 0:Hs.color)||"#3B82F6",Ls=Is?jt==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(nn=Bt.actionType)==null?void 0:nn.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${Is?"ring-2 ring-offset-2":""}`,style:Is?{"--tw-ring-color":Gs}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:Gs},children:[e.jsx(Qs,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Ls})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${Bt.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[Bt.contact.first_name," ",Bt.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[cn&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${Bt.contact.phone}`,className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-primary/10 hover:bg-primary/20 text-primary rounded text-xs font-medium transition-colors",title:"Call",children:[e.jsx(pa,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:Fe(Bt.contact.phone,(tn=Bt.script)==null?void 0:tn.script_body,Bt.contact),className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 rounded text-xs font-medium transition-colors",title:"Text",children:[e.jsx(ro,{className:"h-3 w-3"}),"Text"]})]}),qt&&(ue?e.jsxs("button",{onClick:()=>{G({id:Bt.contact.id,first_name:Bt.contact.first_name,last_name:Bt.contact.last_name,email:Bt.contact.email}),q(!0)},className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 rounded text-xs font-medium transition-colors",title:"Compose Email",children:[e.jsx(on,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:dt(Bt.contact.email,(_n=Bt.script)==null?void 0:_n.script_body,(Cn=Bt.script)==null?void 0:Cn.email_subject,(Un=Bt.actionType)==null?void 0:Un.name,Bt.contact),className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 rounded text-xs font-medium transition-colors",title:"Email",children:[e.jsx(on,{className:"h-3 w-3"}),"Email"]}))]}),Is&&e.jsxs("button",{onClick:()=>{const Kr=`${Bt.contact.first_name}${Bt.contact.last_name?" "+Bt.contact.last_name:""}`,jr=jt==="birthday"?"birthday":"home_anniversary",Xs=new URLSearchParams({cardType:jr,contactId:Bt.contact.id,name:Kr,...Bt.contact.address?{address:Bt.contact.address}:{},...jt==="anniversary"&&Bt.contact.home_anniversary?{date:Bt.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${Xs.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(on,{className:"h-3 w-3"}),"Send ",jt==="birthday"?"Birthday":"Anniversary"," Card"]}),!cn&&!qt&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[Bt.relationshipTypeName&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:Bt.relationshipTypeName}),Bt.monthNumber>0&&e.jsxs(qe,{variant:"outline",className:"text-xs",children:["Month ",Bt.monthNumber]})]}),Bt.script&&e.jsx(B,{size:"sm",variant:"outline",className:"w-full",onClick:()=>Ze(Bt),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:()=>{ee(Bt.contact.id),le(`${Bt.contact.first_name} ${Bt.contact.last_name||""}`.trim())},children:[e.jsx(ay,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(B,{size:"sm",className:"flex-1",onClick:()=>{var Kr;return Ue(Bt.contact.id,Bt.actionType.id,(Kr=Bt.script)==null?void 0:Kr.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},Bt.contact.id+At)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"h-full w-full",children:[e.jsx(Hy,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(xd,{children:e.jsx(wa,{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(Fd,{className:"h-3.5 w-3.5 text-orange-500"}),"This week's momentum"]}),e.jsxs("span",{className:"text-xs tabular-nums text-muted-foreground",children:[c.actionsThisWeek," of ",P," touches"]})]}),e.jsx(qi,{value:Math.min(c.actionsThisWeek/P*100,100),className:"h-2.5 w-full max-w-full"}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:c.actionsThisWeek>=P?"Goal hit for the week — anything else is bonus.":`${P-c.actionsThisWeek} more to hit your goal.`})]}),e.jsx(Fs,{open:k,onOpenChange:C,children:e.jsxs(Os,{className:"sm:max-w-[360px]",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Set Weekly Goal"}),e.jsx(kr,{children:"How many touches do you want to complete each week?"})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(ye,{id:"weekly-goal-ic",type:"number",min:"1",value:T,onChange:Bt=>M(Bt.target.value),placeholder:"20",onKeyDown:Bt=>{Bt.key==="Enter"&&ie()}})]}),e.jsx(B,{onClick:ie,className:"w-full",children:"Save Goal"})]})]})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(lAt,{}),e.jsx(Rxn,{})]})]}),e.jsx(Fs,{open:y,onOpenChange:g,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{className:"flex items-center gap-2",children:p&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:p.actionType.color||"#3B82F6"}}),p.actionType.name," Script"]})})}),p&&p.script&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["For: ",e.jsxs("span",{className:"font-medium text-foreground",children:[p.contact.first_name," ",p.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:nt(p.script.script_body,p.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>g(!1),children:"Close"}),e.jsx(B,{className:"flex-1",onClick:()=>{var Bt;return Ue(p.contact.id,p.actionType.id,(Bt=p.script)==null?void 0:Bt.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(bxn,{})]}),ue&&W&&e.jsx(cw,{open:$,onOpenChange:q,contact:W,gmailEmail:oe}),e.jsx(MAe,{open:!!K,onOpenChange:Bt=>!Bt&&ee(null),contactId:K||"",contactName:J})]})}const Uxn=[{value:"bidirectional",label:"Two-Way",icon:_x,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:Gm,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:tx,tooltip:"Only pull BoldTrail → Agent OS"}];function rSe({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(Az,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:Uxn.map(a=>e.jsxs(Cu,{children:[e.jsx(Au,{asChild:!0,children:e.jsxs(aD,{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(ou,{children:a.tooltip})]},a.value))})]})}function Rmt(){const s=as(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,x]=j.useState(0),y=j.useRef(!1),{data:g}=mt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:I,error:O}=await U.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(O)throw O;return I}}),b=(g==null?void 0:g.sync_direction)||"bidirectional",v=d??b,k=vt({mutationFn:async()=>{const{data:I,error:O}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(O)throw O;if(I!=null&&I.error)throw new Error(I.error);return I},onSuccess:I=>{u(null),a(I),n(!0)},onError:I=>{re.error(I.message||"Failed to generate sync preview")}}),C=vt({mutationFn:async()=>{y.current=!1,m("Initializing sync..."),x(5);const{data:I,error:O}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:v}});if(O)throw O;if(I!=null&&I.error)throw new Error(I.error);const $=I;let q=$.sync_log_id,W=$.next_phase,G=$.next_offset,K=$.push_total||0,ee=$.pull_total||0,J=$.update_total||0,le=0,ue=0,oe=0;for(;W!=="finalize"&&!y.current;){const we=K+ee+J;W==="fetch_bt"?m("Fetching BoldTrail contacts..."):W==="analyze"?(m("Analyzing contacts..."),x(15)):W==="push"?(m(`Pushing contacts to BoldTrail... (${le}/${K})`),x(we>0?le/we*90:0)):W==="pull"?(m(`Pulling contacts from BoldTrail... (${ue}/${ee})`),x(we>0?(K+ue)/we*90:0)):W==="update"&&(m(`Updating existing contacts... (${oe}/${J})`),x(we>0?(K+ee+oe)/we*90:0));const{data:je,error:xe}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:W,offset:G,sync_log_id:q,sync_direction:v}});if(xe)throw xe;if(je!=null&&je.error)throw new Error(je.error);const fe=je;le+=fe.chunk_pushed||0,ue+=fe.chunk_pulled||0,oe+=fe.chunk_updated||0,fe.push_total!==void 0&&(K=fe.push_total||0),fe.pull_total!==void 0&&(ee=fe.pull_total||0),fe.update_total!==void 0&&(J=fe.update_total||0),fe.progress&&m(fe.progress),W=fe.next_phase,G=fe.next_offset}m("Finalizing sync..."),x(95);const{data:ie,error:de}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:q,sync_direction:v}});if(de)throw de;return x(100),ie},onSuccess:I=>{m(null),x(0),n(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const O=[`Pushed ${I.contacts_pushed||0}`,`pulled ${I.contacts_pulled||0}`,`updated ${I.contacts_updated||0}`,`skipped ${I.contacts_skipped||0} duplicates`];re.success(`Sync complete! ${O.join(", ")}.`)},onError:I=>{m(null),x(0),re.error(I.message||"Sync failed")}});if(!(g!=null&&g.connected))return null;const T=v==="pull_only"?0:(r==null?void 0:r.to_push)??0,M=v==="push_only"?0:(r==null?void 0:r.to_pull)??0,P=(r==null?void 0:r.to_update)??0,L=T>0||M>0||P>0;return e.jsxs(e.Fragment,{children:[e.jsxs(Cu,{children:[e.jsx(Au,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",onClick:()=>k.mutate(),disabled:k.isPending,className:"shrink-0",children:k.isPending?e.jsx(Ki,{className:"h-4 w-4 animate-spin"}):e.jsx(_x,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(ou,{children:"Sync with BoldTrail"})]}),e.jsx(Fs,{open:t,onOpenChange:I=>{C.isPending||n(I)},children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(_x,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(kr,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(rSe,{value:v,onChange:u,size:"sm"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${v==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:T}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Gm,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${v==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:M}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(tx,{className:"h-3 w-3"})," Pull to Agent OS"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-amber-600",children:P}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(sz,{className:"h-3 w-3"})," To update"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-muted-foreground",children:r.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",r.agent_os_total," contacts · BoldTrail: ",r.boldtrail_total," contacts"]}),P>0&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center bg-amber-50 dark:bg-amber-950/30 rounded-md p-2",children:[e.jsx(sz,{className:"h-3 w-3 inline mr-1"}),P," contacts have missing fields that will be filled from the other system"]}),T>0&&e.jsxs(i0,{open:i,onOpenChange:l,children:[e.jsx(o0,{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(Gm,{className:"h-3 w-3 text-emerald-600"}),T," contacts to push to BoldTrail"]}),e.jsx(Po,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(l0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.push_preview.map((I,O)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:I.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:I.email})]},O)),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"]})]})})]}),M>0&&e.jsxs(i0,{open:o,onOpenChange:c,children:[e.jsx(o0,{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(tx,{className:"h-3 w-3 text-blue-600"}),M," contacts to pull from BoldTrail"]}),e.jsx(Po,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(l0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.pull_preview.map((I,O)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:I.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:I.email})]},O)),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"]})]})})]}),!L&&!C.isPending&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer or update."}),C.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(qi,{value:p||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:h||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),disabled:C.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>C.mutate(),disabled:C.isPending||!L,className:"gap-2",children:[C.isPending?e.jsx(Ki,{className:"h-4 w-4 animate-spin"}):e.jsx(_x,{className:"h-4 w-4"}),C.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const qxn=()=>{const{user:s}=Ns();return mt({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("popby_items").select("*").or(`owner_user_id.is.null,owner_user_id.eq.${s==null?void 0:s.id}`).eq("is_active",!0).order("name");if(n)throw n;return t},enabled:!!s})},PAe=s=>{const{user:t}=Ns();return mt({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let n=U.from("popby_logs").select("*").order("completed_at",{ascending:!1});if(s){const i=new Date;i.setDate(i.getDate()-s),n=n.gte("completed_at",i.toISOString())}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})},_We=()=>{const{user:s}=Ns();return mt({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("relationship_type_popby_defaults").select("*");if(n)throw n;return t},enabled:!!s})},uRt=()=>{const{user:s}=Ns();return mt({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_popby_settings").select("*");if(n)throw n;return t},enabled:!!s})},Vxn=()=>{const{data:s}=av();lw();const{data:t}=PAe(),{data:n}=uRt(),{data:r}=_We(),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=xm(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(g=>i.get(g.relationship_type_id)).filter(g=>g!==void 0);y.length>0&&(u=Math.min(...y))}const h=a.get(d.id)||null,m=h?Fj(o,xm(new Date(h))):null,p=m===null||m>=u,x=p&&m!==null?m-u:0;return{...d,lastPopby:h,daysSinceLastPopby:m,frequencyDays:u,isDue:p,daysOverdue:x}}).sort((d,u)=>u.daysOverdue-d.daysOverdue)},hRt=()=>Vxn().filter(t=>t.isDue),Hxn=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async n=>{const{error:r}=await U.from("popby_items").insert({...n,owner_user_id:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),ba({title:"Popby item created!"})},onError:n=>{ba({title:"Error creating popby item",description:n.message,variant:"destructive"})}})},Gxn=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async n=>{const r=new Date().toISOString(),{error:a}=await U.from("popby_logs").insert({...n,owner_user_id:t==null?void 0:t.id,completed_at:r});if(a)throw a;try{const{data:i}=await U.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await U.from("contact_touch_logs").insert({owner_user_id:t==null?void 0:t.id,contact_id:n.contact_id,action_type_id:i.id,notes:n.notes??"Pop-by logged",completed_at:r})}catch(i){console.error("Failed to log corresponding touch for popby",i)}},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-logs"]}),s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),ba({title:"Popby logged!"})},onError:n=>{ba({title:"Error logging popby",description:n.message,variant:"destructive"})}})},Wxn=()=>{const s=as(),{user:t}=Ns();return vt({mutationFn:async n=>{const{error:r}=await U.from("relationship_type_popby_defaults").upsert({...n,owner_user_id:t==null?void 0:t.id},{onConflict:"relationship_type_id,owner_user_id"});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["relationship-type-popby-defaults"]}),ba({title:"Frequency updated!"})},onError:n=>{ba({title:"Error updating frequency",description:n.message,variant:"destructive"})}})},Kxn=()=>{const{data:s}=PAe(30),t=hRt(),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 Yxn(){const{user:s}=Ns();return mt({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function mRt(s){const{data:t}=Yxn(),{data:n}=uRt(),{data:r}=_We(),{data:a}=_xn();return j.useMemo(()=>{const i=a==null?void 0:a.find(g=>g.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=xm(new Date);if(l&&!W_(l,o))return{nextTouchDate:l,daysUntil:Fj(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(g=>g.contact_id===s.id))||[]).sort((g,b)=>new Date(b.completed_at).getTime()-new Date(g.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let h=90;const m=n==null?void 0:n.find(g=>g.contact_id===s.id&&g.is_active);if(m)h=m.frequency_days;else if(s.tags&&s.tags.length>0){const g=s.tags.map(b=>{const v=r==null?void 0:r.find(k=>k.relationship_type_id===b.relationship_type_id);return v==null?void 0:v.frequency_days}).filter(b=>b!==void 0);g.length>0&&(h=Math.min(...g))}if(!u)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:h,lastTouchDate:null,snoozedUntil:null};const p=jd(xm(u),h),x=Fj(p,o);let y;return x<0?y="overdue":x<=7?y="due-soon":y="on-track",{nextTouchDate:p,daysUntil:x,status:y,frequencyDays:h,lastTouchDate:u,snoozedUntil:null}},[s,t,n,r,a])}function aSe({contact:s}){const t=mRt(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:po,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:Vr,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:Rr,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:ay,text:`Snoozed until ${Bs(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:ra,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs(qe,{variant:r.variant,className:Et("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function Zxn({contact:s,onLogTouch:t,onSnooze:n}){const r=mRt(s),a=jxn(),[i,l]=j.useState(!1),o=()=>{switch(r.status){case"overdue":return"text-destructive";case"due-soon":return"text-amber-600 dark:text-amber-400";case"on-track":return"text-emerald-600 dark:text-emerald-400";case"snoozed":return"text-slate-600 dark:text-slate-400";case"never-touched":return"text-muted-foreground"}},c=()=>{switch(r.status){case"overdue":return e.jsx(po,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(Vr,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(Rr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(ay,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(ra,{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(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Re,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:Et("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:"})," ",Bs(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:"})," ",Bs(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:"})," ",Bs(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(dr,{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(ay,{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(MAe,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const KPe=768;function Tq(){const[s,t]=j.useState(void 0);return j.useEffect(()=>{const n=window.matchMedia(`(max-width: ${KPe-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function Xxn(){const{user:s}=Ns(),{hasLeadSite:t,leadSite:n}=h0(),{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 U.from("lead_site_visitors").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),{data:l}=await U.from("lead_site_consumer_profiles").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),o=new Set;return(i||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),(l||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),o},enabled:!!s&&t,staleTime:5*60*1e3});return{activeContactIds:r??new Set,hasLeadSite:t,isLoading:a}}const Qxn={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"}},Jxn={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 f9e({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=Qxn[s.status],l=Jxn[r],o=e.jsxs("div",{className:Et("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:Et("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return n?e.jsx(RN,{children:e.jsxs(Cu,{children:[e.jsx(Au,{asChild:!0,children:o}),e.jsx(ou,{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:Et("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(qi,{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 egn=[{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}],Dne=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]},tgn=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=Ns(),{toast:i}=pi(),l=j.useRef(null),[o,c]=j.useState("upload"),[d,u]=j.useState([]),[h,m]=j.useState([]),[p,x]=j.useState({}),[y,g]=j.useState([]),[b,v]=j.useState([]),[k,C]=j.useState([]),[T,M]=j.useState(""),[P,L]=j.useState(!1),[I,O]=j.useState([]),[$,q]=j.useState(!1),[W,G]=j.useState(null);j.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:De}=await U.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");v(De||[])})()},[s,a==null?void 0:a.id]);const K=De=>{C(Be=>Be.includes(De)?Be.filter(Ne=>Ne!==De):[...Be,De])},ee=async()=>{const De=T.trim();if(!(!De||!(a!=null&&a.id))){L(!0);try{const{data:Be,error:Ne}=await U.from("contact_custom_tags").insert({owner_user_id:a.id,name:De}).select("id, name, color").single();if(Ne)throw Ne;Be&&(v(Ge=>[...Ge,Be].sort((_e,Oe)=>_e.name.localeCompare(Oe.name))),C(Ge=>[...Ge,Be.id]),M(""))}catch(Be){i({title:"Could not create tag",description:Be.message||"Try a different name.",variant:"destructive"})}finally{L(!1)}}},J=()=>{c("upload"),u([]),m([]),x({}),g([]),C([]),M(""),O([]),G(null),l.current&&(l.current.value="")},le=()=>{J(),t(!1)},ue=De=>{const Be=De.split(` `).map(Xe=>Xe.trim()).filter(Xe=>Xe);if(Be.length===0)return{headers:[],data:[]};const Ne=Xe=>{const Ue=[];let Ze="",Qe=!1;for(let Ye=0;Ye0&&(Ge[0]=Ge[0].replace(/^\uFEFF/,""));const _e=new Map,Oe=Ge.map((Xe,Ue)=>{let Ze=(Xe||"").trim();Ze||(Ze=`Column ${Ue+1}`);const Qe=_e.get(Ze)||0;return _e.set(Ze,Qe+1),Qe===0?Ze:`${Ze} (${Qe+1})`}),Ae=Be.slice(1).map(Ne);return{headers:Oe,data:Ae}},oe=De=>{var Ge;const Be=(Ge=De.target.files)==null?void 0:Ge[0];if(!Be)return;const Ne=new FileReader;Ne.onload=_e=>{var Ze;const Oe=(Ze=_e.target)==null?void 0:Ze.result,{headers:Ae,data:Xe}=ue(Oe);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 Ue={};Ae.forEach(Qe=>{const Ye=Qe.toLowerCase().replace(/[_\s-]/g,"");Ye.includes("firstname")||Ye==="first"?Ue.first_name=Qe:Ye.includes("lastname")||Ye==="last"?Ue.last_name=Qe:Ye.includes("spouse")&&Ye.includes("email")?Ue.spouse_email=Qe:Ye.includes("spouse")||Ye.includes("partner")?Ue.spouse_name=Qe:Ye.includes("email")?Ue.email=Qe:Ye.includes("phone")||Ye.includes("mobile")||Ye.includes("cell")?Ue.phone=Qe:Ye.includes("address")||Ye.includes("street")?Ue.address=Qe:Ye==="city"?Ue.city=Qe:Ye==="state"||Ye==="province"?Ue.state=Qe:Ye==="zip"||Ye==="zipcode"||Ye==="postalcode"?Ue.zip=Qe:Ye.includes("company")||Ye.includes("organization")||Ye.includes("business")?Ue.company_name=Qe:Ye.includes("jobtitle")||Ye.includes("title")&&!Ye.includes("spouse")?Ue.job_title=Qe:Ye.includes("birthday")||Ye.includes("dob")||Ye.includes("birthdate")?Ue.birthday=Qe:Ye.includes("anniversary")||Ye.includes("homeanniversary")?Ue.home_anniversary=Qe:(Ye.includes("notes")||Ye.includes("comment"))&&(Ue.notes=Qe)}),x(Ue),c("mapping")},Ne.readAsText(Be)},ie=(De,Be)=>{x(Ne=>{if(Be==="none"){const{[De]:Ge,..._e}=Ne;return _e}return{...Ne,[De]:Be}})},de=De=>{g(Be=>Be.includes(De)?Be.filter(Ne=>Ne!==De):[...Be,De])},we=async()=>{if(!(a!=null&&a.id))return;const{data:De}=await U.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),Be=new Set((De||[]).filter(_e=>_e.email).map(_e=>_e.email.toLowerCase())),Ne=new Set((De||[]).filter(_e=>_e.phone).map(_e=>_e.phone.replace(/[^0-9]/g,""))),Ge=h.map(_e=>{const Oe=Ye=>{const nt=p[Ye];if(!nt)return"";const rt=d.indexOf(nt);return rt>=0?(_e[rt]||"").trim():""},Ae=Oe("first_name"),Xe=Oe("email"),Ue=Oe("phone"),Ze=Ae.length>0,Qe=!!(Xe&&Be.has(Xe.toLowerCase())||Ue&&Ne.has(Ue.replace(/[^0-9]/g,"")));return{first_name:Ae,last_name:Oe("last_name"),email:Xe,phone:Ue,address:Oe("address"),city:Oe("city"),state:Oe("state"),zip:Oe("zip"),spouse_name:Oe("spouse_name"),spouse_email:Oe("spouse_email"),company_name:Oe("company_name"),job_title:Oe("job_title"),birthday:Oe("birthday"),home_anniversary:Oe("home_anniversary"),notes:Oe("notes"),isValid:Ze,isDuplicate:Qe,error:Ze?void 0:"First name is required"}});O(Ge),c("preview")},je=De=>{const Be=De.trim().split(/\s+/);return{first_name:Be[0],last_name:Be.length>1?Be.slice(1).join(" "):null}},xe=async()=>{if(!(a!=null&&a.id))return;const De=I.filter(_e=>_e.isValid);if(De.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}q(!0);let Be=0,Ne=0,Ge=0;try{for(const _e of De)try{let Oe=null;if(_e.email){const{data:Ue}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",_e.email).maybeSingle();Oe=Ue}if(!Oe&&_e.phone){const Ue=_e.phone.replace(/[^0-9]/g,""),{data:Ze}=await U.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Ze){const Qe=Ze.find(Ye=>Ye.phone&&Ye.phone.replace(/[^0-9]/g,"")===Ue);Qe&&(Oe={id:Qe.id})}}const Ae={owner_user_id:a.id,first_name:_e.first_name,last_name:_e.last_name||null,email:_e.email||null,phone:_e.phone||null,address:_e.address||null,city:_e.city||null,state:_e.state||null,zip:_e.zip||null,spouse_name:_e.spouse_name||null,spouse_email:_e.spouse_email||null,company_name:_e.company_name||null,job_title:_e.job_title||null,birthday:Dne(_e.birthday),home_anniversary:Dne(_e.home_anniversary),notes:_e.notes||null};let Xe=null;if(Oe){const{data:Ue}=await U.from("innercircle_contacts").select("*").eq("id",Oe.id).single();if(Ue){const Ze={},Qe=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const Ye of Qe){const nt=Ue[Ye],rt=Ae[Ye];(!nt||nt==="")&&rt&&(Ze[Ye]=rt)}Object.keys(Ze).length>0&&await U.from("innercircle_contacts").update(Ze).eq("id",Oe.id)}Xe=Oe.id,Ne++}else{const{data:Ue,error:Ze}=await U.from("innercircle_contacts").insert(Ae).select("id").single();Ze?(console.error("Insert error for contact:",_e.first_name,Ze),Ge++):Ue?(Xe=Ue.id,y.length>0&&await U.from("innercircle_contact_tags").insert(y.map(Qe=>({contact_id:Ue.id,relationship_type_id:Qe}))),Be++):Ge++}if(Xe&&k.length>0&&await U.from("contact_custom_tag_assignments").upsert(k.map(Ue=>({contact_id:Xe,tag_id:Ue})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),Xe&&_e.spouse_name){const Ue=je(_e.spouse_name);let Ze=null;if(_e.spouse_email){const{data:Ye}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",_e.spouse_email).maybeSingle();Ze=Ye}if(!Ze){const{data:Ye}=await U.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",Ue.first_name).eq("last_name",Ue.last_name||_e.last_name||"").maybeSingle();Ze=Ye}let Qe=null;if(Ze){Qe=Ze.id;const Ye=Dne(_e.home_anniversary);Ye&&await U.from("innercircle_contacts").update({home_anniversary:Ye}).eq("id",Ze.id).is("home_anniversary",null)}else{const{data:Ye}=await U.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:Ue.first_name,last_name:Ue.last_name||_e.last_name||null,email:_e.spouse_email||null,address:_e.address||null,city:_e.city||null,state:_e.state||null,zip:_e.zip||null,home_anniversary:Dne(_e.home_anniversary),spouse_name:`${_e.first_name}${_e.last_name?" "+_e.last_name:""}`,spouse_email:_e.email||null,notes:`Spouse of ${_e.first_name} ${_e.last_name||""} (imported via CSV)`.trim()}).select("id").single();Ye&&(Qe=Ye.id,Be++)}Qe&&(await U.from("innercircle_contacts").update({spouse_contact_id:Qe}).eq("id",Xe),await U.from("innercircle_contacts").update({spouse_contact_id:Xe}).eq("id",Qe))}}catch(Oe){console.error("Error importing contact:",Oe),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(_e){console.error("Import error:",_e),i({title:"Import Failed",description:_e.message||"Failed to import contacts",variant:"destructive"})}finally{q(!1)}},fe=I.filter(De=>De.isValid).length,Se=I.filter(De=>!De.isValid).length,Ee=I.filter(De=>De.isValid&&De.isDuplicate).length,Le=fe-Ee;return e.jsx(Fs,{open:s,onOpenChange:le,children:e.jsxs(Os,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(pN,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(kr,{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:oe,className:"hidden"}),e.jsx(Ja,{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 De;return(De=l.current)==null?void 0:De.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Supported Fields:"}),e.jsx("p",{className:"text-muted-foreground text-xs mb-3",children:"First Name, Last Name, Email, Phone, Street Address, City, State, Zip, Spouse Name, Spouse Email, Company, Job Title, Birthday, Home Anniversary, Notes"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{const De=`First Name,Last Name,Email,Phone,Street Address,City,State,Zip,Spouse Name,Spouse Email,Company,Job Title,Birthday,Home Anniversary,Notes John,Doe,john@example.com,555-123-4567,123 Main St,Austin,TX,78701,Jane Doe,jane@example.com,ABC Realty,Real Estate Agent,1985-06-15,2020-03-22,Met at open house`,Be=new Blob([De],{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(ii,{className:"h-4 w-4 mr-2"}),"Download Template"]})]})]}),o==="mapping"&&e.jsxs("div",{className:"flex-1 overflow-auto space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:egn.map(De=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(se,{className:"w-40 text-sm",children:[De.label,De.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(vs,{value:p[De.key]||"none",onValueChange:Be=>ie(De.key,Be),children:[e.jsx(gs,{className:"w-48",children:e.jsx(bs,{placeholder:"Select column..."})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"-- Not mapped --"}),d.map(Be=>e.jsx(Je,{value:Be,children:Be},Be))]})]})]},De.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(De=>e.jsx(qe,{variant:y.includes(De.id)?"default":"outline",className:"cursor-pointer",onClick:()=>de(De.id),children:De.name},De.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-base font-medium",children:"Apply Tags to All Imported Contacts (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every contact in this CSV — both newly created and merged duplicates — will receive the selected tags."}),b.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(De=>{const Be=k.includes(De.id);return e.jsxs(qe,{variant:Be?"default":"outline",className:"cursor-pointer gap-1",style:Be&&De.color?{backgroundColor:De.color,borderColor:De.color}:void 0,onClick:()=>K(De.id),children:[De.name,Be&&e.jsx(dr,{className:"h-3 w-3"})]},De.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:T,onChange:De=>M(De.target.value),onKeyDown:De=>{De.key==="Enter"&&(De.preventDefault(),ee())},className:"max-w-xs"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ee,disabled:!T.trim()||P,children:[P?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Js,{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(Rr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Le," new"]})]}),Ee>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(po,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ee," existing (will merge gaps)"]})]}),Se>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(po,{className:"h-4 w-4"}),e.jsxs("span",{children:[Se," invalid"]})]})]}),Ee>0&&e.jsx("div",{className:"bg-muted/50 rounded-lg p-3 text-xs text-muted-foreground",children:"Duplicates matched by email or phone will only fill in missing fields — your existing data won't be overwritten."}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{className:"bg-muted/30",children:[e.jsx(Tt,{children:"First Name"}),e.jsx(Tt,{children:"Last Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(za,{children:I.slice(0,100).map((De,Be)=>e.jsxs(un,{children:[e.jsx(xt,{children:De.first_name}),e.jsx(xt,{children:De.last_name}),e.jsx(xt,{children:De.email}),e.jsx(xt,{children:De.phone}),e.jsx(xt,{children:De.isValid?De.isDuplicate?e.jsx(qe,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(qe,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(qe,{variant:"destructive",children:De.error||"Invalid"})})]},Be))})]}),I.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",I.length," contacts"]})]})]}),o==="result"&&W&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(Rr,{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(Nr,{children:[o==="upload"&&e.jsx(B,{variant:"outline",onClick:le,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:J,children:"Back"}),e.jsx(B,{onClick:we,disabled:!p.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx(B,{onClick:xe,disabled:$||fe===0,children:$?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${fe} Contact${fe!==1?"s":""}`})]}),o==="result"&&e.jsx(B,{onClick:le,children:"Done"})]})]})})};function sgn(){return"contacts"in navigator&&"ContactsManager"in window}function ngn(s){const t=[],n=s.split("BEGIN:VCARD").filter(r=>r.trim());for(const r of n){const a=r.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const u of a){const h=u.replace(/^\s+/,"");if(h.startsWith("N:")||h.startsWith("N;")){const p=h.substring(h.indexOf(":")+1).split(";");l=(p[0]||"").trim(),i=(p[1]||"").trim()}if((h.startsWith("FN:")||h.startsWith("FN;"))&&!i){const p=h.substring(h.indexOf(":")+1).trim().split(" ");i=p[0]||"",l=p.slice(1).join(" ")}(h.startsWith("EMAIL")||h.match(/^item\d+\.EMAIL/i))&&!o&&(o=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("TEL")||h.match(/^item\d+\.TEL/i))&&!c&&(c=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("ADR")||h.match(/^item\d+\.ADR/i))&&!d&&(d=h.substring(h.indexOf(":")+1).split(";").map(x=>x.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function rgn({open:s,onOpenChange:t,onComplete:n}){Ns();const{data:r}=av(),a=q3e(),i=j.useRef(null),[l,o]=j.useState("choose"),[c,d]=j.useState([]),[u,h]=j.useState(new Set),[m,p]=j.useState(0),[x,y]=j.useState(0),g=sgn(),b=j.useCallback(O=>{if(!r)return O;const $=new Set(r.filter(W=>W.email).map(W=>W.email.toLowerCase())),q=new Set(r.filter(W=>W.phone).map(W=>W.phone.replace(/\D/g,"")));return O.map(W=>{var ee,J;const G=(ee=W.email)==null?void 0:ee.toLowerCase(),K=(J=W.phone)==null?void 0:J.replace(/\D/g,"");return G&&$.has(G)?{...W,isDuplicate:!0,duplicateField:"email"}:K&&K.length>=7&&q.has(K)?{...W,isDuplicate:!0,duplicateField:"phone"}:W})},[r]),v=async()=>{try{const O=["name","email","tel","address"],$=await navigator.contacts.select(O,{multiple:!0});if(!$||$.length===0)return;const q=$.map(K=>{var le,ue,oe,ie;const J=(((le=K.name)==null?void 0:le[0])||"").split(" ");return{first_name:J[0]||"",last_name:J.slice(1).join(" "),email:((ue=K.email)==null?void 0:ue[0])||"",phone:((oe=K.tel)==null?void 0:oe[0])||"",address:(ie=K.address)!=null&&ie[0]?[K.address[0].streetAddress,K.address[0].city,K.address[0].region,K.address[0].postalCode].filter(Boolean).join(", "):""}}),W=b(q);d(W);const G=new Set;W.forEach((K,ee)=>{K.isDuplicate||G.add(ee)}),h(G),o("preview")}catch(O){console.error("Contact Picker error:",O),ba({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},k=O=>{var W;const $=(W=O.target.files)==null?void 0:W[0];if(!$)return;const q=new FileReader;q.onload=G=>{var ue;const K=(ue=G.target)==null?void 0:ue.result,ee=ngn(K);if(ee.length===0){ba({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const J=b(ee);d(J);const le=new Set;J.forEach((oe,ie)=>{oe.isDuplicate||le.add(ie)}),h(le),o("preview")},q.readAsText($),i.current&&(i.current.value="")},C=async()=>{const O=c.filter((q,W)=>u.has(W));if(O.length===0)return;o("importing");let $=0;for(const q of O)try{await a.mutateAsync({first_name:q.first_name,last_name:q.last_name||void 0,email:q.email||void 0,phone:q.phone||void 0,address:q.address||void 0}),$++,y(Math.round($/O.length*100))}catch(W){console.error(`Failed to import ${q.first_name} ${q.last_name}:`,W)}p($),o("done")},T=O=>{h($=>{const q=new Set($);return q.has(O)?q.delete(O):q.add(O),q})},M=()=>{u.size===c.length?h(new Set):h(new Set(c.map((O,$)=>$)))},P=O=>{O||(o("choose"),d([]),h(new Set),p(0),y(0),l==="done"&&n()),t(O)},L=c.filter(O=>O.isDuplicate).length,I=u.size;return e.jsx(Fs,{open:s,onOpenChange:P,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Jy,{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(kr,{children:"Add contacts from your phone directly into Agent OS."})]}),l==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[g&&e.jsxs(B,{onClick:v,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(Jy,{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:[g&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),g&&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:g?"outline":"default",onClick:()=>{var O;return(O=i.current)==null?void 0:O.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(Ja,{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:g?"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"}),!g&&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",L>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",L," already exist)"]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:M,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((O,$)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${O.isDuplicate?"opacity-60":""}`,onClick:()=>T($),children:[e.jsx(wi,{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:[O.first_name," ",O.last_name]}),O.isDuplicate&&e.jsxs(qe,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-amber-500/10 text-amber-600 border-amber-200",children:["Exists (",O.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[O.phone&&e.jsx("div",{children:O.phone}),O.email&&e.jsx("div",{className:"truncate",children:O.email})]})]})]},$))})}),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:C,disabled:I===0,children:["Import ",I," Contact",I!==1?"s":""]})]})]}),l==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(Wt,{className:"h-8 w-8 animate-spin text-primary"}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"font-medium",children:"Importing contacts..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[x,"% complete"]})]}),e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${x}%`}})})]}),l==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-500/10 flex items-center justify-center",children:e.jsx(da,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[m," contact",m!==1?"s":""," imported!"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Your contacts are now in Agent OS and ready for touchpoint plans."})]}),e.jsx(B,{onClick:()=>P(!1),className:"mt-2",children:"Done"})]})]})})}function agn(s){return mt({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function ign(){const{user:s}=Ns();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 U.from("video_share_recipients").select("*").eq("owner_user_id",s.id);if(n)throw n;const r=t;return{totalSent:r.length,totalOpened:r.filter(a=>a.opened_at).length,totalClicked:r.filter(a=>a.clicked_at).length,totalWatched:r.filter(a=>a.watched_at).length,openRate:r.length>0?Math.round(r.filter(a=>a.opened_at).length/r.length*100):0,clickRate:r.length>0?Math.round(r.filter(a=>a.clicked_at).length/r.length*100):0,watchRate:r.length>0?Math.round(r.filter(a=>a.watched_at).length/r.length*100):0}},enabled:!!(s!=null&&s.id)})}function ogn(){const{user:s}=Ns();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 U.from("video_share_recipients").select(` *, agent_videos!inner(id, title, thumbnail_url, share_token, duration_seconds) `).eq("owner_user_id",s.id).order("sent_at",{ascending:!1}).limit(200);if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function pRt(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await U.from("video_share_recipients").insert([{video_id:n.video_id,owner_user_id:s.id,recipient_email:n.recipient_email,recipient_name:n.recipient_name||null,contact_id:n.contact_id||null,sent_via:n.sent_via||"gmail",share_token:"placeholder"}]).select().single();if(a)throw a;return r},onSuccess:n=>{t.invalidateQueries({queryKey:["video-share-recipients",n.video_id]}),t.invalidateQueries({queryKey:["video-share-stats"]}),t.invalidateQueries({queryKey:["video-share-history"]})}})}function fRt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function xRt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const lgn=100;function cgn({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=Hn(),o=ei(),c=pRt(),[d,u]=j.useState([]),[h,m]=j.useState(!1),[p,x]=j.useState(""),[y,g]=j.useState(null),[b,v]=j.useState(""),[k,C]=j.useState(""),[T,M]=j.useState(!1),[P,L]=j.useState({done:0,total:0,failed:0}),I=n.filter(J=>!!J.email),O=n.length-I.length,$=I.length>lgn;j.useEffect(()=>{s&&(g(null),x(""),L({done:0,total:0,failed:0}))},[s]),j.useEffect(()=>{!s||!o||(m(!0),U.from("agent_videos").select("id, title, share_token, thumbnail_url, playback_url, duration_seconds, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:J})=>{u(J||[]),m(!1)}))},[s,o]),j.useEffect(()=>{if(!y)return;const J=y.title||"a quick video";v(`I recorded a video for you — ${J}`),C("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[y]);const q=d.filter(J=>!p||(J.title||"").toLowerCase().includes(p.toLowerCase())),W=(J,le)=>{if(!y)return"";const ue=y.share_token?`https://video.relevelup.com/share/video/${y.share_token}`:"",oe=y.share_token?`https://video.relevelup.com/thumb/${y.share_token}`:y.thumbnail_url||"",ie=y.title||"Video Message",we=k.replace(/\{\{first_name\}\}/gi,J).split(/\n\n+/).map(fe=>`

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

`).join(""),je=le?xRt(le):ue,xe=le?``:"";return`
`},G=async()=>{if(!y)return;M(!0),L({done:0,total:I.length,failed:0});let J=0,le=0;for(const ue of I)try{let oe;try{oe=(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(xe){console.warn("Tracking record failed for",ue.email,xe)}const ie=W(ue.first_name,oe),de=b.replace(/\{\{first_name\}\}/gi,ue.first_name),{data:we,error:je}=await U.functions.invoke("gmail-send",{body:{to:ue.email,subject:de,body:ie,contactId:ue.id}});if(je||!(we!=null&&we.success))throw new Error((we==null?void 0:we.error)||(je==null?void 0:je.message)||"Send failed");J+=1}catch(oe){console.error("Failed to send to",ue.email,oe),le+=1}finally{L({done:J+le,total:I.length,failed:le}),await new Promise(oe=>setTimeout(oe,250))}M(!1),le===0?re.success(`Video sent to ${J} ${J===1?"contact":"contacts"}!`):re.warning(`Sent to ${J}, ${le} failed. Check console for details.`),t(!1),i==null||i()},K=()=>{if(!y)return;const J=W("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:I.map(le=>({email:le.email,name:`${le.first_name} ${le.last_name||""}`.trim()})),initialSubject:b,initialBodyHtml:J}}),t(!1)},ee=!!y&&!!b.trim()&&I.length>0&&($?a:r);return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5 text-primary"}),"Send Video to ",I.length," ",I.length===1?"Contact":"Contacts"]}),e.jsxs(kr,{children:[$?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(jh,{className:"h-3.5 w-3.5"}),I.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(on,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),O>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",O," 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(po,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{children:["Mass Email is not set up yet. Verify a sender address in Integrations → Mass Email before sending to ",I.length," recipients."]})]}),!$&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(po,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsx("div",{children:"Gmail isn't connected. Connect Gmail in Integrations to send videos."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Choose a video"}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(Js,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search your video library...",value:p,onChange:J=>x(J.target.value),className:"pl-10"})]}),e.jsx("div",{className:"max-h-[220px] overflow-y-auto space-y-2 border rounded-md p-2",children:h?e.jsxs(e.Fragment,{children:[e.jsx(gn,{className:"h-14 w-full"}),e.jsx(gn,{className:"h-14 w-full"})]}):q.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:d.length===0?"No videos yet. Record one to get started.":"No videos match your search."}):q.map(J=>{const le=(y==null?void 0:y.id)===J.id;return e.jsxs("button",{type:"button",onClick:()=>g(J),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${le?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"}`,children:[e.jsxs("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden relative",children:[J.thumbnail_url?e.jsx("img",{src:J.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(wh,{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(fd,{className:"h-4 w-4 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:J.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[J.duration_seconds?`${Math.round(J.duration_seconds)}s`:"",J.created_at?` · ${new Date(J.created_at).toLocaleDateString()}`:""]})]})]},J.id)})})]}),e.jsx(Xl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(ye,{id:"bulk-video-subject",value:b,onChange:J=>v(J.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(Ds,{id:"bulk-video-message",value:k,onChange:J=>C(J.target.value),rows:4,className:"resize-y"})]}),T&&P.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",P.done," / ",P.total,P.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",P.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:T,children:"Cancel"}),$?e.jsxs(B,{onClick:K,disabled:!ee,className:"gap-2",children:[e.jsx(jh,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(B,{onClick:G,disabled:!ee||T,className:"gap-2",children:[T?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"}),T?"Sending…":`Send to ${I.length}`]})]})]})]})})}function QJ(){const s=ei();return mt({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("drip_campaigns").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("is_starter",{ascending:!1}).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function dgn(s){return mt({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function ugn(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("drip_campaigns").insert({owner_user_id:s,name:n.name,description:n.description??null,category:n.category??"nurture",icon:n.icon??"🌱",cover_color:n.cover_color??"from-emerald-500 to-teal-600",goal:n.goal??null,is_active:!1}).select().single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function gRt(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("drip_campaigns").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["drip-campaigns"]}),s.invalidateQueries({queryKey:["drip-campaign",n.id]})}})}function hgn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("drip_campaigns").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function wWe(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const[{data:r,error:a},{data:i,error:l}]=await Promise.all([U.from("drip_campaigns").select("*").eq("id",n).single(),U.from("drip_campaign_steps").select("*").eq("campaign_id",n).order("step_order")]);if(a)throw a;if(l)throw l;const{data:o,error:c}=await U.from("drip_campaigns").insert({owner_user_id:s,name:r.name,description:r.description,category:r.category,icon:r.icon,cover_color:r.cover_color,goal:r.goal,is_active:!1,is_starter:!1}).select().single();if(c)throw c;if(i&&i.length>0){const d=i.map(h=>({campaign_id:o.id,step_order:h.step_order,channel:h.channel,subject:h.subject,body:h.body,video_url:h.video_url,delay_type:h.delay_type,delay_days:h.delay_days,delay_hours:h.delay_hours,anchor_field:h.anchor_field,anchor_offset_days:h.anchor_offset_days,send_window_start:h.send_window_start,send_window_end:h.send_window_end})),{error:u}=await U.from("drip_campaign_steps").insert(d);if(u)throw u}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function yRt(s){return mt({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function mgn(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("drip_campaign_steps").insert({campaign_id:t.campaign_id,step_order:t.step_order,channel:t.channel??"email",subject:t.subject??"",body:t.body??"",video_url:t.video_url??null,delay_type:t.delay_type??"relative",delay_days:t.delay_days??0,delay_hours:t.delay_hours??0,anchor_field:t.anchor_field??null,anchor_offset_days:t.anchor_offset_days??0}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["drip-campaign-steps",n.campaign_id]})})}function pgn(){const s=as();return vt({mutationFn:async({id:t,campaign_id:n,...r})=>{const{data:a,error:i}=await U.from("drip_campaign_steps").update(r).eq("id",t).select().single();if(i)throw i;return{data:a,campaign_id:n}},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t.campaign_id]})})}function fgn(){const s=as();return vt({mutationFn:async({id:t,campaign_id:n})=>{const{error:r}=await U.from("drip_campaign_steps").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function xgn(s){return mt({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("drip_campaign_enrollments").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("campaign_id",s).order("enrolled_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function ggn(s){return mt({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:n}=await U.from("drip_campaign_enrollments").select("id",{count:"exact",head:!0}).eq("campaign_id",s).eq("status","active");if(n)throw n;return t??0},enabled:!!s,staleTime:3e4})}function vRt(){const s=as();return vt({mutationFn:async({campaignId:t,contactIds:n})=>{const{data:r,error:a}=await U.functions.invoke("enroll-contacts-in-campaign",{body:{campaign_id:t,contact_ids:n}});if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}function ygn(){const s=as();return vt({mutationFn:async({id:t,status:n})=>{const r={status:n};n==="paused"&&(r.paused_at=new Date().toISOString()),n==="exited"&&(r.exited_at=new Date().toISOString(),r.exit_reason="manual");const{data:a,error:i}=await U.from("drip_campaign_enrollments").update(r).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}const vgn=[{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"}],IAe={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"},bgn={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 _gn({open:s,onOpenChange:t,subject:n,body:r,ownerUserId:a,stepLabel:i}){const[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState("desktop"),[x,y]=j.useState(""),[g,b]=j.useState(!1);j.useEffect(()=>{if(!s)return;let k=!1;return(async()=>{var C,T;o(!0);try{const{data:M}=await U.auth.getSession();x||y(((T=(C=M==null?void 0:M.session)==null?void 0:C.user)==null?void 0:T.email)||"");const{data:P,error:L}=await U.functions.invoke("process-drip-campaigns",{body:{action:"preview",subject:n,body:r,owner_user_id:a||void 0}});if(L)throw L;if(k)return;d((P==null?void 0:P.html)||""),h((P==null?void 0:P.subject)||n)}catch{k||re.error("Could not build preview")}finally{k||o(!1)}})(),()=>{k=!0}},[s,n,r,a]);const v=async()=>{if(x.trim()){b(!0);try{const{data:k,error:C}=await U.functions.invoke("process-drip-campaigns",{body:{action:"test_send",subject:n,body:r,to:x.trim(),owner_user_id:a||void 0}});if(C)throw C;k!=null&&k.success?re.success(`Test email sent to ${x.trim()}`):re.error((k==null?void 0:k.error)||"Could not send test email",{duration:1e4})}catch{re.error("Could not send test email")}finally{b(!1)}}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-3xl max-h-[92vh] flex flex-col p-0 gap-0",children:[e.jsxs($s,{className:"p-5 pb-3 border-b shrink-0",children:[e.jsxs(zs,{children:["Email preview",i?` — ${i}`:""]}),e.jsx(kr,{children:"Exactly how this email will look when it sends, with sample contact details filled in."})]}),e.jsxs("div",{className:"px-5 py-3 border-b shrink-0 space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Subject"}),e.jsx("div",{className:"text-sm font-medium",children:u||n||"(no subject)"}),e.jsxs("div",{className:"flex items-center gap-1.5 pt-1",children:[e.jsxs(B,{variant:m==="desktop"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("desktop"),children:[e.jsx(Cj,{className:"h-3.5 w-3.5 mr-1"})," Desktop"]}),e.jsxs(B,{variant:m==="mobile"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("mobile"),children:[e.jsx(Jy,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"})," Building preview…"]}):e.jsx("div",{className:"mx-auto bg-background rounded-lg overflow-hidden border",style:{maxWidth:m==="mobile"?390:"100%"},children:e.jsx("iframe",{title:"Email preview",srcDoc:c,sandbox:"",className:"w-full",style:{height:620,border:0,background:"#fff"}})})}),e.jsxs("div",{className:"border-t p-4 shrink-0 flex flex-col sm:flex-row sm:items-end gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Send a test to"}),e.jsx(ye,{type:"email",value:x,onChange:k=>y(k.target.value),placeholder:"you@email.com",className:"h-9",onKeyDown:k=>k.key==="Enter"&&v()})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(B,{onClick:v,disabled:g||!x.trim(),children:[g?e.jsx(Wt,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4 mr-1.5"}),"Send test"]})]})]})]})})}function LO({userId:s,onSelect:t,onSelectVideo:n,triggerLabel:r="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=j.useState(!1),[d,u]=j.useState([]),[h,m]=j.useState(!1),[p,x]=j.useState("");j.useEffect(()=>{!o||!s||(m(!0),U.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, created_at, duration_seconds").eq("owner_user_id",s).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:g})=>{u(g||[]),m(!1)}))},[o,s]);const y=d.filter(g=>!p||(g.title||g.recipient_name||"").toLowerCase().includes(p.toLowerCase()));return e.jsxs(Fs,{open:o,onOpenChange:c,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(wh,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(Os,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Select from Video Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a video from your library"})]}),e.jsxs("div",{className:"relative mb-3",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search videos...",value:p,onChange:g=>x(g.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(gn,{className:"h-16 w-full"}),e.jsx(gn,{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(g=>e.jsxs("button",{onClick:()=>{t(g.playback_url||""),n==null||n(g),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:g.thumbnail_url?e.jsx("img",{src:g.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:b=>{const v=b.currentTarget.parentElement;if(v){b.currentTarget.remove();const k=document.createElement("span");k.innerHTML="🎬",k.className="text-lg",v.appendChild(k)}}}):e.jsx(Zr,{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:g.title||g.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.duration_seconds?`${Math.round(g.duration_seconds)}s`:"",g.created_at?` · ${new Date(g.created_at).toLocaleDateString()}`:""]})]})]},g.id))})]})]})}function wgn(){return mt({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await U.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function jgn(s){return mt({queryKey:["video-scripts",s],queryFn:async()=>{let t=U.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:n,error:r}=await t;if(r)throw r;return n}})}function Ngn(){const{user:s}=Ns();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 U.from("user_video_scripts").select("*, category:video_script_categories(*)").eq("owner_user_id",s.id).order("title");if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function kgn(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await U.from("user_video_scripts").insert([{owner_user_id:s.id,source_script_id:n.id,category_id:n.category_id,title:n.title,script_text:n.script_text,tags:n.tags,is_custom:!1}]).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["user-video-scripts"]})}})}function Sgn(s){const{user:t}=Ns();return mt({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let n=U.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("owner_user_id",t.id).order("created_at",{ascending:!1});n=n.eq("is_deleted",!1);const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!(t!=null&&t.id)})}function Cgn(s){return mt({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:n}=await U.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function hS(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await U.from("agent_videos").insert([{owner_user_id:s.id,contact_id:n.contact_id,bunny_video_id:n.bunny_video_id,playback_url:n.playback_url,thumbnail_url:n.thumbnail_url,preview_url:n.preview_url,duration_seconds:n.duration_seconds,file_size_mb:n.file_size_mb||0,title:n.title,notes:n.notes,task_id:n.task_id,status:n.status||"processing",touch_type:n.touch_type||"video",page_template:"default",category:n.category||"general"}]).select("*, share_token").single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-videos"]}),t.invalidateQueries({queryKey:["storage-usage"]})}})}function Agn(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("agent_videos").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["agent-video",t.id]})}})}function Tgn(){const s=as();return vt({mutationFn:async({id:t,bunnyVideoId:n,hardDelete:r=!1})=>{if(console.log("Deleting video:",{id:t,bunnyVideoId:n,hardDelete:r}),n){console.log("Calling bunny-upload delete for videoId:",n);const{data:a,error:i}=await U.functions.invoke("bunny-upload",{body:{action:"delete",videoId:n,isAgentVideo:!0}});i?console.error("Failed to delete from Bunny:",i):console.log("Bunny delete response:",a)}else console.warn("No bunnyVideoId provided, skipping Bunny.net deletion");if(r){console.log("Hard deleting from database:",t);const{error:a}=await U.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await U.from("agent_videos").update({is_deleted:!0}).eq("id",t);if(a)throw a}console.log("Video deletion complete")},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["storage-usage"]})}})}function RAe(){const{user:s}=Ns();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 U.from("agent_storage_usage").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t||{user_id:s.id,total_storage_mb:0,storage_tier:"basic",max_storage_mb:1024}},enabled:!!(s!=null&&s.id)})}function bRt(){const{data:s,isLoading:t}=RAe(),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 w6(s){const{data:t,error:n}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(n)throw n;return t}async function j6(s){const{data:t,error:n}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}async function $j(s){const{data:t,error:n}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}function Egn(){const{user:s}=Ns(),t=as();return vt({mutationFn:async({contactId:n,videoId:r,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await U.from("action_types").select("id").eq("name","Video").single();if(!i)throw new Error("Video action type not found");const{data:l,error:o}=await U.from("contact_touch_logs").insert([{owner_user_id:s.id,contact_id:n,action_type_id:i.id,notes:a||`Quick Video Touch - Video ID: ${r}`}]).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts"]})}})}function _Rt({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=av(),{data:a}=RAe(),i=hS(),l=j.useRef(null),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(""),[y,g]=j.useState(!1),[b,v]=j.useState(0),[k,C]=j.useState("idle"),T=(a==null?void 0:a.total_storage_mb)||0,P=((a==null?void 0:a.max_storage_mb)||1024)-T,L=q=>{var K;const W=(K=q.target.files)==null?void 0:K[0];if(!W)return;if(!W.type.startsWith("video/")){re.error("Please select a video file");return}const G=W.size/(1024*1024);if(G>500){re.error("Video file must be less than 500MB");return}if(G>P){re.error(`Not enough storage. You have ${P.toFixed(1)} MB remaining.`);return}c(W),d||u(W.name.replace(/\.[^/.]+$/,""))},I=async()=>{if(!o){re.error("Please select a video file");return}g(!0),v(0),C("creating");try{const{data:q,error:W}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(W)throw new Error(W.message);const{videoId:G,libraryId:K}=q;C("uploading");const{data:ee,error:J}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:G,isAgentVideo:!0}});if(J)throw new Error(J.message);await new Promise((oe,ie)=>{const de=new XMLHttpRequest;de.upload.addEventListener("progress",we=>{if(we.lengthComputable){const je=Math.round(we.loaded/we.total*100);v(je)}}),de.addEventListener("load",()=>{de.status>=200&&de.status<300?oe():ie(new Error(`Upload failed with status ${de.status}`))}),de.addEventListener("error",()=>ie(new Error("Upload failed"))),de.open("PUT",ee.uploadUrl),de.setRequestHeader("AccessKey",ee.apiKey),de.send(o)}),C("processing");const le=o.size/(1024*1024),ue=`https://iframe.mediadelivery.net/embed/${K}/${G}`;await i.mutateAsync({bunny_video_id:G,playback_url:ue,file_size_mb:le,title:d||o.name,notes:h||void 0,contact_id:p||void 0,status:"processing",touch_type:"video_upload"}),re.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(ue),O()}catch(q){console.error("Upload error:",q),re.error(q instanceof Error?q.message:"Failed to upload video")}finally{g(!1),C("idle")}},O=()=>{y||(c(null),u(""),m(""),x(""),v(0),C("idle"),t(!1))},$=()=>{switch(k){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${b}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(Fs,{open:s,onOpenChange:O,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Upload Video"}),e.jsx(kr,{children:"Upload a video file from your device to your video library."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(Zr,{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:q=>{q.stopPropagation(),c(null)},children:e.jsx(dr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"border-2 border-dashed border-muted-foreground/25 rounded-lg p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",onClick:()=>{var q;return(q=l.current)==null?void 0:q.click()},children:[e.jsx(Ja,{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:L,disabled:y})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",value:d,onChange:q=>u(q.target.value),placeholder:"Enter video title",disabled:y})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Associate with Contact (optional)"}),e.jsxs(vs,{value:p||"__none__",onValueChange:q=>x(q==="__none__"?"":q),disabled:y,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a contact"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"__none__",children:"No contact"}),r==null?void 0:r.map(q=>e.jsxs(Je,{value:q.id,children:[q.first_name," ",q.last_name||""]},q.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(Ds,{id:"notes",value:h,onChange:q=>m(q.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(Wt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:$()})]}),e.jsx(qi,{value:k==="uploading"?b:k==="processing"?100:10})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:O,disabled:y,children:"Cancel"}),e.jsx(B,{onClick:I,disabled:!o||y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const Mgn=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],Lgn={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},Dmt=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=>Lgn[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function wRt({open:s,onOpenChange:t,campaignId:n}){const[r,a]=j.useState(n??null),[i,l]=j.useState("details");j.useEffect(()=>{a(n??null),l("details")},[n,s]);const o=r,c=!!o,{data:d}=dgn(o||void 0),{data:u,isLoading:h}=yRt(o||void 0),m=ugn(),p=gRt(),x=mgn(),[y,g]=j.useState(""),[b,v]=j.useState(""),[k,C]=j.useState("nurture"),[T,M]=j.useState("🌱"),[P,L]=j.useState("");j.useEffect(()=>{d?(g(d.name),v(d.description||""),C(d.category),M(d.icon),L(d.goal||"")):c||(g(""),v(""),C("nurture"),M("🌱"),L(""))},[d,c,s]);const I=bgn[k],O=async()=>{if(!y.trim()){re.error("Give your campaign a name");return}try{if(c&&o)await p.mutateAsync({id:o,name:y,description:b,category:k,icon:T,goal:P,cover_color:I}),re.success("Campaign updated");else{const q=await m.mutateAsync({name:y,description:b,category:k,icon:T,goal:P,cover_color:I});return re.success("Campaign created — now add your first step!"),a(q.id),l("steps"),q}}catch(q){re.error(q.message||"Failed to save")}},$=async()=>{if(!o){re.error("Save the campaign first, then add steps");return}const q=((u==null?void 0:u.length)||0)+1;try{await x.mutateAsync({campaign_id:o,step_order:q,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:q===1?0:2,delay_hours:0})}catch{re.error("Failed to add step")}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${I} p-5 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-4xl drop-shadow-sm",children:T}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(zs,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(kr,{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(fa,{value:i,onValueChange:q=>l(q),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(xa,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(ss,{value:"details",children:"Details"}),e.jsxs(ss,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx(qe,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(ns,{value:"details",className:"flex-1 overflow-y-auto overscroll-contain mt-0 min-h-0 data-[state=inactive]:hidden",children:e.jsx("div",{children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Campaign Name *"}),e.jsx(ye,{value:y,onChange:q=>g(q.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Description"}),e.jsx(Ds,{value:b,onChange:q=>v(q.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Goal (optional)"}),e.jsx(ye,{value:P,onChange:q=>L(q.target.value),placeholder:"e.g. Book a buyer consultation within 14 days",className:"mt-1"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Category"}),e.jsxs(vs,{value:k,onValueChange:q=>C(q),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:Object.entries(IAe).map(([q,W])=>e.jsx(Je,{value:q,children:W},q))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:Mgn.map(q=>e.jsx("button",{type:"button",onClick:()=>M(q),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${T===q?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:q},q))})]})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:c?"Save changes, then jump to the Steps tab to manage your sequence.":"Save to create the campaign, then you can add steps to it."})})]})})}),e.jsx(ns,{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(yn,{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:x.isPending,children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((q,W)=>e.jsx(Pgn,{step:q,index:W,totalSteps:u.length},q.id)),e.jsxs(B,{variant:"outline",size:"sm",onClick:$,disabled:x.isPending,className:"w-full",children:[x.isPending?e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Js,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(Nr,{className:"border-t p-4 shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(B,{onClick:O,disabled:m.isPending||p.isPending,children:[(m.isPending||p.isPending)&&e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function Pgn({step:s,index:t,totalSteps:n}){const r=pgn(),a=fgn(),i=ei(),[l,o]=j.useState(!1),[c,d]=j.useState(()=>({...s,body:Dmt(s.body)})),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[x,y]=j.useState(""),[g,b]=j.useState(!1),[v,k]=j.useState(!1);j.useEffect(()=>{d({...s,body:Dmt(s.body)})},[s]);const C=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}),re.success(`Step ${t+1} saved`)}catch{re.error("Failed to save step")}finally{h(!1)}},M=async()=>{if(await Bi(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),re.success("Step deleted")}catch{re.error("Failed to delete")}},P=I=>{d({...c,body:c.body+I})},L=()=>{if(c.delay_type==="calendar_anchor"){const O=c.anchor_field==="birthday"?"birthday":"home anniversary",$=c.anchor_offset_days||0;return $===0?`On their ${O}`:$<0?`${Math.abs($)}d before ${O}`:`${$}d after ${O}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const I=[];return c.delay_days&&I.push(`${c.delay_days}d`),c.delay_hours&&I.push(`${c.delay_hours}h`),t===0?`After ${I.join(" ")||"0"}`:`+${I.join(" ")||"0"}`};return e.jsxs("div",{className:"border rounded-lg bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 hover:bg-muted/30 cursor-pointer",onClick:()=>o(!l),children:[e.jsx("div",{className:"h-7 w-7 shrink-0 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:t+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[c.delay_type==="calendar_anchor"?e.jsx(ra,{className:"h-3 w-3"}):e.jsx(Vr,{className:"h-3 w-3"}),e.jsx("span",{children:L()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(on,{className:"h-3 w-3"}):e.jsx(ro,{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(Qy,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Po,{className:"h-4 w-4 text-muted-foreground"})]}),l&&e.jsxs("div",{className:"border-t p-4 space-y-3 bg-muted/10",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Channel"}),e.jsxs(vs,{value:c.channel,onValueChange:I=>d({...c,channel:I}),children:[e.jsx(gs,{className:"mt-1 h-9",children:e.jsx(bs,{})}),e.jsx(ys,{children:e.jsx(Je,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Timing Type"}),e.jsxs(vs,{value:c.delay_type,onValueChange:I=>d({...c,delay_type:I}),children:[e.jsx(gs,{className:"mt-1 h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"relative",children:"⏱ Relative delay"}),e.jsx(Je,{value:"calendar_anchor",children:"📅 Calendar date"})]})]})]})]}),c.delay_type==="relative"?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Days delay"}),e.jsx(ye,{type:"number",min:0,value:c.delay_days,onChange:I=>d({...c,delay_days:parseInt(I.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Hours delay"}),e.jsx(ye,{type:"number",min:0,max:23,value:c.delay_hours,onChange:I=>d({...c,delay_hours:parseInt(I.target.value)||0}),className:"mt-1 h-9"})]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Anchor"}),e.jsxs(vs,{value:c.anchor_field||"birthday",onValueChange:I=>d({...c,anchor_field:I}),children:[e.jsx(gs,{className:"mt-1 h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"birthday",children:"🎂 Birthday"}),e.jsx(Je,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(ye,{type:"number",value:c.anchor_offset_days||0,onChange:I=>d({...c,anchor_offset_days:parseInt(I.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject Line"}),e.jsx(ye,{value:c.subject,onChange:I=>d({...c,subject:I.target.value}),placeholder:"e.g. Quick question about your home search, {{client_first_name}}",className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(se,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(Ds,{value:c.body,onChange:I=>d({...c,body:I.target.value}),placeholder:`Hi {{client_first_name}}, I wanted to reach out and...`,rows:6,className:"mt-1 font-mono text-xs"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground mr-1",children:"Insert:"}),vgn.map(I=>e.jsx("button",{type:"button",onClick:()=>P(I.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:I.label},I.key))]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Video (optional)"}),c.video_url?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:[e.jsx(Zr,{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(LO,{userId:i||void 0,onSelect:I=>d({...c,video_url:I}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>b(!0),children:[e.jsx(Ja,{className:"h-3 w-3"})," Upload"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{y(""),p(!0)},children:[e.jsx(vc,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(_Rt,{open:g,onOpenChange:b,onUploadComplete:I=>d({...c,video_url:I})}),e.jsx(Fs,{open:m,onOpenChange:p,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Add video URL"}),e.jsx(kr,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(ye,{value:x,onChange:I=>y(I.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:I=>{I.key==="Enter"&&x.trim()&&(d({...c,video_url:x.trim()}),p(!1))}}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx(B,{disabled:!x.trim(),onClick:()=>{d({...c,video_url:x.trim()}),p(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:M,className:"text-destructive hover:text-destructive",children:[e.jsx(Rn,{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(ma,{className:"h-3.5 w-3.5 mr-1.5"})," Preview"]}),e.jsxs(B,{size:"sm",onClick:T,disabled:!C||u,children:[u&&e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]}),e.jsx(_gn,{open:v,onOpenChange:k,subject:c.subject||"",body:c.body||"",ownerUserId:i,stepLabel:`Step ${t+1}`})]})]})}function Ign({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=QJ(),l=vRt(),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(!1),p=(a||[]).filter(g=>!g.is_starter),x=p.filter(g=>g.name.toLowerCase().includes(o.toLowerCase())||(g.description||"").toLowerCase().includes(o.toLowerCase())),y=async()=>{if(d)try{const g=await l.mutateAsync({campaignId:d,contactIds:n}),b=[`${g.enrolled} enrolled`];g.skipped>0&&b.push(`${g.skipped} skipped`),g.errors>0&&b.push(`${g.errors} errors`),re.success(b.join(" · ")),t(!1),u(null),r==null||r()}catch(g){re.error(g.message||"Failed to enroll contacts")}};return e.jsxs(Fs,{open:s,onOpenChange:t,children:[e.jsxs(Os,{className:"max-w-md",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(kr,{children:[n.length," contact",n.length!==1?"s":""," will be added to the selected campaign. Already-enrolled contacts will be skipped."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search campaigns...",value:o,onChange:g=>c(g.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..."}):x.length===0?e.jsx("div",{className:"text-center py-8",children:p.length===0?e.jsxs(e.Fragment,{children:[e.jsx(yn,{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(Js,{className:"h-3.5 w-3.5 mr-1.5"})," Create campaign"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No campaigns match your search."})}):e.jsx("div",{className:"space-y-1.5",children:x.map(g=>e.jsxs("button",{onClick:()=>u(g.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===g.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 ${g.cover_color} flex items-center justify-center text-lg`,children:g.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:g.name}),g.is_active&&e.jsx(qe,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),g.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:g.description})]}),d===g.id&&e.jsx(da,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},g.id))})})]}),e.jsxs(Nr,{className:"gap-2 sm:gap-2",children:[p.length>0&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"mr-auto text-xs",children:[e.jsx(Js,{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(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(wRt,{open:h,onOpenChange:m})]})}function Rgn({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=Hn(),{data:c}=lw(),d=wVe(),u=as(),{isGmailConnected:h}=Tf(),{isReady:m}=Cq(),{data:p}=Aq(),x=yWe(),y=oRt(),[g,b]=j.useState(!1),[v,k]=j.useState(!1),[C,T]=j.useState(!1),[M,P]=j.useState(!1),[L,I]=j.useState(!1),[O,$]=j.useState(""),q=s.size;if(q===0)return null;const W=async oe=>{b(!0);try{const de=Array.from(s).map(je=>({contact_id:je,relationship_type_id:oe})),{error:we}=await U.from("innercircle_contact_tags").upsert(de,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(we)throw we;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ba({title:`Assigned type to ${q} contacts`}),n()}catch(ie){ba({title:"Error assigning type",description:ie.message,variant:"destructive"})}finally{b(!1)}},G=async oe=>{b(!0);try{const ie=Array.from(s);for(const de of ie)try{await y.mutateAsync({contactId:de,tagId:oe})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),ba({title:`Tagged ${q} contacts`}),I(!1),$("")}catch(ie){ba({title:"Error adding tags",description:ie.message,variant:"destructive"})}finally{b(!1)}},K=async()=>{if(O.trim()){b(!0);try{const oe=await x.mutateAsync({name:O.trim()});await G(oe.id)}catch(oe){ba({title:"Error creating tag",description:oe.message,variant:"destructive"}),b(!1)}}},ee=(p==null?void 0:p.filter(oe=>oe.name.toLowerCase().includes(O.toLowerCase())))||[],J=p==null?void 0:p.find(oe=>oe.name.toLowerCase()===O.trim().toLowerCase()),le=()=>{const oe=t.filter(Se=>s.has(Se.id)),ie=["First Name","Last Name","Email","Phone","Address","Birthday","Home Anniversary","Notes","Relationship Types"],de=oe.map(Se=>{var Ee;return[Se.first_name,Se.last_name||"",Se.email||"",Se.phone||"",Se.address||"",Se.birthday||"",Se.home_anniversary||"",Se.notes||"",((Ee=Se.tags)==null?void 0:Ee.map(Le=>{var De;return(De=Le.relationship_type)==null?void 0:De.name}).join("; "))||""]}),we=[ie.join(","),...de.map(Se=>Se.map(Ee=>`"${(Ee||"").replace(/"/g,'""')}"`).join(","))].join(` `),je=new Blob([we],{type:"text/csv"}),xe=URL.createObjectURL(je),fe=document.createElement("a");fe.href=xe,fe.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,fe.click(),URL.revokeObjectURL(xe),ba({title:`Exported ${q} contacts`})},ue=async()=>{if(await Bi(`Are you sure you want to delete ${q} contacts? This cannot be undone.`)){b(!0);try{const oe=Array.from(s);for(const ie of oe)await d.mutateAsync(ie);n()}catch(oe){ba({title:"Error deleting contacts",description:oe.message,variant:"destructive"})}finally{b(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-primary/5 border border-primary/20 rounded-lg",children:[e.jsxs(qe,{variant:"secondary",className:"font-semibold",children:[q," selected"]}),e.jsxs(vs,{onValueChange:W,disabled:g,children:[e.jsx(gs,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(wf,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(ys,{children:c==null?void 0:c.filter(oe=>oe.active).map(oe=>e.jsx(Je,{value:oe.id,children:oe.name},oe.id))})]}),e.jsxs(lc,{open:L,onOpenChange:I,children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",disabled:g,children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(Jl,{className:"w-56 p-2",align:"start",children:[e.jsx(ye,{placeholder:"Search or create tag...",value:O,onChange:oe=>$(oe.target.value),onKeyDown:oe=>{oe.key==="Enter"&&O.trim()&&!J?(oe.preventDefault(),K()):oe.key==="Enter"&&J&&(oe.preventDefault(),G(J.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[ee.map(oe=>e.jsxs("button",{onClick:()=>G(oe.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:oe.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:oe.name})]},oe.id)),O.trim()&&!J&&e.jsxs("button",{onClick:K,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(Js,{className:"h-3.5 w-3.5"}),'Create "',O.trim(),'"']}),ee.length===0&&!O.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:g,children:[e.jsx(on,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),m&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{const oe=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${oe}`)},disabled:g,children:[e.jsx(jh,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>T(!0),disabled:g,children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>P(!0),disabled:g,children:[e.jsx(yn,{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:g,children:[e.jsx(mN,{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:g,children:[e.jsx(M5,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:le,disabled:g,children:[e.jsx(ii,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ue,disabled:g,className:"text-destructive hover:text-destructive",children:[e.jsx(Rn,{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(dr,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(Ign,{open:M,onOpenChange:P,contactIds:Array.from(s),onSuccess:n}),e.jsx(cw,{open:v,onOpenChange:k,bulkContacts:Array.from(s).map(oe=>{const ie=t.find(de=>de.id===oe);return ie?{id:ie.id,first_name:ie.first_name,last_name:ie.last_name,email:ie.email||""}:null}).filter(oe=>oe!==null&&oe.email!==""),onSendComplete:()=>{k(!1),n()}}),e.jsx(cgn,{open:C,onOpenChange:T,contacts:Array.from(s).map(oe=>t.find(ie=>ie.id===oe)).filter(oe=>!!oe).map(oe=>({id:oe.id,first_name:oe.first_name,last_name:oe.last_name,email:oe.email})),isGmailConnected:!!h,isMassEmailReady:!!m,onSendComplete:()=>{T(!1),n()}})]})}function Omt({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=Hn(),{isReady:d}=Cq(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(Hy,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(wa,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(pa,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(wa,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(wa,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(oi,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(wa,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(wa,{onClick:()=>r(s.id,u),children:[e.jsx(ay,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(wa,{onClick:()=>a(s.id),children:[e.jsx(mN,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(wa,{onClick:()=>l(s.id),children:[e.jsx(M5,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(wa,{onClick:()=>t(s),children:[e.jsx(Za,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(wa,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function Fmt({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=vWe(),a=lRt(),i=cRt(),[l,o]=j.useState(!1),[c,d]=j.useState(""),u=s.search||s.type&&s.type!=="all"||s.status&&s.status!=="all"||s.behavior&&Object.values(s.behavior).some(m=>m!==void 0&&m!==!1),h=async()=>{c.trim()&&(await a.mutateAsync({name:c.trim(),filters:s,sort_by:t}),d(""),o(!1))};return e.jsxs(e.Fragment,{children:[e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Nj,{className:"h-3.5 w-3.5"}),"Smart Filters",r&&r.length>0&&e.jsx(qe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r.length}),e.jsx(Po,{className:"h-3.5 w-3.5"})]})}),e.jsxs(xd,{align:"start",className:"w-56",children:[r&&r.length>0?e.jsxs(e.Fragment,{children:[r.map(m=>e.jsxs(wa,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>n(m.filters,m.sort_by),children:m.name}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:p=>{p.stopPropagation(),i.mutate(m.id)},children:e.jsx(Rn,{className:"h-3 w-3 text-destructive"})})]},m.id)),e.jsx(uy,{})]}):e.jsx(wa,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(wa,{onClick:()=>o(!0),children:[e.jsx($T,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(Fs,{open:l,onOpenChange:o,children:e.jsxs(Os,{className:"max-w-sm",children:[e.jsx($s,{children:e.jsx(zs,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ye,{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 iSe=[{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"}],jRt=[{value:"home_anniversary",label:"Home anniversary"},{value:"wedding_anniversary",label:"Wedding anniversary"}],Dgn=[{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 Ogn({open:s,onOpenChange:t,hasLeadSite:n,behavior:r,onApply:a,selectedType:i,onSelectedTypeChange:l,relationshipTypes:o}){const[c,d]=j.useState(r),[u,h]=j.useState(n?"behavior":"contact"),{data:m}=gO();j.useEffect(()=>{s&&d(r)},[s,r]);const p=y=>d(g=>({...g,...y})),x=Object.entries(c).filter(([,y])=>y!==void 0&&y!==!1&&y!=="").length;return e.jsx(v1,{open:s,onOpenChange:t,children:e.jsxs(rv,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(Lb,{children:[e.jsxs(Pb,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(vJ,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(fa,{value:u,onValueChange:y=>h(y),className:"mt-4",children:[e.jsxs(xa,{className:"grid w-full grid-cols-3",children:[e.jsxs(ss,{value:"contact",className:"gap-1.5",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(ss,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(vf,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(ss,{value:"engagement",children:"Engagement"})]}),e.jsxs(ns,{value:"contact",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contact Type"}),e.jsxs(vs,{value:i,onValueChange:l,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"All types"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Types"}),o==null?void 0:o.map(y=>e.jsx(Je,{value:y.id,children:y.name},y.id))]})]})]}),e.jsxs(JS,{title:"Contact Info Present",children:[e.jsx(Ty,{label:"Has email",checked:c.hasEmail===!0,onChange:y=>p({hasEmail:y||void 0})}),e.jsx(Ty,{label:"Has phone",checked:c.hasPhone===!0,onChange:y=>p({hasPhone:y||void 0})}),e.jsx(Ty,{label:"Has address",checked:c.hasAddress===!0,onChange:y=>p({hasAddress:y||void 0})}),e.jsx(Ty,{label:"Has birthday",checked:c.hasBirthday===!0,onChange:y=>p({hasBirthday:y||void 0})}),e.jsx(Ty,{label:"Has spouse",checked:c.hasSpouse===!0,onChange:y=>p({hasSpouse:y||void 0})}),e.jsx(Ty,{label:"Has company / job",checked:c.hasCompany===!0,onChange:y=>p({hasCompany:y||void 0})}),e.jsx(Ty,{label:"Has notes",checked:c.hasNotes===!0,onChange:y=>p({hasNotes:y||void 0})})]}),e.jsxs(JS,{title:"Location",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(YPe,{label:"City",value:c.city||"",onChange:y=>p({city:y||void 0}),placeholder:"Any city"}),e.jsx(YPe,{label:"State",value:c.state||"",onChange:y=>p({state:y||void 0}),placeholder:"Any state"})]}),e.jsx(YPe,{label:"ZIP / Postal",value:c.zip||"",onChange:y=>p({zip:y||void 0}),placeholder:"Any ZIP"})]}),e.jsxs(JS,{title:"Important Dates",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Birthday month"}),e.jsxs(vs,{value:c.birthdayMonth?String(c.birthdayMonth):"all",onValueChange:y=>p({birthdayMonth:y==="all"?void 0:Number(y)}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Any month"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"Any month"}),iSe.map(y=>e.jsx(Je,{value:String(y.value),children:y.label},y.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Anniversary month"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsxs(vs,{value:c.anniversaryField||"home_anniversary",onValueChange:y=>p({anniversaryField:y}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Field"})}),e.jsx(ys,{children:jRt.map(y=>e.jsx(Je,{value:y.value,children:y.label},y.value))})]}),e.jsxs(vs,{value:c.anniversaryMonth?String(c.anniversaryMonth):"all",onValueChange:y=>p({anniversaryMonth:y==="all"?void 0:Number(y)}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Any month"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"Any month"}),iSe.map(y=>e.jsx(Je,{value:String(y.value),children:y.label},y.value))]})]})]})]})]}),e.jsx(JS,{title:"Date Added",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(zmt,{label:"From",value:c.dateAddedFrom,onChange:y=>p({dateAddedFrom:y||void 0})}),e.jsx(zmt,{label:"To",value:c.dateAddedTo,onChange:y=>p({dateAddedTo:y||void 0})})]})}),e.jsx(JS,{title:"Lead Source",children:e.jsxs(vs,{value:c.leadSourceId||"all",onValueChange:y=>p({leadSourceId:y==="all"?void 0:y}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"All sources"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All sources"}),e.jsx(Je,{value:"none",children:"No source"}),m==null?void 0:m.map(y=>e.jsx(Je,{value:y.id,children:y.name},y.id))]})]})})]}),e.jsx(ns,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(JS,{title:"Last Active On Site",children:[e.jsx(ob,{value:c.lastActive||"",onValueChange:y=>p({lastActive:y||void 0}),className:"grid grid-cols-2 gap-2",children:Dgn.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(eh,{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:()=>p({lastActive:void 0}),children:"Clear"})]}),e.jsxs(JS,{title:"Registration",children:[e.jsx(Ty,{label:"Registered on lead site",checked:c.registered==="yes",onChange:y=>p({registered:y?"yes":void 0})}),e.jsx(Ty,{label:"Anonymous visitors only",checked:c.registered==="no",onChange:y=>p({registered:y?"no":void 0})})]}),e.jsxs(JS,{title:"Property Activity",children:[e.jsx(Ty,{label:"Viewed any listing",checked:c.viewedListing==="any",onChange:y=>p({viewedListing:y?"any":void 0})}),e.jsx(Ty,{label:"Hot buyer — 3+ views in last 7 days",checked:c.viewedListing==="multiple7d",onChange:y=>p({viewedListing:y?"multiple7d":void 0})}),e.jsx(Ty,{label:"Saved a property",checked:!!c.savedProperty,onChange:y=>p({savedProperty:y||void 0})}),e.jsx(Ty,{label:"Has an active saved search / alert",checked:!!c.hasSavedSearch,onChange:y=>p({hasSavedSearch:y||void 0})})]}),e.jsxs(JS,{title:"Requests",children:[e.jsx(Ty,{label:"Requested a showing / asked a question",checked:!!c.requestedShowing,onChange:y=>p({requestedShowing:y||void 0})}),e.jsx(Ty,{label:"Requested a home valuation",checked:!!c.requestedValuation,onChange:y=>p({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(ns,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(Ty,{label:"Any website activity",checked:!!c.websiteActiveOnly,onChange:y=>p({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(fSt,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx(B,{variant:"ghost",onClick:()=>d({}),disabled:x===0,children:"Clear behavior filters"}),e.jsx(B,{onClick:()=>{a(c),t(!1)},children:"Apply"})]})]})})}function JS({title:s,children:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"space-y-2",children:t})]})}function Ty({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(Mn,{checked:t,onCheckedChange:n})]})}function YPe({label:s,value:t,onChange:n,placeholder:r}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{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(dr,{className:"h-3 w-3"})})]})]})}function zmt({label:s,value:t,onChange:n}){const[r,a]=j.useState(!1),i=t?Ep(t):void 0;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs(lc,{open:r,onOpenChange:a,children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal h-8",!i&&"text-muted-foreground"),children:[e.jsx(ra,{className:"mr-2 h-3.5 w-3.5"}),i?Bs(i,"MMM d, yyyy"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Jl,{className:"w-auto p-0",align:"start",children:e.jsx(o1,{mode:"single",selected:i,onSelect:l=>{n(l?Bs(l,"yyyy-MM-dd"):void 0),a(!1)},initialFocus:!0})})]})]})}function Fgn({behavior:s,onRemove:t,onClearAll:n}){const r=zgn(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 zgn(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=iSe.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=iSe.find(i=>i.value===s.anniversaryMonth),a=((n=jRt.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 ${Bs(Ep(s.dateAddedFrom),"MMM d, yyyy")}`}),s.dateAddedTo&&t.push({key:"dateAddedTo",label:`Added on/before ${Bs(Ep(s.dateAddedTo),"MMM d, yyyy")}`}),s.leadSourceId&&t.push({key:"leadSourceId",label:s.leadSourceId==="none"?"No lead source":"Lead source"}),t}async function s7(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 HH(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function Bgn(){const{user:s}=Ns(),{leadSite:t,hasLeadSite:n}=h0(),{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,v)=>{const k=i.get(b)||HH();i.set(b,{...k,...v})},o=await s7((b,v)=>U.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(b,v)),c=new Map,d=new Map;o.forEach(b=>{if(!b.contact_id)return;c.set(b.id,b.contact_id),b.email&&d.set(b.email.toLowerCase(),b.contact_id);const v=i.get(b.contact_id);(!v||!v.lastActiveAt||b.last_seen_at>v.lastActiveAt)&&l(b.contact_id,{lastActiveAt:b.last_seen_at})});const u=await s7((b,v)=>U.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(b,v)),h=new Map;u.forEach(b=>{b.contact_id&&(h.set(b.user_id,b.contact_id),l(b.contact_id,{registered:!0}))});const m=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await s7((b,v)=>U.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(b,v))).forEach(b=>{const v=b.visitor_id?c.get(b.visitor_id):null;if(!v)return;const k=i.get(v)||HH();k.propertyViewCount+=1,b.viewed_at>=m&&(k.propertyViewCount7d+=1),i.set(v,k)}),(await s7((b,v)=>U.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(b,v))).forEach(b=>{const v=h.get(b.user_id);if(!v)return;const k=i.get(v)||HH();k.savedListingCount+=1,i.set(v,k)}),(await s7((b,v)=>U.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(b,v))).forEach(b=>{const v=h.get(b.user_id);if(!v)return;const k=i.get(v)||HH();k.activeSavedSearchCount+=1,i.set(v,k)}),(await s7((b,v)=>U.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(b,v))).forEach(b=>{if(!b.email)return;const v=d.get(b.email.toLowerCase());if(!v)return;const k=i.get(v)||HH(),C=(b.lead_type||"").toLowerCase();(C.includes("showing")||C.includes("question")||C==="contact")&&(k.showingRequests+=1),(C.includes("valuation")||C.includes("cma")||C.includes("home_value"))&&(k.valuationRequests+=1),i.set(v,k)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}const NRt="innercircle_geocode_cache_v1";function $gn(){try{return JSON.parse(localStorage.getItem(NRt)||"{}")}catch{return{}}}function Ugn(s){try{localStorage.setItem(NRt,JSON.stringify(s))}catch{}}function qgn(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 Vgn({open:s,onOpenChange:t,contacts:n,onCitySelect:r}){const a=j.useRef(null),i=j.useRef(null),[l,o]=j.useState(""),[c,d]=j.useState(!0),[u,h]=j.useState([]),[m,p]=j.useState({done:0,total:0}),[x,y]=j.useState(!1),[g,b]=j.useState("heat");j.useEffect(()=>{if(!s)return;let k=!1;return(async()=>{d(!0);const{data:C}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();k||(o((C==null?void 0:C.value)||""),d(!1))})(),()=>{k=!0}},[s]),j.useEffect(()=>{if(!s||!l)return;let k=!1;return(async()=>{const T=$gn(),M=n.map(G=>({c:G,addr:qgn(G)})).filter(G=>G.addr),P=[],L=[];for(const{c:G,addr:K}of M){const ee=T[K];ee!==null&&(ee?P.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:ee.lat,lng:ee.lng}):L.push({c:G,addr:K}))}if(k||h(P),p({done:P.length,total:M.length}),L.length===0)return;y(!0);const I=6;let O=0;const $={...T},q=[...P],W=async()=>{var G;for(;O{k=!0}},[s,l,n]);const v=j.useMemo(()=>{const k=new Map;for(const C of n){const T=(C.city||"").trim();if(!T)continue;const M=(C.state||"").trim()||null,P=`${T.toLowerCase()}|${M||""}`,L=k.get(P);L?L.count++:k.set(P,{city:T,state:M,count:1})}return Array.from(k.values()).sort((C,T)=>T.count-C.count)},[n]);return j.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return $c.accessToken=l,i.current=new $c.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new $c.NavigationControl,"top-right"),()=>{var k;(k=i.current)==null||k.remove(),i.current=null}},[s,l]),j.useEffect(()=>{const k=i.current;if(!k||u.length===0)return;const C=()=>{const M={type:"FeatureCollection",features:u.map(L=>({type:"Feature",properties:{id:L.id,name:L.name},geometry:{type:"Point",coordinates:[L.lng,L.lat]}}))},P=k.getSource("contacts-src");if(P?P.setData(M):(k.addSource("contacts-src",{type:"geojson",data:M}),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",L=>{var $;const I=($=L.features)==null?void 0:$[0];if(!I)return;const O=I.geometry.coordinates.slice();new $c.Popup({offset:12}).setLngLat(O).setHTML(`
${I.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",g==="heat"?"visible":"none"),k.getLayer("contacts-points")&&(k.setPaintProperty("contacts-points","circle-opacity",g==="points"?.9:0),k.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!k._fitDone){const L=new $c.LngLatBounds;u.forEach(I=>L.extend([I.lng,I.lat]));try{k.fitBounds(L,{padding:60,maxZoom:11,duration:600}),k._fitDone=!0}catch{}}};k.isStyleLoaded()?C():k.once("load",C)},[u,g]),e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx($s,{className:"p-4 pb-2 border-b",children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Fd,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(qe,{variant:"secondary",className:"ml-2",children:[u.length," mapped · ",v.length," cities"]})]})}),e.jsxs("div",{className:"flex-1 flex flex-col md:flex-row min-h-0",children:[e.jsx("div",{className:"flex-1 relative min-h-[300px]",children:c?e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx(Wt,{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:g==="heat"?"default":"ghost",onClick:()=>b("heat"),className:"h-8",children:[e.jsx(Fd,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(B,{size:"sm",variant:g==="points"?"default":"ghost",onClick:()=>b("points"),className:"h-8",children:[e.jsx(U9,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),x&&e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border px-2.5 py-1.5 text-xs flex items-center gap-2",children:[e.jsx(Wt,{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(po,{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(oi,{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:[v.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-3 text-center",children:"No city data on your contacts yet. Add city/state to contacts to populate the map."}),v.slice(0,50).map((k,C)=>{var P;const T=((P=v[0])==null?void 0:P.count)||1,M=k.count/T*100;return e.jsx(be,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(k.city,k.state),t(!1)},children:e.jsxs(Re,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${M}%`}}),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:C===0?"🔥 Hottest market":`Rank #${C+1}`})]}),e.jsx(qe,{variant:"secondary",className:"shrink-0",children:k.count})]})]})},`${k.city}-${k.state}-${C}`)})]})})]})]})]})})}function RI(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 Bmt({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=Hn(),c=ZPe(s,"birthday",7),d=ZPe(t,"anniversary",7),u=ZPe(n||null,"anniversary",7);if(!c&&!d&&!u)return null;const h=(m,p,x)=>{x.stopPropagation();const y=new URLSearchParams;a&&y.set("contactId",a),i&&y.set("name",i),l&&y.set("address",l),(m==="home_anniversary"||m==="wedding_anniversary")&&p&&y.set("date",p),y.set("cardType",m),o(`/mission-control/card-studio?${y.toString()}`)};return e.jsxs("div",{className:Et("flex flex-wrap gap-1",r),children:[c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(qe,{variant:"secondary",className:Et("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(on,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(qe,{variant:"secondary",className:Et("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(on,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(qe,{variant:"secondary",className:Et("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(on,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function x9e({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(qe,{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 $mt({count:s,className:t}){return!s||s<=0?null:e.jsxs(qe,{variant:"outline",className:Et("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(nE,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function Hgn(){const s=ei();return mt({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:n}=await U.from("drip_campaign_enrollments").select("contact_id, status").eq("owner_user_id",s).eq("status","active");if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&(r[a.contact_id]=(r[a.contact_id]||0)+1)}),r},enabled:!!s,staleTime:6e4})}function Ggn(){const s=ei();return mt({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_pipeline").select(` id, deal_name, contact_id, deal_type, expected_price, sale_price, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).not("contact_id","is",null);if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&!r[a.contact_id]&&(r[a.contact_id]=a)}),r},enabled:!!s})}function Wgn({contactId:s,compact:t=!1}){const{data:n}=Aq(),{data:r}=Afn(s),a=yWe(),i=oRt(),l=Mfn(),[o,c]=j.useState(!1),[d,u]=j.useState(""),h=j.useRef(null),m=new Set((r==null?void 0:r.map(b=>b.tag_id))||[]),p=(n==null?void 0:n.filter(b=>b.name.toLowerCase().includes(d.toLowerCase())))||[],x=n==null?void 0:n.find(b=>b.name.toLowerCase()===d.trim().toLowerCase()),y=async b=>{m.has(b.id)?await l.mutateAsync({contactId:s,tagId:b.id}):await i.mutateAsync({contactId:s,tagId:b.id})},g=async()=>{if(!(!d.trim()||x))try{const b=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:b.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(b=>{var v,k,C;return e.jsxs(qe,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((v=b.tag)==null?void 0:v.color)||"#6366F1",color:((k=b.tag)==null?void 0:k.color)||"#6366F1"},children:[e.jsx(wf,{className:"h-2.5 w-2.5"}),(C=b.tag)==null?void 0:C.name,e.jsx("button",{onClick:T=>{T.stopPropagation(),l.mutate({contactId:s,tagId:b.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(dr,{className:"h-2.5 w-2.5"})})]},b.id)}),e.jsxs(lc,{open:o,onOpenChange:c,children:[e.jsx(cc,{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:b=>b.stopPropagation(),children:[e.jsx(Js,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(Jl,{className:"w-56 p-2",align:"start",onClick:b=>b.stopPropagation(),children:[e.jsx(ye,{ref:h,placeholder:"Search or create tag...",value:d,onChange:b=>u(b.target.value),onKeyDown:b=>{b.key==="Enter"&&d.trim()&&!x?(b.preventDefault(),g()):b.key==="Enter"&&x&&!m.has(x.id)&&(b.preventDefault(),y(x))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[p.map(b=>e.jsxs("button",{onClick:()=>y(b),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:b.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:b.name}),m.has(b.id)&&e.jsx(da,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},b.id)),d.trim()&&!x&&e.jsxs("button",{onClick:g,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(Js,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),p.length===0&&!d.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create your first tag"})]})]})]})]})}function Umt({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(qe,{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 One=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function Kgn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=Aq(),a=yWe(),i=Efn(),l=Tfn(),[o,c]=j.useState(""),[d,u]=j.useState(One[0]),[h,m]=j.useState(null),[p,x]=j.useState(""),[y,g]=j.useState(""),b=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(One[0]),ba({title:"Tag created"})}catch(T){ba({title:"Error",description:T.message,variant:"destructive"})}},v=async T=>{if(p.trim())try{await i.mutateAsync({id:T,name:p.trim(),color:y}),m(null),ba({title:"Tag updated"})}catch(M){ba({title:"Error",description:M.message,variant:"destructive"})}},k=async(T,M)=>{if(await Bi(`Delete tag "${M}"? It will be removed from all contacts.`))try{await l.mutateAsync(T),ba({title:"Tag deleted"})}catch(P){ba({title:"Error",description:P.message,variant:"destructive"})}},C=T=>{m(T.id),x(T.name),g(T.color)};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"New tag name...",value:o,onChange:T=>c(T.target.value),onKeyDown:T=>T.key==="Enter"&&b(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:b,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Js,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:One.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:One.map(M=>e.jsx("button",{onClick:()=>g(M),className:`h-5 w-5 rounded-full border-2 ${y===M?"border-foreground":"border-transparent"}`,style:{backgroundColor:M}},M))}),e.jsx(ye,{value:p,onChange:M=>x(M.target.value),onKeyDown:M=>M.key==="Enter"&&v(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:()=>v(T.id),children:e.jsx(da,{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(dr,{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:()=>C(T),children:e.jsx(Za,{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(Rn,{className:"h-3.5 w-3.5"})})]})},T.id))]})]})})}function Ygn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=gO(),a=kVe(),i=Jks(),l=e5s(),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(""),p=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(b){re.error(b.message||"Failed to add lead source")}},x=async b=>{if(h.trim())try{await i.mutateAsync({id:b,name:h.trim()}),u(null)}catch(v){re.error(v.message||"Failed to update")}},y=async(b,v)=>{if(await Bi(`Remove lead source "${v}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(b)}catch(k){re.error(k.message||"Failed to remove")}},g=b=>{u(b.id),m(b.name)};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"New lead source name...",value:o,onChange:b=>c(b.target.value),onKeyDown:b=>b.key==="Enter"&&p(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:p,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Js,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[360px] overflow-y-auto",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(n==null?void 0:n.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No lead sources yet. Create one above!"}),n==null?void 0:n.map(b=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===b.id?e.jsxs(e.Fragment,{children:[e.jsx(ye,{value:h,onChange:v=>m(v.target.value),onKeyDown:v=>v.key==="Enter"&&x(b.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(b.id),children:e.jsx(da,{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(dr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:b.name}),b.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>g(b),children:e.jsx(Za,{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(b.id,b.name),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]}),!b.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},b.id))]})]})})}function kRt({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=gO(),a=kVe(),[i,l]=j.useState(!1),[o,c]=j.useState(""),d=async()=>{if(o.trim())try{const u=await a.mutateAsync(o.trim());u&&(t(u.id),c(""),l(!1))}catch{}};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:n}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(gs,{className:"flex-1",children:e.jsx(bs,{placeholder:"Select lead source"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"_none",children:"No source"}),r==null?void 0:r.map(u=>e.jsx(Je,{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(dr,{className:"h-4 w-4"}):e.jsx(Js,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{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 g9e({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=Hn(),c=ei(),[d,u]=j.useState(!1),[h,m]=j.useState(""),{data:p}=mt({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:y,error:g}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(g)throw g;return y},enabled:!!t}),{data:x}=mt({queryKey:["spouse-search",c,s,h],queryFn:async()=>{let y=U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("owner_user_id",c).is("synced_source",null).neq("id",s).order("first_name").limit(20);if(h.trim()){const v=h.replace(/[,()%]/g," ").trim();v&&(y=y.or(`first_name.ilike.%${v}%,last_name.ilike.%${v}%,email.ilike.%${v}%,phone.ilike.%${v}%`))}const{data:g,error:b}=await y;if(b)throw b;return g},enabled:d&&!!c});if(t&&p){const y=`${p.first_name} ${p.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2",children:[e.jsx(Eo,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{onClick:()=>o(`/mission-control/contacts/${p.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:y}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[p.phone,p.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(ZR,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${p.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(Xa,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(n||r)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2",children:[e.jsx(Eo,{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(lc,{open:d,onOpenChange:u,children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(Rc,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(Jl,{className:"w-72 p-2",align:"end",children:e.jsx(qmt,{search:h,setSearch:m,results:x,onSelect:y=>{a(y),u(!1),m("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(lc,{open:d,onOpenChange:u,children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(Rc,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(Jl,{className:"w-72 p-2",align:"start",children:e.jsx(qmt,{search:h,setSearch:m,results:x,onSelect:y=>{a(y),u(!1),m("")}})})]})]}):null}function qmt({search:s,setSearch:t,results:n,onSelect:r}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{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 Fne=new Map;async function Zgn(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 Xgn(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(Fne.has(r))return Fne.get(r)??null;try{const i=`https://gravatar.com/avatar/${await Zgn(n)}?s=${t}&d=404`;return Fne.set(r,i),i}catch{return Fne.set(r,null),null}}function Qgn(s,t=256){const[n,r]=j.useState(null);return j.useEffect(()=>{let a=!0;if(!s){r(null);return}return Xgn(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function jWe({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=Qgn(n?null:r,Math.max(64,a*2)),[u,h]=j.useState(!1);j.useEffect(()=>h(!1),[d]);const m=n||(u?null:d);return e.jsx("div",{className:Et("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 Jgn=5*1024*1024;function SRt({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=j.useRef(null),o=as(),[c,d]=j.useState(!1),u=()=>{o.invalidateQueries({queryKey:["innercircle-contacts"]}),o.invalidateQueries({queryKey:["innercircle-contact"]}),o.invalidateQueries({queryKey:["contact",s]})},h=async x=>{const{error:y}=await U.from("innercircle_contacts").update({avatar_url:x}).eq("id",s);if(y)throw y;u()},m=async x=>{var y;if(!x.type.startsWith("image/")){ba({title:"Please choose an image file",variant:"destructive"});return}if(x.size>Jgn){ba({title:"Image too large",description:"Please use an image under 5MB.",variant:"destructive"});return}d(!0);try{const{data:g}=await U.auth.getUser(),b=(y=g.user)==null?void 0:y.id,v=(x.name.split(".").pop()||"jpg").toLowerCase(),k=`contacts/${b}/${s}-${Date.now()}.${v}`,{error:C}=await U.storage.from("avatars").upload(k,x,{upsert:!0,contentType:x.type});if(C)throw C;const{data:T}=U.storage.from("avatars").getPublicUrl(k);await h(T.publicUrl),ba({title:"Photo updated"})}catch(g){ba({title:"Upload failed",description:g.message,variant:"destructive"})}finally{d(!1),l.current&&(l.current.value="")}},p=async()=>{d(!0);try{await h(null),ba({title:"Photo removed"})}catch(x){ba({title:"Could not remove photo",description:x.message,variant:"destructive"})}finally{d(!1)}};return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{var x;return(x=l.current)==null?void 0:x.click()},disabled:c,className:"relative group rounded-full focus:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":r?"Change contact photo":"Upload contact photo",children:[e.jsx(jWe,{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(Wt,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(s0,{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(Wt,{className:"h-5 w-5 text-background animate-spin"})})]}),r&&e.jsxs(B,{variant:"ghost",size:"sm",className:"text-muted-foreground gap-1.5",onClick:p,disabled:c,children:[e.jsx(Rn,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:x=>{var g;const y=(g=x.target.files)==null?void 0:g[0];y&&m(y)}})]})}const e0n={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},t0n={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 CRt({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:Et("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:e0n[t]})]}),e.jsx("span",{className:Et("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",t0n[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}function s0n(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 n0n({score:s,contact:t,onEdit:n,onLogTouch:r}){const a=s0n(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(da,{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(xN,{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 r0n={warm:"Strong",cooling:"Cooling off","at-risk":"Needs attention"};function a0n({contact:s,deal:t,open:n,onOpenChange:r,onEdit:a,index:i,total:l,onPrev:o,onNext:c}){var P;const d=Hn(),{data:u}=tq(),h=CJ(),[m,p]=j.useState(null),[x,y]=j.useState(!1),{gmailEmail:g}=Tf(),b=s==null?void 0:s.spouse_contact_id,{data:v}=mt({queryKey:["innercircle-contact-spouse",b],queryFn:async()=>{const{data:L,error:I}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday, avatar_url").eq("id",b).maybeSingle();if(I)throw I;return L},enabled:!!b&&n});if(!s)return null;const k=async L=>{p(L);try{await h.mutateAsync({contactId:s.id,actionTypeId:L})}finally{p(null)}},C=`${s.first_name||""} ${s.last_name||""}`.trim();C.split(" ").filter(Boolean).map(L=>L[0]).join("").toUpperCase().slice(0,2);const T=[s.city,s.state].filter(Boolean).join(", "),M=s.relationshipScore;return e.jsxs(v1,{open:n,onOpenChange:r,children:[e.jsxs(rv,{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(Cc,{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(Lb,{className:"space-y-0 text-left",children:[e.jsx(Pb,{className:"sr-only",children:C}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(SRt,{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:C}),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(on,{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(pa,{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(oi,{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:r0n[M.status]??M.status}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:M.lastTouchDate?`Last touch ${Bs(new Date(M.lastTouchDate),"MMM d, yyyy")}`:"Never contacted"})]}),e.jsx(CRt,{score:M.score,status:M.status,size:64})]}),e.jsx(n0n,{score:M,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(aSe,{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(on,{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(ro,{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(pa,{className:"h-4 w-4"})," Call"]})})]}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsxs(B,{variant:"secondary",className:"w-full gap-1.5",disabled:!!m,children:[m?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Rr,{className:"h-4 w-4"}),"Log a touch"]})}),e.jsxs(xd,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(TE,{children:"What did you do?"}),u==null?void 0:u.map(L=>e.jsx(wa,{onClick:()=>k(L.id),children:L.name},L.id))]})]}),(t||s.tags&&s.tags.length>0)&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsx(x9e,{deal:t}),(P=s.tags)==null?void 0:P.map(L=>{var I;return e.jsx(qe,{variant:"secondary",className:"text-xs",children:(I=L.relationship_type)==null?void 0:I.name},L.id)})]}),(v||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(Bn,{className:"h-3.5 w-3.5"})," Spouse / Partner"]}),v?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(jWe,{firstName:v.first_name,lastName:v.last_name,avatarUrl:v.avatar_url,email:v.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/${v.id}`),children:`${v.first_name||""} ${v.last_name||""}`.trim()}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:[v.phone,v.email].filter(Boolean).join(" · ")||"No contact info"})]}),e.jsx(B,{variant:"ghost",size:"icon","aria-label":"Open spouse record",onClick:()=>d(`/mission-control/contacts/${v.id}`),children:e.jsx(Tr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(mo,{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||(v==null?void 0:v.birthday))&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Wm,{className:"h-3.5 w-3.5"}),"Spouse birthday · ",Bs(Ic(s.spouse_birthday||v.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(ra,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Birthday · ",Bs(Ic(s.birthday),"MMM d, yyyy")]}),s.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ia,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Home anniversary · ",Bs(Ic(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(Vr,{className:"h-3.5 w-3.5"}),"Added ",Bs(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(Za,{className:"h-4 w-4"})})]})]})]}),s.email&&e.jsx(cw,{open:x,onOpenChange:y,contact:{id:s.id,first_name:s.first_name,last_name:s.last_name,email:s.email},gmailEmail:g})]})}function i0n({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(Cu,{children:[e.jsx(Au,{asChild:!0,children:e.jsx("span",{role:n?"button":void 0,onClick:n?a=>{a.stopPropagation(),n()}:void 0,className:`inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground ${n?"cursor-pointer hover:bg-accent hover:text-accent-foreground":""}`,"aria-label":r,children:e.jsx(Bn,{className:"h-3 w-3"})})}),e.jsx(ou,{children:r})]})}function ARt(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 Vmt(s){if(!s)return null;const t=Ic(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:Sl,color:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",icon:Vr,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:gj,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:Wm,color:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",icon:ia,color:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",icon:kx,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:Ql,color:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",icon:yn,color:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"missing-info",title:"Missing Info",icon:hd,color:"text-slate-600 dark:text-slate-400",match:s=>ARt(s)}];function o0n({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}=vWe(),m=lRt(),p=cRt(),[x,y]=j.useState(!1),[g,b]=j.useState(""),v=j.useMemo(()=>{const M={"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 M;for(const P of s){const L={hasDeal:!!(t&&t[P.id]),daysToBirthday:Vmt(P.birthday),daysToAnniv:Vmt(P.home_anniversary)};for(const I of Hmt)I.key!=="website-active"&&I.match(P,L)&&M[I.key]++}return M},[s,t,n]),k=!!l.search||!!l.type&&l.type!=="all"||!!l.status&&l.status!=="all"||!!l.behavior&&Object.values(l.behavior).some(M=>M!==void 0&&M!==!1),C=async()=>{g.trim()&&(await m.mutateAsync({name:g.trim(),filters:l,sort_by:o}),b(""),y(!1))},T="inline-flex items-center gap-1.5 h-8 shrink-0 rounded-full border px-3 text-xs font-medium transition-colors whitespace-nowrap";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto pb-1 -mx-1 px-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[e.jsxs("button",{type:"button",onClick:u,className:Et(T,!a&&!c?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),"All Contacts",e.jsx("span",{className:"tabular-nums opacity-70",children:r.toLocaleString()})]}),h==null?void 0:h.map(M=>{const P=c===M.id;return e.jsxs("div",{className:Et(T,"group pr-1",P?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx("button",{type:"button",onClick:()=>d(M.id,M.filters,M.sort_by),children:M.name}),e.jsx("button",{type:"button","aria-label":`Delete view ${M.name}`,className:"h-5 w-5 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-foreground/10",onClick:()=>{p.mutate(M.id),P&&u()},children:e.jsx(dr,{className:"h-3 w-3"})})]},M.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),Hmt.map(M=>{const P=M.icon,L=v[M.key],I=a===M.key;return e.jsxs("button",{type:"button",onClick:()=>i(I?null:M.key),"aria-pressed":I,className:Et(T,I?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border",!I&&L===0&&"opacity-55"),children:[e.jsx(P,{className:Et("h-3.5 w-3.5",I?"":M.color)}),M.title,e.jsx("span",{className:"tabular-nums opacity-70",children:L.toLocaleString()})]},M.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($T,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(Fs,{open:x,onOpenChange:y,children:e.jsxs(Os,{className:"sm:max-w-sm",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Save this view"}),e.jsx(kr,{children:"Your current search, filters, and sorting are saved as a one-click chip."})]}),e.jsx(ye,{autoFocus:!0,placeholder:"e.g. Past clients cooling off",value:g,onChange:M=>b(M.target.value),onKeyDown:M=>M.key==="Enter"&&C()}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(B,{onClick:C,disabled:!g.trim()||m.isPending,children:"Save view"})]})]})})]})}const Gmt=[{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"}],XPe={relationship:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},Wmt="innercircle:contact-columns:v1";function l0n(){const[s,t]=j.useState(()=>{try{const a=localStorage.getItem(Wmt);if(a)return{...XPe,...JSON.parse(a)}}catch{}return XPe});j.useEffect(()=>{try{localStorage.setItem(Wmt,JSON.stringify(s))}catch{}},[s]);const n=j.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=j.useCallback(()=>t(XPe),[]);return{columns:s,toggle:n,reset:r}}function c0n({columns:s,onToggle:t,onReset:n}){const r=Gmt.filter(a=>s[a.key]).length;return e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(lA,{className:"h-3.5 w-3.5"}),"Columns",e.jsx(qe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r})]})}),e.jsxs(Jl,{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(bm,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:Gmt.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(wi,{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 d0n(){var Xr;const s=Hn(),[t,n]=dc(),{user:r}=Ns(),a=Tq(),i=as(),{columns:l,toggle:o,reset:c}=l0n(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:m,isLoading:p}=G3e(),{activeContactIds:x,hasLeadSite:y}=Xxn(),{data:g}=Hgn(),{data:b}=lw(),{data:v}=Ggn(),{data:k}=Aq(),{data:C}=EAe(),[T,M]=j.useState(new Set),[P,L]=j.useState("any"),I=q3e(),O=_Ve(),$=wVe(),q=VCt(),[W,G]=j.useState(""),[K,ee]=j.useState(!1),[J,le]=j.useState(d||"all"),[ue,oe]=j.useState(u||"all"),[ie,de]=j.useState("date-added"),[we,je]=j.useState("all"),[xe,fe]=j.useState({}),Se=j.useMemo(()=>Object.values(xe).filter(Qt=>Qt!==void 0&&Qt!==!1&&Qt!=="").length,[xe]),[Ee,Le]=j.useState(!1),{behaviorMap:De,hasLeadSite:Be}=Bgn(),[Ne,Ge]=j.useState(h),[_e,Oe]=j.useState(null),[Ae,Xe]=j.useState(!1),[Ue,Ze]=j.useState(!1),[Qe,Ye]=j.useState(null),[nt,rt]=j.useState(""),[Fe,dt]=j.useState(new Set),[Dt,pt]=j.useState(!1),[zt,Gt]=j.useState(null),qs=Math.max(1,parseInt(t.get("page")||"1",10)||1),[As,Bt]=j.useState(qs),At=j.useCallback(Qt=>{Bt(Zn=>{const aa=typeof Qt=="function"?Qt(Zn):Qt;return n(zr=>{const Na=new URLSearchParams(zr);return aa<=1?Na.delete("page"):Na.set("page",String(aa)),Na},{replace:!0}),aa})},[]),[Is,jt]=j.useState(50),[Qs,cn]=j.useState("my"),[qt,Gs]=j.useState(!1),[Ls,sn]=j.useState(!1),{data:Hs}=Hj(),{addToLeadPond:nn}=DMt(Hs==null?void 0:Hs.teamId),tn=!!((Xr=Hs==null?void 0:Hs.team)!=null&&Xr.lead_pond_enabled&&(Hs!=null&&Hs.teamId)),_n=!!(Hs!=null&&Hs.teamId),[Cn,Un]=j.useState([]),[Kr,jr]=j.useState(!1),Xs=Qt=>{Un([Qt]),jr(!0)},Ba=Qt=>{Un(Qt),jr(!0)},Hr=Qt=>{Hs!=null&&Hs.teamId&&nn.mutate({contact_id:Qt,team_id:Hs.teamId})},mr=Qt=>{Hs!=null&&Hs.teamId&&Qt.forEach(Zn=>{nn.mutate({contact_id:Zn,team_id:Hs.teamId})})},pr=j.useCallback(Qt=>{pt(!1),dt(Zn=>{const aa=new Set(Zn);return aa.has(Qt)?aa.delete(Qt):aa.add(Qt),aa})},[]);j.useEffect(()=>{if(!(r!=null&&r.id))return;const Qt=U.channel(`innercircle_contacts_inserts_${r.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"innercircle_contacts",filter:`owner_user_id=eq.${r.id}`},()=>{i.invalidateQueries({queryKey:["innercircle-contacts"]}),i.invalidateQueries({queryKey:["innercircle-contact-counts"]})}).subscribe();return()=>{U.removeChannel(Qt)}},[i,r==null?void 0:r.id]),j.useEffect(()=>{u&&oe(u)},[u]);const[rn,Jn]=j.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]});j.useEffect(()=>{h&&Ge(!0)},[h]),j.useEffect(()=>{var Qt;_e&&Jn({first_name:_e.first_name||"",last_name:_e.last_name||"",email:_e.email||"",phone:_e.phone||"",address:_e.address||"",city:_e.city||"",state:_e.state||"",zip_code:_e.zip_code||"",birthday:_e.birthday||"",home_anniversary:_e.home_anniversary||"",spouse_name:_e.spouse_name||"",spouse_email:_e.spouse_email||"",lead_source_id:_e.lead_source_id||"",notes:_e.notes||"",tagIds:((Qt=_e.tags)==null?void 0:Qt.map(Zn=>Zn.relationship_type_id))||[]})},[_e]);const ea=j.useMemo(()=>{const Qt=new Set;return k==null||k.forEach(Zn=>{(Zn.name==="Recruits"||Zn.name==="Brokerage Agents")&&Qt.add(Zn.id)}),Qt},[k]),_s=j.useMemo(()=>Array.from(T).some(Qt=>ea.has(Qt)),[T,ea]),We=j.useMemo(()=>{const Qt={};return(m||[]).forEach(Zn=>{Qt[Zn.id]=`${Zn.first_name||""} ${Zn.last_name||""}`.trim()}),Qt},[m]),it=j.useMemo(()=>{if(!m)return[];let Qt=m.filter(zr=>{var qa,xo,Wo,Co,Ko,Ud,Mu,Qm,Gc,lh,qd;const Na=zr.synced_source;if(!_s&&(Na==="recruit"||Na==="brokerage_agent"))return!1;const ur=W===""||`${zr.first_name} ${zr.last_name}`.toLowerCase().includes(W.toLowerCase())||((qa=zr.email)==null?void 0:qa.toLowerCase().includes(W.toLowerCase()))||((xo=zr.phone)==null?void 0:xo.includes(W))||((Wo=zr.city)==null?void 0:Wo.toLowerCase().includes(W.toLowerCase()))||((Co=zr.state)==null?void 0:Co.toLowerCase().includes(W.toLowerCase()))||((Ko=zr.address)==null?void 0:Ko.toLowerCase().includes(W.toLowerCase()))||((Ud=zr.zip_code)==null?void 0:Ud.toLowerCase().includes(W.toLowerCase())),ao=J==="all"||((Mu=zr.tags)==null?void 0:Mu.some(Wc=>Wc.relationship_type_id===J)),fo=T.size===0||(()=>{const Wc=(C==null?void 0:C.filter(Kh=>Kh.contact_id===zr.id).map(Kh=>Kh.tag_id))||[];return P==="any"?Wc.some(Kh=>T.has(Kh)):Array.from(T).every(Kh=>Wc.includes(Kh))})(),Va=!!((Qm=zr.address)!=null&&Qm.trim()||(Gc=zr.city)!=null&&Gc.trim()||(lh=zr.state)!=null&&lh.trim()||(qd=zr.zip_code)!=null&&qd.trim()),So=we==="all"||we==="has-address"&&Va||we==="no-address"&&!Va,$a=zr,Gr=xe,Qn=(Gr.hasEmail===void 0||!!$a.email===Gr.hasEmail)&&(Gr.hasPhone===void 0||!!$a.phone===Gr.hasPhone)&&(Gr.hasAddress===void 0||Va===Gr.hasAddress)&&(Gr.hasBirthday===void 0||!!$a.birthday===Gr.hasBirthday)&&(Gr.hasSpouse===void 0||!!($a.spouse_name||$a.spouse_contact_id||$a.spouse_email)===Gr.hasSpouse)&&(Gr.hasCompany===void 0||!!($a.company_name||$a.job_title)===Gr.hasCompany)&&(Gr.hasNotes===void 0||!!($a.notes&&$a.notes.trim())===Gr.hasNotes)&&(!Gr.city||($a.city||"").toLowerCase().includes(Gr.city.toLowerCase()))&&(!Gr.state||($a.state||"").toLowerCase().includes(Gr.state.toLowerCase()))&&(!Gr.zip||(($a.zip||"")+($a.zip_code||"")).toLowerCase().includes(Gr.zip.toLowerCase()))&&(!Gr.birthdayMonth||!!$a.birthday&&Ic($a.birthday).getMonth()+1===Gr.birthdayMonth)&&(!Gr.anniversaryMonth||((Gr.anniversaryField||"home_anniversary")==="home_anniversary"?!!$a.home_anniversary&&Ic($a.home_anniversary).getMonth()+1===Gr.anniversaryMonth:!!$a.wedding_anniversary&&Ic($a.wedding_anniversary).getMonth()+1===Gr.anniversaryMonth))&&(!Gr.dateAddedFrom||!!$a.created_at&&$a.created_at.slice(0,10)>=Gr.dateAddedFrom)&&(!Gr.dateAddedTo||!!$a.created_at&&$a.created_at.slice(0,10)<=Gr.dateAddedTo)&&(!Gr.leadSourceId||$a.lead_source_id===Gr.leadSourceId||!$a.lead_source_id&&Gr.leadSourceId==="none");return ur&&ao&&fo&&So&&Qn});ue==="not-touched-90"?Qt=Qt.filter(zr=>{const Na=zr.relationshipScore.daysSinceTouch;return Na===null||Na>90}):ue==="at-risk"?Qt=Qt.filter(zr=>zr.relationshipScore.status==="at-risk"):ue==="cooling"?Qt=Qt.filter(zr=>zr.relationshipScore.status==="cooling"):ue==="warm"?Qt=Qt.filter(zr=>zr.relationshipScore.status==="warm"):ue==="has-deal"?Qt=Qt.filter(zr=>v&&v[zr.id]):ue==="no-deal"?Qt=Qt.filter(zr=>!v||!v[zr.id]):ue==="open-house"?Qt=Qt.filter(zr=>{var oa;return(((oa=zr.lead_source_ref)==null?void 0:oa.name)||zr.lead_source)==="Open House"}):ue==="website-active"?Qt=Qt.filter(zr=>x.has(zr.id)):ue==="never-contacted"?Qt=Qt.filter(zr=>zr.relationshipScore.daysSinceTouch===null):ue==="vips"?Qt=Qt.filter(zr=>zr.relationshipScore.score>=80):ue==="missing-info"?Qt=Qt.filter(zr=>ARt(zr)):ue==="birthdays-soon"?Qt=Qt.filter(zr=>{const Na=RI(zr.birthday);return Na!==null&&Na<=30}):ue==="anniversary-soon"?Qt=Qt.filter(zr=>{const Na=RI(zr.home_anniversary);return Na!==null&&Na<=30}):ue==="in-drip"?Qt=Qt.filter(zr=>((g==null?void 0:g[zr.id])??0)>0):ue==="not-in-drip"&&(Qt=Qt.filter(zr=>((g==null?void 0:g[zr.id])??0)===0));const Zn=xe;if(Zn.lastActive||Zn.registered||Zn.viewedListing||Zn.savedProperty||Zn.hasSavedSearch||Zn.requestedShowing||Zn.requestedValuation||Zn.websiteActiveOnly){const zr=Date.now(),Na={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};Qt=Qt.filter(oa=>{const ur=De.get(oa.id);if(Zn.lastActive==="never"){if(ur!=null&&ur.lastActiveAt)return!1}else if(Zn.lastActive){const ao=zr-Na[Zn.lastActive];if(!(ur!=null&&ur.lastActiveAt)||new Date(ur.lastActiveAt).getTime()0)||Zn.viewedListing==="multiple7d"&&!(ur&&ur.propertyViewCount7d>=3)||Zn.savedProperty&&!(ur&&ur.savedListingCount>0)||Zn.hasSavedSearch&&!(ur&&ur.activeSavedSearchCount>0)||Zn.requestedShowing&&!(ur&&ur.showingRequests>0)||Zn.requestedValuation&&!(ur&&ur.valuationRequests>0)||Zn.websiteActiveOnly&&!x.has(oa.id))})}return Qt=[...Qt].sort((zr,Na)=>{switch(ie){case"important-dates":{const oa=RI(zr.birthday),ur=RI(Na.birthday),ao=RI(zr.home_anniversary),fo=RI(Na.home_anniversary),Va=[oa,ao].filter($a=>$a!==null).sort(($a,Gr)=>($a??1/0)-(Gr??1/0))[0]??1/0,So=[ur,fo].filter($a=>$a!==null).sort(($a,Gr)=>($a??1/0)-(Gr??1/0))[0]??1/0;return Va-So}case"last-touched":{const oa=zr.relationshipScore.lastTouchDate,ur=Na.relationshipScore.lastTouchDate;return!oa&&!ur?0:oa?ur?new Date(oa).getTime()-new Date(ur).getTime():1:-1}case"next-touch":{const oa=zr.relationshipScore.daysSinceTouch,ur=Na.relationshipScore.daysSinceTouch;return oa===null&&ur===null?0:oa===null?-1:ur===null?1:ur-oa}case"score":return zr.relationshipScore.score-Na.relationshipScore.score;case"date-added":{const oa=zr.created_at,ur=Na.created_at;return!oa&&!ur?0:oa?ur?new Date(ur).getTime()-new Date(oa).getTime():-1:1}case"last-name":{const oa=(zr.last_name||"").toLowerCase(),ur=(Na.last_name||"").toLowerCase();if(oa!==ur)return oa.localeCompare(ur);const ao=(zr.first_name||"").toLowerCase(),fo=(Na.first_name||"").toLowerCase();return ao.localeCompare(fo)}case"name":default:{const oa=`${zr.first_name||""} ${zr.last_name||""}`.toLowerCase(),ur=`${Na.first_name||""} ${Na.last_name||""}`.toLowerCase();return oa.localeCompare(ur)}}}),Qt},[m,W,J,T,P,ue,ie,v,C,x,g,we,xe,De,_s]),gt=it.length,St=Math.max(1,Math.ceil(gt/Is)),Ht=Math.min(As,St),ts=j.useMemo(()=>{const Qt=(Ht-1)*Is;return it.slice(Qt,Qt+Is)},[it,Ht,Is]),Ms=j.useRef(!1);j.useEffect(()=>{if(!Ms.current){Ms.current=!0;return}At(1)},[W,J,T,P,ue,ie,we,xe]);const js=j.useCallback(()=>{pt(!1),dt(Qt=>Qt.size>0?new Set:new Set(ts.map(Zn=>Zn.id)))},[ts]),Zs=j.useCallback(()=>{pt(!0),dt(new Set(it.map(Qt=>Qt.id)))},[it]),[Tn,vn]=j.useState(null),_r=j.useCallback((Qt,Zn)=>{G(Qt.search||""),le(Qt.type||"all"),oe(Qt.status||"all"),fe(Qt.behavior||{}),de(Zn||"name")},[]),Jr=()=>{Jn({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},ha=async Qt=>{Qt.preventDefault();const Zn={...rn,lead_source_id:rn.lead_source_id||null};_e?(await O.mutateAsync({id:_e.id,...Zn}),Oe(null)):(await I.mutateAsync(Zn),Ge(!1)),Jr()},Mr=async Qt=>{await Bi("Are you sure you want to delete this contact?")&&await $.mutateAsync(Qt)};return e.jsx(Vs,{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"})]}),Hs&&e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsx("button",{onClick:()=>cn("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Qs==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Contacts"}),(Hs.team.contact_visibility==="full_team"||Hs.team.contact_visibility==="leader_only"&&Hs.role==="team_leader")&&e.jsxs("button",{onClick:()=>cn("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${Qs==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),"Team"]}),Hs.team.lead_pond_enabled&&e.jsxs("button",{onClick:()=>cn("lead-pond"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${Qs==="lead-pond"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(mN,{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(Cc,{className:"h-4 w-4 mr-1"}),"Back"]})}),Qs==="team"?e.jsx(QHe,{}):Qs==="lead-pond"&&Hs?e.jsx(JHe,{teamId:Hs.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(o0n,{contacts:m,contactDealsMap:v,websiteActiveIds:x,totalCount:(m||[]).length,activeViewId:Tn,currentFilters:{search:W,type:J,status:ue,behavior:xe},currentSortBy:ie,onApplyView:(Qt,Zn,aa)=>{vn(Qt),_r(Zn,aa),At(1)},onClearAll:()=>{vn(null),_r({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:Qt=>{const aa=Qt?{"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"}[Qt]:"all";oe(aa),At(1)}}),e.jsxs(be,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search contacts...",value:W,onChange:Qt=>G(Qt.target.value),className:"pl-9 h-10 rounded-xl bg-muted/40"})]}),e.jsxs(v1,{children:[e.jsx(yJ,{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(sE,{className:"h-4 w-4"}),(()=>{const Qt=(J!=="all"?1:0)+(ue!=="all"?1:0)+(we!=="all"?1:0)+T.size+Se;return Qt>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:Qt}):null})()]})}),e.jsxs(rv,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(Lb,{className:"text-left",children:e.jsx(Pb,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(vs,{value:J,onValueChange:le,children:[e.jsx(gs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(bs,{placeholder:"All Types"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Types"}),b==null?void 0:b.filter(Qt=>Qt.active).map(Qt=>e.jsx(Je,{value:Qt.id,children:Qt.name},Qt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(vs,{value:ue,onValueChange:oe,children:[e.jsx(gs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(bs,{placeholder:"All Status"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Status"}),e.jsx(Je,{value:"warm",children:"🟢 Warm"}),e.jsx(Je,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Je,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Je,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Je,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Je,{value:"open-house",children:"🏠 Open House"}),y&&e.jsx(Je,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Je,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Je,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(vs,{value:we,onValueChange:Qt=>je(Qt),children:[e.jsx(gs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(bs,{placeholder:"All Addresses"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Addresses"}),e.jsx(Je,{value:"has-address",children:"Has Address"}),e.jsx(Je,{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(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>L("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${P==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>L("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${P==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.map(Qt=>{const Zn=T.has(Qt.id);return e.jsxs("button",{onClick:()=>{M(aa=>{const zr=new Set(aa);return zr.has(Qt.id)?zr.delete(Qt.id):zr.add(Qt.id),zr})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${Zn?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:Qt.color}}),Qt.name]},Qt.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(vs,{value:ie,onValueChange:de,children:[e.jsx(gs,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"name",children:"Name (A-Z)"}),e.jsx(Je,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(Je,{value:"important-dates",children:"Important Dates"}),e.jsx(Je,{value:"last-touched",children:"Last Touched"}),e.jsx(Je,{value:"next-touch",children:"Next Touch Due"}),e.jsx(Je,{value:"score",children:"Relationship Score"}),e.jsx(Je,{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:()=>Le(!0),children:[e.jsx(yn,{className:"h-4 w-4"})," Advanced"]}),e.jsxs(B,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Gs(!0),children:[e.jsx(wf,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(Fmt,{currentFilters:{search:W,type:J,status:ue,behavior:xe},currentSortBy:ie,onApplySmartList:_r})}),e.jsx(B,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{le("all"),oe("all"),je("all"),M(new Set),fe({})},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(Js,{className:"h-4 w-4 mr-1.5"})," Add Contact"]}),e.jsxs(B,{onClick:()=>ee(!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(Fd,{className:"h-4 w-4 mr-1.5"})," Heat Map"]})]}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full h-10 rounded-xl gap-2",children:[e.jsx(Ja,{className:"h-4 w-4"})," Import & Sync"]})}),e.jsxs(xd,{align:"center",className:"w-[calc(100vw-2rem)] max-w-sm",children:[e.jsxs(wa,{onClick:()=>Xe(!0),children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(wa,{onClick:()=>Ze(!0),children:[e.jsx(Jy,{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(Rmt,{})})]})]})]}),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(Fr,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or phone...",value:W,onChange:Qt=>G(Qt.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(Bn,{className:"h-3.5 w-3.5"}),"Grid"]}),e.jsxs("button",{type:"button",onClick:()=>ee(!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(Fd,{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(Js,{className:"h-4 w-4"}),"Add Contact"]}),e.jsxs(kd,{children:[e.jsx(Sd,{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(xd,{align:"end",children:[e.jsxs(wa,{onClick:()=>Xe(!0),children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),"Import CSV"]}),e.jsxs(wa,{onClick:()=>Ze(!0),children:[e.jsx(Jy,{className:"h-4 w-4 mr-2"}),"Import from Phone"]})]})]})]}),e.jsx(Rmt,{}),e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(kj,{className:"h-4 w-4"})})}),e.jsxs(Jl,{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(Qt=>e.jsx("button",{onClick:()=>de(Qt.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${ie===Qt.v?"bg-accent font-medium text-primary":""}`,children:Qt.l},Qt.v))]})]})]})]}),e.jsxs("div",{className:"hidden sm:flex px-3 sm:px-4 py-3 bg-muted/40 border-t flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(vs,{value:J,onValueChange:le,children:[e.jsx(gs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(bs,{placeholder:"All Types"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Types"}),b==null?void 0:b.filter(Qt=>Qt.active).map(Qt=>e.jsx(Je,{value:Qt.id,children:Qt.name},Qt.id))]})]}),e.jsxs(vs,{value:ue,onValueChange:oe,children:[e.jsx(gs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(bs,{placeholder:"All Status"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Status"}),e.jsx(Je,{value:"warm",children:"🟢 Warm"}),e.jsx(Je,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Je,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Je,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Je,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Je,{value:"open-house",children:"🏠 Open House"}),y&&e.jsx(Je,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Je,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Je,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(vs,{value:we,onValueChange:Qt=>je(Qt),children:[e.jsx(gs,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(bs,{placeholder:"All Addresses"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Addresses"}),e.jsx(Je,{value:"has-address",children:"Has Address"}),e.jsx(Je,{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(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs("button",{className:"pl-2.5 pr-2 h-full text-xs font-medium text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5",children:[e.jsx(wf,{className:"h-3.5 w-3.5"}),T.size===0?"Filter by Tags":`${T.size} tag${T.size>1?"s":""}`]})}),e.jsx(Jl,{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:()=>L("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${P==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>L("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${P==="all"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:k.map(Qt=>{const Zn=T.has(Qt.id);return e.jsxs("button",{onClick:()=>{M(aa=>{const zr=new Set(aa);return zr.has(Qt.id)?zr.delete(Qt.id):zr.add(Qt.id),zr})},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(wi,{checked:Zn,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:Qt.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:Qt.name})]},Qt.id)})}),T.size>0&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>M(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs(kd,{children:[e.jsx(Sd,{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(ic,{className:"h-3.5 w-3.5"})})}),e.jsxs(xd,{align:"end",children:[e.jsxs(wa,{onClick:()=>Gs(!0),children:[e.jsx(wf,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(wa,{onClick:()=>sn(!0),children:[e.jsx(mN,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fmt,{currentFilters:{search:W,type:J,status:ue,behavior:xe},currentSortBy:ie,onApplySmartList:_r}),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:()=>Le(!0),children:[e.jsx(yn,{className:"h-3.5 w-3.5"}),"Advanced Filters",Se>0&&e.jsx(qe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Se})]}),e.jsx(c0n,{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(Fgn,{behavior:xe,onRemove:Qt=>fe(Zn=>{const aa={...Zn};return delete aa[Qt],aa}),onClearAll:()=>fe({})})})]}),e.jsx(Ogn,{open:Ee,onOpenChange:Le,hasLeadSite:Be||y,behavior:xe,onApply:fe,selectedType:J,onSelectedTypeChange:le,relationshipTypes:b}),e.jsx(Rgn,{selectedIds:Fe,contacts:it,onClearSelection:()=>{dt(new Set),pt(!1)},showLeadPondAction:tn,onSendToLeadPond:mr,showTransferAction:_n,onTransfer:Ba}),Fe.size>0&&Fe.size===ts.length&&!Dt&>>Is&&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 ",ts.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 ",gt.toLocaleString()," matching contacts"]})]}),Dt&&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 ",gt.toLocaleString()," matching contacts are selected.",e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{dt(new Set),pt(!1)},children:"Clear selection"})]}),gt>Is&&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 ",(Ht-1)*Is+1,"–",Math.min(Ht*Is,gt)," of ",gt.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",disabled:Ht<=1,onClick:()=>At(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ht<=1,onClick:()=>At(Qt=>Qt-1),children:e.jsx(Cc,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Ht," of ",St]}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ht>=St,onClick:()=>At(Qt=>Qt+1),children:e.jsx(Qa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ht>=St,onClick:()=>At(St),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:p?e.jsx(be,{className:"p-6 text-center text-muted-foreground",children:"Loading contacts..."}):it.length===0?e.jsx(be,{className:"p-6 text-center text-muted-foreground",children:W||J!=="all"||ue!=="all"||we!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"}):ts.map(Qt=>{var aa,zr,Na;const{relationshipScore:Zn}=Qt;return e.jsx(be,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>{const oa=new URLSearchParams;W&&oa.set("search",W),J!=="all"&&oa.set("type",J),ue!=="all"&&oa.set("filter",ue),T.size>0&&(oa.set("tags",Array.from(T).join(",")),oa.set("tagMode",P));const ur=oa.toString();s(`/mission-control/contacts/${Qt.id}${ur?`?${ur}`:""}`)},children:e.jsx(Re,{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:[Qt.first_name," ",Qt.last_name]}),e.jsx($mt,{count:(g==null?void 0:g[Qt.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:[Qt.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(on,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:Qt.email})]}),Qt.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(pa,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Qt.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(f9e,{score:Zn,size:"sm"}),e.jsx(aSe,{contact:Qt}),(((aa=Qt.lead_source_ref)==null?void 0:aa.name)||Qt.lead_source)&&e.jsx(qe,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((zr=Qt.lead_source_ref)==null?void 0:zr.name)||Qt.lead_source}),(Na=Qt.tags)==null?void 0:Na.map(oa=>{var ur;return e.jsx(qe,{variant:"secondary",className:"text-xs",children:(ur=oa.relationship_type)==null?void 0:ur.name},oa.id)}),e.jsx(Umt,{contactId:Qt.id,tags:C==null?void 0:C.filter(oa=>oa.contact_id===Qt.id)}),e.jsx(x9e,{deal:v==null?void 0:v[Qt.id]})]}),e.jsx(Bmt,{birthday:Qt.birthday,homeAnniversary:Qt.home_anniversary,weddingAnniversary:Qt.wedding_anniversary,className:"mb-2",contactId:Qt.id,contactName:`${Qt.first_name}${Qt.last_name?" "+Qt.last_name:""}`,contactAddress:[Qt.address,Qt.city,Qt.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[Zn.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),Bs(new Date(Zn.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),Qt.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ra,{className:"h-3 w-3"}),Bs(Ic(Qt.birthday),"MMM d")]}),Qt.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3 w-3"}),Bs(Ic(Qt.home_anniversary),"MMM d")]}),Qt.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Js,{className:"h-3 w-3"}),"Added ",Bs(new Date(Qt.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:oa=>oa.stopPropagation(),children:e.jsx(Omt,{contact:Qt,onEdit:Oe,onDelete:Mr,onSnooze:(oa,ur)=>{Ye(oa),rt(ur)},showLeadPondAction:tn,onSendToLeadPond:Hr,showTransferAction:_n,onTransfer:Xs})})]})})},Qt.id)})}):e.jsx(be,{children:e.jsx(Re,{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(Tt,{className:"w-[40px]",children:e.jsx(wi,{checked:ts.length>0&&ts.every(Qt=>Fe.has(Qt.id)),onCheckedChange:()=>js()})}),e.jsx(Tt,{children:e.jsxs("button",{onClick:()=>de(Qt=>Qt==="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",ie==="name"&&e.jsx(Qa,{className:"h-3 w-3 rotate-90 text-primary"}),ie==="last-name"&&e.jsx(Qa,{className:"h-3 w-3 -rotate-90 text-primary"})]})}),l.relationship&&e.jsx(Tt,{children:"Relationship"}),l.stage&&e.jsx(Tt,{children:"Stage"}),l.leadSource&&e.jsx(Tt,{children:"Lead Source"}),l.tags&&e.jsx(Tt,{children:"Tags"}),l.lastTouch&&e.jsx(Tt,{children:"Last Touch"}),l.nextAction&&e.jsx(Tt,{children:"Next Action"}),l.dealValue&&e.jsx(Tt,{title:"Total value of deals linked to this contact in your pipeline",children:"Pipeline Value"}),l.email&&e.jsx(Tt,{children:"Email"}),l.phone&&e.jsx(Tt,{children:"Phone"}),l.address&&e.jsx(Tt,{children:"Address"}),l.birthday&&e.jsx(Tt,{children:"Birthday"}),e.jsx(Tt,{className:"w-[50px]"})]})}),e.jsx(za,{children:p?e.jsx(un,{children:e.jsx(xt,{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(xt,{colSpan:3+Object.values(l).filter(Boolean).length,className:"text-center py-8 text-muted-foreground",children:W||J!=="all"||ue!=="all"||we!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"})}):ts.map(Qt=>{var zr;const{relationshipScore:Zn}=Qt,aa=v==null?void 0:v[Qt.id];return e.jsxs(un,{className:`cursor-pointer hover:bg-accent/50 ${Fe.has(Qt.id)?"bg-accent/30":""}`,onClick:()=>Gt(Qt),children:[e.jsx(xt,{onClick:Na=>Na.stopPropagation(),children:e.jsx(wi,{checked:Fe.has(Qt.id),onCheckedChange:()=>pr(Qt.id)})}),e.jsx(xt,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(jWe,{firstName:Qt.first_name,lastName:Qt.last_name,avatarUrl:Qt.avatar_url,email:Qt.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:[Qt.first_name," ",Qt.last_name]}),e.jsx(i0n,{linked:!!Qt.spouse_contact_id||!!Qt.spouse_name,spouseName:Qt.spouse_contact_id&&We[Qt.spouse_contact_id]||Qt.spouse_name||null}),e.jsx($mt,{count:(g==null?void 0:g[Qt.id])??0})]}),Qt.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Qt.email}),Qt.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Qt.phone})]})]})}),l.relationship&&e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(CRt,{score:Zn.score,status:Zn.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:Zn.status==="warm"?"Strong":Zn.status==="cooling"?"Cooling":"At Risk"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Zn.daysSinceTouch===null?"Never contacted":Zn.daysSinceTouch===0?"Touched today":`${Zn.daysSinceTouch}d since touch`})]})]})}),l.stage&&e.jsx(xt,{children:e.jsx(x9e,{deal:aa})}),l.leadSource&&e.jsx(xt,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((zr=Qt.lead_source_ref)==null?void 0:zr.name)||Qt.lead_source||"—"}),l.tags&&e.jsx(xt,{children:e.jsx("div",{className:"flex flex-wrap items-center gap-1 max-w-[220px]",children:e.jsx(Umt,{contactId:Qt.id,tags:C==null?void 0:C.filter(Na=>Na.contact_id===Qt.id)})})}),l.lastTouch&&e.jsx(xt,{children:Zn.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Vr,{className:"h-3.5 w-3.5"}),Bs(new Date(Zn.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-xs italic text-muted-foreground",children:"No activity"})}),l.nextAction&&e.jsx(xt,{children:e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(aSe,{contact:Qt}),e.jsx(Bmt,{birthday:Qt.birthday,homeAnniversary:Qt.home_anniversary,weddingAnniversary:Qt.wedding_anniversary,contactId:Qt.id,contactName:`${Qt.first_name}${Qt.last_name?" "+Qt.last_name:""}`,contactAddress:[Qt.address,Qt.city,Qt.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(xt,{children:(()=>{const Na=(aa==null?void 0:aa.sale_price)??(aa==null?void 0:aa.expected_price);return Na?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:Su(Number(Na))}),(aa==null?void 0:aa.deal_type)&&e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:String(aa.deal_type).replace(/_/g," ")})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})})()}),l.email&&e.jsx(xt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:Qt.email||"—"}),l.phone&&e.jsx(xt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:Qt.phone||"—"}),l.address&&e.jsx(xt,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[Qt.address,Qt.city,Qt.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(xt,{className:"text-sm text-muted-foreground whitespace-nowrap",children:Qt.birthday?(()=>{const[Na,oa,ur]=String(Qt.birthday).split(/[-/T]/).map(Number);return oa&&ur?`${oa}/${ur}${Na&&Na>1900?`/${Na}`:""}`:"—"})():"—"}),e.jsx(xt,{onClick:Na=>Na.stopPropagation(),children:e.jsx(Omt,{contact:Qt,onEdit:Oe,onDelete:Mr,onSnooze:(Na,oa)=>{Ye(Na),rt(oa)},showLeadPondAction:tn,onSendToLeadPond:Hr,showTransferAction:_n,onTransfer:Xs})})]},Qt.id)})})]})})}),e.jsx(a0n,{contact:zt,deal:zt?v==null?void 0:v[zt.id]:void 0,open:!!zt,onOpenChange:Qt=>{Qt||Gt(null)},onEdit:Qt=>{Gt(null),Oe(Qt)},index:zt?ts.findIndex(Qt=>Qt.id===zt.id):void 0,total:ts.length,onPrev:(()=>{if(!zt)return;const Qt=ts.findIndex(Zn=>Zn.id===zt.id);return Qt>0?()=>Gt(ts[Qt-1]):void 0})(),onNext:(()=>{if(!zt)return;const Qt=ts.findIndex(Zn=>Zn.id===zt.id);return Qt>=0&&QtGt(ts[Qt+1]):void 0})()}),gt>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 ",(Ht-1)*Is+1,"–",Math.min(Ht*Is,gt)," of ",gt.toLocaleString()," contacts"]}),e.jsxs(vs,{value:String(Is),onValueChange:Qt=>{jt(Number(Qt)),At(1)},children:[e.jsx(gs,{className:"w-[80px] h-8",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"50",children:"50"}),e.jsx(Je,{value:"100",children:"100"}),e.jsx(Je,{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:Ht<=1,onClick:()=>At(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ht<=1,onClick:()=>At(Qt=>Qt-1),children:e.jsx(Cc,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Ht," of ",St]}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ht>=St,onClick:()=>At(Qt=>Qt+1),children:e.jsx(Qa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:Ht>=St,onClick:()=>At(St),children:"Last"})]})]}),e.jsx(Fs,{open:Ne||!!_e,onOpenChange:Qt=>{Qt||(Ge(!1),Oe(null),Jr())},children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:_e?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:ha,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"first_name",children:"First Name *"}),e.jsx(ye,{id:"first_name",value:rn.first_name,onChange:Qt=>Jn({...rn,first_name:Qt.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"last_name",children:"Last Name"}),e.jsx(ye,{id:"last_name",value:rn.last_name,onChange:Qt=>Jn({...rn,last_name:Qt.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",value:rn.email,onChange:Qt=>Jn({...rn,email:Qt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Phone"}),e.jsx(ye,{id:"phone",value:rn.phone,onChange:Qt=>Jn({...rn,phone:Qt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"address",children:"Address"}),e.jsx(ye,{id:"address",value:rn.address,onChange:Qt=>Jn({...rn,address:Qt.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(ye,{id:"city",value:rn.city,onChange:Qt=>Jn({...rn,city:Qt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:rn.state,onChange:Qt=>Jn({...rn,state:Qt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"zip_code",children:"Zip"}),e.jsx(ye,{id:"zip_code",value:rn.zip_code,onChange:Qt=>Jn({...rn,zip_code:Qt.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"birthday",children:"Birthday"}),e.jsx(ye,{id:"birthday",type:"date",value:rn.birthday,onChange:Qt=>Jn({...rn,birthday:Qt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(ye,{id:"home_anniversary",type:"date",value:rn.home_anniversary,onChange:Qt=>Jn({...rn,home_anniversary:Qt.target.value})})]})]}),_e&&e.jsx(g9e,{contactId:_e.id,currentSpouseContactId:(_e==null?void 0:_e.spouse_contact_id)||null,currentSpouseName:(_e==null?void 0:_e.spouse_name)||null,currentSpouseEmail:(_e==null?void 0:_e.spouse_email)||null,onLink:Qt=>q.mutate({contactId:_e.id,spouseContactId:Qt}),onUnlink:()=>q.mutate({contactId:_e.id,spouseContactId:null}),isEditing:!0}),e.jsx(kRt,{value:rn.lead_source_id,onChange:Qt=>Jn({...rn,lead_source_id:Qt})}),e.jsxs("div",{children:[e.jsx(se,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:b==null?void 0:b.filter(Qt=>Qt.active).map(Qt=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(wi,{checked:rn.tagIds.includes(Qt.id),onCheckedChange:Zn=>{Jn(Zn?{...rn,tagIds:[...rn.tagIds,Qt.id]}:{...rn,tagIds:rn.tagIds.filter(aa=>aa!==Qt.id)})}}),e.jsx("span",{className:"text-sm",children:Qt.name})]},Qt.id))})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Ds,{id:"notes",value:rn.notes,onChange:Qt=>Jn({...rn,notes:Qt.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{Ge(!1),Oe(null),Jr()},children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:I.isPending||O.isPending,children:[_e?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(tgn,{open:Ae,onOpenChange:Xe,relationshipTypes:(b==null?void 0:b.filter(Qt=>Qt.active))||[],onSuccess:()=>{Xe(!1)}}),e.jsx(rgn,{open:Ue,onOpenChange:Ze,onComplete:()=>Ze(!1)}),e.jsx(MAe,{open:!!Qe,onOpenChange:Qt=>{Qt||Ye(null)},contactId:Qe||"",contactName:nt}),e.jsx(Kgn,{open:qt,onOpenChange:Gs}),e.jsx(Ygn,{open:Ls,onOpenChange:sn}),e.jsx(Vgn,{open:K,onOpenChange:ee,contacts:m||[],onCitySelect:Qt=>{G(Qt),At(1)}}),e.jsx(OMt,{open:Kr,onOpenChange:jr,contactIds:Cn,contactNames:Cn.map(Qt=>{const Zn=it.find(aa=>aa.id===Qt);return Zn?`${Zn.first_name} ${Zn.last_name||""}`.trim():""}),onComplete:()=>{Un([]),dt(new Set),pt(!1)}})]})]})})}const u0n="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function h0n({open:s,onOpenChange:t,contact:n}){var q;const{user:r}=Ns(),a=Hn(),i=as(),{intakePage:l,isLoading:o}=LAe(),{isGmailConnected:c,gmailEmail:d}=Tf(),u=CJ(),{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 U.from("profiles").select("name, email, avatar_url").eq("id",r.id).maybeSingle();return W}}),m=(h==null?void 0:h.name)||((q=r==null?void 0:r.email)==null?void 0:q.split("@")[0])||"Your Agent",p=m.split(" ")[0],x=l?`https://contacts.relevelup.com/${l.slug}`:"",y=j.useMemo(()=>`Hi ${n.first_name}, I'm updating my contact list and want to make sure I have your latest info — the best phone, email, address, and a couple of dates I love to remember (like your birthday and home anniversary). It only takes about a minute, and it helps me stay in touch the right way. Thanks so much!`,[n.first_name]),[g,b]=j.useState("gmail"),[v,k]=j.useState(""),[C,T]=j.useState(""),[M,P]=j.useState(!1);j.useEffect(()=>{s&&(k(`Quick favor, ${n.first_name} — can you update your info?`),T(y),b(c?"gmail":"system"))},[s,y,n.first_name,c]);const L=j.useMemo(()=>C.split(/\n\n+/).map(W=>`

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

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

A note from ${m}

${L}

Update Your Info

Takes about a minute — promise

Share My Info →

${x}

Sent with care by ${m}

Powered by ReLevelUp

`,O=async()=>{if(!l){re.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!v.trim()||!C.trim()){re.error("Subject and message are required");return}P(!0);const W=I(),G=async()=>{const{data:K,error:ee}=await U.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:v,htmlBody:W,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:m}});if(ee)throw ee;if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Failed to send")};try{if(g==="gmail"&&c){const{data:K,error:ee}=await U.functions.invoke("gmail-send",{body:{to:n.email,subject:v,body:W,contactId:n.id}});let J=K&&K.error?K:null;if(ee){J={error:"send_failed",message:ee.message};const le=ee.context;if(le&&typeof le.json=="function")try{J=await le.clone().json()}catch{}}if(J)if(J.error==="insufficient_scope")await G(),re.warning("Sent using system email — your Gmail connection is missing send permission. Reconnect Gmail in Integrations to send from your own inbox.",{duration:8e3});else throw new Error(J.message||J.error||"Failed to send");else if(!(K!=null&&K.success))throw new Error("Failed to send")}else await G();try{await u.mutateAsync({contactId:n.id,actionTypeId:u0n,notes:`Sent Connect Page invite — Subject: "${v}"`})}catch(K){console.warn("Failed to log activity:",K)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),re.success("Connect Page invite sent!"),t(!1)}catch(K){console.error("Send error:",K),re.error(K instanceof Error?K.message:"Failed to send invite")}finally{P(!1)}},$=I();return e.jsx(Fs,{open:s,onOpenChange:W=>!M&&t(W),children:e.jsxs(Os,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(yn,{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(Wt,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(fa,{value:g,onValueChange:W=>b(W),className:"mt-1.5",children:e.jsxs(xa,{className:"grid w-full grid-cols-2",children:[e.jsxs(ss,{value:"gmail",disabled:!c,children:[e.jsx(on,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(ss,{value:"system",children:[e.jsx(yn,{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:g==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(h==null?void 0:h.email)||(r==null?void 0:r.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(ye,{id:"invite-subject",value:v,onChange:W=>k(W.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Ds,{id:"invite-message",value:C,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(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(Tr,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-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:M,children:"Cancel"}),e.jsx(B,{onClick:O,disabled:M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(po,{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(Rc,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function m0n(){const{user:s}=Ns();return mt({queryKey:["cmas",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("cmas").select("*").eq("agent_id",s.id).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function p0n(s){return mt({queryKey:["cma",s],queryFn:async()=>{const{data:t,error:n}=await U.from("cmas").select("*").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function f0n(s){return mt({queryKey:["cma-comps",s],queryFn:async()=>{const{data:t,error:n}=await U.from("cma_comps").select("*").eq("cma_id",s).order("position",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function TRt(){const s=as(),{user:t}=Ns(),{leadSite:n}=h0();return vt({mutationFn:async r=>{const{data:a,error:i}=await U.from("cmas").insert({agent_id:t.id,lead_site_id:(n==null?void 0:n.id)??null,contact_id:r.contactId??null,deal_id:r.dealId??null,buyer_mode:!!r.buyerMode,title:r.title??r.subject.address,subject:r.subject,settings:{sqftPct:.2,monthsBack:6,statuses:["Active","Pending","Closed"]}}).select("*").single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function x0n(){const s=as();return vt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await U.from("cmas").update(n).eq("id",t).select("*").single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cma",n.id]}),s.invalidateQueries({queryKey:["cmas"]})}})}function g0n(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function y0n(){const{leadSite:s}=h0();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.functions.invoke("cma-subject-lookup",{body:{...t,leadSiteId:(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function v0n(){const{leadSite:s}=h0();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.functions.invoke("cma-comp-search",{body:{...t,leadSiteId:t.leadSiteId??(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function b0n(){const s=as();return vt({mutationFn:async({cmaId:t,comps:n})=>{if(await U.from("cma_comps").delete().eq("cma_id",t),!n.length)return;const r=n.map((i,l)=>({cma_id:t,mls_number:i.mlsNumber??null,source_provider:i.source_provider??null,selected:i.selected!==!1,manual:!!i.manual,score:i.score??null,position:l,snapshot:i})),{error:a}=await U.from("cma_comps").insert(r);if(a)throw a},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["cma-comps",n.cmaId]})})}function Kmt(s,t){const n=t.filter(h=>{var m,p;return h.selected!==!1&&(((m=h.snapshot)==null?void 0:m.sqft)||h.sqft)&&(((p=h.snapshot)==null?void 0:p.price)||h.price)});if(!n.length||!s.sqft)return{low:null,likely:null,high:null,ppsf:null};const r=n.map(h=>{const m=h.snapshot||h;return(m.soldPrice||m.price)/m.sqft}).filter(h=>Number.isFinite(h)&&h>0).sort((h,m)=>h-m);if(!r.length)return{low:null,likely:null,high:null,ppsf:null};const a=r[Math.floor(r.length/2)],i=r.reduce((h,m)=>h+m,0)/r.length,l=r.reduce((h,m)=>h+(m-i)**2,0)/r.length,o=Math.sqrt(l),c=Math.round(a*s.sqft),d=Math.round((a-o)*s.sqft),u=Math.round((a+o)*s.sqft);return{low:d,likely:c,high:u,ppsf:Math.round(a)}}function _0n(s){return mt({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("video_replies").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url) `).eq("contact_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function w0n(s){return mt({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function NWe(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("client_portals").insert({deal_id:n.deal_id,owner_user_id:s,slug:"",is_enabled:n.is_enabled??!0,visibility:n.visibility||"private",require_onboarding:n.require_onboarding??!0,allow_spouse:n.allow_spouse??!1,client_name:n.client_name||null,client_email:n.client_email||null,client_phone:n.client_phone||null,invite_method:n.invite_method||"email"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["client-portal",r.deal_id]})}})}function Eq(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("client_portals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function ERt(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("client_portals").update({archived_at:new Date().toISOString(),is_enabled:!1}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function MRt(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("client_portals").update({archived_at:null}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function LRt(){const s=as();return vt({mutationFn:async({id:t,dealId:n})=>{await U.from("portal_updates").delete().eq("portal_id",t);const{error:r}=await U.from("client_portals").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function j0n(s){return mt({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function PRt(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("portal_updates").insert({portal_id:t.portal_id,title:t.title,content:t.content||null,video_url:t.video_url||null,is_stage_change:t.is_stage_change||!1}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-updates",n.portal_id]})}})}function N0n(){const s=ei();return mt({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("portal_custom_questions").select("*").eq("owner_user_id",s).eq("is_active",!0).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function k0n(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("portal_custom_questions").insert({owner_user_id:s,question_text:n.question_text,field_type:n.field_type,options:n.options||[],is_required:n.is_required||!1,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function S0n(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("portal_custom_questions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function C0n(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function q5(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function A0n({contactId:s}){const t=Hn(),n=as(),[r,a]=j.useState(null),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(null),y=Eq(),g=PRt(),{data:b,isLoading:v}=mt({queryKey:["contact-portals",s],queryFn:async()=>{const{data:L,error:I}=await U.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(I)throw I;if(!L||L.length===0)return[];const O=L.map(W=>W.id),{data:$,error:q}=await U.from("client_portals").select("*").in("deal_id",O).is("archived_at",null);if(q)throw q;return($||[]).map(W=>({...W,deal:L.find(G=>G.id===W.deal_id)}))},enabled:!!s}),k=(b==null?void 0:b.map(L=>L.id))||[],{data:C}=mt({queryKey:["contact-portal-updates",k],queryFn:async()=>{if(k.length===0)return{};const{data:L,error:I}=await U.from("portal_updates").select("*").in("portal_id",k).order("created_at",{ascending:!1});if(I)throw I;const O={};return(L||[]).forEach($=>{O[$.portal_id]||(O[$.portal_id]=$)}),O},enabled:k.length>0}),T=L=>{navigator.clipboard.writeText(q5(L)),a(L),re.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},M=async L=>{d.trim()&&(await g.mutateAsync({portal_id:L,title:d,content:h||void 0}),c(!1),u(""),m(""),n.invalidateQueries({queryKey:["contact-portal-updates"]}),re.success("Portal update posted!"))},P=async()=>{p&&(await y.mutateAsync({id:p.id,welcome_message:p.welcome_message,next_step_text:p.next_step_text,is_enabled:p.is_enabled,show_post_close_tips:p.show_post_close_tips,review_url:p.review_url}),l(!1),x(null),n.invalidateQueries({queryKey:["contact-portals",s]}),re.success("Portal settings updated!"))};return v||!b||b.length===0?null:e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(Ql,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Re,{className:"space-y-3",children:b.map(L=>{var q,W,G;const I=((q=L.stage_mapping)==null?void 0:q.length)>0?L.stage_mapping:L3e(((W=L.deal)==null?void 0:W.deal_type)||"buyer"),O=I==null?void 0:I[L.current_stage_index??0],$=C==null?void 0:C[L.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=L.deal)==null?void 0:G.deal_name)||"Portal"}),O&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",O.label||O.name]})]}),e.jsx(qe,{variant:L.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:L.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:Bs(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(L.slug),children:[r===L.slug?e.jsx(da,{className:"h-3 w-3 mr-1"}):e.jsx(ja,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(q5(L.slug),"_blank"),children:[e.jsx(Tr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(Fs,{open:o,onOpenChange:c,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(ro,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:d,onChange:K=>u(K.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Details (optional)"}),e.jsx(Ds,{value:h,onChange:K=>m(K.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(B,{onClick:()=>M(L.id),disabled:!d.trim()||g.isPending,className:"w-full",children:[e.jsx(Dr,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(Fs,{open:i,onOpenChange:l,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{x({...L}),l(!0)},children:[e.jsx(ic,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Portal Settings"})}),p&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Portal Enabled"}),e.jsx(Mn,{checked:p.is_enabled,onCheckedChange:K=>x({...p,is_enabled:K})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Welcome Message"}),e.jsx(Ds,{value:p.welcome_message||"",onChange:K=>x({...p,welcome_message:K.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Next Step"}),e.jsx(ye,{value:p.next_step_text||"",onChange:K=>x({...p,next_step_text:K.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Review URL"}),e.jsx(ye,{value:p.review_url||"",onChange:K=>x({...p,review_url:K.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Show Post-Close Tips"}),e.jsx(Mn,{checked:p.show_post_close_tips,onCheckedChange:K=>x({...p,show_post_close_tips:K})})]}),e.jsx(Xl,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{onClick:P,disabled:y.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${L.deal_id}`),children:[e.jsx(Xa,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),b.length>1&&e.jsx(Xl,{})]},L.id)})})]})}function T0n({contactId:s}){const{data:t}=mt({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await U.from("lead_sites").select("id, subdomain_slug").eq("is_active",!0);if(o)throw o;return new Map((l||[]).map(c=>[c.id,c.subdomain_slug]))},staleTime:6e5}),n=t&&t.size>0,{data:r,isLoading:a}=mt({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await U.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!n});if(!n||a||!r||r.length===0)return null;const i=l=>{const o=t==null?void 0:t.get(l.lead_site_id);return o?`https://${o}.thelocalmove.com/listing/${l.mls_number}`:null};return e.jsxs(be,{className:"overflow-hidden",children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:"h-7 w-7 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(ma,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(qe,{variant:"secondary",className:"text-xs ml-auto",children:[r.length," ",r.length===1?"property":"properties"]})]})}),e.jsx(Re,{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(ia,{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(Vr,{className:"h-3 w-3"}),e.jsx("span",{title:Bs(new Date(l.viewed_at),"PPp"),children:oc(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 E0n=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function Ymt({value:s,onChange:t,onAdd:n,suggestions:r,placeholder:a,icon:i}){const[l,o]=j.useState(!1),c=j.useRef(null),d=j.useRef(null);j.useEffect(()=>{const h=m=>{d.current&&!d.current.contains(m.target)&&c.current&&!c.current.contains(m.target)&&o(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const u=r.filter(h=>h.toLowerCase().includes(s.toLowerCase()));return e.jsxs("div",{className:"relative flex-1",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ye,{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(Po,{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(Js,{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(oi,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function M0n({contactId:s,contactName:t}){var ie,de,we;const{user:n}=Ns(),r=ei(),{hasLeadSite:a}=h0(),i=as(),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(!1),[x,y]=j.useState(""),[g,b]=j.useState(null),[v,k]=j.useState(!1),[C,T]=j.useState(!1),{data:M}=mt({queryKey:["agent-lead-site-config",r],queryFn:async()=>{const{data:je,error:xe}=await U.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(xe||!je)return{cities:[],zipCodes:[]};const fe=je.theme_config||{},Se=Array.isArray(fe.searchCities)?fe.searchCities:[];je.mls_market_area&&!Se.includes(je.mls_market_area)&&Se.unshift(je.mls_market_area);const Ee=Array.isArray(fe.searchZipCodes)?fe.searchZipCodes:[];return{cities:Se,zipCodes:Ee}},enabled:!!r}),{data:P,isLoading:L}=mt({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:je,error:xe}=await U.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(xe)throw xe;return je},enabled:!!s&&!!n}),[I,O]=j.useState({}),$=()=>{O({is_active:(P==null?void 0:P.is_active)??!0,min_price:(P==null?void 0:P.min_price)??null,max_price:(P==null?void 0:P.max_price)??null,min_beds:(P==null?void 0:P.min_beds)??null,min_baths:(P==null?void 0:P.min_baths)??null,min_sqft:(P==null?void 0:P.min_sqft)??null,max_sqft:(P==null?void 0:P.max_sqft)??null,cities:(P==null?void 0:P.cities)??[],zip_codes:(P==null?void 0:P.zip_codes)??[],property_types:(P==null?void 0:P.property_types)??[],frequency:(P==null?void 0:P.frequency)??"daily"}),o(!0)},q=vt({mutationFn:async()=>{const je={contact_id:s,owner_user_id:r,is_active:I.is_active??!0,min_price:I.min_price||null,max_price:I.max_price||null,min_beds:I.min_beds||null,min_baths:I.min_baths||null,min_sqft:I.min_sqft||null,max_sqft:I.max_sqft||null,cities:I.cities||[],zip_codes:I.zip_codes||[],property_types:I.property_types||[],frequency:I.frequency||"daily"};if(P!=null&&P.id){const{error:xe}=await U.from("contact_property_alerts").update(je).eq("id",P.id);if(xe)throw xe}else{const{error:xe}=await U.from("contact_property_alerts").insert(je);if(xe)throw xe}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),re.success("Property alert saved!")},onError:je=>{re.error(je.message||"Failed to save alert")}}),W=vt({mutationFn:async()=>{if(!(P!=null&&P.id))return;const{error:je}=await U.from("contact_property_alerts").delete().eq("id",P.id);if(je)throw je},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),re.success("Property alert removed")}}),G=je=>{var fe;const xe=je.trim();xe&&!((fe=I.cities)!=null&&fe.includes(xe))&&O(Se=>({...Se,cities:[...Se.cities||[],xe]})),d("")},K=je=>{var fe;const xe=je.trim();xe&&!((fe=I.zip_codes)!=null&&fe.includes(xe))&&O(Se=>({...Se,zip_codes:[...Se.zip_codes||[],xe]})),h("")},ee=je=>{O(xe=>{const fe=xe.property_types||[];return{...xe,property_types:fe.includes(je)?fe.filter(Se=>Se!==je):[...fe,je]}})},J=async()=>{if(P!=null&&P.id){k(!0),p(!0),y(""),b(null);try{const{data:je,error:xe}=await U.functions.invoke("process-property-alerts",{body:{alert_id:P.id,mode:"preview"}});if(xe)throw xe;je!=null&&je.html?(y(je.html),b({count:je.listings_count||0,recipient:je.recipient,subject:je.subject})):b({count:0,message:(je==null?void 0:je.message)||"No matching listings found right now."})}catch(je){re.error(je.message||"Failed to generate preview"),p(!1)}finally{k(!1)}}},le=async()=>{if(P!=null&&P.id&&await Bi(`Send property alert email to ${t} now?`)){T(!0);try{const{data:je,error:xe}=await U.functions.invoke("process-property-alerts",{body:{alert_id:P.id,mode:"send"}});if(xe)throw xe;je!=null&&je.sent_count?(re.success(`Sent ${je.sent_count} ${je.sent_count===1?"listing":"listings"} to ${je.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):re.info((je==null?void 0:je.message)||"No new matching listings to send right now.")}catch(je){re.error(je.message||"Failed to send alert")}finally{T(!1)}}};if(!a||L)return null;if(P&&!l)return e.jsxs(e.Fragment,{children:[e.jsxs(be,{className:"overflow-hidden",children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${P.is_active?"bg-green-500/10":"bg-muted"}`,children:P.is_active?e.jsx(Nx,{className:"h-4 w-4 text-green-600"}):e.jsx(L5,{className:"h-4 w-4 text-muted-foreground"})}),"Property Alerts",e.jsxs(qe,{variant:P.is_active?"default":"secondary",className:"text-xs ml-auto",children:[P.is_active?"Active":"Paused"," · ",P.frequency]})]})}),e.jsxs(Re,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[P.min_price||P.max_price?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(Od,{className:"h-3 w-3"}),P.min_price?`$${(P.min_price/1e3).toFixed(0)}k`:"$0"," - ",P.max_price?`$${(P.max_price/1e3).toFixed(0)}k`:"Any"]}):null,P.min_beds?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(p3,{className:"h-3 w-3"}),P.min_beds,"+ beds"]}):null,P.min_baths?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(t0,{className:"h-3 w-3"}),P.min_baths,"+ baths"]}):null,(ie=P.cities)==null?void 0:ie.map(je=>e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(oi,{className:"h-3 w-3"}),je]},je)),(de=P.zip_codes)==null?void 0:de.map(je=>e.jsx(qe,{variant:"outline",children:je},je)),(we=P.property_types)==null?void 0:we.map(je=>e.jsx(qe,{variant:"outline",children:je},je))]}),P.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(P.last_sent_at).toLocaleDateString()]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:J,disabled:v,children:[v?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ma,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs(B,{size:"sm",onClick:le,disabled:C||!P.is_active,title:P.is_active?"Send this alert email now":"Activate alert to send",children:[C?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Dr,{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(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(dr,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(Fs,{open:m,onOpenChange:p,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Property Alert Email Preview"}),(g==null?void 0:g.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:"})," ",g.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",g.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",g.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:v?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(Wt,{className:"h-5 w-5 mr-2 animate-spin"})," Building preview…"]}):x?e.jsx("iframe",{srcDoc:x,title:"Property alert preview",className:"w-full h-[65vh] bg-white rounded-md"}):e.jsx("div",{className:"flex items-center justify-center h-96 text-sm text-muted-foreground p-6 text-center",children:(g==null?void 0:g.message)||"No matching listings found right now."})}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>p(!1),children:"Close"}),x&&e.jsxs(B,{onClick:()=>{p(!1),le()},disabled:C||!P.is_active,children:[e.jsx(Dr,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]});const ue=((M==null?void 0:M.cities)||[]).filter(je=>{var xe;return!((xe=I.cities)!=null&&xe.includes(je))}),oe=((M==null?void 0:M.zipCodes)||[]).filter(je=>{var xe;return!((xe=I.zip_codes)!=null&&xe.includes(je))});return l?e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(Nx,{className:"h-4 w-4 text-primary"}),P?"Edit":"Setup"," Property Alert for ",t]})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Alert Active"}),e.jsx(Mn,{checked:I.is_active??!0,onCheckedChange:je=>O(xe=>({...xe,is_active:je}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Od,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ye,{type:"number",placeholder:"Min price",value:I.min_price??"",onChange:je=>O(xe=>({...xe,min_price:je.target.value?Number(je.target.value):null}))}),e.jsx(ye,{type:"number",placeholder:"Max price",value:I.max_price??"",onChange:je=>O(xe=>({...xe,max_price:je.target.value?Number(je.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(p3,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(vs,{value:I.min_beds?String(I.min_beds):"any",onValueChange:je=>O(xe=>({...xe,min_beds:je==="any"?null:Number(je)})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Any"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"any",children:"Any"}),[1,2,3,4,5].map(je=>e.jsxs(Je,{value:String(je),children:[je,"+"]},je))]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(t0,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(vs,{value:I.min_baths?String(I.min_baths):"any",onValueChange:je=>O(xe=>({...xe,min_baths:je==="any"?null:Number(je)})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Any"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(je=>e.jsxs(Je,{value:String(je),children:[je,"+"]},je))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(j3,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ye,{type:"number",placeholder:"Min sqft",value:I.min_sqft??"",onChange:je=>O(xe=>({...xe,min_sqft:je.target.value?Number(je.target.value):null}))}),e.jsx(ye,{type:"number",placeholder:"Max sqft",value:I.max_sqft??"",onChange:je=>O(xe=>({...xe,max_sqft:je.target.value?Number(je.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(oi,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(Ymt,{value:c,onChange:d,onAdd:G,suggestions:ue,placeholder:"Type to search cities..."}),I.cities&&I.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:I.cities.map(je=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[je,e.jsx("button",{onClick:()=>O(xe=>{var fe;return{...xe,cities:(fe=xe.cities)==null?void 0:fe.filter(Se=>Se!==je)}}),children:e.jsx(dr,{className:"h-3 w-3"})})]},je))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(Ymt,{value:u,onChange:h,onAdd:K,suggestions:oe,placeholder:"Type to search zip codes...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),I.zip_codes&&I.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:I.zip_codes.map(je=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[je,e.jsx("button",{onClick:()=>O(xe=>{var fe;return{...xe,zip_codes:(fe=xe.zip_codes)==null?void 0:fe.filter(Se=>Se!==je)}}),children:e.jsx(dr,{className:"h-3 w-3"})})]},je))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ia,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:E0n.map(je=>{var xe;return e.jsx(qe,{variant:(xe=I.property_types)!=null&&xe.includes(je)?"default":"outline",className:"cursor-pointer",onClick:()=>ee(je),children:je},je)})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"mb-1.5",children:"Frequency"}),e.jsxs(vs,{value:I.frequency||"daily",onValueChange:je=>O(xe=>({...xe,frequency:je})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"daily",children:"Daily"}),e.jsx(Je,{value:"weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>q.mutate(),disabled:q.isPending,className:"flex-1",children:[q.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-1"}),"Save Alert"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),P&&e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>W.mutate(),disabled:W.isPending,children:e.jsx(dr,{className:"h-4 w-4"})})]})]})]}):e.jsx(be,{className:"overflow-hidden",children:e.jsx(Re,{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(Nx,{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 L0n({contactId:s,contactName:t}){var ee;const{user:n}=Ns(),r=ei(),{hasLeadSite:a}=h0(),i=as(),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,p]=j.useState(!1),[x,y]=j.useState(!1),[g,b]=j.useState(!1),[v,k]=j.useState(""),C=j.useRef(null),T=j.useRef(null),{data:M}=mt({queryKey:["agent-lead-site-cities",r],queryFn:async()=>{const{data:J,error:le}=await U.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(le||!J)return[];const ue=J.theme_config||{},oe=Array.isArray(ue.searchCities)?ue.searchCities:[];return J.mls_market_area&&!oe.includes(J.mls_market_area)&&oe.unshift(J.mls_market_area),oe},enabled:!!r}),{data:P,isLoading:L}=mt({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:J,error:le}=await U.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(le)throw le;return J},enabled:!!s&&!!n});j.useEffect(()=>{const J=le=>{T.current&&!T.current.contains(le.target)&&C.current&&!C.current.contains(le.target)&&y(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[]);const I=()=>{p((P==null?void 0:P.market_report_enabled)??!1),h((P==null?void 0:P.market_report_cities)??[]),o(!0)},O=J=>{const le=(J||c).trim();le&&!u.includes(le)&&h([...u,le]),d(""),y(!1)},$=(M||[]).filter(J=>!u.includes(J)&&J.toLowerCase().includes(c.toLowerCase())),q=vt({mutationFn:async()=>{const{data:J,error:le}=await U.functions.invoke("send-market-report",{body:{action:"preview",agentId:r,cities:(P==null?void 0:P.market_report_cities)??[]}});if(le)throw new Error(le.message||"Failed to generate preview");if(J&&!J.ok&&J.error)throw new Error(J.error);return J},onSuccess:J=>{k(J.html),b(!0)},onError:J=>{re.error(J.message||"Failed to generate preview")}}),W=vt({mutationFn:async()=>{const{data:J,error:le}=await U.functions.invoke("send-market-report",{body:{action:"send",agentId:r,cities:(P==null?void 0:P.market_report_cities)??[],contactIds:[s]}});if(le)throw new Error(le.message||"Failed to send report");if(J&&!J.ok&&J.error)throw new Error(J.error);return J},onSuccess:()=>{re.success(`Market report sent to ${t}!`)},onError:J=>{re.error(J.message||"Failed to send report")}}),G=vt({mutationFn:async()=>{const{error:J}=await U.from("innercircle_contacts").update({market_report_enabled:m,market_report_cities:u}).eq("id",s);if(J)throw J},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),re.success(m?"Monthly market report enabled!":"Market report disabled")},onError:J=>{re.error(J.message||"Failed to save")}}),K=vt({mutationFn:async()=>{const{error:J}=await U.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(J)throw J},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),p(!1),h([]),re.success("Market report removed")},onError:J=>{re.error(J.message||"Failed to remove market report")}});return!a||L?null:P!=null&&P.market_report_enabled&&!l?e.jsxs(be,{className:"overflow-hidden",children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:"h-7 w-7 rounded-lg flex items-center justify-center bg-primary/10",children:e.jsx(ol,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(qe,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Re,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((ee=P.market_report_cities)==null?void 0:ee.length)>0?P.market_report_cities.map(J=>e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(oi,{className:"h-3 w-3"}),J]},J)):e.jsx("span",{className:"text-muted-foreground",children:"Using default market area"})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t," receives a branded market report on the 1st of each month."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>q.mutate(),disabled:q.isPending,className:"flex-1",children:[q.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ma,{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(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:I,className:"flex-1",children:"Manage"}),e.jsxs(B,{variant:"destructive",size:"sm",onClick:()=>K.mutate(),disabled:K.isPending,className:"flex-1",children:[K.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(dr,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(Fs,{open:g,onOpenChange:b,children:e.jsxs(Os,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(ol,{className:"h-5 w-5 text-primary"}),"Market Report Preview"]})}),e.jsx("div",{className:"flex-1 overflow-y-auto -mx-6 px-6",children:e.jsx("div",{className:"border rounded-lg overflow-hidden",dangerouslySetInnerHTML:{__html:v}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs(B,{onClick:()=>{b(!1),W.mutate()},disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(B,{variant:"outline",onClick:()=>b(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(ol,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Send Monthly Report"}),e.jsx(Mn,{checked:m,onCheckedChange:p})]}),m&&e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(oi,{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(ye,{ref:C,value:c,onChange:J=>{d(J.target.value),y(!0)},onFocus:()=>y(!0),placeholder:"Type to search cities...",onKeyDown:J=>{J.key==="Enter"&&(J.preventDefault(),$.length>0?O($[0]):O())}}),e.jsx(Po,{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:()=>O(),children:e.jsx(Js,{className:"h-4 w-4"})})]}),x&&$.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(J=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>O(J),children:[e.jsx(oi,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),J]},J))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(J=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[J,e.jsx("button",{onClick:()=>h(u.filter(le=>le!==J)),children:e.jsx(dr,{className:"h-3 w-3"})})]},J))})]}),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(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(be,{className:"overflow-hidden",children:e.jsx(Re,{className:"p-4",children:e.jsxs("button",{onClick:I,className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed border-primary/30 hover:bg-primary/5 transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(ol,{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 P0n(s){return mt({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:n}=await U.from("drip_campaign_enrollments").select("id, campaign_id, current_step, status, next_send_at, enrolled_at, completed_at, exited_at, exit_reason").eq("contact_id",s).order("enrolled_at",{ascending:!1});if(n)throw console.error("[ContactDripActivity] enrollments error",n),n;const r=(t||[]).map(c=>c.id),a=Array.from(new Set((t||[]).map(c=>c.campaign_id)));let i=new Map;if(a.length>0){const{data:c}=await U.from("drip_campaigns").select("id, name, description, is_active").in("id",a);(c||[]).forEach(d=>i.set(d.id,d))}const l=(t||[]).map(c=>({...c,campaign:i.get(c.campaign_id)||null}));let o=[];if(r.length>0){const{data:c,error:d}=await U.from("drip_campaign_step_log").select("id, enrollment_id, campaign_id, step_order, channel, recipient_email, subject, status, error_message, sent_at").in("enrollment_id",r).order("sent_at",{ascending:!1});d?console.error("[ContactDripActivity] step log error",d):o=(c||[]).map(u=>{var h;return{...u,campaign:{name:((h=i.get(u.campaign_id))==null?void 0:h.name)??""}}})}return{enrollments:l,stepLogs:o}},enabled:!!s})}function I0n(s){switch(s){case"active":return e.jsx(qe,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(qe,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(qe,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(qe,{variant:"outline",children:"Exited"});default:return e.jsx(qe,{variant:"outline",children:s})}}function Zmt(s){return s==="sent"?e.jsx(Rr,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(hd,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(ay,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Vr,{className:"h-4 w-4 text-muted-foreground"})}function R0n({contactId:s}){const t=Hn(),{data:n,isLoading:r}=P0n(s),[a,i]=j.useState(null);if(r)return null;const l=(n==null?void 0:n.enrollments)||[],o=(n==null?void 0:n.stepLogs)||[];return l.length===0&&o.length===0?null:e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(nE,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Re,{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(nE,{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"}),I0n(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: ",oc(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",oc(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",oc(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(Fs,{open:(a==null?void 0:a.id)===c.id,onOpenChange:h=>!h&&i(null),children:[e.jsx(Io,{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:Zmt(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(ro,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(on,{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"," · ",Bs(new Date(c.sent_at),"MMM d, h:mm a")]}),c.status==="failed"&&c.error_message&&e.jsx("p",{className:"text-xs text-destructive mt-0.5 truncate",children:c.error_message})]})]})}),e.jsxs(Os,{className:"max-w-lg",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[Zmt(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:Bs(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 IRt({contactId:s}={}){const{user:t}=Ns();return mt({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const n=t.id;let r=U.from("gmail_sent_emails").select("id, contact_id, to_email, subject, sent_at, source").eq("user_id",n).or("source.is.null,source.neq.drip_campaign").order("sent_at",{ascending:!1}).limit(1e3);s&&(r=r.eq("contact_id",s));let a=U.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source, opened_at, clicked_at").eq("user_id",n).order("sent_at",{ascending:!1}).limit(1e3);s&&(a=a.eq("contact_id",s));const i=await U.from("email_campaigns").select("id, subject").eq("user_id",n),l=(i.data||[]).map(y=>y.id),o=new Map((i.data||[]).map(y=>[y.id,y.subject]));let c=[];if(l.length>0){let y=U.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",l).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1}).limit(1e3);s&&(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})),p=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})),x=[...h,...m,...p];return x.sort((y,g)=>y.sent_at0&&e.jsx(qe,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Re,{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(on,{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(qe,{variant:"outline",className:`text-xs ${D0n[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Bs(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(Yn,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function F0n({videoId:s}){var l;const{data:t,isLoading:n,error:r}=Cgn(s);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(gn,{className:"w-full aspect-video rounded-lg"}),e.jsx(gn,{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(hd,{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 z0n({contactId:s}){const t=Hn(),[n,r]=j.useState(!1),{data:a,isLoading:i}=mt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await U.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(m)throw m;return h},enabled:!!s}),l=async(h,m)=>{const p=m==="done"?"todo":"done";await U.from("deal_tasks").update({status:p,completed_at:p==="done"?new Date().toISOString():null}).eq("id",h),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=mt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await U.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(m)throw m;return h},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(h=>h.status!=="done"))||[],u=(a==null?void 0:a.filter(h=>h.status==="done"))||[];return e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(qe,{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(Js,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Re,{className:"space-y-1",children:i?e.jsx(gn,{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:Bs(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(B0n,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function B0n({contactId:s,open:t,onOpenChange:n}){const[r,a]=j.useState(""),[i,l]=j.useState("medium"),[o,c]=j.useState(),{data:d}=mt({queryKey:["session"],queryFn:async()=>{const{data:h}=await U.auth.getSession();return h.session}}),u=async()=>{var m;if(!r.trim()||!((m=d==null?void 0:d.user)!=null&&m.id))return;const{error:h}=await U.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:r.trim(),priority:i,status:"todo",due_date:o?Bs(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(Fs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"sm:max-w-[400px]",children:[e.jsx($s,{children:e.jsx(zs,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:r,onChange:h=>a(h.target.value),placeholder:"Task title...",onKeyDown:h=>h.key==="Enter"&&u()})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Priority"}),e.jsxs("select",{value:i,onChange:h=>l(h.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"low",children:"🟢 Low"}),e.jsx("option",{value:"medium",children:"🟡 Medium"}),e.jsx("option",{value:"high",children:"🟠 High"}),e.jsx("option",{value:"urgent",children:"🔴 Urgent"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due Date"}),e.jsx(ye,{type:"date",value:o?Bs(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 $0n({contactId:s}){const t=Hn(),{data:n,isLoading:r}=mt({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await U.from("deal_pipeline").select(` id, deal_name, deal_type, expected_price, property_address, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).eq("contact_id",s).order("updated_at",{ascending:!1});if(i)throw i;return a},enabled:!!s});return r||!n||n.length===0?null:e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(kx,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Re,{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(qe,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(qe,{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(Xa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function U0n(){var At,Is,jt,Qs,cn;const{contactId:s}=$i(),t=Hn(),[n]=dc(),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=j.useMemo(()=>new Set(l.split(",").map(qt=>qt.trim()).filter(Boolean)),[l]),{data:d,isLoading:u}=rks(s||""),{data:h}=lw(),{data:m}=tq(),{data:p}=sq(3650),{data:x}=PAe(365),{data:y}=_0n(s),{contactsWithScores:g}=G3e(),{data:b}=EAe(),v=_Ve(),k=wVe(),C=CJ(),T=VCt(),[M,P]=j.useState(!1),[L,I]=j.useState({}),[O,$]=j.useState(!1),[q,W]=j.useState(null),[G,K]=j.useState(""),[ee,J]=j.useState(void 0),[le,ue]=j.useState(""),[oe,ie]=j.useState(null),[de,we]=j.useState(!1),[je,xe]=j.useState(null),[fe,Se]=j.useState(!1),{isGmailConnected:Ee,gmailEmail:Le}=Tf(),{isReady:De}=Cq(),Be=De||Ee,Ne=TRt(),[Ge,_e]=j.useState(!1),{data:Oe}=mt({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:qt}}=await U.auth.getUser();if(!qt)return!1;const{data:Gs}=await U.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",qt.id);return(Gs||[]).some(Ls=>Ls.is_active&&Ls.mls_provider_id&&!Ls.no_mls_mode)}}),Ae=async()=>{var Hs,nn,tn,_n;if(!d)return;const qt=(Hs=d.address)==null?void 0:Hs.trim(),Gs=(nn=d.city)==null?void 0:nn.trim(),Ls=(tn=d.state)==null?void 0:tn.trim().toUpperCase(),sn=((_n=d.zip_code)==null?void 0:_n.trim())||"";if(!qt||!Gs||!Ls){re.error("Add a full address (street, city, state) before creating a CMA.");return}try{_e(!0);const Cn=await Ne.mutateAsync({subject:{address:qt,city:Gs,state:Ls,zip:sn},contactId:d.id,title:`${d.first_name||""} ${d.last_name||""}`.trim()+" — "+qt});t(`/mission-control/cma/${Cn.id}`)}catch(Cn){re.error("Could not create CMA: "+((Cn==null?void 0:Cn.message)||"unknown error"))}finally{_e(!1)}},{data:Xe}=mt({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:qt,error:Gs}=await U.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(Gs)throw Gs;return qt},enabled:!!s}),Ue=qt=>{if(!qt)return null;const Gs=qt.match(/Video ID:\s*([a-f0-9-]+)/i);return Gs?Gs[1]:null},Ze=j.useMemo(()=>{if(!g)return[];const qt=new Map;if(c.size>0&&b)for(const Ls of b)qt.has(Ls.contact_id)||qt.set(Ls.contact_id,new Set),qt.get(Ls.contact_id).add(Ls.tag_id);let Gs=g.filter(Ls=>{var tn,_n,Cn;const sn=r===""||`${Ls.first_name} ${Ls.last_name}`.toLowerCase().includes(r.toLowerCase())||((tn=Ls.email)==null?void 0:tn.toLowerCase().includes(r.toLowerCase()))||((_n=Ls.phone)==null?void 0:_n.includes(r)),Hs=a==="all"||((Cn=Ls.tags)==null?void 0:Cn.some(Un=>Un.relationship_type_id===a));let nn=!0;if(c.size>0){const Un=qt.get(Ls.id)||new Set;o==="all"?nn=Array.from(c).every(Kr=>Un.has(Kr)):nn=Array.from(c).some(Kr=>Un.has(Kr))}return sn&&Hs&&nn});return i==="not-touched-90"?Gs=Gs.filter(Ls=>{const sn=Ls.relationshipScore.daysSinceTouch;return sn===null||sn>90}):i==="at-risk"?Gs=Gs.filter(Ls=>Ls.relationshipScore.status==="at-risk"):i==="cooling"?Gs=Gs.filter(Ls=>Ls.relationshipScore.status==="cooling"):i==="warm"&&(Gs=Gs.filter(Ls=>Ls.relationshipScore.status==="warm")),Gs.map(Ls=>Ls.id)},[g,r,a,i,c,o,b]),Qe=Ze.indexOf(s||""),Ye=Qe>0?Ze[Qe-1]:null,nt=Qe1&&Qe!==-1,Fe=qt=>{const Gs=new URLSearchParams;r&&Gs.set("search",r),a!=="all"&&Gs.set("type",a),i!=="all"&&Gs.set("status",i),c.size>0&&(Gs.set("tags",Array.from(c).join(",")),Gs.set("tagMode",o));const Ls=Gs.toString();return`/mission-control/contacts/${qt}${Ls?`?${Ls}`:""}`},dt=j.useMemo(()=>{const qt=((p==null?void 0:p.filter(Ls=>Ls.contact_id===s))||[]).map(Ls=>{var tn,_n,Cn;const sn=Ue(Ls.notes);let Hs=((tn=Ls.action_type)==null?void 0:tn.name)||"Touch",nn=Ls.notes;if(Hs==="Other"&&((_n=Ls.notes)!=null&&_n.startsWith("["))){const Un=Ls.notes.indexOf("]");Un>0&&(Hs=Ls.notes.substring(1,Un),nn=Ls.notes.substring(Un+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:Ls.id,type:"touch",completed_at:Ls.completed_at,name:Hs,color:((Cn=Ls.action_type)==null?void 0:Cn.color)||"#3B82F6",notes:nn,videoId:sn}}),Gs=((x==null?void 0:x.filter(Ls=>Ls.contact_id===s))||[]).map(Ls=>({id:Ls.id,type:"popby",completed_at:Ls.completed_at,name:"Pop-by",color:"#F97316",notes:Ls.notes,videoId:null}));return[...qt,...Gs].sort((Ls,sn)=>new Date(sn.completed_at).getTime()-new Date(Ls.completed_at).getTime())},[p,x,s]),Dt=()=>{var qt;d&&(I({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:((qt=d.tags)==null?void 0:qt.map(Gs=>Gs.relationship_type_id))||[]}),P(!0))},pt=async()=>{await v.mutateAsync({id:s,...L,lead_source_id:L.lead_source_id||null}),P(!1)},zt=async()=>{await Bi("Are you sure you want to delete this contact?")&&(await k.mutateAsync(s),t("/mission-control/contacts"))},qs=((At=m==null?void 0:m.find(qt=>qt.id===q))==null?void 0:At.name)==="Other",As=async()=>{if(!q||qs&&!le.trim())return;const qt=ee?new Date(ee.getFullYear(),ee.getMonth(),ee.getDate(),12,0,0).toISOString():void 0,Gs=qs?`[${le.trim()}]${G?" — "+G:""}`:G;await C.mutateAsync({contactId:s,actionTypeId:q,notes:Gs,completedAt:qt}),$(!1),W(null),K(""),J(void 0),ue("")},Bt=(qt,Gs)=>{Be&&d?(xe({email:qt,name:Gs||`${d.first_name} ${d.last_name||""}`.trim()}),we(!0)):window.location.href=`mailto:${qt}`};return u?e.jsx(Vs,{title:"Contact Details",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):d?e.jsxs(e.Fragment,{children:[e.jsx(Vs,{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(Cc,{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:()=>Ye&&t(Fe(Ye)),disabled:!Ye,className:"px-2",children:[e.jsx(Cc,{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:[Qe+1," of ",Ze.length]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>nt&&t(Fe(nt)),disabled:!nt,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(ro,{className:"h-4 w-4 mr-1"}),"Text"]}),d.email&&e.jsxs(B,{variant:"outline",onClick:()=>Bt(d.email,`${d.first_name} ${d.last_name||""}`.trim()),children:[e.jsx(on,{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(yn,{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(Zr,{className:"h-4 w-4 mr-1"}),"Quick Video Touch"]}),e.jsxs(Fs,{open:O,onOpenChange:$,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(Js,{className:"h-4 w-4 mr-1"}),"Log Action"]})}),e.jsxs(Os,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Action Type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2 mt-2",children:m==null?void 0:m.filter(qt=>qt.active).map(qt=>e.jsxs("button",{onClick:()=>W(qt.id),className:` p-3 rounded-lg border text-left transition-all ${q===qt.id?"border-primary bg-primary/10":"hover:bg-accent"} `,children:[e.jsx("div",{className:"font-medium",children:qt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:qt.description})]},qt.id))}),qs&&e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(ye,{id:"custom-action-name",value:le,onChange:qt=>ue(qt.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Date (optional — backdate if needed)"}),e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal mt-2",!ee&&"text-muted-foreground"),children:[e.jsx(ra,{className:"h-4 w-4 mr-2"}),ee?Bs(ee,"PPP"):"Today (default)"]})}),e.jsx(Jl,{className:"w-auto p-0",align:"start",children:e.jsx(o1,{mode:"single",selected:ee,onSelect:J,disabled:qt=>qt>new Date,initialFocus:!0,className:Et("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(Ds,{id:"action-notes",value:G,onChange:qt=>K(qt.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(B,{onClick:As,disabled:!q||qs&&!le.trim()||C.isPending,className:"w-full",children:[e.jsx(da,{className:"h-4 w-4 mr-1"}),"Complete Action"]})]})]})]}),e.jsxs(B,{variant:"outline",onClick:Dt,children:[e.jsx(kp,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsx(B,{variant:"destructive",size:"icon",onClick:zt,children:e.jsx(Rn,{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(SRt,{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||""]}),(((Is=d.lead_source_ref)==null?void 0:Is.name)||d.lead_source)&&e.jsx(qe,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((jt=d.lead_source_ref)==null?void 0:jt.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:()=>Bt(d.email),className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(on,{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(pa,{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(aSe,{contact:d}),(Qs=d.tags)==null?void 0:Qs.map(qt=>{const Gs=h==null?void 0:h.find(Ls=>Ls.id===qt.relationship_type_id);return Gs?e.jsx(qe,{variant:"secondary",className:"text-xs",children:Gs.name},qt.id):null})]}),e.jsx("div",{className:"mt-2",children:e.jsx(Wgn,{contactId:s})})]})}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs(be,{className:"md:col-span-2",children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Contact Information"})}),e.jsx(Re,{children:M?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"first_name",children:"First Name"}),e.jsx(ye,{id:"first_name",value:L.first_name,onChange:qt=>I({...L,first_name:qt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"last_name",children:"Last Name"}),e.jsx(ye,{id:"last_name",value:L.last_name,onChange:qt=>I({...L,last_name:qt.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",value:L.email,onChange:qt=>I({...L,email:qt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"phone",children:"Phone"}),e.jsx(ye,{id:"phone",value:L.phone,onChange:qt=>I({...L,phone:qt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"address",children:"Street Address"}),e.jsx(ye,{id:"address",value:L.address,onChange:qt=>I({...L,address:qt.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(se,{htmlFor:"city",children:"City"}),e.jsx(ye,{id:"city",value:L.city,onChange:qt=>I({...L,city:qt.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:L.state,onChange:qt=>I({...L,state:qt.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(ye,{id:"zip_code",value:L.zip_code,onChange:qt=>I({...L,zip_code:qt.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(se,{htmlFor:"birthday",children:"Birthday"}),e.jsx(ye,{id:"birthday",type:"date",value:L.birthday,onChange:qt=>I({...L,birthday:qt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(ye,{id:"home_anniversary",type:"date",value:L.home_anniversary,onChange:qt=>I({...L,home_anniversary:qt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(ye,{id:"wedding_anniversary",type:"date",value:L.wedding_anniversary||"",onChange:qt=>I({...L,wedding_anniversary:qt.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(ye,{id:"spouse_birthday",type:"date",value:L.spouse_birthday,onChange:qt=>I({...L,spouse_birthday:qt.target.value})})]})]}),e.jsx(Xl,{}),e.jsx(g9e,{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:qt=>T.mutate({contactId:s,spouseContactId:qt}),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(se,{htmlFor:"company_name",children:"Company"}),e.jsx(ye,{id:"company_name",value:L.company_name,onChange:qt=>I({...L,company_name:qt.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"job_title",children:"Job Title"}),e.jsx(ye,{id:"job_title",value:L.job_title,onChange:qt=>I({...L,job_title:qt.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(kRt,{value:L.lead_source_id||"",onChange:qt=>I({...L,lead_source_id:qt})}),e.jsxs("div",{children:[e.jsx(se,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:h==null?void 0:h.filter(qt=>qt.active).map(qt=>{var Gs;return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(wi,{checked:(Gs=L.tagIds)==null?void 0:Gs.includes(qt.id),onCheckedChange:Ls=>{var sn;I(Ls?{...L,tagIds:[...L.tagIds||[],qt.id]}:{...L,tagIds:(sn=L.tagIds)==null?void 0:sn.filter(Hs=>Hs!==qt.id)})}}),e.jsx("span",{className:"text-sm",children:qt.name})]},qt.id)})})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Ds,{id:"notes",value:L.notes,onChange:qt=>I({...L,notes:qt.target.value}),rows:4})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{onClick:pt,disabled:v.isPending,children:"Save Changes"}),e.jsx(B,{variant:"outline",onClick:()=>P(!1),children:"Cancel"})]})]}):e.jsxs("div",{className:"space-y-4",children:[dt.length>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Last Contacted:"})," ",Bs(new Date(dt[0].completed_at),"MMM d, yyyy")," ","(",dt[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(on,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("button",{onClick:()=>Bt(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(pa,{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(oi,{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}`]})]})]}),Oe&&d.address&&d.city&&d.state&&e.jsxs(B,{size:"sm",variant:"outline",onClick:Ae,disabled:Ge,children:[Ge?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(P5,{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(ra,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Birthday: ",Bs(Ic(d.birthday),Ic(d.birthday).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Home Anniversary: ",Bs(Ic(d.home_anniversary),Ic(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(mo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Spouse Birthday: ",Bs(Ic(d.spouse_birthday),Ic(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(mo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Wedding Anniversary: ",Bs(Ic(d.wedding_anniversary),Ic(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(Js,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Date Added: ",Bs(new Date(d.created_at),"MMMM d, yyyy")]})]})]}),e.jsx(Xl,{}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(g9e,{contactId:s,currentSpouseContactId:(d==null?void 0:d.spouse_contact_id)||null,currentSpouseName:d.spouse_name||null,currentSpouseEmail:d.spouse_email||null,onLink:qt=>T.mutate({contactId:s,spouseContactId:qt}),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(Ni,{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(Xl,{}),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:(cn=d.tags)!=null&&cn.length?d.tags.map(qt=>{var Gs;return e.jsx(qe,{variant:"secondary",children:(Gs=qt.relationship_type)==null?void 0:Gs.name},qt.id)}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No relationship types assigned"})})]}),d.notes&&e.jsxs(e.Fragment,{children:[e.jsx(Xl,{}),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(Zxn,{contact:d,onLogTouch:()=>$(!0)}),e.jsx($0n,{contactId:s}),e.jsx(A0n,{contactId:s}),e.jsx(T0n,{contactId:s}),e.jsx(M0n,{contactId:s,contactName:d.first_name}),e.jsx(L0n,{contactId:s,contactName:d.first_name}),e.jsx(z0n,{contactId:s}),e.jsx(R0n,{contactId:s}),e.jsx(O0n,{contactId:s}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Activity Log"})}),e.jsx(Re,{children:dt.length>0?e.jsx("div",{className:"space-y-4",children:dt.map(qt=>{var Gs;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:qt.color},children:qt.type==="popby"?e.jsx(zo,{className:"h-4 w-4"}):(Gs=qt.name)==null?void 0:Gs.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:qt.name}),qt.videoId&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>ie(qt.videoId),children:[e.jsx(fd,{className:"h-3 w-3 mr-1"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Bs(new Date(qt.completed_at),"MMM d, yyyy h:mm a")}),qt.notes&&!qt.videoId&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:qt.notes})]})]},qt.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(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ro,{className:"h-5 w-5 text-primary"}),"Video Replies"]})}),e.jsx(Re,{children:e.jsx("div",{className:"space-y-4",children:y.map(qt=>{var Gs,Ls;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[(Gs=qt.video)!=null&&Gs.thumbnail_url?e.jsx("img",{src:qt.video.thumbnail_url,alt:qt.video.title||"Video",className:"h-12 w-16 object-cover rounded cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>ie(qt.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:()=>ie(qt.video_id),children:e.jsx(Zr,{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: ",((Ls=qt.video)==null?void 0:Ls.title)||"Untitled Video"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs flex-shrink-0",onClick:()=>ie(qt.video_id),children:[e.jsx(fd,{className:"h-3 w-3 mr-1"}),"Watch"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Bs(new Date(qt.created_at),"MMM d, yyyy h:mm a")}),qt.message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:['"',qt.message,'"']})]})]},qt.id)})})})]}),Xe&&Xe.length>0&&e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5 text-sky-500"}),"Sent Emails"]})}),e.jsx(Re,{children:e.jsx("div",{className:"space-y-3",children:Xe.map(qt=>e.jsxs(Fs,{children:[e.jsx(Io,{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(on,{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:qt.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",qt.to_email," · ",Bs(new Date(qt.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(Os,{className:"max-w-2xl max-h-[85vh] flex flex-col",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-sky-500"}),qt.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",qt.to_email," · ",Bs(new Date(qt.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:qt.body,className:"w-full h-[400px] border-0",sandbox:"",title:`Email: ${qt.subject}`})})]})]},qt.id))})})]})]}),e.jsx(Fs,{open:!!oe,onOpenChange:qt=>!qt&&ie(null),children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx($s,{children:e.jsx(zs,{children:"Video Preview"})}),oe&&e.jsx(F0n,{videoId:oe})]})})]})]})}),Be&&d&&je&&e.jsx(cw,{open:de,onOpenChange:we,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:je.email},gmailEmail:Le}),d&&d.email&&e.jsx(h0n,{open:fe,onOpenChange:Se,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:d.email}})]}):e.jsx(Vs,{title:"Contact Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This contact was not found."}),e.jsx(B,{onClick:()=>t("/mission-control/contacts"),children:"Back to Contacts"})]})})}function q0n({rangeDays:s}){const{user:t}=Ns(),n=as(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),{data:d=[],isLoading:u}=mt({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let p=U.from("email_campaigns").select("id, name, subject, status, sent_at, scheduled_at, created_at, total_recipients, sent_count, open_count, click_count, bounce_count").eq("user_id",t.id).like("name","Newsletter:%").order("created_at",{ascending:!1}).limit(50);if(s){const g=new Date(Date.now()-s*864e5).toISOString();p=p.gte("created_at",g)}const{data:x,error:y}=await p;if(y)throw y;return x||[]}}),{data:h}=mt({queryKey:["newsletter-campaign-recipients",r],enabled:!!r,queryFn:async()=>{const{data:p,error:x}=await U.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",r).order("sent_at",{ascending:!1}).limit(2e3);if(x)throw x;return p||[]}}),m=async()=>{if(!(!i||!t)){c(!0);try{const{data:p,error:x}=await U.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(x)throw x;if(!p||p.length===0){re.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:y}=await U.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:g,error:b}=await U.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:y.subject,body_html:y.body_html,from_email:y.from_email,reply_to_email:y.reply_to_email,total_recipients:p.length,status:"draft"}).select("id").single();if(b)throw b;const v=p.map(C=>({campaign_id:g.id,contact_id:C.contact_id,email:C.email,name:C.name,status:"pending"}));for(let C=0;C{const x=p.sent_count||0,y=x>0?p.open_count/x*100:0,g=x>0?p.click_count/x*100:0,b=p.sent_at?Fj(new Date,new Date(p.sent_at)):0,v=p.status==="sent"&&b>=3&&x>0&&p.open_counta(p.id),children:[e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),v&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>l(p),children:[e.jsx(WR,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),p.status==="sent"&&x>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(zne,{icon:e.jsx(Dr,{className:"h-3.5 w-3.5"}),label:"Sent",value:x,sub:`of ${p.total_recipients}`}),e.jsx(zne,{icon:e.jsx(ma,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:p.open_count,sub:`${y.toFixed(1)}%`,children:e.jsx(qi,{value:y,className:"h-1 mt-1"})}),e.jsx(zne,{icon:e.jsx(lu,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:p.click_count,sub:`${g.toFixed(1)}%`,children:e.jsx(qi,{value:g,className:"h-1 mt-1"})}),e.jsx(zne,{icon:e.jsx(W9,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:p.bounce_count,sub:p.bounce_count>0?"review":"none"})]})]},p.id)})})]})}),e.jsx(v1,{open:!!r,onOpenChange:p=>!p&&a(null),children:e.jsxs(rv,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(Lb,{children:e.jsx(Pb,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:h?h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recipients yet."}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs uppercase text-muted-foreground border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2",children:"Recipient"}),e.jsx("th",{className:"text-left py-2",children:"Opened"}),e.jsx("th",{className:"text-left py-2",children:"Clicked"}),e.jsx("th",{className:"text-left py-2",children:"Status"})]})}),e.jsx("tbody",{children:h.map(p=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"py-2",children:[e.jsx("div",{className:"font-medium truncate max-w-[180px]",children:p.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:p.email})]}),e.jsx("td",{className:"py-2 text-xs",children:p.opened_at?e.jsx(qe,{variant:"default",className:"text-xs",children:Bs(new Date(p.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:p.clicked_at?e.jsx(qe,{variant:"default",className:"text-xs bg-purple-600",children:Bs(new Date(p.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[p.status==="sent"&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"sent"}),p.status==="pending"&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:"queued"}),p.status==="failed"&&e.jsx(qe,{variant:"destructive",className:"text-xs",title:p.error_message||"",children:"failed"}),p.status==="suppressed"&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},p.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Nl,{open:!!i,onOpenChange:p=>!p&&l(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Resend to non-openers?"}),e.jsxs(xl,{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(pl,{children:[e.jsx(gl,{disabled:o,children:"Cancel"}),e.jsx(cl,{onClick:m,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(WR,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function zne({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 iX(){var r;const{data:{session:s}}=await U.auth.getSession(),t=s!=null&&s.expires_at?s.expires_at*1e3:0;if(!(s!=null&&s.access_token)||t-Date.now()<12e4){const{data:a,error:i}=await U.auth.refreshSession();if(i||!((r=a.session)!=null&&r.access_token))throw new Error("Your session expired. Please refresh the page (or sign in again) and try sending once more.");return a.session.access_token}return s.access_token}function V0n(){const{user:s}=Ns(),t=Hn(),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 U.from("email_campaigns").select("id, name, subject, scheduled_at, total_recipients, status, created_at").eq("user_id",s.id).eq("status","scheduled").order("scheduled_at",{ascending:!0});if(u)throw u;return d||[]},refetchInterval:3e4}),i=async(d,u)=>{const h=await iX(),p=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-schedule-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({action:d,campaign_id:u})})).json();if(!p.success)throw new Error(p.error||`Failed to ${d}`);return p},l=vt({mutationFn:d=>i("cancel",d),onSuccess:()=>{re.success("Schedule cancelled — saved as draft"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>re.error(d.message)}),o=vt({mutationFn:d=>i("delete",d),onSuccess:()=>{re.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>re.error(d.message)}),c=vt({mutationFn:async({id:d,iso:u})=>{const{error:h}=await U.from("email_campaigns").update({scheduled_at:u,status:"scheduled"}).eq("id",d);if(h)throw h;await i("schedule",d)},onSuccess:()=>{re.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>re.error(d.message)});return a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading scheduled emails..."}):r.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Vr,{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(H0n,{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 H0n({campaign:s,onEdit:t,onCancel:n,onDelete:r,onReschedule:a,isBusy:i}){const l=s.scheduled_at?new Date(s.scheduled_at):null,[o,c]=j.useState(!1),[d,u]=j.useState(l||void 0),[h,m]=j.useState(l?`${String(l.getHours()).padStart(2,"0")}:${String(l.getMinutes()).padStart(2,"0")}`:"09:00"),p=()=>{if(!d)return re.error("Pick a date");const x=new Date(`${Bs(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(x).getTime()xm(x.target.value)})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:p,disabled:i,children:[i&&e.jsx(Wt,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(Rd,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Cancel this scheduled send?"}),e.jsxs(xl,{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(pl,{children:[e.jsx(gl,{children:"Keep scheduled"}),e.jsx(cl,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(Rn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete this scheduled email?"}),e.jsx(xl,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Keep"}),e.jsx(cl,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}function G0n({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 Bne({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:Et("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 W0n({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(G0n,{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(Bne,{icon:e.jsx(Rr,{className:"h-3.5 w-3.5"}),label:"Delivered",value:s.toLocaleString(),hint:"All sends completed"}),e.jsx(Bne,{icon:e.jsx(ma,{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(Bne,{icon:e.jsx(lu,{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(Bne,{icon:e.jsx(Vr,{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 Xmt=["Gmail","Mass Email","Campaign","Client Portal Invite"],K0n={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 Y0n(){const{user:s}=Ns(),[t,n]=dc(),{data:r=[],isLoading:a}=IRt(),[i,l]=j.useState(""),[o,c]=j.useState("all"),[d,u]=j.useState("30"),[h,m]=j.useState(!1),[p,x]=j.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:y}=Tf(),{data:g=0}=mt({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:P}=await U.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return P||0},refetchInterval:3e4});j.useEffect(()=>{const P=new URLSearchParams(t);p==="scheduled"?P.set("tab","scheduled"):P.delete("tab"),n(P,{replace:!0})},[p]);const b=j.useMemo(()=>Array.from(new Set(r.map(P=>P.contact_id).filter(Boolean))),[r]),{data:v}=mt({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,b.length],enabled:b.length>0,queryFn:async()=>{const{data:P}=await U.from("innercircle_contacts").select("id, first_name, last_name").in("id",b),L=new Map;return(P||[]).forEach(I=>{L.set(I.id,[I.first_name,I.last_name].filter(Boolean).join(" ")||"Contact")}),L}}),k=j.useMemo(()=>{const P=d==="all"?null:Date.now()-parseInt(d)*864e5,L=i.trim().toLowerCase();return r.filter(I=>{if(o!=="all"&&I.channel!==o||P&&new Date(I.sent_at).getTime(){const P={};let L=0,I=0,O=0;return k.forEach($=>{P[$.channel]=(P[$.channel]||0)+1,($.channel==="Campaign"||$.channel==="Mass Email")&&(O++,$.opened_at&&L++,$.clicked_at&&I++)}),{byChannel:P,opened:L,clicked:I,trackable:O}},[k]),T=d==="all"?"All time":`Last ${d} days`,M=Xmt.map(P=>C.byChannel[P]?`${C.byChannel[P]} ${P}`:null).filter(Boolean).join(" · ");return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-5 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Dr,{className:"h-6 w-6"})," Sent Emails"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every send in one place — Gmail, mass emails, campaigns, and portal invites."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex rounded-full border bg-muted/40 p-1",children:[e.jsxs("button",{onClick:()=>x("sent"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${p==="sent"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Dr,{className:"h-3.5 w-3.5"})," Sent"]}),e.jsxs("button",{onClick:()=>x("scheduled"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${p==="scheduled"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Vr,{className:"h-3.5 w-3.5"})," Scheduled",g>0&&e.jsx(qe,{variant:"secondary",className:"ml-0.5 h-5 min-w-5 px-1.5 text-xs",children:g})]})]}),e.jsxs(B,{onClick:()=>m(!0),className:"rounded-full",children:[e.jsx(on,{className:"h-4 w-4 mr-2"})," Send Email"]})]})]}),e.jsxs(fa,{value:p,onValueChange:P=>x(P),className:"space-y-5",children:[e.jsxs(ns,{value:"sent",className:"space-y-5 mt-0",children:[e.jsx(W0n,{total:k.length,opened:C.opened,clicked:C.clicked,trackable:C.trackable,scheduled:g,rangeLabel:T,channelSummary:M,onScheduledClick:()=>x("scheduled")}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-2xl border bg-card p-2 md:flex-row md:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search subject, recipient, contact...",value:i,onChange:P=>l(P.target.value),className:"pl-9 border-0 bg-transparent shadow-none focus-visible:ring-0"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(vs,{value:o,onValueChange:c,children:[e.jsx(gs,{className:"w-[170px] rounded-full h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Channels"}),Xmt.map(P=>e.jsx(Je,{value:P,children:P},P))]})]}),e.jsxs(vs,{value:d,onValueChange:u,children:[e.jsx(gs,{className:"w-[150px] rounded-full h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"7",children:"Last 7 days"}),e.jsx(Je,{value:"30",children:"Last 30 days"}),e.jsx(Je,{value:"90",children:"Last 90 days"}),e.jsx(Je,{value:"365",children:"Last year"}),e.jsx(Je,{value:"all",children:"All time"})]})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-3 px-1",children:[e.jsx(I5,{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(q0n,{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(be,{className:"rounded-2xl",children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(on,{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(be,{className:"rounded-2xl overflow-hidden",children:e.jsx(Re,{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(RN,{children:e.jsxs(Cu,{children:[e.jsxs(Au,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(I5,{className:"h-3 w-3"})]}),e.jsx(ou,{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(P=>{const L=P.contact_id?v==null?void 0:v.get(P.contact_id):null,I=P.channel==="Campaign"||P.channel==="Mass Email";return e.jsxs("tr",{className:"border-t hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 whitespace-nowrap text-muted-foreground",children:Bs(new Date(P.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(qe,{variant:"outline",className:K0n[P.channel],children:P.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:P.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:P.to_email}),e.jsx("td",{className:"py-3 px-4",children:P.contact_id&&L?e.jsx(Yn,{to:`/mission-control/contacts/${P.contact_id}`,className:"text-primary hover:underline",children:L}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-3 px-4",children:I?e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsxs(qe,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(Rr,{className:"h-3 w-3"})," Delivered"]}),P.opened_at&&e.jsxs(qe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(ma,{className:"h-3 w-3"})," Opened"]}),P.clicked_at&&e.jsxs(qe,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(lu,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},P.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(ns,{value:"scheduled",className:"mt-0",children:e.jsx(V0n,{})})]}),e.jsx(cw,{open:h,onOpenChange:m,gmailEmail:y})]})})}const Qmt={Crown:sy,FileText:$r,Users:Bn,Globe:Ql,Star:Wa,Phone:pa,MessageSquare:ro,PenTool:XT,Video:Zr,Gift:zo},$ne=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Z0n(){var pt,zt;const s=Hn(),{user:t}=Ns(),{data:n}=lw(),{data:r}=iks(),{data:a}=mks(),{data:i}=qCt(),{data:l}=tq(),{data:o}=aks(),c=pks(),d=oks(),u=cks(),h=dks(),m=uks(),p=hks(),x=lks(),[y,g]=j.useState(null),[b,v]=j.useState(!1),[k,C]=j.useState(null),[T,M]=j.useState(""),[P,L]=j.useState(""),[I,O]=j.useState([]),[$,q]=j.useState(null),[W,G]=j.useState(null),[K,ee]=j.useState(null),[J,le]=j.useState(!1),[ue,oe]=j.useState(""),[ie,de]=j.useState(""),[we,je]=j.useState(""),[xe,fe]=j.useState(""),Se=(Gt,qs)=>a==null?void 0:a.some(As=>As.plan_id===Gt&&As.relationship_type_id===qs&&As.active),Ee=Gt=>a==null?void 0:a.find(qs=>qs.relationship_type_id===Gt&&qs.active),Le=async(Gt,qs)=>{const As=Se(Gt,qs);await c.mutateAsync({planId:Gt,relationshipTypeId:qs,active:!As})},De=(r==null?void 0:r.filter(Gt=>Gt.active&&!Gt.owner_user_id))||[],Be=(r==null?void 0:r.filter(Gt=>Gt.owner_user_id===(t==null?void 0:t.id)))||[],Ne=n==null?void 0:n.find(Gt=>Gt.id===y),Ge=y?Ee(y):null,_e=r==null?void 0:r.find(Gt=>Gt.id===(Ge==null?void 0:Ge.plan_id)),Oe=async()=>{if(!T.trim())return;const Gt=await d.mutateAsync({name:T,description:P});Gt&&I.length>0&&await m.mutateAsync({planId:Gt.id,items:I}),Ze()},Ae=async()=>{!T.trim()||!k||(await u.mutateAsync({id:k,name:T,description:P}),await m.mutateAsync({planId:k,items:I}),Ze())},Xe=Gt=>{var qs;C(Gt.id),M(Gt.name),L(Gt.description||""),O(((qs=Gt.items)==null?void 0:qs.map(As=>({month_number:As.month_number,action_type_id:As.action_type_id,default_script_id:As.default_script_id||void 0,notes:As.notes||void 0})))||[]),v(!0)},Ue=async(Gt,qs)=>{if(Gt.owner_user_id===(t==null?void 0:t.id)){Xe(Gt);return}try{const As=await x.mutateAsync({sourcePlanId:Gt.id,newName:`${Gt.name} (My Copy)`});if(!As)return;await c.mutateAsync({planId:Gt.id,relationshipTypeId:qs,active:!1}),await c.mutateAsync({planId:As.id,relationshipTypeId:qs,active:!0}),C(As.id),M(As.name),L(As.description||""),O((Gt.items||[]).map(Bt=>({month_number:Bt.month_number,action_type_id:Bt.action_type_id,default_script_id:Bt.default_script_id||void 0,notes:Bt.notes||void 0}))),v(!0)}catch{}},Ze=()=>{v(!1),C(null),M(""),L(""),O([])},Qe=(Gt,qs)=>{G(qs)},Ye=(Gt,qs,As)=>{O(Bt=>[...Bt.filter(Is=>Is.month_number!==Gt),{month_number:Gt,action_type_id:qs,default_script_id:As}]),q(null),G(null)},nt=Gt=>{O(qs=>qs.filter(As=>As.month_number!==Gt))},rt=async()=>{if(!ue.trim()||!ie.trim()||!W)return;const Gt=await p.mutateAsync({actionTypeId:W,title:ue,scriptBody:ie,emailSubject:we||void 0,tone:xe||void 0});Gt&&$!==null&&Ye($,W,Gt.id),le(!1),oe(""),de(""),je(""),fe("")},Fe=W?o==null?void 0:o.filter(Gt=>Gt.action_type_id===W&&Gt.active):[],dt=Gt=>Qmt[Gt||"Phone"]||pa,Dt=Gt=>Qmt[Gt||"Users"]||Bn;return e.jsxs(Vs,{title:"Touchpoint Plans",description:"Assign plans to your contact groups",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Touchpoint Plans"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(Cc,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(B,{onClick:()=>v(!0),className:"w-full sm:w-auto",children:[e.jsx(Js,{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(Gt=>Gt.active).map(Gt=>{const qs=Dt(Gt.icon),As=(i==null?void 0:i[Gt.id])||0,Bt=Ee(Gt.id),At=r==null?void 0:r.find(jt=>jt.id===(Bt==null?void 0:Bt.plan_id)),Is=y===Gt.id;return e.jsxs("button",{onClick:()=>g(Gt.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${Is?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(qs,{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:Gt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[As," contacts"]})]}),At?e.jsxs(qe,{variant:"secondary",className:"text-xs",children:[e.jsx(To,{className:"h-3 w-3 mr-1"}),At.name.split(" ")[0]]}):e.jsx(qe,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},Gt.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:y&&Ne?e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[(()=>{const Gt=Dt(Ne.icon);return e.jsx(Gt,{className:"h-5 w-5"})})(),Ne.name," Touchpoint Plan"]}),e.jsxs(fr,{children:["Choose a plan for your ",Ne.name," contacts"]})]}),e.jsxs(Re,{className:"space-y-6",children:[_e&&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(To,{className:"h-4 w-4 text-green-500"}),"Currently using: ",_e.name]}),_e.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:_e.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:x.isPending||c.isPending,onClick:()=>Ue(_e,y),children:[e.jsx(oj,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>Le(_e.id,y),children:"Disable"})]})]}),_e.items&&_e.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(ra,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:$ne.map((Gt,qs)=>{var Is,jt;const As=((Is=_e.items)==null?void 0:Is.filter(Qs=>Qs.month_number===qs+1))||[],Bt=(jt=As[0])==null?void 0:jt.action_type,At=Bt?dt(Bt.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${As.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:Gt}),At&&e.jsx(At,{className:"h-4 w-4 mx-auto mt-1",style:{color:(Bt==null?void 0:Bt.color)||"#3B82F6"}})]},qs)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:_e?"Switch to a Different Plan":"Choose a Plan"}),De.length>0&&e.jsxs("div",{className:"space-y-2 mb-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Pre-built Templates"}),De.map(Gt=>{var As;const qs=(_e==null?void 0:_e.id)===Gt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${qs?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Gt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((As=Gt.items)==null?void 0:As.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>ee(Gt.id),children:e.jsx(ma,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:x.isPending,onClick:()=>{const Bt=`${Gt.name} (Copy)`;x.mutate({sourcePlanId:Gt.id,newName:Bt})},children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:qs?"outline":"default",disabled:qs||c.isPending,onClick:()=>Le(Gt.id,y),children:qs?"Active":"Use This"})]})]},Gt.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(Gt=>{var As;const qs=(_e==null?void 0:_e.id)===Gt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${qs?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Gt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((As=Gt.items)==null?void 0:As.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>ee(Gt.id),children:e.jsx(ma,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>Xe(Gt),children:e.jsx(oj,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(Gt.id),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})}),e.jsx(B,{size:"sm",variant:qs?"outline":"default",disabled:qs||c.isPending,onClick:()=>Le(Gt.id,y),children:qs?"Active":"Use This"})]})]},Gt.id)})]}),De.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(be,{children:e.jsxs(Re,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ra,{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(be,{className:"bg-muted/50",children:e.jsx(Re,{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(Fs,{open:b,onOpenChange:Gt=>{Gt?v(!0):Ze()},children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{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(se,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(ye,{id:"plan-name",value:T,onChange:Gt=>M(Gt.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Ds,{id:"plan-description",value:P,onChange:Gt=>L(Gt.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"12-Month Schedule"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Click on a month to add a touchpoint"}),e.jsx("div",{className:"grid grid-cols-6 gap-2",children:$ne.map((Gt,qs)=>{const As=qs+1,Bt=I.find(jt=>jt.month_number===As),At=Bt?l==null?void 0:l.find(jt=>jt.id===Bt.action_type_id):null,Is=At?dt(At.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>q($===As?null:As),className:` w-full p-3 rounded-lg border text-center transition-all ${Bt?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${$===As?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:Gt}),Is?e.jsx(Is,{className:"h-5 w-5 mx-auto mt-1",style:{color:(At==null?void 0:At.color)||"#3B82F6"}}):e.jsx(Js,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),Bt&&e.jsx("button",{type:"button",onClick:jt=>{jt.stopPropagation(),nt(As)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(dr,{className:"h-3 w-3"})})]},qs)})}),$!==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 ",$ne[$-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(Gt=>Gt.active).map(Gt=>{const qs=dt(Gt.icon);return e.jsxs("button",{type:"button",onClick:()=>Qe($,Gt.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(qs,{className:"h-4 w-4",style:{color:Gt.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:Gt.name})]},Gt.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(Cc,{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:()=>Ye($,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"})]})}),Fe==null?void 0:Fe.map(Gt=>e.jsx("button",{type:"button",onClick:()=>Ye($,W,Gt.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:Gt.title}),Gt.tone&&e.jsx(qe,{variant:"secondary",className:"text-xs mt-1",children:Gt.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[Gt.script_body.substring(0,100),"..."]})]})},Gt.id)),e.jsxs("button",{type:"button",onClick:()=>le(!0),className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed bg-background hover:bg-accent transition-colors text-left",children:[e.jsx(Js,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Create Custom Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Write your own script for this action"})]})]})]})]})]}),I.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[I.length," touchpoint",I.length!==1?"s":""," per year"]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:Ze,children:"Cancel"}),e.jsxs(B,{onClick:k?Ae:Oe,disabled:!T.trim()||d.isPending||u.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),k?"Save Changes":"Create Plan"]})]})]})}),e.jsx(Fs,{open:J,onOpenChange:le,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx($s,{children:e.jsx(zs,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-title",children:"Script Title"}),e.jsx(ye,{id:"script-title",value:ue,onChange:Gt=>oe(Gt.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(vs,{value:xe,onValueChange:fe,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select tone..."})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"friendly",children:"Friendly"}),e.jsx(Je,{value:"professional",children:"Professional"}),e.jsx(Je,{value:"casual",children:"Casual"}),e.jsx(Je,{value:"formal",children:"Formal"})]})]})]}),((zt=(pt=l==null?void 0:l.find(Gt=>Gt.id===W))==null?void 0:pt.name)==null?void 0:zt.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(ye,{id:"script-email-subject",value:we,onChange:Gt=>je(Gt.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Ds,{id:"script-body",value:ie,onChange:Gt=>de(Gt.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(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>le(!1),children:"Cancel"}),e.jsxs(B,{onClick:rt,disabled:!ue.trim()||!ie.trim()||p.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(Fs,{open:!!K,onOpenChange:Gt=>{Gt||ee(null)},children:e.jsx(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const Gt=r==null?void 0:r.find(Bt=>Bt.id===K);if(!Gt)return null;const qs=Gt.owner_user_id===(t==null?void 0:t.id),As=[...Gt.items||[]].sort((Bt,At)=>Bt.month_number-At.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[Gt.name,!qs&&e.jsx(qe,{variant:"secondary",children:"Template"})]}),Gt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Gt.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[As.length," touchpoint",As.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(Bt,At)=>At+1).map(Bt=>{const At=As.find(cn=>cn.month_number===Bt),Is=At?l==null?void 0:l.find(cn=>cn.id===At.action_type_id):null,jt=At!=null&&At.default_script_id?o==null?void 0:o.find(cn=>cn.id===At.default_script_id):null,Qs=Is?dt(Is.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:$ne[Bt-1]}),At&&Is?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Qs&&e.jsx(Qs,{className:"h-4 w-4",style:{color:Is.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:Is.name}),jt&&e.jsx(qe,{variant:"outline",className:"text-xs",children:jt.title})]}),jt&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:jt.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"})]},Bt)})})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>ee(null),children:"Close"}),qs?e.jsxs(B,{onClick:()=>{const Bt=r==null?void 0:r.find(At=>At.id===K);Bt&&(ee(null),Xe(Bt))},children:[e.jsx(oj,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs(B,{disabled:x.isPending,onClick:()=>{x.mutate({sourcePlanId:Gt.id,newName:`${Gt.name} (Copy)`}),ee(null)},children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const QPe="https://cma.relevelup.com";function RRt({open:s,onOpenChange:t,cma:n}){var ee;const{user:r}=Ns(),{toast:a}=pi(),[i,l]=j.useState([]),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,x]=j.useState(""),[y,g]=j.useState(""),[b,v]=j.useState(!1),[k,C]=j.useState(null),[T,M]=j.useState(!1),[P,L]=j.useState(!1),[I,O]=j.useState(null);j.useEffect(()=>{!s||!r||(async()=>{var je;const[J,le,ue,oe,ie]=await Promise.all([U.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r.id).not("email","is",null).order("first_name"),U.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",r.id).maybeSingle(),U.from("gmail_integrations").select("id, is_active").eq("user_id",r.id).maybeSingle(),U.from("ses_verified_emails").select("email, status").eq("user_id",r.id).eq("status","Success").limit(1),U.from("mass_email_settings").select("*").eq("user_id",r.id).maybeSingle()]),de=(J.data||[]).filter(xe=>xe.email&&xe.email.includes("@"));l(de),C(le.data||null),M(!!((je=ue.data)!=null&&je.is_active)),L(!!(oe.data&&oe.data.length>0)),O(ie.data||null);const we=n.contact_id?de.find(xe=>xe.id===n.contact_id):null;we&&(c(we),m(we.email))})()},[s,r,n.contact_id]),j.useEffect(()=>{var oe;if(!s)return;const J=((oe=n.subject)==null?void 0:oe.address)||"your home",le=((k==null?void 0:k.name)||"").split(" ")[0]||"your agent",ue=(o==null?void 0:o.first_name)||"there";x(`Your home value report for ${J}`),g(`Hi ${ue}, I put together a fresh market analysis for ${J}. It pulls live comparable sales, active listings, and pending homes near you so you can see exactly where your value sits today. Take a look here — it only takes a minute: {{cma_link}} When you've had a chance to review, I'd love to hear your thoughts. Reply to this email or give me a call any time. Talk soon, ${(k==null?void 0:k.name)||le}`)},[s,o==null?void 0:o.id,k==null?void 0:k.name,(ee=n.subject)==null?void 0:ee.address]);const $=j.useMemo(()=>T?"Gmail (your inbox)":P?"Amazon SES":null,[T,P]),q=!!(h.trim()&&p.trim()&&y.trim()&&$&&!b),W=J=>{c(J),m(J.email||""),u(!1)},G=J=>{const le=`${QPe}/${n.share_token}?e=${J}`,ie=y.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(je=>`

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

`).join(""),de=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?``:""}
`,we=``;return`
${ie} ${de}
Prepared with LevelUp · ReLevelUp Real Estate
${we}
`},K=async()=>{if(!(!r||!q)){v(!0);try{const{data:J,error:le}=await U.from("cma_email_sends").insert({cma_id:n.id,agent_id:r.id,contact_id:(o==null?void 0:o.id)??null,recipient_email:h.trim(),subject:p.trim(),sent_via:T?"gmail":"ses"}).select("id").single();if(le)throw le;const ue=G(J.id);if(T){const{data:oe,error:ie}=await U.functions.invoke("gmail-send",{body:{to:h.trim(),subject:p.trim(),body:ue}});if(ie)throw ie;if(!(oe!=null&&oe.success))throw new Error((oe==null?void 0:oe.error)||"Gmail send failed")}else if(P){const oe=(I==null?void 0:I.display_name)||(k==null?void 0:k.name)||"ReLevelUp",ie=`${oe.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:de,error:we}=await U.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${oe} <${ie}>`,subject:p.trim(),body_html:ue,reply_to:(I==null?void 0:I.reply_to_email)||(k==null?void 0:k.email)||void 0}});if(we)throw we;if(!(de!=null&&de.success))throw new Error((de==null?void 0:de.error)||"SES send failed")}o&&!n.contact_id&&await U.from("cmas").update({contact_id:o.id}).eq("id",n.id),a({title:"CMA sent",description:`Delivered to ${h.trim()}`}),t(!1)}catch(J){console.error("Send CMA error:",J),a({title:"Send failed",description:J.message||"Could not send email",variant:"destructive"})}finally{v(!1)}}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{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(se,{children:"Contact"}),e.jsxs(lc,{open:d,onOpenChange:u,children:[e.jsx(cc,{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(fb,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(Jl,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Sb,{children:[e.jsx(Cb,{placeholder:"Search contacts…"}),e.jsxs(Ab,{children:[e.jsx(Tb,{children:"No contacts with email found."}),e.jsx(Eb,{children:i.map(J=>e.jsxs(Yy,{value:`${J.first_name} ${J.last_name||""} ${J.email}`,onSelect:()=>W(J),children:[e.jsx(da,{className:Et("w-4 h-4 mr-2",(o==null?void 0:o.id)===J.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[J.first_name," ",J.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:J.email})]})]},J.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"To email"}),e.jsx(ye,{type:"email",value:h,onChange:J=>m(J.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subject"}),e.jsx(ye,{value:p,onChange:J=>x(J.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Message"}),e.jsx(Ds,{rows:10,value:y,onChange:J=>g(J.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("code",{children:"{{cma_link}}"})," will be replaced with a styled button linking to ",e.jsxs("code",{children:["cma.relevelup.com/",n.share_token]}),". Email opens are tracked and shown on the contact's Signals."]})]}),e.jsxs("div",{className:"rounded border bg-muted/40 p-3 text-sm flex items-center gap-2",children:[e.jsx(Tr,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Public link:"}),e.jsx("a",{className:"text-primary underline truncate",href:`${QPe}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${QPe}/${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(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:K,disabled:!q,children:[b?e.jsx(Wt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Dr,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function X0n({onCreated:s}){const[t,n]=j.useState(!1),[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),h=y0n(),m=TRt(),{toast:p}=pi(),[x,y]=j.useState([]),g=async()=>{var k;y([]);try{const C=await h.mutateAsync({address:r,city:i,state:o,zip:d});y(C.matches||[]),(k=C.matches)!=null&&k.length||p({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(C){p({title:"Search failed",description:C.message,variant:"destructive"})}},b=async k=>{const C=await m.mutateAsync({subject:k});n(!1),s(C.id)},v=async()=>{if(!r||!i||!o){p({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(Fs,{open:t,onOpenChange:n,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Js,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx($s,{children:e.jsx(zs,{children:"Start a CMA"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(ye,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:k=>a(k.target.value)}),e.jsx(ye,{placeholder:"City",value:i,onChange:k=>l(k.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"ST",maxLength:2,value:o,onChange:k=>c(k.target.value.toUpperCase())}),e.jsx(ye,{placeholder:"ZIP",value:d,onChange:k=>u(k.target.value)})]})]}),e.jsxs(B,{onClick:g,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(Wt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Fr,{className:"w-4 h-4 mr-2"}),"Find in MLS"]}),x.length>0&&e.jsxs("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[x.length," match(es) — pick the subject property:"]}),x.map((k,C)=>{var T;return e.jsxs("button",{onClick:()=>b(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]})]},C)})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsxs(B,{variant:"outline",onClick:v,disabled:m.isPending,className:"w-full",children:[e.jsx(ia,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function Q0n(){const{data:s,isLoading:t}=m0n(),n=g0n(),r=Hn(),{toast:a}=pi(),[i,l]=j.useState(null);return e.jsx(Vs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-6xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl md:text-3xl font-bold flex items-center gap-2",children:[e.jsx($r,{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(X0n,{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(be,{className:"hover:shadow-md transition",children:e.jsxs(Re,{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(qe,{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(on,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:async()=>{await Bi("Delete this CMA?")&&n.mutate(o.id)},children:e.jsx(Rn,{className:"w-4 h-4"})})]})]})},o.id)})}):e.jsx(be,{children:e.jsx(Re,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(RRt,{open:!!i,onOpenChange:o=>!o&&l(null),cma:i})]})})}function J0n(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 Jmt(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 eyn({subject:s,comps:t,radiusMiles:n,onMarkerClick:r}){const a=j.useRef(null),i=j.useRef(null),l=j.useRef([]),[o,c]=j.useState(null);j.useEffect(()=>{let u=!1;return(async()=>{const{data:h}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();!u&&(h!=null&&h.value)&&c(h.value)})(),()=>{u=!0}},[]);const d=j.useMemo(()=>{const u=Number(s==null?void 0:s.latitude),h=Number(s==null?void 0:s.longitude);return!Number.isFinite(u)||!Number.isFinite(h)?null:{lat:u,lng:h}},[s==null?void 0:s.latitude,s==null?void 0:s.longitude]);return j.useEffect(()=>{if(!o||!a.current||i.current||!d)return;$c.accessToken=o;const u=new $c.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new $c.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:Jmt(d.lat,d.lng,n)}),u.addLayer({id:"radius-fill",type:"fill",source:"radius",paint:{"fill-color":"#2563eb","fill-opacity":.08}}),u.addLayer({id:"radius-line",type:"line",source:"radius",paint:{"line-color":"#2563eb","line-width":2,"line-dasharray":[2,2],"line-opacity":.5}})}),i.current=u,()=>{u.remove(),i.current=null}},[o,d]),j.useEffect(()=>{const u=i.current;if(!u||!d)return;const h=()=>{const m=u.getSource("radius");m&&m.setData(Jmt(d.lat,d.lng,n))};u.isStyleLoaded()?h():u.once("load",h)},[n,d]),j.useEffect(()=>{const u=i.current;if(!u||!d)return;l.current.forEach(g=>g.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 $c.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new $c.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(m);const p=new $c.LngLatBounds;p.extend([d.lng,d.lat]),t.forEach((g,b)=>{const v=Number(g.latitude),k=Number(g.longitude);if(!Number.isFinite(v)||!Number.isFinite(k))return;const C=J0n(g.status),T=document.createElement("div");T.style.cssText="width:22px;height:22px;";const M=document.createElement("div");M.style.cssText=` width: 22px; height: 22px; border-radius: 50%; background: ${C}; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.25); cursor: pointer; opacity: ${g.selected===!1?.4:1}; transition: transform 0.15s; transform-origin: center; `,M.onmouseenter=()=>{M.style.transform="scale(1.25)"},M.onmouseleave=()=>{M.style.transform="scale(1)"},r&&(M.onclick=()=>r(b)),T.appendChild(M);const P=g.soldPrice||g.price,L=new $c.Popup({offset:14}).setHTML(`
${g.address??""}
${g.status??""}`+(P?` · $${P.toLocaleString()}`:"")+"
"),I=new $c.Marker({element:T}).setLngLat([k,v]).setPopup(L).addTo(u);l.current.push(I),p.extend([k,v])});const y=n*1.60934/110.574;p.extend([d.lng,d.lat+y]),p.extend([d.lng,d.lat-y]);try{u.fitBounds(p,{padding:60,maxZoom:14,duration:600})}catch{}},[t,d,n,s.address,r]),d?e.jsxs("div",{className:"relative w-full h-[420px] rounded-xl overflow-hidden border shadow-sm",children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),!o&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted/40 text-sm text-muted-foreground",children:"Loading map…"}),e.jsxs("div",{className:"absolute bottom-3 left-3 bg-background/95 backdrop-blur rounded-lg shadow-md border px-3 py-2 text-xs space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"hsl(222 47% 11%)"}}),"Subject"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#2563eb"}}),"Active"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#f59e0b"}}),"Pending"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#16a34a"}}),"Closed"]})]})]}):e.jsx("div",{className:"w-full h-[420px] rounded-xl border bg-muted/30 flex items-center justify-center text-sm text-muted-foreground",children:"Subject property has no coordinates — map unavailable."})}let $1=null;function tyn(){if($1)return $1;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return $1={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},$1;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 $1={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},$1;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?($1={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},$1):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?($1={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},$1):($1={canRunVirtualBg:!0,renderer:r},$1)}catch{return $1={canRunVirtualBg:!0},$1}}const syn=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function nyn({value:s,onChange:t,isLoading:n=!1,disabled:r=!1,className:a}){const i=j.useRef(null),[l,o]=j.useState(!1),[c]=j.useState(()=>tyn()),d=!c.canRunVirtualBg,{data:u=[],refetch:h}=mt({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:g}}=await U.auth.getUser();if(!g)return[];const{data:b,error:v}=await U.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return v?(console.error("Failed to load backgrounds:",v),[]):b||[]}}),m=u.map(g=>({type:"image",label:g.name,imageUrl:g.image_url,thumbnail:g.thumbnail_url||g.image_url})),p=[...syn,...m],x=g=>g.type!==s.type?!1:g.type==="image"?g.imageUrl===s.imageUrl:!0,y=async g=>{var v;const b=(v=g.target.files)==null?void 0:v[0];if(b){if(!b.type.startsWith("image/")){re.error("Please select an image file");return}if(b.size>5*1024*1024){re.error("Image must be under 5MB");return}o(!0);try{const{data:{user:k}}=await U.auth.getUser();if(!k)throw new Error("Not authenticated");const C=b.name.split(".").pop()||"jpg",T=`${k.id}/${crypto.randomUUID()}.${C}`,{error:M}=await U.storage.from("video-backgrounds").upload(T,b,{contentType:b.type});if(M)throw M;const{data:P}=U.storage.from("video-backgrounds").getPublicUrl(T),L=P.publicUrl,{error:I}=await U.from("video_backgrounds").insert({name:b.name.replace(/\.[^.]+$/,""),image_url:L,thumbnail_url:L,category:"custom",is_stock:!1,user_id:k.id});if(I)throw I;await h(),t({type:"image",imageUrl:L,blurRadius:15}),re.success("Background uploaded!")}catch(k){console.error("Upload error:",k),re.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Et("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(hd,{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(Wt,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),p.map((g,b)=>{const v=x(g);return e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:g.type,imageUrl:g.imageUrl,blurRadius:15}),className:Et("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 p-1 transition-all","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30",v?"border-primary bg-primary/10":"border-transparent bg-muted/50",r&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("div",{className:"w-12 h-8 rounded flex items-center justify-center overflow-hidden bg-muted",children:[g.type==="none"&&e.jsx(R9,{className:"h-4 w-4 text-muted-foreground"}),g.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"})}),g.type==="image"&&g.thumbnail&&e.jsx("img",{src:g.thumbnail,alt:g.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:g.label})]},`${g.type}-${g.imageUrl||b}`)}),e.jsxs("button",{type:"button",disabled:r||l,onClick:()=>{var g;return(g=i.current)==null?void 0:g.click()},className:Et("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(Wt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(Js,{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:Et("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(zW,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var oU=typeof self<"u"?self:{};function DRt(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=oU,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 FRt(s){oU.setTimeout(()=>{throw s},0)}var y9e,oyn=DRt(610401301,!1),tpt=DRt(748402147,!0);function spt(){var s=oU.navigator;return s&&(s=s.userAgent)?s:""}const npt=oU.navigator;function DAe(s){return DAe[" "](s),s}y9e=npt&&npt.userAgentData||null,DAe[" "]=function(){};const zRt={};let HG=null;function lyn(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 BRt(){if(!HG){HG={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));zRt[n]=r;for(let a=0;a0)&&(spt().indexOf("Trident")!=-1||spt().indexOf("MSIE")!=-1))&&typeof btoa=="function";const rpt=/[-_.]/g,dyn={"-":"+",_:"/",".":"="};function uyn(s){return dyn[s]||""}function URt(s){if(!$Rt)return lyn(s);s=rpt.test(s)?s.replace(rpt,uyn):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,VRt(s=Error(),"incident"),FRt(s))}}function Mq(){return typeof BigInt=="function"}var Lq=typeof Symbol=="function"&&typeof Symbol()=="symbol";function mS(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 pyn=mS("jas",void 0,!0),apt=mS(void 0,"0di"),GH=mS(void 0,"1oa"),X_=mS(void 0,Symbol()),fyn=mS(void 0,"0ub"),xyn=mS(void 0,"0ubs"),b9e=mS(void 0,"0ubsb"),gyn=mS(void 0,"0actk"),dU=mS("m_m","Pa",!0),ipt=mS();const HRt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},GRt=Object.defineProperties,_o=Lq?pyn:"Ga";var PO;const opt=[];function JJ(s,t){Lq||_o in s||GRt(s,HRt),s[_o]|=t}function gg(s,t){Lq||_o in s||GRt(s,HRt),s[_o]=t}function eee(s){return JJ(s,34),s}function oX(s){return JJ(s,8192),s}gg(opt,7),PO=Object.freeze(opt);var uU={};function sw(s,t){return t===void 0?s.h!==ZD&&!!(2&(0|s.v[_o])):!!(2&t)&&s.h!==ZD}const ZD={};function CWe(s,t){if(s!=null){if(typeof s=="string")s=s?new V5(s,lU):YD();else if(s.constructor!==V5)if(kWe(s))s=s.length?new V5(new Uint8Array(s),lU):YD();else{if(!t)throw Error();s=void 0}}return s}let lpt=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 yyn=Object.freeze({});function WRt(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"),cpt=OAe(s=>typeof s=="string"),byn=OAe(s=>typeof s=="boolean"),FAe=typeof oU.BigInt=="function"&&typeof oU.BigInt(0)=="bigint";function Q_(s){var t=s;if(cpt(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(vyn(t)&&!Number.isSafeInteger(t))throw Error(String(t));return FAe?BigInt(s):s=byn(s)?s?"1":"0":cpt(s)?s.trim()||"0":String(s)}var _9e=OAe(s=>FAe?s>=wyn&&s<=Nyn:s[0]==="-"?dpt(s,_yn):dpt(s,jyn));const _yn=Number.MIN_SAFE_INTEGER.toString(),wyn=FAe?BigInt(Number.MIN_SAFE_INTEGER):void 0,jyn=Number.MAX_SAFE_INTEGER.toString(),Nyn=FAe?BigInt(Number.MAX_SAFE_INTEGER):void 0;function dpt(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;Cp=t,vx=(s-t)/4294967296>>>0}function hU(s){if(s<0){upt(-s);const[t,n]=EWe(Cp,vx);Cp=t>>>0,vx=n>>>0}else upt(s)}function AWe(s){const t=Syn||(Syn=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),vx=0,Cp=t.getUint32(0,!0)}function YRt(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:lX(s,t)}function Cyn(s,t){return Q_(Mq()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):lX(s,t))}function ZRt(s,t){return Mq()?Q_(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else Mq()?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+hpt(n)+hpt(s));return n}function hpt(s){return s=String(s),"0000000".slice(s.length)+s}function TWe(s,t){if(2147483648&t)if(Mq())s=""+(BigInt(0|t)<>>0));else{const[n,r]=EWe(s,t);s="-"+lX(n,r)}else s=lX(s,t);return s}function zAe(s){if(s.length<16)hU(Number(s));else if(Mq())s=BigInt(s),Cp=Number(s&BigInt(4294967295))>>>0,vx=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");vx=Cp=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));vx*=1e6,Cp=1e6*Cp+i,Cp>=4294967296&&(vx+=Math.trunc(Cp/4294967296),vx>>>=0,Cp>>>=0)}if(t){const[r,a]=EWe(Cp,vx);Cp=r,vx=a}}}function EWe(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function NN(s){return Array.prototype.slice.call(s)}const tee=typeof BigInt=="function"?BigInt.asIntN:void 0,Ayn=typeof BigInt=="function"?BigInt.asUintN:void 0,XD=Number.isSafeInteger,BAe=Number.isFinite,mU=Math.trunc,Tyn=Q_(0);function GG(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 N5(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function cX(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 XRt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const Eyn=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function see(s){switch(typeof s){case"bigint":return!0;case"number":return BAe(s);case"string":return Eyn.test(s);default:return!1}}function Iq(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return BAe(s)?0|s:void 0}function QRt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return BAe(s)?s>>>0:void 0}function JRt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(zAe(s),TWe(Cp,vx))}function MWe(s){if(s=mU(s),!XD(s)){hU(s);var t=Cp,n=vx;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=YRt(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function eDt(s){var t=mU(Number(s));return XD(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),JRt(s))}function tDt(s){var t=mU(Number(s));return XD(t)?Q_(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),Mq()?Q_(tee(64,BigInt(s))):Q_(JRt(s)))}function sDt(s){return XD(s)?s=Q_(MWe(s)):(s=mU(s),XD(s)?s=String(s):(hU(s),s=TWe(Cp,vx)),s=Q_(s)),s}function oSe(s){const t=typeof s;return s==null?s:t==="bigint"?Q_(tee(64,s)):see(s)?t==="string"?tDt(s):sDt(s):void 0}function nDt(s){if(typeof s!="string")throw Error();return s}function nee(s){if(s!=null&&typeof s!="string")throw Error();return s}function ly(s){return s==null||typeof s=="string"?s:void 0}function LWe(s,t,n,r){return s!=null&&s[dU]===uU?s:Array.isArray(s)?((r=(n=0|s[_o])|32&r|2&r)!==n&&gg(s,r),new t(s)):(n?2&r?((s=t[apt])||(eee((s=new t).v),s=t[apt]=s),t=s):t=new t:t=void 0,t)}function Myn(s,t,n){if(t)e:{if(!see(t=s))throw v9e("int64");switch(typeof t){case"string":t=tDt(t);break e;case"bigint":t=Q_(tee(64,t));break e;default:t=sDt(t)}}else t=oSe(s);return(s=t)==null?n?Tyn:void 0:s}const Lyn={};let Pyn=function(){try{return DAe(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),eIe=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 Iyn=Pyn?(Object.setPrototypeOf(eIe.prototype,Map.prototype),Object.defineProperties(eIe.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),eIe):class extends Map{constructor(){super()}};function mpt(s){return s}function tIe(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var V3=class extends Iyn{constructor(s,t,n=mpt,r=mpt){super(),this.J=0|s[_o],this.K=t,this.S=n,this.fa=this.K?Ryn:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return tIe(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 Ryn(s,t,n,r,a,i){return s=LWe(s,r,n,i),a&&(s=IWe(s)),s}function Dyn(s){return[s,this.get(s)]}let Oyn;function ppt(){return Oyn||(Oyn=new V3(eee([]),void 0,void 0,void 0,Lyn))}function $Ae(s){return X_?s[X_]:void 0}function lSe(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}V3.prototype.toJSON=void 0;var w9e=class{};const Fyn={Ka:!0};function zyn(s,t){t<100||cU(xyn,1)}function UAe(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=X_;!a&&Lq&&l&&(i=s[l])&&lSe(i,zyn),l=[];var o=s.length;let c;i=4294967295;let d=!1;const u=!!(64&t),h=u?128&t?0:-1:void 0;1&t||(c=o&&s[o-1],c!=null&&typeof c=="object"&&c.constructor===Object?i=--o:c=void 0,!u||128&t||a||(d=!0,i=i-h+h)),t=void 0;for(var m=0;m=i){const x=m-h;(t??(t={}))[x]=p}else l[m]=p}if(c)for(let p in c){if((o=c[p])==null||(o=n(o,r))==null)continue;let x;m=+p,u&&!Number.isNaN(m)&&(x=m+h){x[g]=NN(b)}),x.da=p.da,x}(s)),l}function Byn(s){return s[0]=dX(s[0]),s[1]=dX(s[1]),s}function dX(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return _9e(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[_o];return s.length===0&&1&t?void 0:UAe(s,t,dX)}if(s!=null&&s[dU]===uU)return rDt(s);if(s instanceof V5){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if($Rt){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 V3?s=s.size!==0?s.V(Byn):void 0:void 0}return s}let $yn,Uyn;function rDt(s){return UAe(s=s.v,0|s[_o],dX)}function dD(s,t){return aDt(s,t[0],t[1])}function aDt(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[_o],tpt&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(tpt)throw Error("carr");cU(gyn,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&gg(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 gg(s,64|a|r),s}function qyn(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[_o];return s.length===0&&1&n?void 0:fpt(s,n,t)}if(s!=null&&s[dU]===uU)return xpt(s);if(s instanceof V3){if(2&(t=s.J))return s;if(!s.size)return;if(n=eee(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 nh(s,t,n,r){Oq(s),pg(s=s.v,0|s[_o],t,n,r)}function pg(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[_o]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function p8(){return yyn===void 0?2:4}function f8(s,t,n,r,a){let i=s.v,l=0|i[_o];r=sw(s,l)?1:r,a=!!a||r===3,r===2&&Dq(s)&&(i=s.v,l=0|i[_o]);let o=(s=DWe(i,t))===PO?7:0|s[_o],c=OWe(o,l);var d=!(4&c);if(d){4&c&&(s=NN(s),o=0,c=hD(c,l),l=pg(i,l,t,s));let u=0,h=0;for(;u{const o=LWe(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!sw(r)&&IO(s,t),r}function Kd(s,t,n,r){let a=s.v,i=0|a[_o];if((t=uDt(a,i,t,n,r))==null)return t;if(i=0|a[_o],!sw(s,i)){const l=IWe(t);l!==t&&(Dq(s)&&(a=s.v,i=0|a[_o]),i=pg(a,i,n,t=l,r),IO(a,i))}return t}function hDt(s,t,n,r,a,i,l,o){var c=sw(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&Dq(s)&&(n=0|(t=s.v)[_o]);var d=(s=DWe(t,a))===PO?7:0|s[_o],u=OWe(d,n);if(o=!(4&u)){var h=s,m=n;const p=!!(2&u);p&&(m|=2);let x=!p,y=!0,g=0,b=0;for(;g32)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 VWe(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function dSe(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],mD(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 Vyn(s){return DE(s)}function mD(s,t){if(s.g=t,t>s.l)throw Error()}function pDt(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 fDt(s,t){if(t==0)return YD();var n=pDt(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):kyn?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?YD():new V5(n,lU)}var gpt=[];function xDt(s,t,n,r){if(uSe.length){const a=uSe.pop();return a.o(r),a.g.init(s,t,n,r),a}return new Hyn(s,t,n,r)}function gDt(s){s.g.clear(),s.l=-1,s.h=-1,uSe.length<100&&uSe.push(s)}function yDt(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=eS(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function zje(s){switch(s.h){case 0:s.h!=0?zje(s):VWe(s.g);break;case 1:mD(s=s.g,s.g+8);break;case 2:if(s.h!=2)zje(s);else{var t=eS(s.g);mD(s=s.g,s.g+t)}break;case 5:mD(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!yDt(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}zje(s)}break;default:throw Error()}}function ree(s,t,n){const r=s.g.l;var a=eS(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 HWe(s){var t=eS(s.g),n=pDt(s=s.g,t);if(s=s.h,ryn){var r,a=s;(r=JPe)||(r=JPe=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(Une===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),Une=!0}catch{Une=!1}}throw!Une&&(JPe=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?pM():(o=s[i++],l<194||(192&o)!=128?(i--,pM()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?pM():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,pM()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?pM():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,pM()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):pM(),n.length>=8192&&(c=ept(c,n),n.length=0)}i=ept(c,n)}return i}function vDt(s){const t=eS(s.g);return fDt(s.g,t)}function VAe(s,t,n){var r=eS(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let Gyn;function vpt(s){return s?/^-?\d+$/.test(s)?(zAe(s),new N9e(Cp,vx)):null:Wyn||(Wyn=new N9e(0,0))}var N9e=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let Wyn;function Pz(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 zq(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function HAe(s,t){if(t>=0)zq(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function GWe(s){var t=Cp;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 pU(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function Xj(s,t,n){zq(s.g,8*t+n)}function WWe(s,t){return Xj(s,t,2),t=s.g.end(),pU(s,t),t.push(s.h),t}function KWe(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 GAe(s,t,n){Xj(s,t,2),zq(s.g,n.length),pU(s,s.g.end()),pU(s,n)}function hSe(s,t,n,r){n!=null&&(t=WWe(s,t),r(n,s),KWe(s,t))}function pS(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var YWe=pS(),bDt=pS(),ZWe=pS(),XWe=pS(),QWe=pS(),_Dt=pS(),Kyn=pS(),WAe=pS(),wDt=pS(),jDt=pS();function fS(s,t,n){var r=s.v;X_&&X_ in r&&(r=r[X_])&&delete r[t.g],t.h?t.j(s,t.h,t.g,n,t.l):t.j(s,t.g,n,t.l)}var wo=class{constructor(s,t){this.v=aDt(s,t,void 0,2048)}toJSON(){return rDt(this)}j(){var a;var s=Tvn,t=this.v,n=s.g,r=X_;if(Lq&&r&&((a=t[r])==null?void 0:a[n])!=null&&cU(fyn,3),t=s.g,ipt&&X_&&ipt===void 0&&(r=(n=this.v)[X_])&&(r=r.da))try{r(n,t,Fyn)}catch(i){FRt(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[_o];return RWe(this,s,t)?PWe(this,s,!0):new this.constructor(Rq(s,t,!1))}};wo.prototype[dU]=uU,wo.prototype.toString=function(){return this.v.toString()};var Bq=class{constructor(s,t,n){this.g=s,this.h=t,s=YWe,this.l=!!s&&n===s||!1}};function KAe(s,t){return new Bq(s,t,YWe)}function NDt(s,t,n,r,a){hSe(s,n,ADt(t,r),a)}const Yyn=KAe(function(s,t,n,r,a){return s.h===2&&(ree(s,BWe(t,r,n),a),!0)},NDt),Zyn=KAe(function(s,t,n,r,a){return s.h===2&&(ree(s,BWe(t,r,n),a),!0)},NDt);var YAe=Symbol(),ZAe=Symbol(),k9e=Symbol(),bpt=Symbol(),_pt=Symbol();let kDt,SDt;function RO(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 $yn||($yn=[0,void 0,!0]);case"number":return h>0?void 0:h===0?Uyn||(Uyn=[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,kDt??(kDt=i),SDt??(SDt=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 eKe(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=RO(ZAe,JWe,eKe,r).T),l||(l=tKe(r)),a)}function tKe(s){let t=s[k9e];if(t!=null)return t;const n=RO(ZAe,JWe,eKe,s);return t=n.ma?(r,a)=>kDt(r,a,n):(r,a)=>{for(;yDt(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=Qyn(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,zje(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=fDt(o.g,c);l=void 0,o=r,c&&((l=o[X_]??(o[X_]=new w9e))[i]??(l[i]=[])).push(c)}}return(r=$Ae(r))&&(r.da=n.qa[_pt]),!0},s[k9e]=t,s[_pt]=Xyn.bind(s),t}function Xyn(s,t,n,r){var a=this[ZAe];const i=this[k9e],l=dD(void 0,a.T),o=$Ae(s);if(o){var c=!1,d=a.ba;if(d){if(a=(u,h,m)=>{if(m.length!==0)if(d[h])for(const p of m){u=xDt(p);try{c=!0,i(l,u)}finally{gDt(u)}}else r==null||r(s,h,m)},t==null)lSe(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[_o];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=Pq(u),m=(p,x)=>{if(H3(s,p,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}x!=null&&(u=pg(s,u,p,x,h)),delete o[p]};t==null?WRt(l,0|l[_o],(p,x)=>{m(p,x)}):m(t,H3(l,t,h))}}}}function Qyn(s){const t=(s=CDt(s))[0].g;if(s=s[1]){const n=tKe(s),r=RO(ZAe,JWe,eKe,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function XAe(s,t,n){s[t]=n.h}function QAe(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=RO(YAe,XAe,QAe,r).T),a||(a=TDt(r)))}function TDt(s){let t=s[bpt];if(!t){const n=RO(YAe,XAe,QAe,s);t=(r,a)=>EDt(r,a,n),s[bpt]=t}return t}function EDt(s,t,n){WRt(s,0|s[_o],(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=CDt(c))[0].h;if(c=c[1]){const u=TDt(c),h=RO(YAe,XAe,QAe,c).T;c=l.ma?SDt(h,u):(m,p,x)=>d(m,p,x,h,u)}else c=d;return l[o]=c}}(n,r);i?i(t,a,r):r<500||cU(b9e,3)}}),(s=$Ae(s))&&lSe(s,(r,a,i)=>{for(pU(t,t.g.end()),r=0;r{hSe(s,n,dD([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),Pz(s.g,n.h,n.g);break;default:n=vpt(t),Pz(s.g,n.h,n.g)}}function PDt(s,t,n){(t=Iq(t))!=null&&t!=null&&(Xj(s,n,0),HAe(s.g,t))}function IDt(s,t,n){(t=XRt(t))!=null&&(Xj(s,n,0),s.g.g.push(t?1:0))}function RDt(s,t,n){(t=ly(t))!=null&&GAe(s,n,ORt(t))}function DDt(s,t,n,r,a){hSe(s,n,ADt(t,r),a)}function ODt(s,t,n){(t=t==null||typeof t=="string"||t instanceof V5?t:void 0)!=null&&GAe(s,n,UWe(t,!0).buffer)}function FDt(s,t,n){(t=QRt(t))!=null&&t!=null&&(Xj(s,n,0),zq(s.g,t))}function zDt(s,t,n){return(s.h===5||s.h===2)&&(t=Fq(t,0|t[_o],n),s.h==2?VAe(s,dSe,t):t.push(dSe(s.g)),!0)}var jx=cv(function(s,t,n){return s.h===5&&(dv(t,n,dSe(s.g)),!0)},MDt,WAe),tvn=Uq(zDt,function(s,t,n){if((t=$q(N5,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"))||(zAe(r),r=lX(Cp,vx))),r;if(a==="number")return(r=mU(r))>=0&&XD(r)||(hU(r),r=YRt(Cp,vx)),r}}(t),t!=null&&(typeof t=="string"&&ypt(t),t!=null))switch(Xj(s,n,0),typeof t){case"number":s=s.g,hU(t),Pz(s,Cp,vx);break;case"bigint":n=BigInt.asUintN(64,t),n=new j9e(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),Pz(s.g,n.h,n.g);break;default:n=ypt(t),Pz(s.g,n.h,n.g)}},Kyn),cg=cv(function(s,t,n){return s.h===0&&(dv(t,n,DE(s.g)),!0)},PDt,XWe),aee=Uq(function(s,t,n){return(s.h===0||s.h===2)&&(t=Fq(t,0|t[_o],n),s.h==2?VAe(s,DE,t):t.push(DE(s.g)),!0)},function(s,t,n){if((t=$q(Iq,t))!=null&&t.length){n=WWe(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=xDt(n,void 0,void 0,i);try{const l=new s,o=l.v;tKe(t)(o,n);var a=l}finally{gDt(n)}}return a}}function JAe(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}}}};EDt(this.v,t,RO(YAe,XAe,QAe,s)),pU(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=Npt.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=rIe)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function qne(s,...t){if(t.length===0)return kpt(s[0]);let n=s[0];for(let r=0;r({index:bj(r,1)??0??-1,score:qf(r,2)??0,categoryName:ly(Pp(r,3))??""??"",displayName:ly(Pp(r,4))??""??""})),headIndex:t,headName:n}}function Pvn(s){const t={classifications:G3(s,pvn,1).map(n=>{var r;return dKe(((r=Kd(n,KDt,4))==null?void 0:r.g())??[],bj(n,2)??0,ly(Pp(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(_9e(n)?n=Number(n):(n=tee(64,n),n=_9e(n)?Number(n):String(n)),n):see(n)?typeof n=="number"?MWe(n):eDt(n):void 0}(Pp(s,2,void 0,void 0,oSe))!=null&&(t.timestampMs=_Ot(Pp(s,2,void 0,void 0,oSe)??iDt)),t}function wOt(s){var l,o;var t=f8(s,3,N5,p8()),n=f8(s,2,Iq,p8()),r=f8(s,1,ly,p8()),a=f8(s,9,ly,p8());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function Opt(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 Fpt(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 kOt(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 No(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 zpt(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]=kOt(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 Bpt(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 _k(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function OC(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)}}R7.forVisionTasks=function(s,t=!1){return Hne("vision",s??qne``,t)},R7.forTextTasks=function(s,t=!1){return Hne("text",s??qne``,t)},R7.forGenAiTasks=function(s,t=!1){return Hne("genai",s??qne``,t)},R7.forAudioTasks=function(s,t=!1){return Hne("audio",s??qne``,t)},R7.isSimdSupported=function(s=!1){return jOt(s)};async function Rvn(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await Fpt(i),!self.ModuleFactory||l&&(await Fpt(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 oIe(s,t){const n=Kd(s.baseOptions,mSe,1)||new mSe;typeof t=="string"?(nh(n,2,nee(t)),nh(n,1)):t instanceof Uint8Array&&(nh(n,1,CWe(t,!1)),nh(n,2)),Qo(s.baseOptions,0,1,n)}function $pt(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 no(s,t){s.C=Math.max(s.C,t)}function nTe(s,t){s.B=new Ob,nw(s.B,2,"PassThroughCalculator"),Km(s.B,"free_memory"),wd(s.B,"free_memory_unused_out"),$p(t,"free_memory"),Qj(t,s.B)}function fU(s,t){Km(s.B,t),wd(s.B,t+"_unused_out")}function rTe(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var E9e=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=Kd(this.baseOptions,mSe,1))!=null&&a.g()||(i=Kd(this.baseOptions,mSe,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=Kd(d.baseOptions,Lpt,3);if(!h){var m=h=new Lpt,p=new Spt;iY(m,4,Bje,p)}"delegate"in u&&(u.delegate==="GPU"?(u=h,m=new ovn,iY(u,2,Bje,m)):(u=h,m=new Spt,iY(u,4,Bje,m))),Qo(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),oIe(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)oIe(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const u=[];for(var h=0;;){const{done:m,value:p}=await d.read();if(m)break;u.push(p),h+=p.length}if(u.length===0)return new Uint8Array(0);if(u.length===1)return u[0];d=new Uint8Array(h),h=0;for(const m of u)d.set(m,h),h+=m.length;return d}(c.modelAssetBuffer).then(d=>{oIe(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=lvn(t)}),!s)throw Error("Failed to retrieve CalculatorGraphConfig");return s}setGraph(s,t){this.g.attachErrorListener((n,r)=>{this.H.push(Error(r))}),this.g.Ja(),this.g.setGraph(s,t),this.B=void 0,$pt(this)}finishProcessing(){this.g.finishProcessing(),$pt(this)}close(){this.B=void 0,this.g.closeGraph()}};function xE(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}E9e.prototype.close=E9e.prototype.close;class Dvn{constructor(t,n,r,a){this.g=t,this.h=n,this.m=r,this.l=a}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function Upt(s,t,n){const r=s.g;if(n=xE(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 qpt(s,t){const n=s.g,r=xE(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=xE(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=xE(n.createBuffer(),"Failed to create buffer");return n.bindBuffer(n.ARRAY_BUFFER,i),n.enableVertexAttribArray(s.L),n.vertexAttribPointer(s.L,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array(t?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),n.bindVertexArray(null),new Dvn(n,r,a,i)}function uKe(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function Ovn(s,t,n,r){return uKe(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=qpt(s,!0)),n=s.u):(s.A||(s.A=qpt(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function SOt(s,t,n){return uKe(s,t),s=xE(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 COt(s,t,n){uKe(s,t),s.B||(s.B=xE(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 Fvn(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var AOt=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=xE(s.createProgram(),"Failed to create WebGL program"),this.X=Upt(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=Upt(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 t3(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 M9e(s){var t=t3(s,1);if(!t){if(t=t3(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=xU(s);var n=hKe(s);if(COt(n,r,TOt(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 M9e(this)}N(){return TOt(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=xU(this),a=hKe(this);r.activeTexture(r.TEXTURE1),n=SOt(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=EOt(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),COt(a,r,n),Ovn(a,r,!1,()=>{MOt(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),L9e(this)}),Fvn(a),L9e(this)}}s.push(n)}return new Fg(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&xU(this).deleteTexture(t3(this,2)),Vpt=-1}};Fg.prototype.close=Fg.prototype.close,Fg.prototype.clone=Fg.prototype.clone,Fg.prototype.getAsWebGLTexture=Fg.prototype.N,Fg.prototype.getAsFloat32Array=Fg.prototype.ia,Fg.prototype.getAsUint8Array=Fg.prototype.ja,Fg.prototype.hasWebGLTexture=Fg.prototype.R,Fg.prototype.hasFloat32Array=Fg.prototype.ka,Fg.prototype.hasUint8Array=Fg.prototype.Fa;var Vpt=250;function UN(...s){return s.map(([t,n])=>({start:t,end:n}))}const zvn=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((Hpt=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:NOt()?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?'),No(this,r||"input_audio",i=>{No(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){_k(this,"__graph_config__",t=>{s(t)}),No(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),No(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){No(this,t,r=>{const[a,i]=zpt(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){No(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){No(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){No(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){No(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){No(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){No(this,t,r=>{No(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){No(this,t,r=>{Bpt(this,Object.keys(s),a=>{Bpt(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){No(this,n,a=>{No(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){No(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){No(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){No(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){No(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){No(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){No(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){No(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)No(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){No(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){No(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){No(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){No(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){No(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){No(this,t,n=>{No(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){No(this,n,r=>{No(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){No(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){No(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){No(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){No(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){No(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){No(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)No(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){_k(this,s,t),No(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){OC(this,s,t),No(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){_k(this,s,t),No(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){OC(this,s,t),No(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){_k(this,s,t),No(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){OC(this,s,t),No(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){_k(this,s,t),No(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){OC(this,s,t),No(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){_k(this,s,t),No(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){OC(this,s,t),No(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){_k(this,s,t),No(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){OC(this,s,t),No(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){_k(this,s,t),No(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){OC(this,s,t),No(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?'),_k(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),No(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 Hpt{get ga(){return this.i}pa(s,t,n){No(this,t,r=>{const[a,i]=zpt(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){_k(this,s,t),No(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){OC(this,s,t),No(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var Hpt,qN=class extends zvn{};async function Bd(s,t,n){return async function(r,a,i,l){return Rvn(r,a,i,l)}(s,n.canvas??(NOt()?void 0:document.createElement("canvas")),t,n)}function LOt(s,t,n,r){if(s.U){const i=new JDt;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].");Lo(i,1,(a.left+a.right)/2),Lo(i,2,(a.top+a.bottom)/2),Lo(i,4,a.right-a.left),Lo(i,3,a.bottom-a.top)}else Lo(i,1,.5),Lo(i,2,.5),Lo(i,4,1),Lo(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(Lo(i,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[l,o]=kOt(t);n=qf(i,3)*o/l,a=qf(i,4)*l/o,Lo(i,4,n),Lo(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 VN(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'.");LOt(s,t,n,s.C+1)}function gS(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'.");LOt(s,t,n,r)}function gU(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 Fg([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var rw=class extends E9e{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new AOt}l(s,t=!0){if("runningMode"in s&&nh(this.baseOptions,2,cX(!!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()}};rw.prototype.close=rw.prototype.close;var $w=class extends rw{constructor(s,t){super(new qN(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},Qo(s=this.h=new tTe,0,1,t=new Sf),Lo(this.h,2,.5),Lo(this.h,3,.3)}get baseOptions(){return Kd(this.h,Sf,1)}set baseOptions(s){Qo(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&Lo(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&Lo(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},VN(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},gS(this,s,n,t),this.j}m(){var s=new uw;$p(s,"image_in"),$p(s,"norm_rect_in"),iu(s,"detections");const t=new dw;fS(t,bvn,this.h);const n=new Ob;nw(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),Km(n,"IMAGE:image_in"),Km(n,"NORM_RECT:norm_rect_in"),wd(n,"DETECTIONS:detections"),n.o(t),Qj(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=ZDt(i),this.j.detections.push(wOt(r));no(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{no(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};$w.prototype.detectForVideo=$w.prototype.G,$w.prototype.detect=$w.prototype.F,$w.prototype.setOptions=$w.prototype.o,$w.createFromModelPath=async function(s,t){return Bd($w,s,{baseOptions:{modelAssetPath:t}})},$w.createFromModelBuffer=function(s,t){return Bd($w,s,{baseOptions:{modelAssetBuffer:t}})},$w.createFromOptions=function(s,t){return Bd($w,s,t)};var mKe=UN([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]),pKe=UN([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]),fKe=UN([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),POt=UN([474,475],[475,476],[476,477],[477,474]),xKe=UN([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]),gKe=UN([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),IOt=UN([469,470],[470,471],[471,472],[472,469]),yKe=UN([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]),ROt=[...mKe,...pKe,...fKe,...xKe,...gKe,...yKe],DOt=UN([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 Gpt(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var nf=class extends rw{constructor(s,t){super(new qN(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,Qo(s=this.h=new rOt,0,1,t=new Sf),this.A=new nOt,Qo(this.h,0,3,this.A),this.u=new tTe,Qo(this.h,0,2,this.u),W3(this.u,4,1),Lo(this.u,2,.5),Lo(this.A,2,.5),Lo(this.h,4,.5)}get baseOptions(){return Kd(this.h,Sf,1)}set baseOptions(s){Qo(this.h,0,1,s)}o(s){return"numFaces"in s&&W3(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&Lo(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&Lo(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&Lo(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 Gpt(this),VN(this,s,t),this.j}G(s,t,n){return Gpt(this),gS(this,s,n,t),this.j}m(){var s=new uw;$p(s,"image_in"),$p(s,"norm_rect"),iu(s,"face_landmarks");const t=new dw;fS(t,wvn,this.h);const n=new Ob;nw(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),Km(n,"IMAGE:image_in"),Km(n,"NORM_RECT:norm_rect"),wd(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),Qj(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=iee(i),this.j.faceLandmarks.push(sTe(r));no(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{no(this,r)}),this.outputFaceBlendshapes&&(iu(s,"blendshapes"),wd(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=eTe(i),this.j.faceBlendshapes.push(dKe(r.g()??[]));no(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{no(this,r)})),this.outputFacialTransformationMatrixes&&(iu(s,"face_geometry"),wd(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=Kd(r=_vn(i),hvn,2))&&this.j.facialTransformationMatrixes.push({rows:bj(r,1)??0??0,columns:bj(r,2)??0??0,data:f8(r,3,N5,p8()).slice()??[]});no(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{no(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};nf.prototype.detectForVideo=nf.prototype.G,nf.prototype.detect=nf.prototype.F,nf.prototype.setOptions=nf.prototype.o,nf.createFromModelPath=function(s,t){return Bd(nf,s,{baseOptions:{modelAssetPath:t}})},nf.createFromModelBuffer=function(s,t){return Bd(nf,s,{baseOptions:{modelAssetBuffer:t}})},nf.createFromOptions=function(s,t){return Bd(nf,s,t)},nf.FACE_LANDMARKS_LIPS=mKe,nf.FACE_LANDMARKS_LEFT_EYE=pKe,nf.FACE_LANDMARKS_LEFT_EYEBROW=fKe,nf.FACE_LANDMARKS_LEFT_IRIS=POt,nf.FACE_LANDMARKS_RIGHT_EYE=xKe,nf.FACE_LANDMARKS_RIGHT_EYEBROW=gKe,nf.FACE_LANDMARKS_RIGHT_IRIS=IOt,nf.FACE_LANDMARKS_FACE_OVAL=yKe,nf.FACE_LANDMARKS_CONTOURS=ROt,nf.FACE_LANDMARKS_TESSELATION=DOt;var vKe=UN([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 Wpt(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function Kpt(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 Ypt(s,t=!0){const n=[];for(const a of s){var r=eTe(a);s=[];for(const i of r.g())r=t&&bj(i,1)!=null?bj(i,1)??0:-1,s.push({score:qf(i,2)??0,index:r,categoryName:ly(Pp(i,3))??""??"",displayName:ly(Pp(i,4))??""??""});n.push(s)}return n}var n_=class extends rw{constructor(s,t){super(new qN(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Qo(s=this.j=new oOt,0,1,t=new Sf),this.u=new iKe,Qo(this.j,0,2,this.u),this.D=new aKe,Qo(this.u,0,3,this.D),this.A=new iOt,Qo(this.u,0,2,this.A),this.h=new jvn,Qo(this.j,0,3,this.h),Lo(this.A,2,.5),Lo(this.u,4,.5),Lo(this.D,2,.5)}get baseOptions(){return Kd(this.j,Sf,1)}set baseOptions(s){Qo(this.j,0,1,s)}o(s){var a,i,l,o;if(W3(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&Lo(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Lo(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Lo(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new r7,n=t,r=T9e(s.cannedGesturesClassifierOptions,(a=Kd(this.h,r7,3))==null?void 0:a.l());Qo(n,0,2,r),Qo(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=Kd(this.h,r7,3))==null||i.g());return s.customGesturesClassifierOptions?(Qo(n=t=new r7,0,2,r=T9e(s.customGesturesClassifierOptions,(l=Kd(this.h,r7,4))==null?void 0:l.l())),Qo(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=Kd(this.h,r7,4))==null||o.g()),this.l(s)}Ha(s,t){return Wpt(this),VN(this,s,t),Kpt(this)}Ia(s,t,n){return Wpt(this),gS(this,s,n,t),Kpt(this)}m(){var s=new uw;$p(s,"image_in"),$p(s,"norm_rect"),iu(s,"hand_gestures"),iu(s,"hand_landmarks"),iu(s,"world_hand_landmarks"),iu(s,"handedness");const t=new dw;fS(t,Nvn,this.j);const n=new Ob;nw(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),Km(n,"IMAGE:image_in"),Km(n,"NORM_RECT:norm_rect"),wd(n,"HAND_GESTURES:hand_gestures"),wd(n,"LANDMARKS:hand_landmarks"),wd(n,"WORLD_LANDMARKS:world_hand_landmarks"),wd(n,"HANDEDNESS:handedness"),n.o(t),Qj(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=iee(i);const l=[];for(const o of G3(r,QDt,1))l.push({x:qf(o,1)??0,y:qf(o,2)??0,z:qf(o,3)??0,visibility:qf(o,4)??0});this.landmarks.push(l)}no(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{no(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r){r=Iz(i);const l=[];for(const o of G3(r,XDt,1))l.push({x:qf(o,1)??0,y:qf(o,2)??0,z:qf(o,3)??0,visibility:qf(o,4)??0});this.worldLandmarks.push(l)}no(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{no(this,r)}),this.g.attachProtoVectorListener("hand_gestures",(r,a)=>{this.gestures.push(...Ypt(r,!1)),no(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{no(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...Ypt(r)),no(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{no(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function Zpt(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}n_.prototype.recognizeForVideo=n_.prototype.Ia,n_.prototype.recognize=n_.prototype.Ha,n_.prototype.setOptions=n_.prototype.o,n_.createFromModelPath=function(s,t){return Bd(n_,s,{baseOptions:{modelAssetPath:t}})},n_.createFromModelBuffer=function(s,t){return Bd(n_,s,{baseOptions:{modelAssetBuffer:t}})},n_.createFromOptions=function(s,t){return Bd(n_,s,t)},n_.HAND_CONNECTIONS=vKe;var r_=class extends rw{constructor(s,t){super(new qN(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Qo(s=this.h=new iKe,0,1,t=new Sf),this.u=new aKe,Qo(this.h,0,3,this.u),this.j=new iOt,Qo(this.h,0,2,this.j),W3(this.j,3,1),Lo(this.j,2,.5),Lo(this.u,2,.5),Lo(this.h,4,.5)}get baseOptions(){return Kd(this.h,Sf,1)}set baseOptions(s){Qo(this.h,0,1,s)}o(s){return"numHands"in s&&W3(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&Lo(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Lo(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Lo(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],VN(this,s,t),Zpt(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],gS(this,s,n,t),Zpt(this)}m(){var s=new uw;$p(s,"image_in"),$p(s,"norm_rect"),iu(s,"hand_landmarks"),iu(s,"world_hand_landmarks"),iu(s,"handedness");const t=new dw;fS(t,kvn,this.h);const n=new Ob;nw(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),Km(n,"IMAGE:image_in"),Km(n,"NORM_RECT:norm_rect"),wd(n,"LANDMARKS:hand_landmarks"),wd(n,"WORLD_LANDMARKS:world_hand_landmarks"),wd(n,"HANDEDNESS:handedness"),n.o(t),Qj(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=iee(i),this.landmarks.push(sTe(r));no(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{no(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r)r=Iz(i),this.worldLandmarks.push(lY(r));no(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{no(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of r){r=eTe(c);const d=[];for(const u of r.g())d.push({score:qf(u,2)??0,index:bj(u,1)??0??-1,categoryName:ly(Pp(u,3))??""??"",displayName:ly(Pp(u,4))??""??""});o.push(d)}l.call(i,...o),no(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{no(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};r_.prototype.detectForVideo=r_.prototype.G,r_.prototype.detect=r_.prototype.F,r_.prototype.setOptions=r_.prototype.o,r_.createFromModelPath=function(s,t){return Bd(r_,s,{baseOptions:{modelAssetPath:t}})},r_.createFromModelBuffer=function(s,t){return Bd(r_,s,{baseOptions:{modelAssetBuffer:t}})},r_.createFromOptions=function(s,t){return Bd(r_,s,t)},r_.HAND_CONNECTIONS=vKe;var OOt=UN([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 Xpt(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function Qpt(s){try{if(!s.D)return s.h;s.D(s.h)}finally{rTe(s)}}function Wne(s,t){s=iee(s),t.push(sTe(s))}var Im=class extends rw{constructor(s,t){super(new qN(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,Qo(s=this.j=new hOt,0,1,t=new Sf),this.I=new aKe,Qo(this.j,0,2,this.I),this.W=new Svn,Qo(this.j,0,3,this.W),this.u=new tTe,Qo(this.j,0,4,this.u),this.O=new nOt,Qo(this.j,0,5,this.O),this.A=new dOt,Qo(this.j,0,6,this.A),this.M=new uOt,Qo(this.j,0,7,this.M),Lo(this.u,2,.5),Lo(this.u,3,.3),Lo(this.O,2,.5),Lo(this.A,2,.5),Lo(this.A,3,.3),Lo(this.M,2,.5),Lo(this.I,2,.5)}get baseOptions(){return Kd(this.j,Sf,1)}set baseOptions(s){Qo(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&Lo(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&Lo(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&Lo(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&Lo(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&Lo(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&Lo(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&Lo(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,Xpt(this),VN(this,s,r),Qpt(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,Xpt(this),gS(this,s,a,t),Qpt(this)}m(){var s=new uw;$p(s,"input_frames_image"),iu(s,"pose_landmarks"),iu(s,"pose_world_landmarks"),iu(s,"face_landmarks"),iu(s,"left_hand_landmarks"),iu(s,"left_hand_world_landmarks"),iu(s,"right_hand_landmarks"),iu(s,"right_hand_world_landmarks");const t=new dw,n=new wpt;nw(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))nh(a,2,UAe(i,0,dX));else{if(!(typeof i=="string"||i instanceof V5||kWe(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");yA(a,2,CWe(i,!1),YD())}}(n,this.j.g());const r=new Ob;nw(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),$We(r,8,wpt,n),Km(r,"IMAGE:input_frames_image"),wd(r,"POSE_LANDMARKS:pose_landmarks"),wd(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),wd(r,"FACE_LANDMARKS:face_landmarks"),wd(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),wd(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),wd(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),wd(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),Qj(s,r),nTe(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{Wne(a,this.h.poseLandmarks),no(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{no(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=Iz(a),l.push(lY(a)),no(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{no(this,a)}),this.outputPoseSegmentationMasks&&(wd(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),fU(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[gU(this,a,!0,!this.D)],no(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],no(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{Wne(a,this.h.faceLandmarks),no(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{no(this,a)}),this.outputFaceBlendshapes&&(iu(s,"extra_blendshapes"),wd(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=eTe(a),l.push(dKe(a.g()??[]))),no(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{no(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{Wne(a,this.h.leftHandLandmarks),no(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{no(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=Iz(a),l.push(lY(a)),no(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{no(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{Wne(a,this.h.rightHandLandmarks),no(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{no(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=Iz(a),l.push(lY(a)),no(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{no(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Im.prototype.detectForVideo=Im.prototype.G,Im.prototype.detect=Im.prototype.F,Im.prototype.setOptions=Im.prototype.o,Im.createFromModelPath=function(s,t){return Bd(Im,s,{baseOptions:{modelAssetPath:t}})},Im.createFromModelBuffer=function(s,t){return Bd(Im,s,{baseOptions:{modelAssetBuffer:t}})},Im.createFromOptions=function(s,t){return Bd(Im,s,t)},Im.HAND_CONNECTIONS=vKe,Im.POSE_CONNECTIONS=OOt,Im.FACE_LANDMARKS_LIPS=mKe,Im.FACE_LANDMARKS_LEFT_EYE=pKe,Im.FACE_LANDMARKS_LEFT_EYEBROW=fKe,Im.FACE_LANDMARKS_LEFT_IRIS=POt,Im.FACE_LANDMARKS_RIGHT_EYE=xKe,Im.FACE_LANDMARKS_RIGHT_EYEBROW=gKe,Im.FACE_LANDMARKS_RIGHT_IRIS=IOt,Im.FACE_LANDMARKS_FACE_OVAL=yKe,Im.FACE_LANDMARKS_CONTOURS=ROt,Im.FACE_LANDMARKS_TESSELATION=DOt;var Uw=class extends rw{constructor(s,t){super(new qN(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},Qo(s=this.h=new mOt,0,1,t=new Sf)}get baseOptions(){return Kd(this.h,Sf,1)}set baseOptions(s){Qo(this.h,0,1,s)}o(s){return Qo(this.h,0,2,T9e(s,Kd(this.h,nKe,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},VN(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},gS(this,s,n,t),this.j}m(){var s=new uw;$p(s,"input_image"),$p(s,"norm_rect"),iu(s,"classifications");const t=new dw;fS(t,Cvn,this.h);const n=new Ob;nw(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),Km(n,"IMAGE:input_image"),Km(n,"NORM_RECT:norm_rect"),wd(n,"CLASSIFICATIONS:classifications"),n.o(t),Qj(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=Pvn(fvn(r)),no(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{no(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Uw.prototype.classifyForVideo=Uw.prototype.ta,Uw.prototype.classify=Uw.prototype.sa,Uw.prototype.setOptions=Uw.prototype.o,Uw.createFromModelPath=function(s,t){return Bd(Uw,s,{baseOptions:{modelAssetPath:t}})},Uw.createFromModelBuffer=function(s,t){return Bd(Uw,s,{baseOptions:{modelAssetBuffer:t}})},Uw.createFromOptions=function(s,t){return Bd(Uw,s,t)};var a_=class extends rw{constructor(s,t){super(new qN(s,t),"image_in","norm_rect",!0),this.h=new pOt,this.embeddings={embeddings:[]},Qo(s=this.h,0,1,t=new Sf)}get baseOptions(){return Kd(this.h,Sf,1)}set baseOptions(s){Qo(this.h,0,1,s)}o(s){var t=this.h,n=Kd(this.h,Mpt,2);return n=n?n.clone():new Mpt,s.l2Normalize!==void 0?nh(n,1,cX(s.l2Normalize)):"l2Normalize"in s&&nh(n,1),s.quantize!==void 0?nh(n,2,cX(s.quantize)):"quantize"in s&&nh(n,2),Qo(t,0,2,n),this.l(s)}za(s,t){return VN(this,s,t),this.embeddings}Aa(s,t,n){return gS(this,s,n,t),this.embeddings}m(){var s=new uw;$p(s,"image_in"),$p(s,"norm_rect"),iu(s,"embeddings_out");const t=new dw;fS(t,Avn,this.h);const n=new Ob;nw(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),Km(n,"IMAGE:image_in"),Km(n,"NORM_RECT:norm_rect"),wd(n,"EMBEDDINGS:embeddings_out"),n.o(t),Qj(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=yvn(r),this.embeddings=function(i){return{embeddings:G3(i,gvn,1).map(l=>{var d,u;const o={headIndex:bj(l,3)??0??-1,headName:ly(Pp(l,4))??""??""};var c=l.v;return uDt(c,0|c[_o],Ept,sIe(l,1))!==void 0?(l=f8(l=Kd(l,Ept,sIe(l,1),void 0),1,N5,p8()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=Kd(l,xvn,sIe(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:_Ot(Pp(i,2,void 0,void 0,oSe)??iDt)}}(r),no(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{no(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};a_.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=Opt(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=Opt(Dpt(s.quantizedEmbedding),Dpt(t.quantizedEmbedding))}return s},a_.prototype.embedForVideo=a_.prototype.Aa,a_.prototype.embed=a_.prototype.za,a_.prototype.setOptions=a_.prototype.o,a_.createFromModelPath=function(s,t){return Bd(a_,s,{baseOptions:{modelAssetPath:t}})},a_.createFromModelBuffer=function(s,t){return Bd(a_,s,{baseOptions:{modelAssetBuffer:t}})},a_.createFromOptions=function(s,t){return Bd(a_,s,t)};var P9e=class{constructor(s,t,n){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=n}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(n=>{n.close()}),(t=this.categoryMask)==null||t.close()}};function Bvn(s){var n,r;const t=function(a){return G3(a,Ob,1)}(s.ca()).filter(a=>(ly(Pp(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=Kd(t[0],dw,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=ly(Pp(a,1))??""})}function Jpt(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function eft(s){try{const t=new P9e(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{rTe(s)}}P9e.prototype.close=P9e.prototype.close;var Pv=class extends rw{constructor(s,t){super(new qN(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new cKe,this.A=new fOt,Qo(this.h,0,3,this.A),Qo(s=this.h,0,1,t=new Sf)}get baseOptions(){return Kd(this.h,Sf,1)}set baseOptions(s){Qo(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?nh(this.h,2,nee(s.displayNamesLocale)):"displayNamesLocale"in s&&nh(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){Bvn(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,Jpt(this),VN(this,s,r),eft(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,Jpt(this),gS(this,s,a,t),eft(this)}Da(){return this.u}m(){var s=new uw;$p(s,"image_in"),$p(s,"norm_rect");const t=new dw;fS(t,gOt,this.h);const n=new Ob;nw(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),Km(n,"IMAGE:image_in"),Km(n,"NORM_RECT:norm_rect"),n.o(t),Qj(s,n),nTe(this,s),this.outputConfidenceMasks&&(iu(s,"confidence_masks"),wd(n,"CONFIDENCE_MASKS:confidence_masks"),fU(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>gU(this,i,!0,!this.j)),no(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],no(this,r)})),this.outputCategoryMask&&(iu(s,"category_mask"),wd(n,"CATEGORY_MASK:category_mask"),fU(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=gU(this,r,!1,!this.j),no(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,no(this,r)})),iu(s,"quality_scores"),wd(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,no(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,no(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Pv.prototype.getLabels=Pv.prototype.Da,Pv.prototype.segmentForVideo=Pv.prototype.La,Pv.prototype.segment=Pv.prototype.segment,Pv.prototype.setOptions=Pv.prototype.o,Pv.createFromModelPath=function(s,t){return Bd(Pv,s,{baseOptions:{modelAssetPath:t}})},Pv.createFromModelBuffer=function(s,t){return Bd(Pv,s,{baseOptions:{modelAssetBuffer:t}})},Pv.createFromOptions=function(s,t){return Bd(Pv,s,t)};var I9e=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()}};I9e.prototype.close=I9e.prototype.close;var wk=class extends rw{constructor(s,t){super(new qN(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new cKe,this.u=new fOt,Qo(this.h,0,3,this.u),Qo(s=this.h,0,1,t=new Sf)}get baseOptions(){return Kd(this.h,Sf,1)}set baseOptions(s){Qo(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 yOt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new iIe;yA(i,3,cX(!0),!1),yA(i,1,GG(t.keypoint.x),0),yA(i,2,GG(t.keypoint.y),0),iY(r,1,A9e,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new Evn;for(i of t.scribble)yA(t=new iIe,3,cX(!0),!1),yA(t,1,GG(i.x),0),yA(t,2,GG(i.y),0),$We(o,1,iIe,t);iY(r,2,A9e,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),VN(this,s,a);e:{try{const o=new I9e(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{rTe(this)}l=void 0}return l}m(){var s=new uw;$p(s,"image_in"),$p(s,"roi_in"),$p(s,"norm_rect_in");const t=new dw;fS(t,gOt,this.h);const n=new Ob;nw(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),Km(n,"IMAGE:image_in"),Km(n,"ROI:roi_in"),Km(n,"NORM_RECT:norm_rect_in"),n.o(t),Qj(s,n),nTe(this,s),this.outputConfidenceMasks&&(iu(s,"confidence_masks"),wd(n,"CONFIDENCE_MASKS:confidence_masks"),fU(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>gU(this,i,!0,!this.j)),no(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],no(this,r)})),this.outputCategoryMask&&(iu(s,"category_mask"),wd(n,"CATEGORY_MASK:category_mask"),fU(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=gU(this,r,!1,!this.j),no(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,no(this,r)})),iu(s,"quality_scores"),wd(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,no(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,no(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};wk.prototype.segment=wk.prototype.segment,wk.prototype.setOptions=wk.prototype.o,wk.createFromModelPath=function(s,t){return Bd(wk,s,{baseOptions:{modelAssetPath:t}})},wk.createFromModelBuffer=function(s,t){return Bd(wk,s,{baseOptions:{modelAssetBuffer:t}})},wk.createFromOptions=function(s,t){return Bd(wk,s,t)};var qw=class extends rw{constructor(s,t){super(new qN(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},Qo(s=this.h=new vOt,0,1,t=new Sf)}get baseOptions(){return Kd(this.h,Sf,1)}set baseOptions(s){Qo(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?nh(this.h,2,nee(s.displayNamesLocale)):"displayNamesLocale"in s&&nh(this.h,2),s.maxResults!==void 0?W3(this.h,3,s.maxResults):"maxResults"in s&&nh(this.h,3),s.scoreThreshold!==void 0?Lo(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&nh(this.h,4),s.categoryAllowlist!==void 0?cSe(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&nh(this.h,5),s.categoryDenylist!==void 0?cSe(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&nh(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},VN(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},gS(this,s,n,t),this.j}m(){var s=new uw;$p(s,"input_frame_gpu"),$p(s,"norm_rect"),iu(s,"detections");const t=new dw;fS(t,Mvn,this.h);const n=new Ob;nw(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),Km(n,"IMAGE:input_frame_gpu"),Km(n,"NORM_RECT:norm_rect"),wd(n,"DETECTIONS:detections"),n.o(t),Qj(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=ZDt(i),this.j.detections.push(wOt(r));no(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{no(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};qw.prototype.detectForVideo=qw.prototype.G,qw.prototype.detect=qw.prototype.F,qw.prototype.setOptions=qw.prototype.o,qw.createFromModelPath=async function(s,t){return Bd(qw,s,{baseOptions:{modelAssetPath:t}})},qw.createFromModelBuffer=function(s,t){return Bd(qw,s,{baseOptions:{modelAssetBuffer:t}})},qw.createFromOptions=function(s,t){return Bd(qw,s,t)};var R9e=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 tft(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function sft(s){try{const t=new R9e(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{rTe(s)}}R9e.prototype.close=R9e.prototype.close;var i_=class extends rw{constructor(s,t){super(new qN(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,Qo(s=this.h=new bOt,0,1,t=new Sf),this.A=new uOt,Qo(this.h,0,3,this.A),this.j=new dOt,Qo(this.h,0,2,this.j),W3(this.j,4,1),Lo(this.j,2,.5),Lo(this.A,2,.5),Lo(this.h,4,.5)}get baseOptions(){return Kd(this.h,Sf,1)}set baseOptions(s){Qo(this.h,0,1,s)}o(s){return"numPoses"in s&&W3(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&Lo(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&Lo(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&Lo(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,tft(this),VN(this,s,r),sft(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,tft(this),gS(this,s,a,t),sft(this)}m(){var s=new uw;$p(s,"image_in"),$p(s,"norm_rect"),iu(s,"normalized_landmarks"),iu(s,"world_landmarks"),iu(s,"segmentation_masks");const t=new dw;fS(t,Lvn,this.h);const n=new Ob;nw(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),Km(n,"IMAGE:image_in"),Km(n,"NORM_RECT:norm_rect"),wd(n,"NORM_LANDMARKS:normalized_landmarks"),wd(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),Qj(s,n),nTe(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=iee(i),this.landmarks.push(sTe(r));no(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",r=>{this.landmarks=[],no(this,r)}),this.g.attachProtoVectorListener("world_landmarks",(r,a)=>{this.worldLandmarks=[];for(const i of r)r=Iz(i),this.worldLandmarks.push(lY(r));no(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],no(this,r)}),this.outputSegmentationMasks&&(wd(n,"SEGMENTATION_MASK:segmentation_masks"),fU(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>gU(this,i,!0,!this.u)),no(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",r=>{this.segmentationMasks=[],no(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};i_.prototype.detectForVideo=i_.prototype.G,i_.prototype.detect=i_.prototype.F,i_.prototype.setOptions=i_.prototype.o,i_.createFromModelPath=function(s,t){return Bd(i_,s,{baseOptions:{modelAssetPath:t}})},i_.createFromModelBuffer=function(s,t){return Bd(i_,s,{baseOptions:{modelAssetBuffer:t}})},i_.createFromOptions=function(s,t){return Bd(i_,s,t)},i_.POSE_CONNECTIONS=OOt;let x8=null,WG=null;async function $vn(){return x8||WG||(WG=(async()=>{const s=await R7.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return x8=await Pv.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}),x8})(),WG)}function Uvn(s,t,n,r,a){const i=new Float32Array(s.length);for(let l=0;l=0&&(o-=s[c+u]);const m=Math.min(h,n-1)-Math.max(u+1,0)+1;i[c+d]=o/m}}for(let l=0;l=0&&(o-=i[d*n+l]);const h=Math.min(u,r-1)-Math.max(d+1,0)+1;t[c*n+l]=o/h}}}function qvn(){x8&&(x8.close(),x8=null,WG=null)}function Vvn(s,t){const n=j.useRef(null),r=j.useRef(null),a=j.useRef(null),i=j.useRef(null),l=j.useRef(0);j.useRef(0);const[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(null),p=t.type!=="none"&&s!==null;return j.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const x=new Image;x.crossOrigin="anonymous",x.src=t.imageUrl,x.onload=()=>{i.current=x}}else i.current=null},[t.type,t.imageUrl]),j.useEffect(()=>{if(!p||!s){a.current&&(a.current.srcObject=null,a.current=null);return}const x=document.createElement("video");return x.srcObject=s,x.muted=!0,x.playsInline=!0,x.autoplay=!0,x.play().catch(()=>{}),a.current=x,()=>{x.srcObject=null,a.current=null}},[p,s]),j.useEffect(()=>{if(!p){c(null),m(null);return}let x=!1;return(async()=>{u(!0),m(null);try{const g=await $vn();if(x)return;u(!1);const b=a.current;if(!b||(await new Promise(Se=>{if(b.videoWidth>0)return Se();b.onloadedmetadata=()=>Se(),setTimeout(Se,2e3)}),x))return;const v=b.videoWidth||640,k=b.videoHeight||480,C=n.current;if(!C)return;C.width=v,C.height=k;const T=C.getContext("2d",{willReadFrequently:!1,alpha:!1});r.current||(r.current=document.createElement("canvas"));const M=r.current;M.width=v,M.height=k;const P=M.getContext("2d",{willReadFrequently:!1}),L=document.createElement("canvas");L.width=v,L.height=k;const I=L.getContext("2d",{alpha:!1}),O=document.createElement("canvas");O.width=v,O.height=k;const $=O.getContext("2d",{willReadFrequently:!1}),q=$.createImageData(v,k),W=q.data;for(let Se=0;SeG.addTrack(Se)),x||c(G);const ee=t.blurRadius??15,J=t.mirror??!1,le=new Float32Array(v*k),ue=new Float32Array(v*k),oe=new Float32Array(v*k);let ie=!1;const de=4,we=.35,je=typeof b.requestVideoFrameCallback=="function",xe=()=>{if(x||!a.current)return;const Se=a.current;if(Se.readyState<2){fe(Se);return}try{const Ee=performance.now(),De=g.segmentForVideo(Se,Ee).confidenceMasks;if(De&&De.length>0){ue.fill(0);for(let Be=1;Be1?1:Oe}}if(Uvn(ue,le,v,k,de),ie)for(let Be=0;Be=1?255:Ge*255|0}if($.putImageData(q,0,0),t.type==="blur")I.filter=`blur(${ee}px)`,I.drawImage(Se,0,0,v,k),I.filter="none",T.drawImage(L,0,0);else if(t.type==="image"&&i.current){const Be=i.current,Ne=Be.width/Be.height,Ge=v/k;let _e=0,Oe=0,Ae=Be.width,Xe=Be.height;Ne>Ge?(Ae=Be.height*Ge,_e=(Be.width-Ae)/2):(Xe=Be.width/Ge,Oe=(Be.height-Xe)/2),T.drawImage(Be,_e,Oe,Ae,Xe,0,0,v,k)}else T.fillStyle="#000",T.fillRect(0,0,v,k);P.globalCompositeOperation="source-over",P.clearRect(0,0,v,k),P.drawImage(Se,0,0,v,k),P.globalCompositeOperation="destination-in",P.drawImage(O,0,0),P.globalCompositeOperation="source-over",J?(T.save(),T.translate(v,0),T.scale(-1,1),T.drawImage(M,0,0),T.restore()):T.drawImage(M,0,0);for(const Be of De)Be.close()}else T.drawImage(Se,0,0,v,k)}catch{T.drawImage(Se,0,0,v,k)}fe(Se)},fe=Se=>{x||(je?Se.requestVideoFrameCallback(()=>xe()):l.current=requestAnimationFrame(xe))};fe(b)}catch(g){console.error("[useVirtualBackground] init error:",g),x||(u(!1),m(g.message||"Failed to initialize virtual background"))}})(),()=>{x=!0,l.current&&cancelAnimationFrame(l.current),c(null)}},[p,t.type,t.blurRadius,t.imageUrl,s]),j.useEffect(()=>()=>{qvn()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:p,error:h}}function k6({maxDurationSeconds:s=600,onRecordingComplete:t,onError:n,onRecordingStateChange:r,className:a,teleprompterContent:i}){const l=j.useRef(null),o=j.useRef(null),c=j.useRef(null),[d,u]=j.useState(null),h=j.useRef([]),m=j.useRef(null),p=j.useRef(null),x=j.useRef(null),y=j.useRef(null),g=Tq(),[b,v]=j.useState("camera"),k=j.useRef(null),C=j.useRef(null),T=j.useRef(null),M=j.useRef(null),P=j.useRef(null),L=j.useRef(null),[I,O]=j.useState(!0),[$,q]=j.useState(!0),[W,G]=j.useState(null),[K,ee]=j.useState(!1),[J,le]=j.useState(!1),[ue,oe]=j.useState(null),[ie,de]=j.useState(null),[we,je]=j.useState(0),[xe,fe]=j.useState("user"),[Se,Ee]=j.useState(0),[Le,De]=j.useState(!1),[Be,Ne]=j.useState(!0),[Ge,_e]=j.useState(null),[Oe,Ae]=j.useState(!1),[Xe,Ue]=j.useState(null),Ze=j.useRef(null),[Qe,Ye]=j.useState(()=>{try{const mr=localStorage.getItem("video-bg-config");if(mr)return JSON.parse(mr)}catch{}return{type:"none"}});j.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(Qe))}catch{}},[Qe]);const[nt,rt]=j.useState([]),[Fe,dt]=j.useState([]),[Dt,pt]=j.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[zt,Gt]=j.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});j.useEffect(()=>{try{localStorage.setItem("video-mic-id",Dt)}catch{}},[Dt]),j.useEffect(()=>{try{localStorage.setItem("video-cam-id",zt)}catch{}},[zt]),j.useEffect(()=>{var pr,rn,Jn;if(!((pr=navigator.mediaDevices)!=null&&pr.enumerateDevices))return;const mr=async()=>{try{const ea=await navigator.mediaDevices.enumerateDevices();rt(ea.filter(_s=>_s.kind==="audioinput")),dt(ea.filter(_s=>_s.kind==="videoinput"))}catch(ea){console.warn("[VideoRecorder] enumerateDevices failed",ea)}};return mr(),(Jn=(rn=navigator.mediaDevices).addEventListener)==null||Jn.call(rn,"devicechange",mr),()=>{var ea,_s;return(_s=(ea=navigator.mediaDevices).removeEventListener)==null?void 0:_s.call(ea,"devicechange",mr)}},[W]);const{canvasRef:qs,compositedStream:As,isLoading:Bt,isActive:At,error:Is}=Vvn(d,Qe),jt=j.useRef(n);jt.current=n;const Qs=j.useCallback(mr=>{O(mr)},[]),cn=j.useRef(I),qt=j.useCallback(()=>{T.current&&(cancelAnimationFrame(T.current),T.current=null),M.current&&(M.current.terminate(),M.current=null),k.current&&(k.current.getTracks().forEach(mr=>mr.stop()),k.current=null),P.current&&(P.current.getTracks().forEach(mr=>mr.stop()),P.current=null),L.current&&(L.current.srcObject=null,L.current=null)},[]),Gs=j.useCallback(async()=>{var mr;try{const pr=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});k.current=pr;let rn=null;try{rn=await navigator.mediaDevices.getUserMedia({video:zt?{deviceId:{exact:zt},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let Jn=null;try{Jn=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...Dt?{deviceId:{exact:Dt}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",Jn.getAudioTracks().map(Mr=>Mr.label))}catch(Mr){console.warn("[VideoRecorder] No mic audio for screen recording",Mr);try{Jn=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const ea=pr.getVideoTracks()[0],_s=ea.getSettings(),We=_s.width||1920,it=_s.height||1080,gt=document.createElement("canvas");gt.width=We,gt.height=it,C.current=gt;const St=gt.getContext("2d");let Ht=null;rn&&(Ht=document.createElement("video"),Ht.srcObject=rn,Ht.muted=!0,Ht.playsInline=!0,Ht.autoplay=!0,await Ht.play(),L.current=Ht);const ts=document.createElement("video");ts.srcObject=pr,ts.muted=!0,ts.playsInline=!0,ts.autoplay=!0,await ts.play();const Ms=()=>{if(St.drawImage(ts,0,0,We,it),Ht&&Ht.readyState>=2){const Mr=Math.round(We*.2),Xr=Math.round(Mr*(Ht.videoHeight/Ht.videoWidth||.75)),Qt=We-Mr-20,Zn=it-Xr-20,aa=12;St.save(),St.beginPath(),St.moveTo(Qt+aa,Zn),St.lineTo(Qt+Mr-aa,Zn),St.quadraticCurveTo(Qt+Mr,Zn,Qt+Mr,Zn+aa),St.lineTo(Qt+Mr,Zn+Xr-aa),St.quadraticCurveTo(Qt+Mr,Zn+Xr,Qt+Mr-aa,Zn+Xr),St.lineTo(Qt+aa,Zn+Xr),St.quadraticCurveTo(Qt,Zn+Xr,Qt,Zn+Xr-aa),St.lineTo(Qt,Zn+aa),St.quadraticCurveTo(Qt,Zn,Qt+aa,Zn),St.closePath(),St.clip(),St.translate(Qt+Mr,Zn),St.scale(-1,1),St.drawImage(Ht,0,0,Mr,Xr),St.restore(),St.strokeStyle="rgba(255,255,255,0.6)",St.lineWidth=2,St.beginPath(),St.moveTo(Qt+aa,Zn),St.lineTo(Qt+Mr-aa,Zn),St.quadraticCurveTo(Qt+Mr,Zn,Qt+Mr,Zn+aa),St.lineTo(Qt+Mr,Zn+Xr-aa),St.quadraticCurveTo(Qt+Mr,Zn+Xr,Qt+Mr-aa,Zn+Xr),St.lineTo(Qt+aa,Zn+Xr),St.quadraticCurveTo(Qt,Zn+Xr,Qt,Zn+Xr-aa),St.lineTo(Qt,Zn+aa),St.quadraticCurveTo(Qt,Zn,Qt+aa,Zn),St.closePath(),St.stroke()}},js="let id=null;onmessage=(e)=>{if(e.data&&e.data.type==='start'){clearInterval(id);id=setInterval(()=>postMessage('tick'),Math.round(1000/(e.data.fps||30)))}else if(e.data==='stop'){clearInterval(id);id=null}}",Zs=new Blob([js],{type:"application/javascript"}),Tn=new Worker(URL.createObjectURL(Zs));M.current=Tn,Tn.onmessage=()=>Ms(),Tn.postMessage({type:"start",fps:30}),Ms();const vn=gt.captureStream(30),_r=[],Jr=pr.getAudioTracks();Jr.length&&_r.push(...Jr),Jn&&_r.push(...Jn.getAudioTracks());const ha=new MediaStream([...vn.getVideoTracks(),..._r]);return P.current=ha,ea.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),qt()},ha}catch(pr){return console.error("[VideoRecorder] Screen capture error:",pr),pr.name!=="NotAllowedError"&&((mr=jt.current)==null||mr.call(jt,"Failed to start screen capture: "+(pr.message||"Unknown error"))),null}},[qt]),Ls=j.useCallback(async()=>{var pr,rn;q(!0),_e(null);const mr=g&&I;console.log("[VideoRecorder] initCamera start",{isMobile:g,usePortraitMode:I,shouldBePortrait:mr,facingMode:xe});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(St=>St.stop()));const Jn=g&&mr?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},ea=zt?{...Jn,deviceId:{exact:zt}}:{...Jn,facingMode:{ideal:xe}},_s={echoCancellation:!0,noiseSuppression:!0,...Dt?{deviceId:{exact:Dt}}:{}};console.log("[VideoRecorder] requesting getUserMedia",ea);const We=await navigator.mediaDevices.getUserMedia({video:ea,audio:_s});if(console.log("[VideoRecorder] getUserMedia success"),We.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=We,u(We),G(!0);const gt=We.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",gt.width,"x",gt.height),l.current){const St=l.current;St.srcObject=We,St.muted=!0,St.playsInline=!0,St.autoplay=!0,St.setAttribute("muted",""),St.setAttribute("playsinline",""),St.setAttribute("autoplay","");try{(pr=St.load)==null||pr.call(St)}catch(ts){console.warn("[VideoRecorder] videoEl.load failed",ts)}const Ht=async()=>{try{return await St.play(),console.log("[VideoRecorder] preview play ok"),Ae(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:St.readyState,videoWidth:St.videoWidth,videoHeight:St.videoHeight})},300),!0}catch(ts){return console.warn("[VideoRecorder] preview play blocked",ts),Ae(!0),!1}};await new Promise(ts=>{let Ms=!1;const js=()=>{Ms||(Ms=!0,ts())},Zs=()=>{Ht().finally(js)};St.onloadedmetadata=Zs,St.onloadeddata=Zs,setTimeout(js,1500)})}try{p.current=new AudioContext;const St=p.current.createMediaStreamSource(We);x.current=p.current.createAnalyser(),x.current.fftSize=256,St.connect(x.current);const Ht=()=>{if(x.current){const ts=new Uint8Array(x.current.frequencyBinCount);x.current.getByteFrequencyData(ts);const Ms=ts.reduce((js,Zs)=>js+Zs)/ts.length;Ee(Math.min(100,Ms/128*100))}y.current=requestAnimationFrame(Ht)};Ht()}catch(St){console.warn("Audio context not available:",St)}}catch(Jn){console.error("Camera initialization error:",Jn),G(!1);let ea="Failed to access camera or microphone.";Jn.name==="NotAllowedError"?ea="Camera permission denied. Please allow camera access in your browser settings.":Jn.name==="NotFoundError"?ea="No camera found. Please connect a camera and try again.":Jn.name==="NotReadableError"?ea="Camera is in use by another application. Please close other apps using the camera.":Jn.message&&(ea=Jn.message),_e(ea),(rn=jt.current)==null||rn.call(jt,ea)}finally{q(!1)}},[xe,g,I,Dt,zt]);j.useEffect(()=>{cn.current!==I&&W&&!K&&!ie&&(cn.current=I,Ls())},[I,W,K,ie,Ls]),j.useEffect(()=>(Ls(),()=>{c.current&&c.current.getTracks().forEach(mr=>mr.stop()),m.current&&clearInterval(m.current),y.current&&cancelAnimationFrame(y.current),p.current&&p.current.close(),Ze.current&&clearInterval(Ze.current),ie&&URL.revokeObjectURL(ie),qt()}),[Ls,ie]),j.useEffect(()=>{if($||W!==!0||ie)return;const mr=c.current,pr=l.current;!mr||!pr||At||(pr.srcObject!==mr&&(pr.srcObject=mr,pr.muted=!0,pr.playsInline=!0,pr.autoplay=!0,pr.setAttribute("muted",""),pr.setAttribute("playsinline",""),pr.setAttribute("autoplay","")),pr.play().then(()=>Ae(!1)).catch(rn=>{Ae(!0),console.warn("Live preview play blocked on mount:",rn)}))},[W,$,ie,At]),j.useEffect(()=>{r==null||r(K)},[K,r]);const sn=j.useCallback(async()=>{if(ie)return;const mr=l.current;if(mr)try{await mr.play(),Ae(!1)}catch(pr){Ae(!0),console.warn("Live preview still blocked (needs user gesture):",pr)}},[ie]),Hs=j.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),m.current&&(clearInterval(m.current),m.current=null),qt(),ee(!1),le(!1)},[qt]),nn=j.useCallback(async()=>{let mr=null;if(b==="screen"){if(mr=await Gs(),!mr)return}else mr=At&&As?As:c.current;if(!mr)return;sn(),h.current=[],je(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(ea=>MediaRecorder.isTypeSupported(ea)),Jn=new MediaRecorder(mr,rn?{mimeType:rn,videoBitsPerSecond:b==="screen"?4e6:25e5}:{videoBitsPerSecond:b==="screen"?4e6:25e5});Jn.ondataavailable=ea=>{ea.data.size>0&&h.current.push(ea.data)},Jn.onstop=()=>{var it;const ea=Jn.mimeType||rn||((it=h.current[0])==null?void 0:it.type)||"video/webm",_s=new Blob(h.current,{type:ea});oe(_s);const We=URL.createObjectURL(_s);de(We)},o.current=Jn,Jn.start(100),ee(!0),m.current=setInterval(()=>{je(ea=>ea>=s-1?(Hs(),s):ea+1)},1e3)},[sn,s,Hs,At,As,b,Gs]),tn=j.useCallback(()=>{Ze.current&&(clearInterval(Ze.current),Ze.current=null),Ue(3);let mr=3;Ze.current=setInterval(()=>{mr-=1,mr<=0?(Ze.current&&clearInterval(Ze.current),Ze.current=null,Ue(null),nn()):Ue(mr)},1e3)},[nn]),_n=j.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),le(!0),m.current&&clearInterval(m.current))},[]),Cn=j.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),le(!1),m.current=setInterval(()=>{je(mr=>mr>=s-1?(Hs(),s):mr+1)},1e3))},[s,Hs]),Un=j.useCallback(()=>{ie&&URL.revokeObjectURL(ie),oe(null),de(null),je(0),De(!1),Ne(!0),l.current&&c.current&&!At&&(l.current.srcObject=c.current,l.current.muted=!0,sn())},[sn,ie,At]),Kr=j.useCallback(()=>{fe(mr=>mr==="user"?"environment":"user")},[]),jr=j.useCallback(()=>{ue&&t(ue,we)},[ue,we,t]),Xs=j.useCallback(()=>{l.current&&ie&&(Le?l.current.pause():(Ne(!1),l.current.muted=!1,l.current.play()),De(!Le))},[ie,Le]);j.useEffect(()=>{if(!ie)return;const mr=l.current;if(!mr)return;Ne(!1),mr.pause(),mr.removeAttribute("src"),mr.srcObject=null,mr.load(),mr.src=ie,mr.currentTime=0,mr.playsInline=!0,mr.muted=!1,mr.onended=()=>De(!1);const pr=()=>{var ea;const rn=mr.error,Jn=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),(ea=jt.current)==null||ea.call(jt,Jn)};return mr.addEventListener("error",pr),mr.load(),()=>{mr.removeEventListener("error",pr)}},[ie]);const Ba=mr=>{const pr=Math.floor(mr/60),rn=mr%60;return`${pr}:${rn.toString().padStart(2,"0")}`},Hr=b==="screen"?"aspect-video":g&&I?"aspect-[9/16]":"aspect-video";return $?e.jsx("div",{className:Et("flex items-center justify-center bg-black rounded-lg",Hr,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(Wt,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):W===!1?e.jsx("div",{className:Et("flex items-center justify-center bg-black rounded-lg",Hr,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(po,{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:()=>Ls(),variant:"secondary",className:"w-full",children:[e.jsx(Ki,{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:Et("flex flex-col gap-2",a),children:[!K&&!ie&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(B,{variant:b==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>v("camera"),children:[e.jsx(s0,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(B,{variant:b==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>v("screen"),children:[e.jsx(HR,{className:"h-4 w-4"}),"Screen"]})]}),b==="camera"&&!K&&!ie&&e.jsx(nyn,{value:Qe,onChange:Ye,isLoading:Bt,disabled:K}),!K&&!ie&&(nt.length>0||Fe.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[nt.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Sj,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(vs,{value:Dt||"default",onValueChange:mr=>pt(mr==="default"?"":mr),children:[e.jsx(gs,{className:"h-8 text-xs",children:e.jsx(bs,{placeholder:"Default microphone"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"default",children:"Default microphone"}),nt.map(mr=>e.jsx(Je,{value:mr.deviceId,children:mr.label||`Microphone ${mr.deviceId.slice(0,6)}`},mr.deviceId))]})]})]}),Fe.length>1&&b==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(s0,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(vs,{value:zt||"default",onValueChange:mr=>Gt(mr==="default"?"":mr),children:[e.jsx(gs,{className:"h-8 text-xs",children:e.jsx(bs,{placeholder:"Default camera"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"default",children:"Default camera"}),Fe.map(mr=>e.jsx(Je,{value:mr.deviceId,children:mr.label||`Camera ${mr.deviceId.slice(0,6)}`},mr.deviceId))]})]})]})]}),b==="camera"&&g&&!K&&!ie&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(Cj,{className:Et("h-4 w-4",I?"text-muted-foreground":"text-primary")}),e.jsx(se,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(Mn,{id:"orientation-toggle",checked:I,onCheckedChange:Qs}),e.jsx(se,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(Jy,{className:Et("h-4 w-4",I?"text-primary":"text-muted-foreground")})]}),b==="screen"&&!K&&!ie&&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(HR,{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:Et("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{sn()},children:[e.jsx("video",{ref:l,src:ie??void 0,className:Et("w-full bg-black",I&&!ie?"object-contain":"object-cover",Hr,!ie&&xe==="user"!==(Qe.mirror??!1)&&"scale-x-[-1]",At&&!ie&&"hidden"),playsInline:!0,controls:!!ie,muted:ie?Be:!0,autoPlay:!ie},ie??"live"),At&&!ie&&e.jsx("canvas",{ref:qs,className:Et("w-full bg-black",I?"object-contain":"object-cover",Hr,xe==="user"!==(Qe.mirror??!1)&&"scale-x-[-1]")}),At&&Bt&&!ie&&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(Wt,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!ie&&Oe&&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 sn(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!ie&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),Xe!==null&&!ie&&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…"})]})}),K&&e.jsxs("div",{className:"absolute top-4 left-4 flex items-center gap-2 bg-black/50 px-3 py-1.5 rounded-full",children:[e.jsx("div",{className:Et("w-3 h-3 rounded-full",J?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[Ba(we)," / ",Ba(s)]})]}),K&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(qi,{value:we/s*100,className:"h-1 rounded-none"})}),!ie&&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(Sj,{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:ie?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:Un,children:[e.jsx(Ki,{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:Xs,children:Le?e.jsx(ay,{className:"h-5 w-5"}):e.jsx(fd,{className:"h-5 w-5"})}),e.jsxs(B,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:jr,children:[e.jsx(da,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[b==="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:Kr,disabled:K||Xe!==null,children:e.jsx(bm,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!K&&Xe===null?e.jsx(B,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:b==="screen"?nn:tn,children:b==="screen"?e.jsx(HR,{className:"h-6 w-6"}):e.jsx(Zr,{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:J?Cn:_n,children:J?e.jsx(fd,{className:"h-5 w-5"}):e.jsx(ay,{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:Hs,children:e.jsx(H_,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function Hvn({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=Ns(),{toast:a}=pi(),[i,l]=j.useState(!1),o=async(c,d)=>{if(r){l(!0);try{const u=c.type.includes("mp4")?"mp4":"webm",h=`${r.id}/${crypto.randomUUID()}.${u}`,{error:m}=await U.storage.from("cma-videos").upload(h,c,{contentType:c.type||"video/webm",upsert:!1});if(m)throw m;const{data:p,error:x}=await U.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(x||!(p!=null&&p.signedUrl))throw x||new Error("Could not sign video URL");n(p.signedUrl,Math.round(d)),a({title:"Video added to your CMA"}),t(!1)}catch(u){a({title:"Upload failed",description:u==null?void 0:u.message,variant:"destructive"})}finally{l(!1)}}};return e.jsx(Fs,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Record a personal message"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A 30-second hello goes a long way. Welcome your client, explain the price, and invite their reply."})]}),i?e.jsxs("div",{className:"py-12 flex flex-col items-center gap-3",children:[e.jsx(Wt,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(k6,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function Gvn({value:s,onChange:t}){const{user:n}=Ns(),[r,a]=j.useState(!1);return e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(Zr,{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(Re,{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(dr,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(fd,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(LO,{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(Zr,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(Hvn,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function J2(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function Wvn({open:s,onOpenChange:t,subject:n,onSave:r,isSaving:a}){const[i,l]=j.useState({bedrooms:"",bathrooms:"",sqft:"",yearBuilt:"",propertyType:"",propertySubType:""});j.useEffect(()=>{s&&l({bedrooms:(n==null?void 0:n.bedrooms)!=null?String(n.bedrooms):"",bathrooms:(n==null?void 0:n.bathrooms)!=null?String(n.bathrooms):"",sqft:(n==null?void 0:n.sqft)!=null?String(n.sqft):"",yearBuilt:(n==null?void 0:n.yearBuilt)!=null?String(n.yearBuilt):"",propertyType:(n==null?void 0:n.propertyType)||"Residential",propertySubType:(n==null?void 0:n.propertySubType)||"Single Family"})},[s,n]);const o=async()=>{await r({bedrooms:J2(i.bedrooms),bathrooms:J2(i.bathrooms),sqft:J2(i.sqft),yearBuilt:J2(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx($s,{children:e.jsx(zs,{children:"Fill in the subject property basics"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"When the MLS feed does not return the home details, add the basics here and LevelUp will keep the CMA moving."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Beds"}),e.jsx(ye,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Baths"}),e.jsx(ye,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Sq Ft"}),e.jsx(ye,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Year Built"}),e.jsx(ye,{inputMode:"numeric",value:i.yearBuilt,onChange:c=>l(d=>({...d,yearBuilt:c.target.value})),placeholder:"2006"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Property Type"}),e.jsx(ye,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subtype"}),e.jsx(ye,{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(Wt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function Kvn({open:s,onOpenChange:t,subject:n,onAdd:r}){const[a,i]=j.useState({address:"",city:"",state:"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""});j.useEffect(()=>{s&&i({address:"",city:(n==null?void 0:n.city)||"",state:(n==null?void 0:n.state)||"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""})},[s,n]);const l=()=>{const o=J2(a.price),c=J2(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:J2(a.bedrooms),bathrooms:J2(a.bathrooms),sqft:c,yearBuilt:J2(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx($s,{children:e.jsx(zs,{children:"Add a comparable manually"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use this when the MLS feed misses a property or you already know the best comp. Add at least the address, price, and square footage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{className:"text-xs",children:"Address"}),e.jsx(ye,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"City"}),e.jsx(ye,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"State"}),e.jsx(ye,{maxLength:2,value:a.state,onChange:o=>i(c=>({...c,state:o.target.value.toUpperCase()}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Status"}),e.jsx(ye,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Price"}),e.jsx(ye,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Sq Ft"}),e.jsx(ye,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Beds"}),e.jsx(ye,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Baths"}),e.jsx(ye,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Year Built"}),e.jsx(ye,{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()||!J2(a.price)||!J2(a.sqft),children:[e.jsx(Js,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function Yvn(){var fe,Se,Ee,Le,De,Be,Ne;const{id:s}=$i(),t=Hn(),{toast:n}=pi(),{data:r,isLoading:a}=p0n(s),{data:i}=f0n(s),l=x0n(),o=v0n(),c=b0n(),{leadSite:d,isLoading:u}=h0(),[h,m]=j.useState([]),[p,x]=j.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[y,g]=j.useState(null),[b,v]=j.useState(!1),[k,C]=j.useState({low:"",likely:"",high:"",note:""}),[T,M]=j.useState(!1),[P,L]=j.useState(!1),[I,O]=j.useState(!1),[$,q]=j.useState(null),W=async Ge=>{var Ze,Qe;if(!r||!(Ge!=null&&Ge.address)||!(Ge!=null&&Ge.city)||!(Ge!=null&&Ge.state))return Ge;let _e={...Ge};const Oe=async Ye=>{const{data:nt,error:rt}=await U.functions.invoke("cma-subject-lookup",{body:{address:Ye.address,city:Ye.city,state:Ye.state,zip:Ye.zip,latitude:Ye.latitude,longitude:Ye.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(rt)throw rt;return(nt==null?void 0:nt.matches)||[]},Ae=Ye=>{const rt=Ye.find(pt=>Number.isFinite(Number(pt.latitude))&&Number.isFinite(Number(pt.longitude)))||Ye[0];if(!rt)return;const Fe=typeof rt.match_type=="string"&&rt.match_type.startsWith("nearby-"),dt=Fe&&Number.isFinite(Number(_e.latitude))&&Number.isFinite(Number(_e.longitude)),Dt=pt=>rt[pt]!==void 0&&rt[pt]!==null&&rt[pt]!==""&&rt[pt]!==0?rt[pt]:_e[pt];_e={..._e,bedrooms:Dt("bedrooms"),bathrooms:Dt("bathrooms"),sqft:Dt("sqft"),yearBuilt:Dt("yearBuilt"),lotSize:Dt("lotSize"),propertyType:Dt("propertyType"),propertySubType:Dt("propertySubType"),source_provider:rt.source_provider??_e.source_provider,match_type:rt.match_type??_e.match_type,matched_mls_address:Fe?rt.address:_e.matched_mls_address,latitude:dt?_e.latitude:rt.latitude??_e.latitude,longitude:dt?_e.longitude:rt.longitude??_e.longitude,mlsNumber:Fe?_e.mlsNumber:rt.mlsNumber??_e.mlsNumber,photos:!Fe&&Array.isArray(rt.photos)&&rt.photos.length?rt.photos:_e.photos}};Ae(await Oe(_e));const Xe=()=>Number.isFinite(Number(_e.latitude))&&Number.isFinite(Number(_e.longitude));if(!Xe()){const{data:Ye}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),nt=Ye==null?void 0:Ye.value;if(nt){const rt=encodeURIComponent(`${_e.address}, ${_e.city}, ${_e.state} ${_e.zip||""}`.trim()),dt=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${rt}.json?access_token=${nt}&limit=1&country=us`)).json(),Dt=(Qe=(Ze=dt==null?void 0:dt.features)==null?void 0:Ze[0])==null?void 0:Qe.center;Array.isArray(Dt)&&Dt.length===2&&(_e.longitude=Dt[0],_e.latitude=Dt[1])}}if((!_e.bedrooms||!_e.bathrooms||!_e.sqft||!_e.yearBuilt)&&Xe())try{Ae(await Oe(_e))}catch(Ye){console.warn("second-pass subject lookup failed",Ye)}return JSON.stringify(_e)!==JSON.stringify(Ge)&&await l.mutateAsync({id:r.id,patch:{subject:_e}}),_e};j.useEffect(()=>{var Oe,Ae;r!=null&&r.settings&&x({sqftPct:r.settings.sqftPct??.2,monthsBack:r.settings.monthsBack??6,maxMiles:r.settings.maxMiles??5,statuses:r.settings.statuses??["Active","Pending","Closed"]});const Ge=(Oe=r==null?void 0:r.settings)==null?void 0:Oe.priceOverride;Ge!=null&&Ge.enabled&&(v(!0),C({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 _e=(Ae=r==null?void 0:r.settings)==null?void 0:Ae.personalVideo;_e!=null&&_e.url&&q({url:_e.url,thumb:_e.thumb,label:_e.label})},[r==null?void 0:r.id]);const G=j.useRef(!1);j.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 K=j.useRef(null);j.useEffect(()=>{if(!r||u)return;const Ge=r.subject||{},_e=Number.isFinite(Number(Ge.latitude))&&Number.isFinite(Number(Ge.longitude)),Oe=!!(Number(Ge.bedrooms)||Number(Ge.bathrooms)||Number(Ge.sqft)||Number(Ge.yearBuilt));if(_e&&Oe)return;const Ae=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;K.current!==Ae&&(!Ge.address||!Ge.city||!Ge.state||(K.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 ee=j.useMemo(()=>r?Kmt(r.subject,h):null,[r,h]),J=async()=>{if(r)try{const Ge=await W(r.subject),_e=await o.mutateAsync({subject:Ge,filters:p,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});m(_e.comps.map(Oe=>({...Oe,selected:!0})).slice(0,12)),n({title:`Found ${_e.comps.length} comps`,description:`Top ${Math.min(12,_e.comps.length)} auto-selected.`})}catch(Ge){n({title:"Search failed",description:Ge.message,variant:"destructive"})}},le=Ge=>{m(_e=>_e.map((Oe,Ae)=>Ae===Ge?{...Oe,selected:!Oe.selected}:Oe))},ue=Ge=>{m(_e=>_e.filter((Oe,Ae)=>Ae!==Ge))},oe=async Ge=>{if(!r)return;const _e=Object.fromEntries(Object.entries(Ge).filter(([,Ae])=>Ae!=null&&Ae!=="")),Oe={...r.subject,..._e,manually_enriched:!0};await l.mutateAsync({id:r.id,patch:{subject:Oe}}),n({title:"Subject details saved",description:Oe.sqft?"You can now find comps or add your own.":"Add square footage to unlock suggested pricing."})},ie=Ge=>{m(_e=>[{...Ge,selected:!0,manual:!0},..._e]),n({title:"Manual comp added"})},de=async(Ge=!1)=>{if(!r)return;const _e=Kmt(r.subject,h),Oe=Qe=>{const Ye=Number(String(Qe).replace(/[^0-9.]/g,""));return Number.isFinite(Ye)&&Ye>0?Math.round(Ye):null},Ae=b?Oe(k.likely):null,Xe=b?Oe(k.low):null,Ue=b?Oe(k.high):null,Ze=b&&Ae;await l.mutateAsync({id:r.id,patch:{settings:{...p,priceOverride:{enabled:b,low:Xe,likely:Ae,high:Ue,note:k.note||null},personalVideo:$},price_low:Ze?Xe??Ae:_e.low??null,price_likely:Ze?Ae:_e.likely??null,price_high:Ze?Ue??Ae:_e.high??null,status:Ge?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Ge?"CMA published":"CMA saved"})},we=r?`https://cma.relevelup.com/${r.share_token}`:"";if(a||!r)return e.jsx(Vs,{children:e.jsx("div",{className:"p-6",children:e.jsx(Wt,{className:"w-6 h-6 animate-spin"})})});const je=h.filter(Ge=>Ge.selected).length,xe=!((fe=r.subject)!=null&&fe.bedrooms)||!((Se=r.subject)!=null&&Se.bathrooms)||!((Ee=r.subject)!=null&&Ee.sqft)||!((Le=r.subject)!=null&&Le.yearBuilt);return e.jsx(Vs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-7xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-2 flex-wrap",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/cma"),children:[e.jsx(_a,{className:"w-4 h-4 mr-1"})," All CMAs"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>de(!1),disabled:l.isPending,children:[e.jsx(Jo,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs(B,{onClick:()=>de(!0),disabled:l.isPending,children:[e.jsx(zd,{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(we),n({title:"Link copied"})},children:[e.jsx(Tr,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs(B,{onClick:()=>M(!0),children:[e.jsx(on,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Subject Property"})}),e.jsxs(Re,{className:"space-y-2 text-sm",children:[e.jsx("div",{className:"font-semibold",children:r.subject.address}),e.jsxs("div",{className:"text-muted-foreground",children:[r.subject.city,", ",r.subject.state," ",r.subject.zip]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Beds:"})," ",r.subject.bedrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Baths:"})," ",r.subject.bathrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"SqFt:"})," ",((De=r.subject.sqft)==null?void 0:De.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),xe&&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:()=>L(!0),children:[e.jsx(Za,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!xe&&e.jsxs(B,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>L(!0),children:[e.jsx(Za,{className:"w-3.5 h-3.5 mr-1"}),"Edit details"]}),!r.subject.sqft&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsx(se,{className:"text-xs",children:"Subject SqFt (needed for price band)"}),e.jsx(ye,{type:"number",defaultValue:"",onBlur:async Ge=>{const _e=Number(Ge.target.value);_e>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:_e}}})}})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(P5,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Re,{className:"space-y-3",children:[ee!=null&&ee.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(b&&Number(k.likely)>0?Number(k.likely):ee.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(Be=ee.low)==null?void 0:Be.toLocaleString()," – $",(Ne=ee.high)==null?void 0:Ne.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",ee.ppsf,"/sqft median · ",je," comps"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add comps with sqft + price to see suggested pricing."}),e.jsxs("div",{className:"pt-3 border-t space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(Mn,{id:"override-toggle",checked:b,onCheckedChange:v})]}),b&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"My suggested price"}),e.jsx(ye,{type:"number",placeholder:"e.g. 750000",value:k.likely,onChange:Ge=>C(_e=>({..._e,likely:Ge.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Range low"}),e.jsx(ye,{type:"number",placeholder:"optional",value:k.low,onChange:Ge=>C(_e=>({..._e,low:Ge.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Range high"}),e.jsx(ye,{type:"number",placeholder:"optional",value:k.high,onChange:Ge=>C(_e=>({..._e,high:Ge.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Ds,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:k.note,onChange:Ge=>C(_e=>({..._e,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(Gvn,{value:$,onChange:q}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Filters"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(p.sqftPct*100),"%"]}),e.jsx(Qf,{value:[p.sqftPct*100],min:5,max:50,step:5,onValueChange:([Ge])=>x(_e=>({..._e,sqftPct:Ge/100}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Search radius: ",p.maxMiles," mi"]}),e.jsx(Qf,{value:[p.maxMiles],min:1,max:25,step:1,onValueChange:([Ge])=>x(_e=>({..._e,maxMiles:Ge}))})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs",children:["Sold within: ",p.monthsBack," months"]}),e.jsx(Qf,{value:[p.monthsBack],min:1,max:24,step:1,onValueChange:([Ge])=>x(_e=>({..._e,monthsBack:Ge}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Ge=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(wi,{checked:p.statuses.includes(Ge),onCheckedChange:_e=>x(Oe=>({...Oe,statuses:_e?[...Oe.statuses,Ge]:Oe.statuses.filter(Ae=>Ae!==Ge)}))})," ",Ge]},Ge))]}),e.jsxs(B,{className:"w-full",onClick:J,disabled:o.isPending,children:[o.isPending?e.jsx(Wt,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(yn,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>O(!0),children:[e.jsx(Js,{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(eyn,{subject:r.subject,comps:h,radiusMiles:p.maxMiles,onMarkerClick:Ge=>g(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:[je," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Ge,_e)=>{var Oe;return e.jsx(be,{className:Ge.selected?"":"opacity-50",children:e.jsxs(Re,{className:"p-3 flex gap-3 items-center",children:[e.jsx(wi,{checked:Ge.selected,onCheckedChange:()=>le(_e)}),e.jsxs("button",{type:"button",onClick:()=>g(_e),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(HNe,{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 · ",((Oe=Ge.sqft)==null?void 0:Oe.toLocaleString())??"?"," sqft",Ge.yearBuilt?` · ${Ge.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx(qe,{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:()=>g(_e),title:"View details",children:e.jsx(ma,{className:"w-4 h-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ue(_e),title:"Remove",children:e.jsx(Rn,{className:"w-4 h-4"})})]})},_e)})}):e.jsx(be,{children:e.jsx(Re,{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:[xe&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>L(!0),children:"Fill subject details"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>O(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(M3t,{comp:y!=null?h[y]:null,open:y!=null,onClose:()=>g(null)}),e.jsx(Wvn,{open:P,onOpenChange:L,subject:r.subject,onSave:oe,isSaving:l.isPending}),e.jsx(Kvn,{open:I,onOpenChange:O,subject:r.subject,onAdd:ie}),e.jsx(RRt,{open:T,onOpenChange:M,cma:r})]})})}const FE="listing-presentations";function FOt(){const{user:s}=Ns(),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 U.from("listing_presentation_saved_templates").select("*").eq("owner_user_id",s.id).order("updated_at",{ascending:!1});if(c)throw c;return o}}),r=()=>t.invalidateQueries({queryKey:["listing-presentation-saved-templates",s==null?void 0:s.id]}),a=vt({mutationFn:async o=>{const{data:c,error:d}=await U.from("listing_presentation_saved_templates").insert({...o,owner_user_id:s.id}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),re.success("Template saved")},onError:o=>re.error(o.message||"Could not save the template")}),i=vt({mutationFn:async({id:o,...c})=>{const{error:d}=await U.from("listing_presentation_saved_templates").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),re.success("Template updated")},onError:o=>re.error(o.message||"Could not update the template")}),l=vt({mutationFn:async o=>{const{error:c}=await U.from("listing_presentation_saved_templates").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),re.success("Template deleted")},onError:o=>re.error(o.message||"Could not delete the template")});return{savedTemplates:n.data??[],isLoading:n.isLoading,save:a,update:i,remove:l}}function Zvn(){return mt({queryKey:["listing-presentation-templates"],staleTime:10*60*1e3,queryFn:async()=>{const{data:s,error:t}=await U.from("listing_presentation_templates").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});if(t)throw t;return s}})}function zOt(){const{user:s}=Ns(),t=as(),n=mt({queryKey:["listing-presentations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await U.from("listing_presentations").select("*").eq("owner_user_id",s.id).order("updated_at",{ascending:!1});if(d)throw d;return c}}),r=()=>t.invalidateQueries({queryKey:["listing-presentations",s==null?void 0:s.id]}),a=vt({mutationFn:async c=>{const{data:d,error:u}=await U.from("listing_presentations").insert({...c,owner_user_id:s.id}).select().single();if(u)throw u;return d},onSuccess:r,onError:c=>re.error(c.message||"Could not create presentation")}),i=vt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await U.from("listing_presentations").update(d).eq("id",c).select().single();if(h)throw h;return u},onSuccess:c=>{r(),t.invalidateQueries({queryKey:["listing-presentation",c.id]})},onError:c=>re.error(c.message||"Could not save presentation")}),l=vt({mutationFn:async c=>{let d=null;const{data:u,error:h}=await U.from("listing_presentations").insert({owner_user_id:s.id,title:`${c.title} (Copy)`,template_id:c.template_id,status:"draft",property_address_line1:c.property_address_line1,city:c.city,state:c.state,postal_code:c.postal_code,list_price:c.list_price,beds:c.beds,baths:c.baths,sqft:c.sqft,agent_snapshot:c.agent_snapshot,co_agent:c.co_agent,custom_pages:c.custom_pages,services:c.services,page_settings:c.page_settings,photo_focal:c.photo_focal}).select().single();if(h)throw h;if(c.property_photo_path){d=`${s.id}/${u.id}/photo.jpg`;const{error:m}=await U.storage.from(FE).copy(c.property_photo_path,d);m||await U.from("listing_presentations").update({property_photo_path:d}).eq("id",u.id)}return u},onSuccess:()=>{r(),re.success("Presentation duplicated")},onError:c=>re.error(c.message||"Could not duplicate")}),o=vt({mutationFn:async c=>{const d=[c.property_photo_path,c.pdf_path,c.thumbnail_path].filter(Boolean);d.length&&await U.storage.from(FE).remove(d);const{error:u}=await U.from("listing_presentations").delete().eq("id",c.id);if(u)throw u},onSuccess:()=>{r(),re.success("Presentation deleted")},onError:c=>re.error(c.message||"Could not delete")});return{presentations:n.data??[],isLoading:n.isLoading,create:a,update:i,duplicate:l,remove:o}}function Xvn(s){return mt({queryKey:["listing-presentation",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_presentations").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}async function Qvn(s,t=3600){if(!s)return null;const{data:n,error:r}=await U.storage.from(FE).createSignedUrl(s,t);return r?null:(n==null?void 0:n.signedUrl)??null}const Jvn="#2a4c64",e1n="#B8965A";function BOt(){const{user:s}=Ns();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([U.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),U.from("lead_sites").select("brand_color, accent_color, agent_license_number, brokerage_license_number, license_state, brokerage_legal_name, team_logo_url, is_active, created_at").eq("agent_id",t).order("created_at",{ascending:!0}).limit(5),U.from("agent_cards").select("brokerage_display_name, brokerage_logo_url, team_logo_url, title, positioning_statement, display_email").eq("user_id",t).maybeSingle()]),i=n.data||{},l=r.data||[],o=l.find(u=>u.is_active)||l[0]||{},c=a.data||{};let d=i.brokerage_name||c.brokerage_display_name||o.brokerage_legal_name||null;if(!d&&i.brokerage_id){const{data:u}=await U.from("brokerages").select("name").eq("id",i.brokerage_id).maybeSingle();d=(u==null?void 0:u.name)||null}return{name:i.name||s.email||"Your Name",headshotUrl:i.avatar_url||null,brokerageName:d,brokerageLogoUrl:c.brokerage_logo_url||c.team_logo_url||o.team_logo_url||null,licenseNumber:o.agent_license_number||null,licenseState:o.license_state||null,phone:i.phone||null,email:c.display_email||i.email||s.email||null,website:i.website_url||null,brandColor:o.brand_color||Jvn,accentColor:o.accent_color||e1n,tagline:c.positioning_statement||i.title||c.title||null}}})}const D9e={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."}},t1n={cover:"Cover",welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function $Ot(s,t){var i;const n=((i=s==null?void 0:s.copy)==null?void 0:i[t])||{},r=D9e[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 UOt={enabled:!1,name:"",title:null,headshotUrl:null,phone:null,email:null,brokerageName:null,licenseNumber:null,bio:null};function qOt(s){return{...UOt,...s||{}}}const lIe=[{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."}],VOt=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`cp_${Math.random().toString(36).slice(2)}`;function bKe(s,t=0){const n={id:VOt(),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 HOt(s){return Array.isArray(s)?s.filter(t=>t&&typeof t=="object").map((t,n)=>({...bKe(t.layout||"story",n),...t,id:t.id||VOt(),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 O9e={hidden:["overview"]},F9e={x:.5,y:.5},Nc=(s,t,n=!0)=>({key:s,label:t,enabled:n}),pSe=[{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:[Nc("hdr","Full HDR interior and exterior photo set"),Nc("drone","Aerial drone photography of the home and lot"),Nc("twilight","Twilight exterior session for the hero image"),Nc("staging","Virtual staging for vacant or transitional rooms",!1),Nc("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:[Nc("walkthrough","Cinematic full-property walkthrough video"),Nc("reels","Vertical short-form cuts for Reels, Shorts, and TikTok"),Nc("oncamera","On-camera agent introduction to the home"),Nc("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:[Nc("data","Complete, accurate MLS data so your home shows in every filter"),Nc("copy","Copywriting that leads with the features buyers pay for"),Nc("pricing","Pricing built on live comparable and absorption data"),Nc("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:[Nc("zillow","Zillow — the highest-traffic buyer search portal"),Nc("realtor","Realtor.com — direct MLS-sourced listing feed"),Nc("homes","Homes.com — agent-attributed listing exposure"),Nc("others","Redfin, Trulia, Movoto, and hundreds of partner sites"),Nc("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:[Nc("gallery","Full-screen gallery, video, and floor plan in one place"),Nc("mobile","Mobile-first design with a one-tap inquiry form"),Nc("link","Shareable link used across ads, email, and QR signage"),Nc("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:[Nc("organic","Just-listed launch across feed, stories, and reels"),Nc("ads","Geo-targeted paid campaigns aimed at active buyers"),Nc("retarget","Retargeting so interested viewers keep seeing your home"),Nc("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:[Nc("database","Direct email to my buyer and past-client database"),Nc("agents","Broadcast to area agents with matching buyers"),Nc("referral","Referral partner network notified at launch"),Nc("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:[Nc("public","Strategically timed public open houses"),Nc("broker","Broker open house for agents with active buyers"),Nc("signin","Digital sign-in that captures every visitor"),Nc("neighbors","Neighbor invitations and just-listed mailers"),Nc("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:[Nc("weekly","Weekly seller report on the schedule you prefer"),Nc("feedback","Showing feedback delivered as it comes in"),Nc("analytics","Online traffic and engagement analytics"),Nc("access","Direct access to me by call, text, or email")]}],s1n=Object.fromEntries(pSe.map(s=>[s.key,(s.options||[]).map(t=>t.label)]));function z9e(s){return s!=null&&s.length?pSe.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}}):pSe.map(t=>{var n;return{...t,options:(n=t.options)==null?void 0:n.map(r=>({...r}))}})}const n1n={welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function Gu(s){"@babel/helpers - typeof";return Gu=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},Gu(s)}var LN=Uint8Array,z_=Uint16Array,_Ke=Int32Array,wKe=new LN([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]),jKe=new LN([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]),nft=new LN([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),GOt=function(s,t){for(var n=new z_(31),r=0;r<31;++r)n[r]=t+=1<>1|(mm&21845)<<1;FC=(FC&52428)>>2|(FC&13107)<<2,FC=(FC&61680)>>4|(FC&3855)<<4,$9e[mm]=((FC&65280)>>8|(FC&255)<<8)>>1}var cY=function(s,t,n){for(var r=s.length,a=0,i=new z_(t);a>c]=d}else for(o=new z_(r),a=0;a>15-s[a]);return o},QD=new LN(288);for(var mm=0;mm<144;++mm)QD[mm]=8;for(var mm=144;mm<256;++mm)QD[mm]=9;for(var mm=256;mm<280;++mm)QD[mm]=7;for(var mm=280;mm<288;++mm)QD[mm]=8;var fSe=new LN(32);for(var mm=0;mm<32;++mm)fSe[mm]=5;var i1n=cY(QD,9,0),o1n=cY(fSe,5,0),KOt=function(s){return(s+7)/8|0},l1n=function(s,t,n){return(n==null||n>s.length)&&(n=s.length),new LN(s.subarray(t,n))},e4=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8},WH=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},cIe=function(s,t){for(var n=[],r=0;rm&&(m=i[r].s);var p=new z_(m+1),x=U9e(n[u-1],p,0);if(x>t){var r=0,y=0,g=x-t,b=1<t)y+=b-(1<>=g;y>0;){var k=i[r].s;p[k]=0&&y;--r){var C=i[r].s;p[C]==t&&(--p[C],++y)}x=t}return{t:new LN(p),l:x}},U9e=function(s,t,n){return s.s==-1?Math.max(U9e(s.l,t,n+1),U9e(s.r,t,n+1)):t[s.s]=n},aft=function(s){for(var t=s.length;t&&!s[--t];);for(var n=new z_(++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}},KH=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&&!O[nft[q-1]];--q);var W=d+5<<3,G=KH(a,QD)+KH(i,fSe)+l,K=KH(a,m)+KH(i,y)+l+14+3*q+KH(P,O)+2*P[16]+3*P[17]+7*P[18];if(c>=0&&W<=G&&W<=K)return YOt(t,u,s.subarray(c,c+d));var ee,J,le,ue;if(e4(t,u,1+(K15&&(e4(t,u,we[L]>>5&127),u+=we[L]>>12)}}else ee=i1n,J=QD,le=o1n,ue=fSe;for(var L=0;L255){var je=xe>>18&31;WH(t,u,ee[je+257]),u+=J[je+257],je>7&&(e4(t,u,xe>>23&31),u+=wKe[je]);var fe=xe&31;WH(t,u,le[fe]),u+=ue[fe],fe>3&&(WH(t,u,xe>>5&8191),u+=jKe[fe])}else WH(t,u,ee[xe]),u+=J[xe]}return WH(t,u,ee[256]),u+J[256]},c1n=new _Ke([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ZOt=new LN(0),d1n=function(s,t,n,r,a,i){var l=i.z||s.length,o=new LN(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=c1n[t-1],m=h>>13,p=h&8191,x=(1<7e3||O>24576)&&(ee>423||!d)){u=ift(s,c,0,C,T,M,L,O,q,I-q,u),O=P=L=0,q=I;for(var J=0;J<286;++J)T[J]=0;for(var J=0;J<30;++J)M[J]=0}var le=2,ue=0,oe=p,ie=G-K&32767;if(ee>2&&W==k(I-ie))for(var de=Math.min(m,ee)-1,we=Math.min(32767,I),je=Math.min(258,ee);ie<=we&&--oe&&G!=K;){if(s[I+le]==s[I+le-ie]){for(var xe=0;xele){if(le=xe,ue=ie,xe>de)break;for(var fe=Math.min(ie,xe-2),Se=0,J=0;JSe&&(Se=De,K=Ee)}}}G=K,K=y[G],ie+=G-K&32767}if(ue){C[O++]=268435456|B9e[le]<<18|rft[ue];var Be=B9e[le]&31,Ne=rft[ue]&31;L+=wKe[Be]+jKe[Ne],++T[257+Be],++M[Ne],$=I+le,++P}else C[O++]=s[I],++T[s[I]]}}for(I=Math.max(I,$);I=l&&(c[u/8|0]=d,Ge=l),u=YOt(c,u+1,s.subarray(I,Ge))}i.i=l}return l1n(o,0,r+KOt(u)+a)},XOt=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}}},u1n=function(s,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new LN(i.length+s.length);l.set(i),l.set(s,i.length),s=l,a.w=i.length}return d1n(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)},QOt=function(s,t,n){for(;n;++t)s[t]=n,n>>>=8},h1n=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=XOt();a.p(t.dictionary),QOt(s,2,a.d())}};function q9e(s,t){t||(t={});var n=XOt();n.p(s);var r=u1n(s,t,t.dictionary?6:2,4);return h1n(r,t),QOt(r,r.length-4,n.d()),r}var m1n=typeof TextDecoder<"u"&&new TextDecoder,p1n=0;try{m1n.decode(ZOt,{stream:!0}),p1n=1}catch{}function f1n(s){if(Array.isArray(s))return s}function x1n(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 oft(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])})(),dIe={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 NKe{constructor(t=_1n,n={}){Ar(this,"buffer");Ar(this,"byteLength");Ar(this,"byteOffset");Ar(this,"length");Ar(this,"offset");Ar(this,"lastWrittenByte");Ar(this,"littleEndian");Ar(this,"_data");Ar(this,"_mark");Ar(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 NKe)&&(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=dIe[n].BYTES_PER_ELEMENT*t,a=this.byteOffset+this.offset,i=this.buffer.slice(a,a+r);if(this.littleEndian===w1n&&n!=="uint8"&&n!=="int8"){const o=new Uint8Array(this.buffer.slice(a,a+r));o.reverse();const c=new dIe[n](o.buffer);return this.offset+=r,c.reverse(),c}const l=new dIe[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 j1n=4,dft=0,uft=1,N1n=2;function qq(s){let t=s.length;for(;--t>=0;)s[t]=0}const k1n=0,JOt=1,S1n=2,C1n=3,A1n=258,kKe=29,oee=256,uX=oee+1+kKe,Rz=30,SKe=19,eFt=2*uX+1,g8=15,uIe=16,T1n=7,CKe=256,tFt=16,sFt=17,nFt=18,V9e=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]),$je=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]),E1n=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),rFt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),M1n=512,S4=new Array((uX+2)*2);qq(S4);const dY=new Array(Rz*2);qq(dY);const hX=new Array(M1n);qq(hX);const mX=new Array(A1n-C1n+1);qq(mX);const AKe=new Array(kKe);qq(AKe);const xSe=new Array(Rz);qq(xSe);function hIe(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 aFt,iFt,oFt;function mIe(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}const lFt=s=>s<256?hX[s]:hX[256+(s>>>7)],pX=(s,t)=>{s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255},cb=(s,t,n)=>{s.bi_valid>uIe-n?(s.bi_buf|=t<>uIe-s.bi_valid,s.bi_valid+=n-uIe):(s.bi_buf|=t<{cb(s,n[t*2],n[t*2+1])},cFt=(s,t)=>{let n=0;do n|=s&1,s>>>=1,n<<=1;while(--t>0);return n>>>1},L1n=s=>{s.bi_valid===16?(pX(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)},P1n=(s,t)=>{const n=t.dyn_tree,r=t.max_code,a=t.stat_desc.static_tree,i=t.stat_desc.has_stree,l=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,u,h,m,p,x,y=0;for(m=0;m<=g8;m++)s.bl_count[m]=0;for(n[s.heap[s.heap_max]*2+1]=0,d=s.heap_max+1;dc&&(m=c,y++),n[u*2+1]=m,!(u>r)&&(s.bl_count[m]++,p=0,u>=o&&(p=l[u-o]),x=n[u*2],s.opt_len+=x*(m+p),i&&(s.static_len+=x*(a[u*2+1]+p)));if(y!==0){do{for(m=c-1;s.bl_count[m]===0;)m--;s.bl_count[m]--,s.bl_count[m+1]+=2,s.bl_count[c]--,y-=2}while(y>0);for(m=c;m!==0;m--)for(u=s.bl_count[m];u!==0;)h=s.heap[--d],!(h>r)&&(n[h*2+1]!==m&&(s.opt_len+=(m-n[h*2+1])*n[h*2],n[h*2+1]=m),u--)}},dFt=(s,t,n)=>{const r=new Array(g8+1);let a=0,i,l;for(i=1;i<=g8;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]=cFt(r[o]++,o))}},I1n=()=>{let s,t,n,r,a;const i=new Array(g8+1);for(n=0,r=0;r>=7;r{let t;for(t=0;t{s.bi_valid>8?pX(s,s.bi_buf):s.bi_valid>0&&(s.pending_buf[s.pending++]=s.bi_buf),s.bi_buf=0,s.bi_valid=0},hft=(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?g5(s,a,t):(l=mX[a],g5(s,l+oee+1,t),o=V9e[l],o!==0&&(a-=AKe[l],cb(s,a,o)),r--,l=lFt(r),g5(s,l,n),o=$je[l],o!==0&&(r-=xSe[l],cb(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=eFt,l=0;l>1;l>=1;l--)pIe(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],pIe(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++,pIe(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],P1n(s,t),dFt(n,c,s.bl_count)},pft=(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(pft(s,s.dyn_ltree,s.l_desc.max_code),pft(s,s.dyn_dtree,s.d_desc.max_code),H9e(s,s.bl_desc),t=SKe-1;t>=3&&s.bl_tree[rFt[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t},D1n=(s,t,n,r)=>{let a;for(cb(s,t-257,5),cb(s,n-1,5),cb(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 dft;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return uft;for(n=32;n{xft||(I1n(),xft=!0),s.l_desc=new mIe(s.dyn_ltree,aFt),s.d_desc=new mIe(s.dyn_dtree,iFt),s.bl_desc=new mIe(s.bl_tree,oFt),s.bi_buf=0,s.bi_valid=0,uFt(s)},mFt=(s,t,n,r)=>{cb(s,(k1n<<1)+(r?1:0),3),hFt(s),pX(s,n),pX(s,~n),n&&s.pending_buf.set(s.window.subarray(t,t+n),s.pending),s.pending+=n},z1n=s=>{cb(s,JOt<<1,3),g5(s,CKe,S4),L1n(s)},B1n=(s,t,n,r)=>{let a,i,l=0;s.level>0?(s.strm.data_type===N1n&&(s.strm.data_type=O1n(s)),H9e(s,s.l_desc),H9e(s,s.d_desc),l=R1n(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?mFt(s,t,n,r):s.strategy===j1n||i===a?(cb(s,(JOt<<1)+(r?1:0),3),mft(s,S4,dY)):(cb(s,(S1n<<1)+(r?1:0),3),D1n(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),mft(s,s.dyn_ltree,s.dyn_dtree)),uFt(s),r&&hFt(s)},$1n=(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[(mX[n]+oee+1)*2]++,s.dyn_dtree[lFt(t)*2]++),s.sym_next===s.sym_end);var U1n=F1n,q1n=mFt,V1n=B1n,H1n=$1n,G1n=z1n,W1n={_tr_init:U1n,_tr_stored_block:q1n,_tr_flush_block:V1n,_tr_tally:H1n,_tr_align:G1n};const K1n=(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 fX=K1n;const Y1n=()=>{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},Z1n=new Uint32Array(Y1n()),X1n=(s,t,n,r)=>{const a=Z1n,i=r+n;s^=-1;for(let l=r;l>>8^a[(s^t[l])&255];return s^-1};var Hg=X1n,yU={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"},lee={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:Q1n,_tr_stored_block:G9e,_tr_flush_block:J1n,_tr_tally:gE,_tr_align:ebn}=W1n,{Z_NO_FLUSH:yE,Z_PARTIAL_FLUSH:tbn,Z_FULL_FLUSH:sbn,Z_FINISH:hj,Z_BLOCK:gft,Z_OK:q0,Z_STREAM_END:yft,Z_STREAM_ERROR:H5,Z_DATA_ERROR:nbn,Z_BUF_ERROR:fIe,Z_DEFAULT_COMPRESSION:rbn,Z_FILTERED:abn,Z_HUFFMAN_ONLY:Kne,Z_RLE:ibn,Z_FIXED:obn,Z_DEFAULT_STRATEGY:lbn,Z_UNKNOWN:cbn,Z_DEFLATED:aTe}=lee,dbn=9,ubn=15,hbn=8,mbn=29,pbn=256,W9e=pbn+1+mbn,fbn=30,xbn=19,gbn=2*W9e+1,ybn=15,ud=3,AT=258,G5=AT+ud+1,vbn=32,vU=42,TKe=57,K9e=69,Y9e=73,Z9e=91,X9e=103,y8=113,KG=666,Jv=1,Vq=2,JD=3,Hq=4,bbn=3,v8=(s,t)=>(s.msg=yU[t],t),vft=s=>s*2-(s>4?9:0),LA=s=>{let t=s.length;for(;--t>=0;)s[t]=0},_bn=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 wbn=(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))},B_=(s,t)=>{J1n(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,f_(s.strm)},ru=(s,t)=>{s.pending_buf[s.pending++]=t},YH=(s,t)=>{s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255},Q9e=(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=fX(s.adler,t,a,n):s.state.wrap===2&&(s.adler=Hg(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)},pFt=(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-G5?s.strstart-(s.w_size-G5):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+AT;let p=d[r+l-1],x=d[r+l];s.prev_length>=s.good_match&&(n>>=2),o>s.lookahead&&(o=s.lookahead);do if(a=t,!(d[a+l]!==x||d[a+l-1]!==p||d[a]!==d[r]||d[++a]!==d[r+1])){r+=2,a++;do;while(d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&d[++r]===d[++a]&&rl){if(s.match_start=t,l=i,i>=o)break;p=d[r+l-1],x=d[r+l]}}while((t=h[t&u])>c&&--n!==0);return l<=s.lookahead?l:s.lookahead},bU=s=>{const t=s.w_size;let n,r,a;do{if(r=s.window_size-s.lookahead-s.strstart,s.strstart>=t+(t-G5)&&(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),_bn(s),r+=t),s.strm.avail_in===0)break;if(n=Q9e(s.strm,s.window,s.strstart+s.lookahead,r),s.lookahead+=n,s.lookahead+s.insert>=ud)for(a=s.strstart-s.insert,s.ins_h=s.window[a],s.ins_h=vE(s,s.ins_h,s.window[a+1]);s.insert&&(s.ins_h=vE(s,s.ins_h,s.window[a+ud-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,f_(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&&(Q9e(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&&(Q9e(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===hj)&&t!==yE&&s.strm.avail_in===0&&a<=i)&&(r=a>i?i:a,l=t===hj&&s.strm.avail_in===0&&r===a?1:0,G9e(s,s.block_start,r,l),s.block_start+=r,f_(s.strm)),l?JD:Jv)},xIe=(s,t)=>{let n,r;for(;;){if(s.lookahead=ud&&(s.ins_h=vE(s,s.ins_h,s.window[s.strstart+ud-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-G5&&(s.match_length=pFt(s,n)),s.match_length>=ud)if(r=gE(s,s.strstart-s.match_start,s.match_length-ud),s.lookahead-=s.match_length,s.match_length<=s.max_lazy_match&&s.lookahead>=ud){s.match_length--;do s.strstart++,s.ins_h=vE(s,s.ins_h,s.window[s.strstart+ud-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=vE(s,s.ins_h,s.window[s.strstart+1]);else r=gE(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++;if(r&&(B_(s,!1),s.strm.avail_out===0))return Jv}return s.insert=s.strstart{let n,r,a;for(;;){if(s.lookahead=ud&&(s.ins_h=vE(s,s.ins_h,s.window[s.strstart+ud-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=ud-1,n!==0&&s.prev_length4096)&&(s.match_length=ud-1)),s.prev_length>=ud&&s.match_length<=s.prev_length){a=s.strstart+s.lookahead-ud,r=gE(s,s.strstart-1-s.prev_match,s.prev_length-ud),s.lookahead-=s.prev_length-1,s.prev_length-=2;do++s.strstart<=a&&(s.ins_h=vE(s,s.ins_h,s.window[s.strstart+ud-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=ud-1,s.strstart++,r&&(B_(s,!1),s.strm.avail_out===0))return Jv}else if(s.match_available){if(r=gE(s,0,s.window[s.strstart-1]),r&&B_(s,!1),s.strstart++,s.lookahead--,s.strm.avail_out===0)return Jv}else s.match_available=1,s.strstart++,s.lookahead--}return s.match_available&&(r=gE(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<=AT){if(bU(s),s.lookahead<=AT&&t===yE)return Jv;if(s.lookahead===0)break}if(s.match_length=0,s.lookahead>=ud&&s.strstart>0&&(a=s.strstart-1,r=l[a],r===l[++a]&&r===l[++a]&&r===l[++a])){i=s.strstart+AT;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>=ud?(n=gE(s,1,s.match_length-ud),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=gE(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(B_(s,!1),s.strm.avail_out===0))return Jv}return s.insert=0,t===hj?(B_(s,!0),s.strm.avail_out===0?JD:Hq):s.sym_next&&(B_(s,!1),s.strm.avail_out===0)?Jv:Vq},Nbn=(s,t)=>{let n;for(;;){if(s.lookahead===0&&(bU(s),s.lookahead===0)){if(t===yE)return Jv;break}if(s.match_length=0,n=gE(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(B_(s,!1),s.strm.avail_out===0))return Jv}return s.insert=0,t===hj?(B_(s,!0),s.strm.avail_out===0?JD:Hq):s.sym_next&&(B_(s,!1),s.strm.avail_out===0)?Jv:Vq};function jk(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 YG=[new jk(0,0,0,0,fFt),new jk(4,4,8,4,xIe),new jk(4,5,16,8,xIe),new jk(4,6,32,32,xIe),new jk(4,4,16,16,a7),new jk(8,16,32,32,a7),new jk(8,16,128,128,a7),new jk(8,32,128,256,a7),new jk(32,128,258,1024,a7),new jk(32,258,258,4096,a7)],kbn=s=>{s.window_size=2*s.w_size,LA(s.head),s.max_lazy_match=YG[s.level].max_lazy,s.good_match=YG[s.level].good_length,s.nice_match=YG[s.level].nice_length,s.max_chain_length=YG[s.level].max_chain,s.strstart=0,s.block_start=0,s.lookahead=0,s.insert=0,s.match_length=s.prev_length=ud-1,s.match_available=0,s.ins_h=0};function Sbn(){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=aTe,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(gbn*2),this.dyn_dtree=new Uint16Array((2*fbn+1)*2),this.bl_tree=new Uint16Array((2*xbn+1)*2),LA(this.dyn_ltree),LA(this.dyn_dtree),LA(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(ybn+1),this.heap=new Uint16Array(2*W9e+1),LA(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*W9e+1),LA(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 cee=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.status!==vU&&t.status!==TKe&&t.status!==K9e&&t.status!==Y9e&&t.status!==Z9e&&t.status!==X9e&&t.status!==y8&&t.status!==KG?1:0},xFt=s=>{if(cee(s))return v8(s,H5);s.total_in=s.total_out=0,s.data_type=cbn;const t=s.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap===2?TKe:t.wrap?vU:y8,s.adler=t.wrap===2?0:1,t.last_flush=-2,Q1n(t),q0},gFt=s=>{const t=xFt(s);return t===q0&&kbn(s.state),t},Cbn=(s,t)=>cee(s)||s.state.wrap!==2?H5:(s.state.gzhead=t,q0),yFt=(s,t,n,r,a,i)=>{if(!s)return H5;let l=1;if(t===rbn&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>dbn||n!==aTe||r<8||r>15||t<0||t>9||i<0||i>obn||r===8&&l!==1)return v8(s,H5);r===8&&(r=9);const o=new Sbn;return s.state=o,o.strm=s,o.status=vU,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<yFt(s,t,aTe,ubn,hbn,lbn),Tbn=(s,t)=>{if(cee(s)||t>gft||t<0)return s?v8(s,H5):H5;const n=s.state;if(!s.output||s.avail_in!==0&&!s.input||n.status===KG&&t!==hj)return v8(s,s.avail_out===0?fIe:H5);const r=n.last_flush;if(n.last_flush=t,n.pending!==0){if(f_(s),s.avail_out===0)return n.last_flush=-1,q0}else if(s.avail_in===0&&vft(t)<=vft(r)&&t!==hj)return v8(s,fIe);if(n.status===KG&&s.avail_in!==0)return v8(s,fIe);if(n.status===vU&&n.wrap===0&&(n.status=y8),n.status===vU){let a=aTe+(n.w_bits-8<<4)<<8,i=-1;if(n.strategy>=Kne||n.level<2?i=0:n.level<6?i=1:n.level===6?i=2:i=3,a|=i<<6,n.strstart!==0&&(a|=vbn),a+=31-a%31,YH(n,a),n.strstart!==0&&(YH(n,s.adler>>>16),YH(n,s.adler&65535)),s.adler=1,n.status=y8,f_(s),n.pending!==0)return n.last_flush=-1,q0}if(n.status===TKe){if(s.adler=0,ru(n,31),ru(n,139),ru(n,8),n.gzhead)ru(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)),ru(n,n.gzhead.time&255),ru(n,n.gzhead.time>>8&255),ru(n,n.gzhead.time>>16&255),ru(n,n.gzhead.time>>24&255),ru(n,n.level===9?2:n.strategy>=Kne||n.level<2?4:0),ru(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(ru(n,n.gzhead.extra.length&255),ru(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(s.adler=Hg(s.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=K9e;else if(ru(n,0),ru(n,0),ru(n,0),ru(n,0),ru(n,0),ru(n,n.level===9?2:n.strategy>=Kne||n.level<2?4:0),ru(n,bbn),n.status=y8,f_(s),n.pending!==0)return n.last_flush=-1,q0}if(n.status===K9e){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=Hg(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex+=o,f_(s),n.pending!==0)return n.last_flush=-1,q0;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=Hg(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=Y9e}if(n.status===Y9e){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=Hg(s.adler,n.pending_buf,n.pending-a,a)),f_(s),n.pending!==0)return n.last_flush=-1,q0;a=0}n.gzindexa&&(s.adler=Hg(s.adler,n.pending_buf,n.pending-a,a)),n.gzindex=0}n.status=Z9e}if(n.status===Z9e){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=Hg(s.adler,n.pending_buf,n.pending-a,a)),f_(s),n.pending!==0)return n.last_flush=-1,q0;a=0}n.gzindexa&&(s.adler=Hg(s.adler,n.pending_buf,n.pending-a,a))}n.status=X9e}if(n.status===X9e){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(f_(s),n.pending!==0))return n.last_flush=-1,q0;ru(n,s.adler&255),ru(n,s.adler>>8&255),s.adler=0}if(n.status=y8,f_(s),n.pending!==0)return n.last_flush=-1,q0}if(s.avail_in!==0||n.lookahead!==0||t!==yE&&n.status!==KG){let a=n.level===0?fFt(n,t):n.strategy===Kne?Nbn(n,t):n.strategy===ibn?jbn(n,t):YG[n.level].func(n,t);if((a===JD||a===Hq)&&(n.status=KG),a===Jv||a===JD)return s.avail_out===0&&(n.last_flush=-1),q0;if(a===Vq&&(t===tbn?ebn(n):t!==gft&&(G9e(n,0,0,!1),t===sbn&&(LA(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),f_(s),s.avail_out===0))return n.last_flush=-1,q0}return t!==hj?q0:n.wrap<=0?yft:(n.wrap===2?(ru(n,s.adler&255),ru(n,s.adler>>8&255),ru(n,s.adler>>16&255),ru(n,s.adler>>24&255),ru(n,s.total_in&255),ru(n,s.total_in>>8&255),ru(n,s.total_in>>16&255),ru(n,s.total_in>>24&255)):(YH(n,s.adler>>>16),YH(n,s.adler&65535)),f_(s),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?q0:yft)},Ebn=s=>{if(cee(s))return H5;const t=s.state.status;return s.state=null,t===y8?v8(s,nbn):q0},Mbn=(s,t)=>{let n=t.length;if(cee(s))return H5;const r=s.state,a=r.wrap;if(a===2||a===1&&r.status!==vU||r.lookahead)return H5;if(a===1&&(s.adler=fX(s.adler,t,n,0)),r.wrap=0,n>=r.w_size){a===0&&(LA(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,bU(r);r.lookahead>=ud;){let c=r.strstart,d=r.lookahead-(ud-1);do r.ins_h=vE(r,r.ins_h,r.window[c+ud-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=ud-1,bU(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=ud-1,r.match_available=0,s.next_in=l,s.input=o,s.avail_in=i,r.wrap=a,q0};var Lbn=Abn,Pbn=yFt,Ibn=gFt,Rbn=xFt,Dbn=Cbn,Obn=Tbn,Fbn=Ebn,zbn=Mbn,Bbn="pako deflate (from Nodeca project)",uY={deflateInit:Lbn,deflateInit2:Pbn,deflateReset:Ibn,deflateResetKeep:Rbn,deflateSetHeader:Dbn,deflate:Obn,deflateEnd:Fbn,deflateSetDictionary:zbn,deflateInfo:Bbn};const $bn=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var Ubn=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)$bn(n,r)&&(s[r]=n[r])}}return s},qbn=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;xX[254]=xX[254]=1;var Vbn=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 Hbn=(s,t)=>{if(t<65534&&s.subarray&&vFt)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 Hbn(i,a)},Wbn=(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+xX[s[n]]>t?n:t},gX={string2buf:Vbn,buf2string:Gbn,utf8border:Wbn};function Kbn(){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 bFt=Kbn;const _Ft=Object.prototype.toString,{Z_NO_FLUSH:Ybn,Z_SYNC_FLUSH:Zbn,Z_FULL_FLUSH:Xbn,Z_FINISH:Qbn,Z_OK:gSe,Z_STREAM_END:Jbn,Z_DEFAULT_COMPRESSION:e_n,Z_DEFAULT_STRATEGY:t_n,Z_DEFLATED:s_n}=lee;function EKe(s){this.options=iTe.assign({level:e_n,method:s_n,chunkSize:16384,windowBits:15,memLevel:8,strategy:t_n},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 bFt,this.strm.avail_out=0;let n=uY.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==gSe)throw new Error(yU[n]);if(t.header&&uY.deflateSetHeader(this.strm,t.header),t.dictionary){let r;if(typeof t.dictionary=="string"?r=gX.string2buf(t.dictionary):_Ft.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=uY.deflateSetDictionary(this.strm,r),n!==gSe)throw new Error(yU[n]);this._dict_set=!0}}EKe.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?Qbn:Ybn,typeof s=="string"?n.input=gX.string2buf(s):_Ft.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===Zbn||i===Xbn)&&n.avail_out<=6){this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;continue}if(a=uY.deflate(n,i),a===Jbn)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),a=uY.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===gSe;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};EKe.prototype.onData=function(s){this.chunks.push(s)};EKe.prototype.onEnd=function(s){s===gSe&&(this.result=iTe.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};const Yne=16209,n_n=16191;var r_n=function(t,n){let r,a,i,l,o,c,d,u,h,m,p,x,y,g,b,v,k,C,T,M,P,L,I,O;const $=t.state;r=t.next_in,I=t.input,a=r+(t.avail_in-5),i=t.next_out,O=t.output,l=i-(n-t.avail_out),o=i+(t.avail_out-257),c=$.dmax,d=$.wsize,u=$.whave,h=$.wnext,m=$.window,p=$.hold,x=$.bits,y=$.lencode,g=$.distcode,b=(1<<$.lenbits)-1,v=(1<<$.distbits)-1;e:do{x<15&&(p+=I[r++]<>>24,p>>>=C,x-=C,C=k>>>16&255,C===0)O[i++]=k&65535;else if(C&16){T=k&65535,C&=15,C&&(x>>=C,x-=C),x<15&&(p+=I[r++]<>>24,p>>>=C,x-=C,C=k>>>16&255,C&16){if(M=k&65535,C&=15,xc){t.msg="invalid distance too far back",$.mode=Yne;break e}if(p>>>=C,x-=C,C=i-l,M>C){if(C=M-C,C>u&&$.sane){t.msg="invalid distance too far back",$.mode=Yne;break e}if(P=0,L=m,h===0){if(P+=d-C,C2;)O[i++]=L[P++],O[i++]=L[P++],O[i++]=L[P++],T-=3;T&&(O[i++]=L[P++],T>1&&(O[i++]=L[P++]))}else{P=i-M;do O[i++]=O[P++],O[i++]=O[P++],O[i++]=O[P++],T-=3;while(T>2);T&&(O[i++]=O[P++],T>1&&(O[i++]=O[P++]))}}else if(C&64){t.msg="invalid distance code",$.mode=Yne;break e}else{k=g[(k&65535)+(p&(1<>3,r-=T,x-=T<<3,p&=(1<{const c=o.bits;let d=0,u=0,h=0,m=0,p=0,x=0,y=0,g=0,b=0,v=0,k,C,T,M,P,L=null,I;const O=new Uint16Array(i7+1),$=new Uint16Array(i7+1);let q=null,W,G,K;for(d=0;d<=i7;d++)O[d]=0;for(u=0;u=1&&O[m]===0;m--);if(p>m&&(p=m),m===0)return a[i++]=1<<24|64<<16|0,a[i++]=1<<24|64<<16|0,o.bits=1,0;for(h=1;h0&&(s===wft||m!==1))return-1;for($[1]=0,d=1;dbft||s===jft&&b>_ft)return 1;for(;;){W=d-y,l[u]+1=I?(G=q[l[u]-I],K=L[l[u]-I]):(G=96,K=0),k=1<>y)+C]=W<<24|G<<16|K|0;while(C!==0);for(k=1<>=1;if(k!==0?(v&=k-1,v+=k):v=0,u++,--O[d]===0){if(d===m)break;d=t[n+l[u]]}if(d>p&&(v&M)!==T){for(y===0&&(y=p),P+=h,x=d-y,g=1<bft||s===jft&&b>_ft)return 1;T=v&M,a[T]=p<<24|x<<16|P-i|0}}return v!==0&&(a[P+v]=d-y<<24|64<<16|0),o.bits=p,0};var hY=c_n;const d_n=0,wFt=1,jFt=2,{Z_FINISH:Nft,Z_BLOCK:u_n,Z_TREES:Zne,Z_OK:eO,Z_STREAM_END:h_n,Z_NEED_DICT:m_n,Z_STREAM_ERROR:Uj,Z_DATA_ERROR:NFt,Z_MEM_ERROR:kFt,Z_BUF_ERROR:p_n,Z_DEFLATED:kft}=lee,oTe=16180,Sft=16181,Cft=16182,Aft=16183,Tft=16184,Eft=16185,Mft=16186,Lft=16187,Pft=16188,Ift=16189,ySe=16190,t4=16191,yIe=16192,Rft=16193,vIe=16194,Dft=16195,Oft=16196,Fft=16197,zft=16198,Xne=16199,Qne=16200,Bft=16201,$ft=16202,Uft=16203,qft=16204,Vft=16205,bIe=16206,Hft=16207,Gft=16208,Rm=16209,SFt=16210,CFt=16211,f_n=852,x_n=592,g_n=15,y_n=g_n,Wft=s=>(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24);function v_n(){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 DO=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.modeCFt?1:0},AFt=s=>{if(DO(s))return Uj;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=oTe,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(f_n),t.distcode=t.distdyn=new Int32Array(x_n),t.sane=1,t.back=-1,eO},TFt=s=>{if(DO(s))return Uj;const t=s.state;return t.wsize=0,t.whave=0,t.wnext=0,AFt(s)},EFt=(s,t)=>{let n;if(DO(s))return Uj;const r=s.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?Uj:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,TFt(s))},MFt=(s,t)=>{if(!s)return Uj;const n=new v_n;s.state=n,n.strm=s,n.window=null,n.mode=oTe;const r=EFt(s,t);return r!==eO&&(s.state=null),r},b_n=s=>MFt(s,y_n);let Kft=!0,_Ie,wIe;const __n=s=>{if(Kft){_Ie=new Int32Array(512),wIe=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(hY(wFt,s.lens,0,288,_Ie,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;hY(jFt,s.lens,0,32,wIe,0,s.work,{bits:5}),Kft=!1}s.lencode=_Ie,s.lenbits=9,s.distcode=wIe,s.distbits=5},LFt=(s,t,n,r)=>{let a;const i=s.state;return i.window===null&&(i.wsize=1<=i.wsize?(i.window.set(t.subarray(n-i.wsize,n),0),i.wnext=0,i.whave=i.wsize):(a=i.wsize-i.wnext,a>r&&(a=r),i.window.set(t.subarray(n-r,n-r+a),i.wnext),r-=a,r?(i.window.set(t.subarray(n-r,n),0),i.wnext=r,i.whave=i.wsize):(i.wnext+=a,i.wnext===i.wsize&&(i.wnext=0),i.whave{let n,r,a,i,l,o,c,d,u,h,m,p,x,y,g=0,b,v,k,C,T,M,P,L;const I=new Uint8Array(4);let O,$;const q=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(DO(s)||!s.output||!s.input&&s.avail_in!==0)return Uj;n=s.state,n.mode===t4&&(n.mode=yIe),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,L=eO;e:for(;;)switch(n.mode){case oTe:if(n.wrap===0){n.mode=yIe;break}for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=Hg(n.check,I,2,0),d=0,u=0,n.mode=Sft;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Rm;break}if((d&15)!==kft){s.msg="unknown compression method",n.mode=Rm;break}if(d>>>=4,u-=4,P=(d&15)+8,n.wbits===0&&(n.wbits=P),P>15||P>n.wbits){s.msg="invalid window size",n.mode=Rm;break}n.dmax=1<>8&1),n.flags&512&&n.wrap&4&&(I[0]=d&255,I[1]=d>>>8&255,n.check=Hg(n.check,I,2,0)),d=0,u=0,n.mode=Cft;case Cft:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>8&255,I[2]=d>>>16&255,I[3]=d>>>24&255,n.check=Hg(n.check,I,4,0)),d=0,u=0,n.mode=Aft;case Aft:for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>8),n.flags&512&&n.wrap&4&&(I[0]=d&255,I[1]=d>>>8&255,n.check=Hg(n.check,I,2,0)),d=0,u=0,n.mode=Tft;case Tft:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=Hg(n.check,I,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=Eft;case Eft:if(n.flags&1024&&(p=n.length,p>o&&(p=o),p&&(n.head&&(P=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(i,i+p),P)),n.flags&512&&n.wrap&4&&(n.check=Hg(n.check,r,p,i)),o-=p,i+=p,n.length-=p),n.length))break e;n.length=0,n.mode=Mft;case Mft:if(n.flags&2048){if(o===0)break e;p=0;do P=r[i+p++],n.head&&P&&n.length<65536&&(n.head.name+=String.fromCharCode(P));while(P&&p>9&1,n.head.done=!0),s.adler=n.check=0,n.mode=t4;break;case Ift:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=bIe;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=Rft;break;case 1:if(__n(n),n.mode=Xne,t===Zne){d>>>=2,u-=2;break e}break;case 2:n.mode=Oft;break;case 3:s.msg="invalid block type",n.mode=Rm}d>>>=2,u-=2;break;case Rft: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=Rm;break}if(n.length=d&65535,d=0,u=0,n.mode=vIe,t===Zne)break e;case vIe:n.mode=Dft;case Dft:if(p=n.length,p){if(p>o&&(p=o),p>c&&(p=c),p===0)break e;a.set(r.subarray(i,i+p),l),o-=p,i+=p,c-=p,l+=p,n.length-=p;break}n.mode=t4;break;case Oft: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=Rm;break}n.have=0,n.mode=Fft;case Fft:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[q[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,O={bits:n.lenbits},L=hY(d_n,n.lens,0,19,n.lencode,0,n.work,O),n.lenbits=O.bits,L){s.msg="invalid code lengths set",n.mode=Rm;break}n.have=0,n.mode=zft;case zft:for(;n.have>>24,v=g>>>16&255,k=g&65535,!(b<=u);){if(o===0)break e;o--,d+=r[i++]<>>=b,u-=b,n.lens[n.have++]=k;else{if(k===16){for($=b+2;u<$;){if(o===0)break e;o--,d+=r[i++]<>>=b,u-=b,n.have===0){s.msg="invalid bit length repeat",n.mode=Rm;break}P=n.lens[n.have-1],p=3+(d&3),d>>>=2,u-=2}else if(k===17){for($=b+3;u<$;){if(o===0)break e;o--,d+=r[i++]<>>=b,u-=b,P=0,p=3+(d&7),d>>>=3,u-=3}else{for($=b+7;u<$;){if(o===0)break e;o--,d+=r[i++]<>>=b,u-=b,P=0,p=11+(d&127),d>>>=7,u-=7}if(n.have+p>n.nlen+n.ndist){s.msg="invalid bit length repeat",n.mode=Rm;break}for(;p--;)n.lens[n.have++]=P}}if(n.mode===Rm)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Rm;break}if(n.lenbits=9,O={bits:n.lenbits},L=hY(wFt,n.lens,0,n.nlen,n.lencode,0,n.work,O),n.lenbits=O.bits,L){s.msg="invalid literal/lengths set",n.mode=Rm;break}if(n.distbits=6,n.distcode=n.distdyn,O={bits:n.distbits},L=hY(jFt,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,O),n.distbits=O.bits,L){s.msg="invalid distances set",n.mode=Rm;break}if(n.mode=Xne,t===Zne)break e;case Xne:n.mode=Qne;case Qne: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,r_n(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===t4&&(n.back=-1);break}for(n.back=0;g=n.lencode[d&(1<>>24,v=g>>>16&255,k=g&65535,!(b<=u);){if(o===0)break e;o--,d+=r[i++]<>C)],b=g>>>24,v=g>>>16&255,k=g&65535,!(C+b<=u);){if(o===0)break e;o--,d+=r[i++]<>>=C,u-=C,n.back+=C}if(d>>>=b,u-=b,n.back+=b,n.length=k,v===0){n.mode=Vft;break}if(v&32){n.back=-1,n.mode=t4;break}if(v&64){s.msg="invalid literal/length code",n.mode=Rm;break}n.extra=v&15,n.mode=Bft;case Bft: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=$ft;case $ft:for(;g=n.distcode[d&(1<>>24,v=g>>>16&255,k=g&65535,!(b<=u);){if(o===0)break e;o--,d+=r[i++]<>C)],b=g>>>24,v=g>>>16&255,k=g&65535,!(C+b<=u);){if(o===0)break e;o--,d+=r[i++]<>>=C,u-=C,n.back+=C}if(d>>>=b,u-=b,n.back+=b,v&64){s.msg="invalid distance code",n.mode=Rm;break}n.offset=k,n.extra=v&15,n.mode=Uft;case Uft: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=Rm;break}n.mode=qft;case qft:if(c===0)break e;if(p=m-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){s.msg="invalid distance too far back",n.mode=Rm;break}p>n.wnext?(p-=n.wnext,x=n.wsize-p):x=n.wnext-p,p>n.length&&(p=n.length),y=n.window}else y=a,x=l-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do a[l++]=y[x++];while(--p);n.length===0&&(n.mode=Qne);break;case Vft:if(c===0)break e;a[l++]=n.length,c--,n.mode=Qne;break;case bIe:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<{if(DO(s))return Uj;let t=s.state;return t.window&&(t.window=null),s.state=null,eO},N_n=(s,t)=>{if(DO(s))return Uj;const n=s.state;return n.wrap&2?(n.head=t,t.done=!1,eO):Uj},k_n=(s,t)=>{const n=t.length;let r,a,i;return DO(s)||(r=s.state,r.wrap!==0&&r.mode!==ySe)?Uj:r.mode===ySe&&(a=1,a=fX(a,t,n,0),a!==r.check)?NFt:(i=LFt(s,t,n,n),i?(r.mode=SFt,kFt):(r.havedict=1,eO))};var S_n=TFt,C_n=EFt,A_n=AFt,T_n=b_n,E_n=MFt,M_n=w_n,L_n=j_n,P_n=N_n,I_n=k_n,R_n="pako inflate (from Nodeca project)",C4={inflateReset:S_n,inflateReset2:C_n,inflateResetKeep:A_n,inflateInit:T_n,inflateInit2:E_n,inflate:M_n,inflateEnd:L_n,inflateGetHeader:P_n,inflateSetDictionary:I_n,inflateInfo:R_n};function D_n(){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 O_n=D_n;const PFt=Object.prototype.toString,{Z_NO_FLUSH:F_n,Z_FINISH:z_n,Z_OK:yX,Z_STREAM_END:jIe,Z_NEED_DICT:NIe,Z_STREAM_ERROR:B_n,Z_DATA_ERROR:Yft,Z_MEM_ERROR:$_n}=lee;function dee(s){this.options=iTe.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 bFt,this.strm.avail_out=0;let n=C4.inflateInit2(this.strm,t.windowBits);if(n!==yX)throw new Error(yU[n]);if(this.header=new O_n,C4.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=gX.string2buf(t.dictionary):PFt.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=C4.inflateSetDictionary(this.strm,t.dictionary),n!==yX)))throw new Error(yU[n])}dee.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?z_n:F_n,PFt.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=C4.inflate(n,l),i===NIe&&a&&(i=C4.inflateSetDictionary(n,a),i===yX?i=C4.inflate(n,l):i===Yft&&(i=NIe));n.avail_in>0&&i===jIe&&n.state.wrap>0&&s[n.next_in]!==0;)C4.inflateReset(n),i=C4.inflate(n,l);switch(i){case B_n:case Yft:case NIe:case $_n:return this.onEnd(i),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||i===jIe))if(this.options.to==="string"){let c=gX.utf8border(n.output,n.next_out),d=n.next_out-c,u=gX.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===yX&&o===0)){if(i===jIe)return i=C4.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,!0;if(n.avail_in===0)break}}return!0};dee.prototype.onData=function(s){this.chunks.push(s)};dee.prototype.onEnd=function(s){s===yX&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=iTe.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function MKe(s,t){const n=new dee(t);if(n.push(s),n.err)throw n.msg||yU[n.err];return n.result}function U_n(s,t){return t=t||{},t.raw=!0,MKe(s,t)}var q_n=dee,V_n=MKe,H_n=U_n,G_n=MKe,W_n=lee,K_n={Inflate:q_n,inflate:V_n,inflateRaw:H_n,ungzip:G_n,constants:W_n};const{Inflate:Y_n,inflate:Z_n,inflateRaw:a$n,ungzip:i$n}=K_n;var Zft=Y_n,X_n=Z_n;const IFt=[];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;IFt[s]=t}const Xft=4294967295;function Q_n(s,t,n){let r=s;for(let a=0;a>>8;return r}function J_n(s,t){return(Q_n(Xft,s,t)^Xft)>>>0}function Qft(s,t,n){const r=s.readUint32(),a=J_n(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 RFt(s,t,n){for(let r=0;r>1)&255}else{for(;i>1)&255;for(;i>1)&255}}function zFt(s,t,n,r,a){let i=0;if(n.length===0){for(;i=n||M>=r))for(let P=0;P>8&255}const own=new Uint16Array([255]),lwn=new Uint8Array(own.buffer),cwn=lwn[0]===255,dwn=new Uint8Array(0);function Jft(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=dwn,u=0,h,m;for(let p=0;p>8&255}const Uje=Uint8Array.of(137,80,78,71,13,10,26,10);function ext(s){if(!hwn(s.readBytes(Uje.length)))throw new Error("wrong PNG signature")}function hwn(s){if(s.length79)throw new Error("keyword length must be between 1 and 79")}const xwn=/^[\u0000-\u00FF]*$/;function gwn(s){if(!xwn.test(s))throw new Error("invalid latin1 text")}function ywn(s,t,n){const r=$Ft(t);s[r]=vwn(t,n-r.length-1)}function $Ft(s){for(s.mark();s.readByte()!==pwn;);const t=s.offset;s.reset();const n=BFt.decode(s.readBytes(t-s.offset-1));return s.skip(1),fwn(n),n}function vwn(s,t){return BFt.decode(s.readBytes(t))}const o_={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},kIe={UNKNOWN:-1,DEFLATE:0},txt={UNKNOWN:-1,ADAPTIVE:0},SIe={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},Jne={NONE:0,BACKGROUND:1,PREVIOUS:2},CIe={SOURCE:0,OVER:1};class bwn extends NKe{constructor(n,r={}){super(n);Ar(this,"_checkCrc");Ar(this,"_inflator");Ar(this,"_png");Ar(this,"_apng");Ar(this,"_end");Ar(this,"_hasPalette");Ar(this,"_palette");Ar(this,"_hasTransparency");Ar(this,"_transparency");Ar(this,"_compressionMethod");Ar(this,"_filterMethod");Ar(this,"_interlaceMethod");Ar(this,"_colorType");Ar(this,"_isAnimated");Ar(this,"_numberOfFrames");Ar(this,"_numberOfPlays");Ar(this,"_frames");Ar(this,"_writingDataChunks");const{checkCrc:a=!1}=r;this._checkCrc=a,this._inflator=new Zft,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=kIe.UNKNOWN,this._filterMethod=txt.UNKNOWN,this._interlaceMethod=SIe.UNKNOWN,this._colorType=o_.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(ext(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeChunk(n,r)}return this.decodeImage(),this._png}decodeApng(){for(ext(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 mwn:ywn(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?Qft(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?Qft(this,n+4,r):this.skip(4)}decodeIHDR(){const n=this._png;n.width=this.readUint32(),n.height=this.readUint32(),n.depth=_wn(this.readUint8());const r=this.readUint8();this._colorType=r;let a;switch(r){case o_.GREYSCALE:a=1;break;case o_.TRUECOLOUR:a=3;break;case o_.INDEXED_COLOUR:a=1;break;case o_.GREYSCALE_ALPHA:a=2;break;case o_.TRUECOLOUR_ALPHA:a=4;break;case o_.UNKNOWN:default:throw new Error(`Unknown color type: ${r}`)}if(this._png.channels=a,this._compressionMethod=this.readUint8(),this._compressionMethod!==kIe.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 CIe.SOURCE:for(let l=0;l=200&&t.status<=299}function ere(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 DI=wl.saveAs||((typeof window>"u"?"undefined":Gu(window))!=="object"||window!==wl?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(s,t,n){var r=wl.URL||wl.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?nxt(a.href)?TIe(s,t,n):ere(a,a.target="_blank"):ere(a)):(a.href=r.createObjectURL(s),setTimeout(function(){r.revokeObjectURL(a.href)},4e4),setTimeout(function(){ere(a)},0))}:"msSaveOrOpenBlob"in navigator?function(s,t,n){if(t=t||s.name||"download",typeof s=="string")if(nxt(s))TIe(s,t,n);else{var r=document.createElement("a");r.href=s,r.target="_blank",setTimeout(function(){ere(r)})}else navigator.msSaveOrOpenBlob(function(a,i){return i===void 0?i={autoBom:!1}:Gu(i)!=="object"&&(gh.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 TIe(s,t,n);var a=s.type==="application/octet-stream",i=/constructor/i.test(wl.HTMLElement)||wl.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||a&&i)&&(typeof FileReader>"u"?"undefined":Gu(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=wl.URL||wl.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 UFt(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 qje=wl.atob.bind(wl),rxt=wl.btoa.bind(wl);/** * @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 EIe(s,t){var n=s[0],r=s[1],a=s[2],i=s[3];n=Ey(n,r,a,i,t[0],7,-680876936),i=Ey(i,n,r,a,t[1],12,-389564586),a=Ey(a,i,n,r,t[2],17,606105819),r=Ey(r,a,i,n,t[3],22,-1044525330),n=Ey(n,r,a,i,t[4],7,-176418897),i=Ey(i,n,r,a,t[5],12,1200080426),a=Ey(a,i,n,r,t[6],17,-1473231341),r=Ey(r,a,i,n,t[7],22,-45705983),n=Ey(n,r,a,i,t[8],7,1770035416),i=Ey(i,n,r,a,t[9],12,-1958414417),a=Ey(a,i,n,r,t[10],17,-42063),r=Ey(r,a,i,n,t[11],22,-1990404162),n=Ey(n,r,a,i,t[12],7,1804603682),i=Ey(i,n,r,a,t[13],12,-40341101),a=Ey(a,i,n,r,t[14],17,-1502002290),n=My(n,r=Ey(r,a,i,n,t[15],22,1236535329),a,i,t[1],5,-165796510),i=My(i,n,r,a,t[6],9,-1069501632),a=My(a,i,n,r,t[11],14,643717713),r=My(r,a,i,n,t[0],20,-373897302),n=My(n,r,a,i,t[5],5,-701558691),i=My(i,n,r,a,t[10],9,38016083),a=My(a,i,n,r,t[15],14,-660478335),r=My(r,a,i,n,t[4],20,-405537848),n=My(n,r,a,i,t[9],5,568446438),i=My(i,n,r,a,t[14],9,-1019803690),a=My(a,i,n,r,t[3],14,-187363961),r=My(r,a,i,n,t[8],20,1163531501),n=My(n,r,a,i,t[13],5,-1444681467),i=My(i,n,r,a,t[2],9,-51403784),a=My(a,i,n,r,t[7],14,1735328473),n=Ly(n,r=My(r,a,i,n,t[12],20,-1926607734),a,i,t[5],4,-378558),i=Ly(i,n,r,a,t[8],11,-2022574463),a=Ly(a,i,n,r,t[11],16,1839030562),r=Ly(r,a,i,n,t[14],23,-35309556),n=Ly(n,r,a,i,t[1],4,-1530992060),i=Ly(i,n,r,a,t[4],11,1272893353),a=Ly(a,i,n,r,t[7],16,-155497632),r=Ly(r,a,i,n,t[10],23,-1094730640),n=Ly(n,r,a,i,t[13],4,681279174),i=Ly(i,n,r,a,t[0],11,-358537222),a=Ly(a,i,n,r,t[3],16,-722521979),r=Ly(r,a,i,n,t[6],23,76029189),n=Ly(n,r,a,i,t[9],4,-640364487),i=Ly(i,n,r,a,t[12],11,-421815835),a=Ly(a,i,n,r,t[15],16,530742520),n=Py(n,r=Ly(r,a,i,n,t[2],23,-995338651),a,i,t[0],6,-198630844),i=Py(i,n,r,a,t[7],10,1126891415),a=Py(a,i,n,r,t[14],15,-1416354905),r=Py(r,a,i,n,t[5],21,-57434055),n=Py(n,r,a,i,t[12],6,1700485571),i=Py(i,n,r,a,t[3],10,-1894986606),a=Py(a,i,n,r,t[10],15,-1051523),r=Py(r,a,i,n,t[1],21,-2054922799),n=Py(n,r,a,i,t[8],6,1873313359),i=Py(i,n,r,a,t[15],10,-30611744),a=Py(a,i,n,r,t[6],15,-1560198380),r=Py(r,a,i,n,t[13],21,1309151649),n=Py(n,r,a,i,t[4],6,-145523070),i=Py(i,n,r,a,t[11],10,-1120210379),a=Py(a,i,n,r,t[2],15,718787259),r=Py(r,a,i,n,t[9],21,-343485551),s[0]=TT(n,s[0]),s[1]=TT(r,s[1]),s[2]=TT(a,s[2]),s[3]=TT(i,s[3])}function lTe(s,t,n,r,a,i){return t=TT(TT(t,s),TT(r,i)),TT(t<>>32-a,n)}function Ey(s,t,n,r,a,i,l){return lTe(t&n|~t&r,s,t,a,i,l)}function My(s,t,n,r,a,i,l){return lTe(t&r|n&~r,s,t,a,i,l)}function Ly(s,t,n,r,a,i,l){return lTe(t^n^r,s,t,a,i,l)}function Py(s,t,n,r,a,i,l){return lTe(n^(t|~r),s,t,a,i,l)}function qFt(s){var t,n=s.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=s.length;t+=64)EIe(r,jwn(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(EIe(r,a),t=0;t<16;t++)a[t]=0;return a[14]=8*n,EIe(r,a),r}function jwn(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 axt="0123456789abcdef".split("");function Nwn(s){for(var t="",n=0;n<4;n++)t+=axt[s>>8*n+4&15]+axt[s>>8*n&15];return t}function kwn(s){return String.fromCharCode(255&s,(65280&s)>>8,(16711680&s)>>16,(4278190080&s)>>24)}function J9e(s){return qFt(s).map(kwn).join("")}var Swn=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 eze(s,t){var n,r,a,i;if(s!==n){for(var l=(a=s,i=1+(256/s.length|0),new Array(i+1).join(a)),o=[],c=0;c<256;c++)o[c]=c;var d=0;for(c=0;c<256;c++){var u=o[c];d=(d+u+l.charCodeAt(c))%256,o[c]=o[d],o[d]=u}n=s,r=o}else o=r;var h=t.length,m=0,p=0,x="";for(c=0;c€/\f©þdSiz";var i=(t+this.padding).substr(0,32),l=(n+this.padding).substr(0,32);this.O=this.processOwnerPassword(i,l),this.P=-(1+(255^a)),this.encryptionKey=J9e(i+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(r)).substr(0,5),this.U=eze(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 oxt(s){if(Gu(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){wl.console&&gh.error("jsPDF PubSub Error",o.message,o)}l[1]&&a.push(i)}a.length&&a.forEach(this.unsubscribe)}},this.getTopics=function(){return t}}function vSe(s){if(!(this instanceof vSe))return new vSe(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 VFt(s,t){this.gState=s,this.matrix=t,this.id="",this.objectNumber=-1}function KI(s,t,n,r,a){if(!(this instanceof KI))return new KI(s,t,n,r,a);this.type=s==="axial"?2:3,this.coords=t,this.colors=n,VFt.call(this,r,a)}function _9(s,t,n,r,a){if(!(this instanceof _9))return new _9(s,t,n,r,a);this.boundingBox=s,this.xStep=t,this.yStep=n,this.stream="",this.cloneIndex=0,VFt.call(this,r,a)}function ho(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;Gu(s=s||{})==="object"&&(n=s.orientation,r=s.unit||r,a=s.format||a,i=s.compress||s.compressPdf||i,(u=s.encryption||null)!==null&&(u.userPassword=u.userPassword||"",u.ownerPassword=u.ownerPassword||"",u.userPermissions=u.userPermissions||[]),o=typeof s.userUnit=="number"?Math.abs(s.userUnit):1,s.precision!==void 0&&(t=s.precision),s.floatPrecision!==void 0&&(c=s.floatPrecision),d=s.defaultPathOperation||"S"),l=s.filters||(i===!0?["FlateEncode"]:l),r=r||"mm",n=(""+(n||"P")).toLowerCase();var h=s.putOnlyUsedFonts||!1,m={},p={internal:{},__private__:{}};p.__private__.PubSub=oxt;var x="1.3",y=p.__private__.getPdfVersion=function(){return x};p.__private__.setPdfVersion=function($e){x=$e};var g={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};p.__private__.getPageFormats=function(){return g};var b=p.__private__.getPageFormat=function($e){return g[$e]};a=a||"a4";var v="compat",k="advanced",C=v;function T(){this.saveGraphicsState(),Oe(new jr(qs,0,0,-qs,0,Xh()*qs).toString()+" cm"),this.setFontSize(this.getFontSize()/qs),d="n",C=k}function M(){this.restoreGraphicsState(),d="S",C=v}var P=p.__private__.combineFontStyleAndFontWeight=function($e,yt){if($e=="bold"&&yt=="normal"||$e=="bold"&&yt==400||$e=="normal"&&yt=="italic"||$e=="bold"&&yt=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return yt&&($e=yt==400||yt==="normal"?$e==="italic"?"italic":"normal":yt!=700&&yt!=="bold"||$e!=="normal"?(yt==700?"bold":yt)+""+$e:"bold"),$e};p.advancedAPI=function($e){var yt=C===v;return yt&&T.call(this),typeof $e!="function"||($e(this),yt&&M.call(this)),this},p.compatAPI=function($e){var yt=C===k;return yt&&M.call(this),typeof $e!="function"||($e(this),yt&&T.call(this)),this},p.isAdvancedAPI=function(){return C===k};var L,I=function($e){if(C!==k)throw new Error($e+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},O=p.roundToPrecision=p.__private__.roundToPrecision=function($e,yt){var is=t||yt;if(isNaN($e)||isNaN(is))throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return $e.toFixed(is).replace(/0+$/,"")};L=p.hpf=p.__private__.hpf=typeof c=="number"?function($e){if(isNaN($e))throw new Error("Invalid argument passed to jsPDF.hpf");return O($e,c)}:c==="smart"?function($e){if(isNaN($e))throw new Error("Invalid argument passed to jsPDF.hpf");return O($e,$e>-1&&$e<1?16:5)}:function($e){if(isNaN($e))throw new Error("Invalid argument passed to jsPDF.hpf");return O($e,16)};var $=p.f2=p.__private__.f2=function($e){if(isNaN($e))throw new Error("Invalid argument passed to jsPDF.f2");return O($e,2)},q=p.__private__.f3=function($e){if(isNaN($e))throw new Error("Invalid argument passed to jsPDF.f3");return O($e,3)},W=p.scale=p.__private__.scale=function($e){if(isNaN($e))throw new Error("Invalid argument passed to jsPDF.scale");return C===v?$e*qs:C===k?$e:void 0},G=function($e){return W(function(yt){return C===v?Xh()-yt:C===k?yt:void 0}($e))};p.__private__.setPrecision=p.setPrecision=function($e){typeof parseInt($e,10)=="number"&&(t=parseInt($e,10))};var K,ee="00000000000000000000000000000000",J=p.__private__.getFileId=function(){return ee},le=p.__private__.setFileId=function($e){return ee=$e!==void 0&&/^[a-fA-F0-9]{32}$/.test($e)?$e.toUpperCase():ee.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),u!==null&&(Co=new D7(u.userPermissions,u.userPassword,u.ownerPassword,ee)),ee};p.setFileId=function($e){return le($e),this},p.getFileId=function(){return J()};var ue=p.__private__.convertDateToPDFDate=function($e){var yt=$e.getTimezoneOffset(),is=yt<0?"+":"-",us=Math.floor(Math.abs(yt/60)),en=Math.abs(yt%60),Dn=[is,je(us),"'",je(en),"'"].join("");return["D:",$e.getFullYear(),je($e.getMonth()+1),je($e.getDate()),je($e.getHours()),je($e.getMinutes()),je($e.getSeconds()),Dn].join("")},oe=p.__private__.convertPDFDateToDate=function($e){var yt=parseInt($e.substr(2,4),10),is=parseInt($e.substr(6,2),10)-1,us=parseInt($e.substr(8,2),10),en=parseInt($e.substr(10,2),10),Dn=parseInt($e.substr(12,2),10),er=parseInt($e.substr(14,2),10);return new Date(yt,is,us,en,Dn,er,0)},ie=p.__private__.setCreationDate=function($e){var yt;if($e===void 0&&($e=new Date),$e instanceof Date)yt=ue($e);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($e))throw new Error("Invalid argument passed to jsPDF.setCreationDate");yt=$e}return K=yt},de=p.__private__.getCreationDate=function($e){var yt=K;return $e==="jsDate"&&(yt=oe(K)),yt};p.setCreationDate=function($e){return ie($e),this},p.getCreationDate=function($e){return de($e)};var we,je=p.__private__.padd2=function($e){return("0"+parseInt($e)).slice(-2)},xe=p.__private__.padd2Hex=function($e){return("00"+($e=$e.toString())).substr($e.length)},fe=0,Se=[],Ee=[],Le=0,De=[],Be=[],Ne=!1,Ge=Ee;p.__private__.setCustomOutputDestination=function($e){Ne=!0,Ge=$e};var _e=function($e){Ne||(Ge=$e)};p.__private__.resetCustomOutputDestination=function(){Ne=!1,Ge=Ee};var Oe=p.__private__.out=function($e){return $e=$e.toString(),Le+=$e.length+1,Ge.push($e),Ge},Ae=p.__private__.write=function($e){return Oe(arguments.length===1?$e.toString():Array.prototype.join.call(arguments," "))},Xe=p.__private__.getArrayBuffer=function($e){for(var yt=$e.length,is=new ArrayBuffer(yt),us=new Uint8Array(is);yt--;)us[yt]=$e.charCodeAt(yt);return is},Ue=[["Helvetica","helvetica","normal","WinAnsiEncoding"],["Helvetica-Bold","helvetica","bold","WinAnsiEncoding"],["Helvetica-Oblique","helvetica","italic","WinAnsiEncoding"],["Helvetica-BoldOblique","helvetica","bolditalic","WinAnsiEncoding"],["Courier","courier","normal","WinAnsiEncoding"],["Courier-Bold","courier","bold","WinAnsiEncoding"],["Courier-Oblique","courier","italic","WinAnsiEncoding"],["Courier-BoldOblique","courier","bolditalic","WinAnsiEncoding"],["Times-Roman","times","normal","WinAnsiEncoding"],["Times-Bold","times","bold","WinAnsiEncoding"],["Times-Italic","times","italic","WinAnsiEncoding"],["Times-BoldItalic","times","bolditalic","WinAnsiEncoding"],["ZapfDingbats","zapfdingbats","normal",null],["Symbol","symbol","normal",null]];p.__private__.getStandardFonts=function(){return Ue};var Ze=s.fontSize||16;p.__private__.setFontSize=p.setFontSize=function($e){return Ze=C===k?$e/qs:$e,this};var Qe,Ye=p.__private__.getFontSize=p.getFontSize=function(){return C===v?Ze:Ze*qs},nt=s.R2L||!1;p.__private__.setR2L=p.setR2L=function($e){return nt=$e,this},p.__private__.getR2L=p.getR2L=function(){return nt};var rt,Fe=p.__private__.setZoomMode=function($e){if(/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test($e))Qe=$e;else if(isNaN($e)){if([void 0,null,"fullwidth","fullheight","fullpage","original"].indexOf($e)===-1)throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "'+$e+'" is not recognized.');Qe=$e}else Qe=parseInt($e,10)};p.__private__.getZoomMode=function(){return Qe};var dt,Dt=p.__private__.setPageMode=function($e){if([void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf($e)==-1)throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+$e+'" is not recognized.');rt=$e};p.__private__.getPageMode=function(){return rt};var pt=p.__private__.setLayoutMode=function($e){if([void 0,null,"continuous","single","twoleft","tworight","two"].indexOf($e)==-1)throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "'+$e+'" is not recognized.');dt=$e};p.__private__.getLayoutMode=function(){return dt},p.__private__.setDisplayMode=p.setDisplayMode=function($e,yt,is){return Fe($e),pt(yt),Dt(is),this};var zt={title:"",subject:"",author:"",keywords:"",creator:""};p.__private__.getDocumentProperty=function($e){if(Object.keys(zt).indexOf($e)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return zt[$e]},p.__private__.getDocumentProperties=function(){return zt},p.__private__.setDocumentProperties=p.setProperties=p.setDocumentProperties=function($e){for(var yt in zt)zt.hasOwnProperty(yt)&&$e[yt]&&(zt[yt]=$e[yt]);return this},p.__private__.setDocumentProperty=function($e,yt){if(Object.keys(zt).indexOf($e)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return zt[$e]=yt};var Gt,qs,As,Bt,At,Is={},jt={},Qs=[],cn={},qt={},Gs={},Ls={},sn=null,Hs=0,nn=[],tn=new oxt(p),_n=s.hotfixes||[],Cn={},Un={},Kr=[],jr=function $e(yt,is,us,en,Dn,er){if(!(this instanceof $e))return new $e(yt,is,us,en,Dn,er);isNaN(yt)&&(yt=1),isNaN(is)&&(is=0),isNaN(us)&&(us=0),isNaN(en)&&(en=1),isNaN(Dn)&&(Dn=0),isNaN(er)&&(er=0),this._matrix=[yt,is,us,en,Dn,er]};Object.defineProperty(jr.prototype,"sx",{get:function(){return this._matrix[0]},set:function($e){this._matrix[0]=$e}}),Object.defineProperty(jr.prototype,"shy",{get:function(){return this._matrix[1]},set:function($e){this._matrix[1]=$e}}),Object.defineProperty(jr.prototype,"shx",{get:function(){return this._matrix[2]},set:function($e){this._matrix[2]=$e}}),Object.defineProperty(jr.prototype,"sy",{get:function(){return this._matrix[3]},set:function($e){this._matrix[3]=$e}}),Object.defineProperty(jr.prototype,"tx",{get:function(){return this._matrix[4]},set:function($e){this._matrix[4]=$e}}),Object.defineProperty(jr.prototype,"ty",{get:function(){return this._matrix[5]},set:function($e){this._matrix[5]=$e}}),Object.defineProperty(jr.prototype,"a",{get:function(){return this._matrix[0]},set:function($e){this._matrix[0]=$e}}),Object.defineProperty(jr.prototype,"b",{get:function(){return this._matrix[1]},set:function($e){this._matrix[1]=$e}}),Object.defineProperty(jr.prototype,"c",{get:function(){return this._matrix[2]},set:function($e){this._matrix[2]=$e}}),Object.defineProperty(jr.prototype,"d",{get:function(){return this._matrix[3]},set:function($e){this._matrix[3]=$e}}),Object.defineProperty(jr.prototype,"e",{get:function(){return this._matrix[4]},set:function($e){this._matrix[4]=$e}}),Object.defineProperty(jr.prototype,"f",{get:function(){return this._matrix[5]},set:function($e){this._matrix[5]=$e}}),Object.defineProperty(jr.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(jr.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(jr.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(jr.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),jr.prototype.join=function($e){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map(L).join($e)},jr.prototype.multiply=function($e){var yt=$e.sx*this.sx+$e.shy*this.shx,is=$e.sx*this.shy+$e.shy*this.sy,us=$e.shx*this.sx+$e.sy*this.shx,en=$e.shx*this.shy+$e.sy*this.sy,Dn=$e.tx*this.sx+$e.ty*this.shx+this.tx,er=$e.tx*this.shy+$e.ty*this.sy+this.ty;return new jr(yt,is,us,en,Dn,er)},jr.prototype.decompose=function(){var $e=this.sx,yt=this.shy,is=this.shx,us=this.sy,en=this.tx,Dn=this.ty,er=Math.sqrt($e*$e+yt*yt),xr=($e/=er)*is+(yt/=er)*us;is-=$e*xr,us-=yt*xr;var Ha=Math.sqrt(is*is+us*us);return xr/=Ha,$e*(us/=Ha)>16&255,us=Ha>>8&255,en=255&Ha}if(us===void 0||Dn===void 0&&is===us&&us===en)yt=typeof is=="string"?is+" "+er[0]:$e.precision===2?$(is/255)+" "+er[0]:q(is/255)+" "+er[0];else if(Dn===void 0||Gu(Dn)==="object"){if(Dn&&!isNaN(Dn.a)&&Dn.a===0)return["1.","1.","1.",er[1]].join(" ");yt=typeof is=="string"?[is,us,en,er[1]].join(" "):$e.precision===2?[$(is/255),$(us/255),$(en/255),er[1]].join(" "):[q(is/255),q(us/255),q(en/255),er[1]].join(" ")}else yt=typeof is=="string"?[is,us,en,Dn,er[2]].join(" "):$e.precision===2?[$(is),$(us),$(en),$(Dn),er[2]].join(" "):[q(is),q(us),q(en),q(Dn),er[2]].join(" ");return yt},St=p.__private__.getFilters=function(){return l},Ht=p.__private__.putStream=function($e){var yt=($e=$e||{}).data||"",is=$e.filters||St(),us=$e.alreadyAppliedFilters||[],en=$e.addLength1||!1,Dn=yt.length,er=$e.objectId,xr=function(ui){return ui};if(u!==null&&er===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");u!==null&&(xr=Co.encryptor(er,0));var Ha={};is===!0&&(is=["FlateEncode"]);var Zi=$e.additionalKeyValues||[],Hi=(Ha=ho.API.processDataByFilters!==void 0?ho.API.processDataByFilters(yt,is):{data:yt,reverseChain:[]}).reverseChain+(Array.isArray(us)?us.join(" "):us.toString());if(Ha.data.length!==0&&(Zi.push({key:"Length",value:Ha.data.length}),en===!0&&Zi.push({key:"Length1",value:Dn})),Hi.length!=0)if(Hi.split("/").length-1==1)Zi.push({key:"Filter",value:Hi});else{Zi.push({key:"Filter",value:"["+Hi+"]"});for(var rl=0;rl>"),Ha.data.length!==0&&(Oe("stream"),Oe(xr(Ha.data)),Oe("endstream"))},ts=p.__private__.putPage=function($e){var yt=$e.number,is=$e.data,us=$e.objId,en=$e.contentsObjId;Jn(us,!0),Oe("<>"),Oe("endobj");var Dn=is.join(` `);return C===k&&(Dn+=` Q`),Jn(en,!0),Ht({data:Dn,filters:St(),objectId:en}),Oe("endobj"),us},Ms=p.__private__.putPages=function(){var $e,yt,is=[];for($e=1;$e<=Hs;$e++)nn[$e].objId=rn(),nn[$e].contentsObjId=rn();for($e=1;$e<=Hs;$e++)is.push(ts({number:$e,data:Be[$e],objId:nn[$e].objId,contentsObjId:nn[$e].contentsObjId,mediaBox:nn[$e].mediaBox,cropBox:nn[$e].cropBox,bleedBox:nn[$e].bleedBox,trimBox:nn[$e].trimBox,artBox:nn[$e].artBox,userUnit:nn[$e].userUnit,rootDictionaryObjId:_s,resourceDictionaryObjId:We}));Jn(_s,!0),Oe("<>"),Oe("endobj"),tn.publish("postPutPages")},js=function($e){tn.publish("putFont",{font:$e,out:Oe,newObject:pr,putStream:Ht}),$e.isAlreadyPutted!==!0&&($e.objectNumber=pr(),Oe("<<"),Oe("/Type /Font"),Oe("/BaseFont /"+O7($e.postScriptName)),Oe("/Subtype /Type1"),typeof $e.encoding=="string"&&Oe("/Encoding /"+$e.encoding),Oe("/FirstChar 32"),Oe("/LastChar 255"),Oe(">>"),Oe("endobj"))},Zs=function($e){$e.objectNumber=pr();var yt=[];yt.push({key:"Type",value:"/XObject"}),yt.push({key:"Subtype",value:"/Form"}),yt.push({key:"BBox",value:"["+[L($e.x),L($e.y),L($e.x+$e.width),L($e.y+$e.height)].join(" ")+"]"}),yt.push({key:"Matrix",value:"["+$e.matrix.toString()+"]"});var is=$e.pages[1].join(` `);Ht({data:is,additionalKeyValues:yt,objectId:$e.objectNumber}),Oe("endobj")},Tn=function($e,yt){yt||(yt=21);var is=pr(),us=function(er,xr){var Ha,Zi=[],Hi=1/(xr-1);for(Ha=0;Ha<1;Ha+=Hi)Zi.push(Ha);if(Zi.push(1),er[0].offset!=0){var rl={offset:0,color:er[0].color};er.unshift(rl)}if(er[er.length-1].offset!=1){var Dc={offset:1,color:er[er.length-1].color};er.push(Dc)}for(var Lr="",ti=0,ui=0;uier[ti+1].offset;)ti++;var Rl=er[ti].offset,bc=(Ha-Rl)/(er[ti+1].offset-Rl),Gi=er[ti].color,Qh=er[ti+1].color;Lr+=xe(Math.round((1-bc)*Gi[0]+bc*Qh[0]).toString(16))+xe(Math.round((1-bc)*Gi[1]+bc*Qh[1]).toString(16))+xe(Math.round((1-bc)*Gi[2]+bc*Qh[2]).toString(16))}return Lr.trim()}($e.colors,yt),en=[];en.push({key:"FunctionType",value:"0"}),en.push({key:"Domain",value:"[0.0 1.0]"}),en.push({key:"Size",value:"["+yt+"]"}),en.push({key:"BitsPerSample",value:"8"}),en.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),en.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),Ht({data:us,additionalKeyValues:en,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:is}),Oe("endobj"),$e.objectNumber=pr(),Oe("<< /ShadingType "+$e.type),Oe("/ColorSpace /DeviceRGB");var Dn="/Coords ["+L(parseFloat($e.coords[0]))+" "+L(parseFloat($e.coords[1]))+" ";$e.type===2?Dn+=L(parseFloat($e.coords[2]))+" "+L(parseFloat($e.coords[3])):Dn+=L(parseFloat($e.coords[2]))+" "+L(parseFloat($e.coords[3]))+" "+L(parseFloat($e.coords[4]))+" "+L(parseFloat($e.coords[5])),Oe(Dn+="]"),$e.matrix&&Oe("/Matrix ["+$e.matrix.toString()+"]"),Oe("/Function "+is+" 0 R"),Oe("/Extend [true true]"),Oe(">>"),Oe("endobj")},vn=function($e,yt){var is=rn(),us=pr();yt.push({resourcesOid:is,objectOid:us}),$e.objectNumber=us;var en=[];en.push({key:"Type",value:"/Pattern"}),en.push({key:"PatternType",value:"1"}),en.push({key:"PaintType",value:"1"}),en.push({key:"TilingType",value:"1"}),en.push({key:"BBox",value:"["+$e.boundingBox.map(L).join(" ")+"]"}),en.push({key:"XStep",value:L($e.xStep)}),en.push({key:"YStep",value:L($e.yStep)}),en.push({key:"Resources",value:is+" 0 R"}),$e.matrix&&en.push({key:"Matrix",value:"["+$e.matrix.toString()+"]"}),Ht({data:$e.stream,additionalKeyValues:en,objectId:$e.objectNumber}),Oe("endobj")},_r=function($e){for(var yt in $e.objectNumber=pr(),Oe("<<"),$e)switch(yt){case"opacity":Oe("/ca "+$($e[yt]));break;case"stroke-opacity":Oe("/CA "+$($e[yt]))}Oe(">>"),Oe("endobj")},Jr=function($e){Jn($e.resourcesOid,!0),Oe("<<"),Oe("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),function(){for(var yt in Oe("/Font <<"),Is)Is.hasOwnProperty(yt)&&(h===!1||h===!0&&m.hasOwnProperty(yt))&&Oe("/"+yt+" "+Is[yt].objectNumber+" 0 R");Oe(">>")}(),function(){if(Object.keys(cn).length>0){for(var yt in Oe("/Shading <<"),cn)cn.hasOwnProperty(yt)&&cn[yt]instanceof KI&&cn[yt].objectNumber>=0&&Oe("/"+yt+" "+cn[yt].objectNumber+" 0 R");tn.publish("putShadingPatternDict"),Oe(">>")}}(),function(yt){if(Object.keys(cn).length>0){for(var is in Oe("/Pattern <<"),cn)cn.hasOwnProperty(is)&&cn[is]instanceof p.TilingPattern&&cn[is].objectNumber>=0&&cn[is].objectNumber>")}}($e.objectOid),function(){if(Object.keys(Gs).length>0){var yt;for(yt in Oe("/ExtGState <<"),Gs)Gs.hasOwnProperty(yt)&&Gs[yt].objectNumber>=0&&Oe("/"+yt+" "+Gs[yt].objectNumber+" 0 R");tn.publish("putGStateDict"),Oe(">>")}}(),function(){for(var yt in Oe("/XObject <<"),Cn)Cn.hasOwnProperty(yt)&&Cn[yt].objectNumber>=0&&Oe("/"+yt+" "+Cn[yt].objectNumber+" 0 R");tn.publish("putXobjectDict"),Oe(">>")}(),Oe(">>"),Oe("endobj")},ha=function($e){jt[$e.fontName]=jt[$e.fontName]||{},jt[$e.fontName][$e.fontStyle]=$e.id},Mr=function($e,yt,is,us,en){var Dn={id:"F"+(Object.keys(Is).length+1).toString(10),postScriptName:$e,fontName:yt,fontStyle:is,encoding:us,isStandardFont:en||!1,metadata:{}};return tn.publish("addFont",{font:Dn,instance:this}),Is[Dn.id]=Dn,ha(Dn),Dn.id},Xr=p.__private__.pdfEscape=p.pdfEscape=function($e,yt){return function(is,us){var en,Dn,er,xr,Ha,Zi,Hi,rl,Dc;if(er=(us=us||{}).sourceEncoding||"Unicode",Ha=us.outputEncoding,(us.autoencode||Ha)&&Is[Gt].metadata&&Is[Gt].metadata[er]&&Is[Gt].metadata[er].encoding&&(xr=Is[Gt].metadata[er].encoding,!Ha&&Is[Gt].encoding&&(Ha=Is[Gt].encoding),!Ha&&xr.codePages&&(Ha=xr.codePages[0]),typeof Ha=="string"&&(Ha=xr[Ha]),Ha)){for(Hi=!1,Zi=[],en=0,Dn=is.length;en>8&&(Hi=!0);is=Zi.join("")}for(en=is.length;Hi===void 0&&en!==0;)is.charCodeAt(en-1)>>8&&(Hi=!0),en--;if(!Hi)return is;for(Zi=us.noBOM?[]:[254,255],en=0,Dn=is.length;en>8)>>8)throw new Error("Character at position "+en+" of string '"+is+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");Zi.push(Dc),Zi.push(rl-(Dc<<8))}return String.fromCharCode.apply(void 0,Zi)}($e,yt).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},Qt=p.__private__.beginPage=function($e){Be[++Hs]=[],nn[Hs]={objId:0,contentsObjId:0,userUnit:Number(o),artBox:null,bleedBox:null,cropBox:null,trimBox:null,mediaBox:{bottomLeftX:0,bottomLeftY:0,topRightX:Number($e[0]),topRightY:Number($e[1])}},zr(Hs),_e(Be[we])},Zn=function($e,yt){var is,us,en;switch(n=yt||n,typeof $e=="string"&&(is=b($e.toLowerCase()),Array.isArray(is)&&(us=is[0],en=is[1])),Array.isArray($e)&&(us=$e[0]*qs,en=$e[1]*qs),isNaN(us)&&(us=a[0],en=a[1]),(us>14400||en>14400)&&(gh.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),us=Math.min(14400,us),en=Math.min(14400,en)),a=[us,en],n.substr(0,1)){case"l":en>us&&(a=[en,us]);break;case"p":us>en&&(a=[en,us])}Qt(a),_m(go),Oe(sp),rp!==0&&Oe(rp+" J"),wm!==0&&Oe(wm+" j"),tn.publish("addPage",{pageNumber:Hs})},aa=function($e){$e>0&&$e<=Hs&&(Be.splice($e,1),nn.splice($e,1),Hs--,we>Hs&&(we=Hs),this.setPage(we))},zr=function($e){$e>0&&$e<=Hs&&(we=$e)},Na=p.__private__.getNumberOfPages=p.getNumberOfPages=function(){return Be.length-1},oa=function($e,yt,is){var us,en=void 0;return is=is||{},$e=$e!==void 0?$e:Is[Gt].fontName,yt=yt!==void 0?yt:Is[Gt].fontStyle,us=$e.toLowerCase(),jt[us]!==void 0&&jt[us][yt]!==void 0?en=jt[us][yt]:jt[$e]!==void 0&&jt[$e][yt]!==void 0?en=jt[$e][yt]:is.disableWarning===!1&&gh.warn("Unable to look up font label for font '"+$e+"', '"+yt+"'. Refer to getFontList() for available fonts."),en||is.noFallback||(en=jt.times[yt])==null&&(en=jt.times.normal),en},ur=p.__private__.putInfo=function(){var $e=pr(),yt=function(us){return us};for(var is in u!==null&&(yt=Co.encryptor($e,0)),Oe("<<"),Oe("/Producer ("+Xr(yt("jsPDF "+ho.version))+")"),zt)zt.hasOwnProperty(is)&&zt[is]&&Oe("/"+is.substr(0,1).toUpperCase()+is.substr(1)+" ("+Xr(yt(zt[is]))+")");Oe("/CreationDate ("+Xr(yt(K))+")"),Oe(">>"),Oe("endobj")},ao=p.__private__.putCatalog=function($e){var yt=($e=$e||{}).rootDictionaryObjId||_s;switch(pr(),Oe("<<"),Oe("/Type /Catalog"),Oe("/Pages "+yt+" 0 R"),Qe||(Qe="fullwidth"),Qe){case"fullwidth":Oe("/OpenAction [3 0 R /FitH null]");break;case"fullheight":Oe("/OpenAction [3 0 R /FitV null]");break;case"fullpage":Oe("/OpenAction [3 0 R /Fit]");break;case"original":Oe("/OpenAction [3 0 R /XYZ null null 1]");break;default:var is=""+Qe;is.substr(is.length-1)==="%"&&(Qe=parseInt(Qe)/100),typeof Qe=="number"&&Oe("/OpenAction [3 0 R /XYZ null null "+$(Qe)+"]")}switch(dt||(dt="continuous"),dt){case"continuous":Oe("/PageLayout /OneColumn");break;case"single":Oe("/PageLayout /SinglePage");break;case"two":case"twoleft":Oe("/PageLayout /TwoColumnLeft");break;case"tworight":Oe("/PageLayout /TwoColumnRight")}rt&&Oe("/PageMode /"+rt),tn.publish("putCatalog"),Oe(">>"),Oe("endobj")},fo=p.__private__.putTrailer=function(){Oe("trailer"),Oe("<<"),Oe("/Size "+(fe+1)),Oe("/Root "+fe+" 0 R"),Oe("/Info "+(fe-1)+" 0 R"),u!==null&&Oe("/Encrypt "+Co.oid+" 0 R"),Oe("/ID [ <"+ee+"> <"+ee+"> ]"),Oe(">>")},Va=p.__private__.putHeader=function(){Oe("%PDF-"+x),Oe("%ºß¬à")},So=p.__private__.putXRef=function(){var $e="0000000000";Oe("xref"),Oe("0 "+(fe+1)),Oe("0000000000 65535 f ");for(var yt=1;yt<=fe;yt++)typeof Se[yt]=="function"?Oe(($e+Se[yt]()).slice(-10)+" 00000 n "):Se[yt]!==void 0?Oe(($e+Se[yt]).slice(-10)+" 00000 n "):Oe("0000000000 00000 n ")},$a=p.__private__.buildDocument=function(){var $e;fe=0,Le=0,Ee=[],Se=[],De=[],_s=rn(),We=rn(),_e(Ee),tn.publish("buildDocument"),Va(),Ms(),function(){tn.publish("putAdditionalObjects");for(var is=0;is"),Oe("/O <"+Co.toHexString(Co.O)+">"),Oe("/P "+Co.P),Oe(">>"),Oe("endobj")),ur(),ao();var yt=Le;return So(),fo(),Oe("startxref"),Oe(""+yt),Oe("%%EOF"),_e(Be[we]),Ee.join(` `)},Gr=p.__private__.getBlob=function($e){return new Blob([Xe($e)],{type:"application/pdf"})},Qn=function($e){for(;$e.firstChild;)$e.removeChild($e.firstChild)},qa=function($e){var yt,is=$e.document,us=is.documentElement,en=is.head,Dn=is.body;return en||(en=is.createElement("head"),us.appendChild(en)),Dn||(Dn=is.createElement("body"),us.appendChild(Dn)),Qn(en),Qn(Dn),(yt=is.createElement("style")).appendChild(is.createTextNode("html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}")),en.appendChild(yt),{document:is,body:Dn}},xo=p.output=p.__private__.output=(mr=function($e,yt){switch(typeof(yt=yt||{})=="string"?yt={filename:yt}:yt.filename=yt.filename||"generated.pdf",$e){case void 0:return $a();case"save":p.save(yt.filename);break;case"arraybuffer":return Xe($a());case"blob":return Gr($a());case"bloburi":case"bloburl":if(wl.URL!==void 0&&typeof wl.URL.createObjectURL=="function")return wl.URL&&wl.URL.createObjectURL(Gr($a()))||void 0;gh.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.");break;case"datauristring":case"dataurlstring":var is="",us=$a();try{is=rxt(us)}catch{is=rxt(unescape(encodeURIComponent(us)))}return"data:application/pdf;filename="+encodeURIComponent(yt.filename)+";base64,"+is;case"pdfobjectnewwindow":if(Object.prototype.toString.call(wl)==="[object Window]"){var en="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",Dn=!yt.pdfObjectUrl;Dn||(en=yt.pdfObjectUrl);var er=wl.open();if(er!==null){var xr=qa(er),Ha=xr.document.createElement("script"),Zi=this;Ha.src=en,Dn&&(Ha.integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==",Ha.crossOrigin="anonymous"),Ha.onload=function(){er.PDFObject.embed(Zi.output("dataurlstring"),yt)},xr.body.appendChild(Ha)}return er}throw new Error("The option pdfobjectnewwindow just works in a browser-environment.");case"pdfjsnewwindow":if(Object.prototype.toString.call(wl)==="[object Window]"){var Hi=yt.pdfJsUrl||"examples/PDF.js/web/viewer.html",rl=wl.open();if(rl!==null){var Dc=qa(rl),Lr=Dc.document.createElement("iframe"),ti=Hi.indexOf("?")===-1?"?":"&";Zi=this,Lr.id="pdfViewer",Lr.width="500px",Lr.height="400px",Lr.src=Hi+ti+"file=&downloadName="+encodeURIComponent(yt.filename),Lr.onload=function(){rl.document.title=yt.filename,Lr.contentWindow.PDFViewerApplication.open(Zi.output("bloburl"))},Dc.body.appendChild(Lr)}return rl}throw new Error("The option pdfjsnewwindow just works in a browser-environment.");case"dataurlnewwindow":if(Object.prototype.toString.call(wl)!=="[object Window]")throw new Error("The option dataurlnewwindow just works in a browser-environment.");var ui=wl.open();if(ui!==null){var Rl=qa(ui),bc=Rl.document.createElement("iframe");bc.src=this.output("datauristring",yt),Rl.body.appendChild(bc),ui.document.title=yt.filename}if(ui||typeof safari>"u")return ui;break;case"datauri":case"dataurl":return wl.document.location.href=this.output("datauristring",yt);default:return null}},mr.foo=function(){try{return mr.apply(this,arguments)}catch(is){var $e=is.stack||"";~$e.indexOf(" at ")&&($e=$e.split(" at ")[1]);var yt="Error in function "+$e.split(` `)[0].split("<")[0]+": "+is.message;if(!wl.console)throw new Error(yt);wl.console.error(yt,is),wl.alert&&alert(yt)}},mr.foo.bar=mr,mr.foo),Wo=function($e){return Array.isArray(_n)===!0&&_n.indexOf($e)>-1};switch(r){case"pt":qs=1;break;case"mm":qs=72/25.4;break;case"cm":qs=72/2.54;break;case"in":qs=72;break;case"px":qs=Wo("px_scaling")==1?.75:96/72;break;case"pc":case"em":qs=12;break;case"ex":qs=6;break;default:if(typeof r!="number")throw new Error("Invalid unit: "+r);qs=r}var Co=null;ie(),le();var Ko=p.__private__.getPageInfo=p.getPageInfo=function($e){if(isNaN($e)||$e%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfo");return{objId:nn[$e].objId,pageNumber:$e,pageContext:nn[$e]}},Ud=p.__private__.getPageInfoByObjId=function($e){if(isNaN($e)||$e%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");for(var yt in nn)if(nn[yt].objId===$e)break;return Ko(yt)},Mu=p.__private__.getCurrentPageInfo=p.getCurrentPageInfo=function(){return{objId:nn[we].objId,pageNumber:we,pageContext:nn[we]}};p.addPage=function(){return Zn.apply(this,arguments),this},p.setPage=function(){return zr.apply(this,arguments),_e.call(this,Be[we]),this},p.insertPage=function($e){return this.addPage(),this.movePage(we,$e),this},p.movePage=function($e,yt){var is,us;if($e>yt){is=Be[$e],us=nn[$e];for(var en=$e;en>yt;en--)Be[en]=Be[en-1],nn[en]=nn[en-1];Be[yt]=is,nn[yt]=us,this.setPage(yt)}else if($e0&&(typeof $e=="string"?$e=ti.splitTextToSize($e,Hi):Object.prototype.toString.call($e)==="[object Array]"&&($e=$e.reduce(function(Yo,$o){return Yo.concat(ti.splitTextToSize($o,Hi))},[]))),Dn={text:$e,x:yt,y:is,options:us,mutex:{pdfEscape:Xr,activeFontKey:Gt,fonts:Is,activeFontSize:Ze}},tn.publish("preProcessText",Dn),$e=Dn.text,xr=(us=Dn.options).angle,Lr instanceof jr==0&&xr&&typeof xr=="number"){xr*=Math.PI/180,us.rotationDirection===0&&(xr=-xr),C===k&&(xr=-xr);var yy=Math.cos(xr),ad=Math.sin(xr);Lr=new jr(yy,ad,-ad,yy,0,0)}else xr&&xr instanceof jr&&(Lr=xr);C!==k||Lr||(Lr=Ba),(Zi=us.charSpace||Yh)!==void 0&&(bc+=L(W(Zi))+` Tc `,this.setCharSpace(this.getCharSpace()||0)),(Dc=us.horizontalScale)!==void 0&&(bc+=L(100*Dc)+` Tz `),us.lang;var gd=-1,Lu=us.renderingMode!==void 0?us.renderingMode:us.stroke,jm=ti.internal.getCurrentPageInfo().pageContext;switch(Lu){case 0:case!1:case"fill":gd=0;break;case 1:case!0:case"stroke":gd=1;break;case 2:case"fillThenStroke":gd=2;break;case 3:case"invisible":gd=3;break;case 4:case"fillAndAddForClipping":gd=4;break;case 5:case"strokeAndAddPathForClipping":gd=5;break;case 6:case"fillThenStrokeAndAddToPathForClipping":gd=6;break;case 7:case"addToPathForClipping":gd=7}var Lf=jm.usedRenderingMode!==void 0?jm.usedRenderingMode:-1;gd!==-1?bc+=gd+` Tr `:Lf!==-1&&(bc+=`0 Tr `),gd!==-1&&(jm.usedRenderingMode=gd),Ha=us.align||"left";var yl,ka=Ze*Gi,Ir=ti.internal.pageSize.getWidth(),Fl=Is[Gt];Zi=us.charSpace||Yh,Hi=us.maxWidth||0,rl=Object.assign({autoencode:!0,noBOM:!0},us.flags);var Sa=[],Nm=function(Yo){return ti.getStringUnitWidth(Yo,{font:Fl,charSpace:Zi,fontSize:Ze,doKerning:!1})*Ze/Qh};if(Object.prototype.toString.call($e)==="[object Array]"){var id;er=jg($e),Ha!=="left"&&(yl=er.map(Nm));var la,Ox=0;if(Ha==="right"){yt-=yl[0],$e=[],Hd=er.length;for(var Ng=0;Ng0?(Hi-yl[Oc])/dp:0;Oc":")"),_c=parseFloat(er[gu][1]),Fx=parseFloat(er[gu][2]);break;case 0:_0=(Rl?"<":"(")+er[gu]+(Rl?">":")"),_c=tp(yt),Fx=Cd(is)}Sa!==void 0&&Sa[gu]!==void 0&&(If=Sa[gu]+` Tw `),gu===0?$e.push(If+_1(_c,Fx,Lr)+_0):dh===0?$e.push(If+_0):dh===1&&$e.push(If+_1(_c,Fx,Lr)+_0)}$e=dh===0?$e.join(` Tj T* `):$e.join(` Tj `),$e+=` Tj `;var zl=`BT /`;return zl+=Gt+" "+Ze+` Tf `,zl+=L(Ze*Gi)+` TL `,zl+=np+` `,zl+=bc,zl+=$e,Oe(zl+="ET"),m[Gt]=!0,ti};var Qm=p.__private__.clip=p.clip=function($e){return Oe($e==="evenodd"?"W*":"W"),this};p.clipEvenOdd=function(){return Qm("evenodd")},p.__private__.discardPath=p.discardPath=function(){return Oe("n"),this};var Gc=p.__private__.isValidStyle=function($e){var yt=!1;return[void 0,null,"S","D","F","DF","FD","f","f*","B","B*","n"].indexOf($e)!==-1&&(yt=!0),yt};p.__private__.setDefaultPathOperation=p.setDefaultPathOperation=function($e){return Gc($e)&&(d=$e),this};var lh=p.__private__.getStyle=p.getStyle=function($e){var yt=d;switch($e){case"D":case"S":yt="S";break;case"F":yt="f";break;case"FD":case"DF":yt="B";break;case"f":case"f*":case"B":case"B*":yt=$e}return yt},qd=p.close=function(){return Oe("h"),this};p.stroke=function(){return Oe("S"),this},p.fill=function($e){return Wc("f",$e),this},p.fillEvenOdd=function($e){return Wc("f*",$e),this},p.fillStroke=function($e){return Wc("B",$e),this},p.fillStrokeEvenOdd=function($e){return Wc("B*",$e),this};var Wc=function($e,yt){Gu(yt)==="object"?Jm(yt,$e):Oe($e)},Kh=function($e){$e===null||C===k&&$e===void 0||($e=lh($e),Oe($e))};function zb($e,yt,is,us,en){var Dn=new _9(yt||this.boundingBox,is||this.xStep,us||this.yStep,this.gState,en||this.matrix);Dn.stream=this.stream;var er=$e+"$$"+this.cloneIndex+++"$$";return Hr(er,Dn),Dn}var Jm=function($e,yt){var is=qt[$e.key],us=cn[is];if(us instanceof KI)Oe("q"),Oe(xy(yt)),us.gState&&p.setGState(us.gState),Oe($e.matrix.toString()+" cm"),Oe("/"+is+" sh"),Oe("Q");else if(us instanceof _9){var en=new jr(1,0,0,-1,0,Xh());$e.matrix&&(en=en.multiply($e.matrix||Ba),is=zb.call(us,$e.key,$e.boundingBox,$e.xStep,$e.yStep,en).id),Oe("q"),Oe("/Pattern cs"),Oe("/"+is+" scn"),us.gState&&p.setGState(us.gState),Oe(yt),Oe("Q")}},xy=function($e){switch($e){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"}},Ef=p.moveTo=function($e,yt){return Oe(L(W($e))+" "+L(G(yt))+" m"),this},Mf=p.lineTo=function($e,yt){return Oe(L(W($e))+" "+L(G(yt))+" l"),this},pu=p.curveTo=function($e,yt,is,us,en,Dn){return Oe([L(W($e)),L(G(yt)),L(W(is)),L(G(us)),L(W(en)),L(G(Dn)),"c"].join(" ")),this};p.__private__.line=p.line=function($e,yt,is,us,en){if(isNaN($e)||isNaN(yt)||isNaN(is)||isNaN(us)||!Gc(en))throw new Error("Invalid arguments passed to jsPDF.line");return C===v?this.lines([[is-$e,us-yt]],$e,yt,[1,1],en||"S"):this.lines([[is-$e,us-yt]],$e,yt,[1,1]).stroke()},p.__private__.lines=p.lines=function($e,yt,is,us,en,Dn){var er,xr,Ha,Zi,Hi,rl,Dc,Lr,ti,ui,Rl,bc;if(typeof $e=="number"&&(bc=is,is=yt,yt=$e,$e=bc),us=us||[1,1],Dn=Dn||!1,isNaN(yt)||isNaN(is)||!Array.isArray($e)||!Array.isArray(us)||!Gc(en)||typeof Dn!="boolean")throw new Error("Invalid arguments passed to jsPDF.lines");for(Ef(yt,is),er=us[0],xr=us[1],Zi=$e.length,ui=yt,Rl=is,Ha=0;Ha>8&255,s>>16&255,s>>24&255)},D7.prototype.toHexString=function(s){return s.split("").map(function(t){return("0"+(255&t.charCodeAt(0)).toString(16)).slice(-2)}).join("")},D7.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 eze(n,r)}},vSe.prototype.equals=function(s){var t,n="id,objectNumber,equals";if(!s||Gu(s)!==Gu(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},ho.API={events:[]},ho.version="4.2.1";var df=ho.API,LKe=1,OO=function(s){return s.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},o7=function(s){return s.replace(/\\\\/g,"\\").replace(/\\\(/g,"(").replace(/\\\)/g,")")},tO=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)})},Dl=function(s){return s.toFixed(2)},zC=function(s){return s.toFixed(5)};df.__acroform__={};var Fb=function(s,t){s.prototype=Object.create(t.prototype),s.prototype.constructor=s},lxt=function(s){return s*LKe},Lk=function(s){var t=new GFt,n=to.internal.getHeight(s)||0,r=to.internal.getWidth(s)||0;return t.BBox=[0,0,Number(Dl(r)),Number(Dl(n))],t},Cwn=df.__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=tre("3",s,i).height,m=s.multiline?l-i:(l-h)/2,p=m+=2,x=0,y=0,g=0;if(i<=0){t=`(...) Tj `,t+="% Width of Text: "+tre(t,s,i=12).width+", FieldWidth:"+o+` `;break}for(var b="",v=0,k=0;kl)continue e;b+=a[k][g],C=!0,y=k,k--}else{b=(b+=a[k][g]+" ").substr(b.length-1)==" "?b.substr(0,b.length-1):b;var T=parseInt(k),M=c(T,b,i),P=k>=a.length-1;if(M&&!P){b+=" ",g=0;continue}if(M||P){if(P)y=T;else if(s.multiline&&(h+2)*(v+2)+2>l)continue e}else{if(!s.multiline||(h+2)*(v+2)+2>l)continue e;y=T}}for(var L="",I=x;I<=y;I++){var O=a[I];if(s.multiline){if(I===y){L+=O[g]+" ",g=(g+1)%O.length;continue}if(I===x){L+=O[O.length-1]+" ";continue}}L+=O[0]+" "}switch(L=L.substr(L.length-1)==" "?L.substr(0,L.length-1):L,u=tre(L,s,i).width,s.textAlign){case"right":d=o-u-2;break;case"center":d=(o-u)/2;break;default:d=2}t+=Dl(d)+" "+Dl(p)+` Td `,t+="("+OO(L)+`) Tj `,t+=-Dl(d)+` 0 Td `,p=-(i+2),u=0,x=C?y:y+1,v++,b=""}break}return r.text=t,r.fontSize=i,r},tre=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}},Lwn={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},Pwn=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)},Iwn=function(s,t){if(t.scope=s,s.internal!==void 0&&(s.internal.acroformPlugin===void 0||s.internal.acroformPlugin.isInitialized===!1)){if(HN.FieldNum=0,s.internal.acroformPlugin=JSON.parse(JSON.stringify(Lwn)),s.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");LKe=s.internal.scaleFactor,s.internal.acroformPlugin.acroFormDictionaryRoot=new WFt,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&&Pwn(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=Ewn(o.Rect,a)),a.internal.newObjectDeferredBegin(o.objId,!0),o.DA=to.createDefaultAppearanceStream(o),Gu(o)==="object"&&typeof o.getKeyValueListForStream=="function"&&(c=o.getKeyValueListForStream()),o.Rect=d,o.hasAppearanceStream&&!o.appearanceStreamContent){var u=Mwn(o);c.push({key:"AP",value:"<>"}),a.internal.acroformPlugin.xForms.push(u)}if(o.appearanceStreamContent){var h="";for(var m in o.appearanceStreamContent)if(o.appearanceStreamContent.hasOwnProperty(m)){var p=o.appearanceStreamContent[m];if(h+="/"+m+" ",h+="<<",Object.keys(p).length>=1||Array.isArray(p)){for(var l in p)if(p.hasOwnProperty(l)){var x=p[l];typeof x=="function"&&(x=x.call(a,o)),h+="/"+l+" "+x+" ",a.internal.acroformPlugin.xForms.indexOf(x)>=0||a.internal.acroformPlugin.xForms.push(x)}}else typeof(x=p)=="function"&&(x=x.call(a,o)),h+="/"+l+" "+x,a.internal.acroformPlugin.xForms.indexOf(x)>=0||a.internal.acroformPlugin.xForms.push(x);h+=">>"}c.push({key:"AP",value:`<< `+h+">>"})}a.internal.putStream({additionalKeyValues:c,objectId:o.objId}),a.internal.out("endobj")}i&&function(y,g){for(var b in y)if(y.hasOwnProperty(b)){var v=b,k=y[b];g.internal.newObjectDeferredBegin(k.objId,!0),Gu(k)==="object"&&typeof k.putStream=="function"&&k.putStream(),delete y[v]}}(a.internal.acroformPlugin.xForms,a)})(n,s)}),s.internal.acroformPlugin.isInitialized=!0}},HFt=df.__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)),"("+OO(n(s))+")"}},set:function(n){s=n}})};Fb(WFt,k5);var HN=function s(){k5.call(this);var t=4;Object.defineProperty(this,"F",{enumerable:!1,configurable:!1,get:function(){return t},set:function(b){if(isNaN(b))throw new Error('Invalid value "'+b+'" for attribute F supplied.');t=b}}),Object.defineProperty(this,"showWhenPrinted",{enumerable:!0,configurable:!0,get:function(){return!!Hf(t,3)},set:function(b){b?this.F=Gf(t,3):this.F=Wf(t,3)}});var n=0;Object.defineProperty(this,"Ff",{enumerable:!1,configurable:!1,get:function(){return n},set:function(b){if(isNaN(b))throw new Error('Invalid value "'+b+'" for attribute Ff supplied.');n=b}});var r=[];Object.defineProperty(this,"Rect",{enumerable:!1,configurable:!1,get:function(){if(r.length!==0)return r},set:function(b){r=b!==void 0?b:[]}}),Object.defineProperty(this,"x",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[0])?0:r[0]},set:function(b){r[0]=b}}),Object.defineProperty(this,"y",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[1])?0:r[1]},set:function(b){r[1]=b}}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[2])?0:r[2]},set:function(b){r[2]=b}}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[3])?0:r[3]},set:function(b){r[3]=b}});var a="";Object.defineProperty(this,"FT",{enumerable:!0,configurable:!1,get:function(){return a},set:function(b){switch(b){case"/Btn":case"/Tx":case"/Ch":case"/Sig":a=b;break;default:throw new Error('Invalid value "'+b+'" for attribute FT supplied.')}}});var i=null;Object.defineProperty(this,"T",{enumerable:!0,configurable:!1,get:function(){if(!i||i.length<1){if(this instanceof bSe)return;i="FieldObject"+s.FieldNum++}var b=function(v){return v};return this.scope&&(b=this.scope.internal.getEncryptor(this.objId)),"("+OO(b(i))+")"},set:function(b){i=b.toString()}}),Object.defineProperty(this,"fieldName",{configurable:!0,enumerable:!0,get:function(){return i},set:function(b){i=b}});var l="helvetica";Object.defineProperty(this,"fontName",{enumerable:!0,configurable:!0,get:function(){return l},set:function(b){l=b}});var o="normal";Object.defineProperty(this,"fontStyle",{enumerable:!0,configurable:!0,get:function(){return o},set:function(b){o=b}});var c=0;Object.defineProperty(this,"fontSize",{enumerable:!0,configurable:!0,get:function(){return c},set:function(b){c=b}});var d=void 0;Object.defineProperty(this,"maxFontSize",{enumerable:!0,configurable:!0,get:function(){return d===void 0?50/LKe:d},set:function(b){d=b}});var u="black";Object.defineProperty(this,"color",{enumerable:!0,configurable:!0,get:function(){return u},set:function(b){u=b}});var h="/F1 0 Tf 0 g";Object.defineProperty(this,"DA",{enumerable:!0,configurable:!1,get:function(){if(!(!h||this instanceof bSe||this instanceof fD))return MIe(h,this.objId,this.scope)},set:function(b){b=b.toString(),h=b}});var m=null;Object.defineProperty(this,"DV",{enumerable:!1,configurable:!1,get:function(){if(m)return this instanceof Zg==0?MIe(m,this.objId,this.scope):m},set:function(b){b=b.toString(),m=this instanceof Zg==0?b.substr(0,1)==="("?o7(b.substr(1,b.length-2)):o7(b):b}}),Object.defineProperty(this,"defaultValue",{enumerable:!0,configurable:!0,get:function(){return this instanceof Zg==1?o7(m.substr(1,m.length-1)):m},set:function(b){b=b.toString(),m=this instanceof Zg==1?"/"+tO(b):b}});var p=null;Object.defineProperty(this,"_V",{enumerable:!1,configurable:!1,get:function(){if(p)return p},set:function(b){this.V=b}}),Object.defineProperty(this,"V",{enumerable:!1,configurable:!1,get:function(){if(p)return this instanceof Zg==0?MIe(p,this.objId,this.scope):p},set:function(b){b=b.toString(),p=this instanceof Zg==0?b.substr(0,1)==="("?o7(b.substr(1,b.length-2)):o7(b):b}}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,get:function(){return this instanceof Zg==1?o7(p.substr(1,p.length-1)):p},set:function(b){b=b.toString(),p=this instanceof Zg==1?"/"+tO(b):b}}),Object.defineProperty(this,"hasAnnotation",{enumerable:!0,configurable:!0,get:function(){return this.Rect}}),Object.defineProperty(this,"Type",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Annot":null}}),Object.defineProperty(this,"Subtype",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Widget":null}});var x,y=!1;Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return y},set:function(b){b=!!b,y=b}}),Object.defineProperty(this,"page",{enumerable:!0,configurable:!0,get:function(){if(x)return x},set:function(b){x=b}}),Object.defineProperty(this,"readOnly",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,1)},set:function(b){b?this.Ff=Gf(this.Ff,1):this.Ff=Wf(this.Ff,1)}}),Object.defineProperty(this,"required",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,2)},set:function(b){b?this.Ff=Gf(this.Ff,2):this.Ff=Wf(this.Ff,2)}}),Object.defineProperty(this,"noExport",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,3)},set:function(b){b?this.Ff=Gf(this.Ff,3):this.Ff=Wf(this.Ff,3)}});var g=null;Object.defineProperty(this,"Q",{enumerable:!0,configurable:!1,get:function(){if(g!==null)return g},set:function(b){if([0,1,2].indexOf(b)===-1)throw new Error('Invalid value "'+b+'" for attribute Q supplied.');g=b}}),Object.defineProperty(this,"textAlign",{get:function(){var b;switch(g){case 0:default:b="left";break;case 1:b="center";break;case 2:b="right"}return b},configurable:!0,enumerable:!0,set:function(b){switch(b){case"right":case 2:g=2;break;case"center":case 1:g=1;break;default:g=0}}})};Fb(HN,k5);var Dz=function(){HN.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 HFt(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!!Hf(this.Ff,18)},set:function(n){n?this.Ff=Gf(this.Ff,18):this.Ff=Wf(this.Ff,18)}}),Object.defineProperty(this,"edit",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,19)},set:function(n){this.combo===!0&&(n?this.Ff=Gf(this.Ff,19):this.Ff=Wf(this.Ff,19))}}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,20)},set:function(n){n?(this.Ff=Gf(this.Ff,20),t.sort()):this.Ff=Wf(this.Ff,20)}}),Object.defineProperty(this,"multiSelect",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,22)},set:function(n){n?this.Ff=Gf(this.Ff,22):this.Ff=Wf(this.Ff,22)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,23)},set:function(n){n?this.Ff=Gf(this.Ff,23):this.Ff=Wf(this.Ff,23)}}),Object.defineProperty(this,"commitOnSelChange",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,27)},set:function(n){n?this.Ff=Gf(this.Ff,27):this.Ff=Wf(this.Ff,27)}}),this.hasAppearanceStream=!1};Fb(Dz,HN);var Oz=function(){Dz.call(this),this.fontName="helvetica",this.combo=!1};Fb(Oz,Dz);var Fz=function(){Oz.call(this),this.combo=!0};Fb(Fz,Oz);var Vje=function(){Fz.call(this),this.edit=!0};Fb(Vje,Fz);var Zg=function(){HN.call(this),this.FT="/Btn",Object.defineProperty(this,"noToggleToOff",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,15)},set:function(n){n?this.Ff=Gf(this.Ff,15):this.Ff=Wf(this.Ff,15)}}),Object.defineProperty(this,"radio",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,16)},set:function(n){n?this.Ff=Gf(this.Ff,16):this.Ff=Wf(this.Ff,16)}}),Object.defineProperty(this,"pushButton",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,17)},set:function(n){n?this.Ff=Gf(this.Ff,17):this.Ff=Wf(this.Ff,17)}}),Object.defineProperty(this,"radioIsUnison",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,26)},set:function(n){n?this.Ff=Gf(this.Ff,26):this.Ff=Wf(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+" ("+OO(n(t[r]))+")");return a.push(">>"),a.join(` `)}},set:function(n){Gu(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="/"+tO(r)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return s.substr(1,s.length-1)},set:function(n){s="/"+tO(n)}})};Fb(Zg,HN);var Hje=function(){Zg.call(this),this.pushButton=!0};Fb(Hje,Zg);var zz=function(){Zg.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:[]}})};Fb(zz,Zg);var bSe=function(){var s,t;HN.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+" ("+OO(a(r[i]))+")");return l.push(">>"),l.join(` `)},set:function(a){Gu(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="/"+tO(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="/"+tO(i)}}),this.caption="l",this.appearanceState="Off",this._AppearanceType=to.RadioButton.Circle,this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(this.optionName)};Fb(bSe,HN),zz.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()}},zz.prototype.createOption=function(s){var t=new bSe;return t.Parent=this,t.optionName=s,this.Kids.push(t),Rwn.call(this.scope,t),t};var Gje=function(){Zg.call(this),this.fontName="zapfdingbats",this.caption="3",this.appearanceState="On",this.value="On",this.textAlign="center",this.appearanceStreamContent=to.CheckBox.createAppearanceStream()};Fb(Gje,Zg);var fD=function(){HN.call(this),this.FT="/Tx",Object.defineProperty(this,"multiline",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,13)},set:function(t){t?this.Ff=Gf(this.Ff,13):this.Ff=Wf(this.Ff,13)}}),Object.defineProperty(this,"fileSelect",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,21)},set:function(t){t?this.Ff=Gf(this.Ff,21):this.Ff=Wf(this.Ff,21)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,23)},set:function(t){t?this.Ff=Gf(this.Ff,23):this.Ff=Wf(this.Ff,23)}}),Object.defineProperty(this,"doNotScroll",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,24)},set:function(t){t?this.Ff=Gf(this.Ff,24):this.Ff=Wf(this.Ff,24)}}),Object.defineProperty(this,"comb",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,25)},set:function(t){t?this.Ff=Gf(this.Ff,25):this.Ff=Wf(this.Ff,25)}}),Object.defineProperty(this,"richText",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,26)},set:function(t){t?this.Ff=Gf(this.Ff,26):this.Ff=Wf(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}})};Fb(fD,HN);var Wje=function(){fD.call(this),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,get:function(){return!!Hf(this.Ff,14)},set:function(s){s?this.Ff=Gf(this.Ff,14):this.Ff=Wf(this.Ff,14)}}),this.password=!0};Fb(Wje,fD);var to={CheckBox:{createAppearanceStream:function(){return{N:{On:to.CheckBox.YesNormal},D:{On:to.CheckBox.YesPushDown,Off:to.CheckBox.OffPushDown}}},YesPushDown:function(s){var t=Lk(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=tze(s,s.caption);return n.push("0.749023 g"),n.push("0 0 "+Dl(to.internal.getWidth(s))+" "+Dl(to.internal.getHeight(s))+" re"),n.push("f"),n.push("BMC"),n.push("q"),n.push("0 0 1 rg"),n.push("/"+r+" "+Dl(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=Lk(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=to.internal.getHeight(s),l=to.internal.getWidth(s),o=tze(s,s.caption);return a.push("1 g"),a.push("0 0 "+Dl(l)+" "+Dl(i)+" re"),a.push("f"),a.push("q"),a.push("0 0 1 rg"),a.push("0 0 "+Dl(l-1)+" "+Dl(i-1)+" re"),a.push("W"),a.push("n"),a.push("0 g"),a.push("BT"),a.push("/"+n+" "+Dl(o.fontSize)+" Tf "+r),a.push(o.text),a.push("ET"),a.push("Q"),t.stream=a.join(` `),t},OffPushDown:function(s){var t=Lk(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Dl(to.internal.getWidth(s))+" "+Dl(to.internal.getHeight(s))+" re"),n.push("f"),t.stream=n.join(` `),t}},RadioButton:{Circle:{createAppearanceStream:function(s){var t={D:{Off:to.RadioButton.Circle.OffPushDown},N:{}};return t.N[s]=to.RadioButton.Circle.YesNormal,t.D[s]=to.RadioButton.Circle.YesPushDown,t},getCA:function(){return"l"},YesNormal:function(s){var t=Lk(s);t.scope=s.scope;var n=[],r=to.internal.getWidth(s)<=to.internal.getHeight(s)?to.internal.getWidth(s)/4:to.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=to.internal.Bezier_C,i=Number((r*a).toFixed(5));return n.push("q"),n.push("1 0 0 1 "+zC(to.internal.getWidth(s)/2)+" "+zC(to.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=Lk(s);t.scope=s.scope;var n=[],r=to.internal.getWidth(s)<=to.internal.getHeight(s)?to.internal.getWidth(s)/4:to.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*to.internal.Bezier_C).toFixed(5)),l=Number((r*to.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+zC(to.internal.getWidth(s)/2)+" "+zC(to.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 "+zC(to.internal.getWidth(s)/2)+" "+zC(to.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=Lk(s);t.scope=s.scope;var n=[],r=to.internal.getWidth(s)<=to.internal.getHeight(s)?to.internal.getWidth(s)/4:to.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*to.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+zC(to.internal.getWidth(s)/2)+" "+zC(to.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:to.RadioButton.Cross.OffPushDown},N:{}};return t.N[s]=to.RadioButton.Cross.YesNormal,t.D[s]=to.RadioButton.Cross.YesPushDown,t},getCA:function(){return"8"},YesNormal:function(s){var t=Lk(s);t.scope=s.scope;var n=[],r=to.internal.calculateCross(s);return n.push("q"),n.push("1 1 "+Dl(to.internal.getWidth(s)-2)+" "+Dl(to.internal.getHeight(s)-2)+" re"),n.push("W"),n.push("n"),n.push(Dl(r.x1.x)+" "+Dl(r.x1.y)+" m"),n.push(Dl(r.x2.x)+" "+Dl(r.x2.y)+" l"),n.push(Dl(r.x4.x)+" "+Dl(r.x4.y)+" m"),n.push(Dl(r.x3.x)+" "+Dl(r.x3.y)+" l"),n.push("s"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=Lk(s);t.scope=s.scope;var n=to.internal.calculateCross(s),r=[];return r.push("0.749023 g"),r.push("0 0 "+Dl(to.internal.getWidth(s))+" "+Dl(to.internal.getHeight(s))+" re"),r.push("f"),r.push("q"),r.push("1 1 "+Dl(to.internal.getWidth(s)-2)+" "+Dl(to.internal.getHeight(s)-2)+" re"),r.push("W"),r.push("n"),r.push(Dl(n.x1.x)+" "+Dl(n.x1.y)+" m"),r.push(Dl(n.x2.x)+" "+Dl(n.x2.y)+" l"),r.push(Dl(n.x4.x)+" "+Dl(n.x4.y)+" m"),r.push(Dl(n.x3.x)+" "+Dl(n.x3.y)+" l"),r.push("s"),r.push("Q"),t.stream=r.join(` `),t},OffPushDown:function(s){var t=Lk(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Dl(to.internal.getWidth(s))+" "+Dl(to.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}};to.internal={Bezier_C:.551915024494,calculateCross:function(s){var t=to.internal.getWidth(s),n=to.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}}}},to.internal.getWidth=function(s){var t=0;return Gu(s)==="object"&&(t=lxt(s.Rect[2])),t},to.internal.getHeight=function(s){var t=0;return Gu(s)==="object"&&(t=lxt(s.Rect[3])),t};var Rwn=df.addField=function(s){if(Iwn(this,s),!(s instanceof HN))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};df.AcroFormChoiceField=Dz,df.AcroFormListBox=Oz,df.AcroFormComboBox=Fz,df.AcroFormEditBox=Vje,df.AcroFormButton=Zg,df.AcroFormPushButton=Hje,df.AcroFormRadioButton=zz,df.AcroFormCheckBox=Gje,df.AcroFormTextField=fD,df.AcroFormPasswordField=Wje,df.AcroFormAppearance=to,df.AcroForm={ChoiceField:Dz,ListBox:Oz,ComboBox:Fz,EditBox:Vje,Button:Zg,PushButton:Hje,RadioButton:zz,CheckBox:Gje,TextField:fD,PasswordField:Wje,Appearance:to},ho.AcroForm={ChoiceField:Dz,ListBox:Oz,ComboBox:Fz,EditBox:Vje,Button:Zg,PushButton:Hje,RadioButton:zz,CheckBox:Gje,TextField:fD,PasswordField:Wje,Appearance:to};function KFt(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($,q){var W,G,K,ee,J,le=n;if((q=q||n)==="RGBA"||$.data!==void 0&&$.data instanceof Uint8ClampedArray&&"height"in $&&"width"in $)return"RGBA";if(M($))for(J in r)for(K=r[J],W=0;W>"}),"transparency"in q&&Array.isArray(q.transparency)&&q.transparency.length>0){for(var J="",le=0,ue=q.transparency.length;le>",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 g=0,b=n,v="",k=0;for(g=0;g>"),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}])}(ho.API),function(s){var t={left:0,top:0,bottom:0,right:0},n=!1,r=function(){this.internal.__cell__===void 0&&(this.internal.__cell__={},this.internal.__cell__.padding=3,this.internal.__cell__.headerFunction=void 0,this.internal.__cell__.margins=Object.assign({},t),this.internal.__cell__.margins.width=this.getPageWidth(),a.call(this))},a=function(){this.internal.__cell__.lastCell=new i,this.internal.__cell__.pages=1},i=function(){var c=arguments[0];Object.defineProperty(this,"x",{enumerable:!0,get:function(){return c},set:function(y){c=y}});var d=arguments[1];Object.defineProperty(this,"y",{enumerable:!0,get:function(){return d},set:function(y){d=y}});var u=arguments[2];Object.defineProperty(this,"width",{enumerable:!0,get:function(){return u},set:function(y){u=y}});var h=arguments[3];Object.defineProperty(this,"height",{enumerable:!0,get:function(){return h},set:function(y){h=y}});var m=arguments[4];Object.defineProperty(this,"text",{enumerable:!0,get:function(){return m},set:function(y){m=y}});var p=arguments[5];Object.defineProperty(this,"lineNumber",{enumerable:!0,get:function(){return p},set:function(y){p=y}});var x=arguments[6];return Object.defineProperty(this,"align",{enumerable:!0,get:function(){return x},set:function(y){x=y}}),this};i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align)},i.prototype.toArray=function(){return[this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align]},s.setHeaderFunction=function(c){return r.call(this),this.internal.__cell__.headerFunction=typeof c=="function"?c:void 0,this},s.getTextDimensions=function(c,d){r.call(this);var u=(d=d||{}).fontSize||this.getFontSize(),h=d.font||this.getFont(),m=d.scaleFactor||this.internal.scaleFactor,p=0,x=0,y=0,g=this;if(!Array.isArray(c)&&typeof c!="string"){if(typeof c!="number")throw new Error("getTextDimensions expects text-parameter to be of type String or type Number or an Array of Strings.");c=String(c)}var b=d.maxWidth;b>0?typeof c=="string"?c=this.splitTextToSize(c,b):Object.prototype.toString.call(c)==="[object Array]"&&(c=c.reduce(function(k,C){return k.concat(g.splitTextToSize(C,b))},[])):c=Array.isArray(c)?c:[c];for(var v=0;vthis.getPageHeight()?(this.cellAddPage(),c.y=h.top,p&&m&&(this.printHeaderRow(c.lineNumber,!0),c.y+=m[0].height)):c.y=d.y+d.height||c.y),c.text[0]!==void 0&&(this.rect(c.x,c.y,c.width,c.height,n===!0?"FD":void 0),c.align==="right"?this.text(c.text,c.x+c.width-u,c.y+u,{align:"right",baseline:"top"}):c.align==="center"?this.text(c.text,c.x+c.width/2,c.y+u,{align:"center",baseline:"top",maxWidth:c.width-u-u}):this.text(c.text,c.x+u,c.y+u,{align:"left",baseline:"top",maxWidth:c.width-u-u})),this.internal.__cell__.lastCell=c,this};s.table=function(c,d,u,h,m){if(r.call(this),!u)throw new Error("No data for PDF table.");var p,x,y,g,b=[],v=[],k=[],C={},T={},M=[],P=[],L=(m=m||{}).autoSize||!1,I=m.printHeaders!==!1,O=m.css&&m.css["font-size"]!==void 0?16*m.css["font-size"]:m.fontSize||12,$=m.margins||Object.assign({width:this.getPageWidth()},t),q=typeof m.padding=="number"?m.padding:3,W=m.headerBackgroundColor||"#c8c8c8",G=m.headerTextColor||"#000";if(a.call(this),this.internal.__cell__.printHeaders=I,this.internal.__cell__.margins=$,this.internal.__cell__.table_font_size=O,this.internal.__cell__.padding=q,this.internal.__cell__.headerBackgroundColor=W,this.internal.__cell__.headerTextColor=G,this.setFontSize(O),h==null)v=b=Object.keys(u[0]),k=b.map(function(){return"left"});else if(Array.isArray(h)&&Gu(h[0])==="object")for(b=h.map(function(oe){return oe.name}),v=h.map(function(oe){return oe.prompt||oe.name||""}),k=h.map(function(oe){return oe.align||"left"}),p=0;p0&&this.setTableHeaderRow(m),this.setFont(void 0,"normal"),n=!1}}(ho.API);var YFt={italic:["italic","oblique","normal"],oblique:["oblique","italic","normal"],normal:["normal","oblique","italic"]},ZFt=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],sze=KFt(ZFt),XFt=[100,200,300,400,500,600,700,800,900],Dwn=KFt(XFt);function LIe(s){var t=s.family.replace(/"|'/g,"").toLowerCase(),n=function(i){return YFt[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 sze[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 cxt(s,t,n,r){var a;for(a=n;a>=0&&a=0&&a>>1)&255}return a}function bxt(s,t,n){var r=s.length,a=[];a[0]=4;for(var i=0;i>i&l}function _xt(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,QFt(s,i)&~(o<>7,l=1<<1+(7&a);s[t++],s[t++];var o=null,c=null;i&&(o=t,c=l,t+=3*l);var d=!0,u=[],h=0,m=null,p=0,x=null;for(this.width=n,this.height=r;d&&t=0))throw Error("Invalid block size");if($===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),p=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 g=s[t++]|s[t++]<<8,b=s[t++]|s[t++]<<8,v=s[t++]|s[t++]<<8,k=s[t++]|s[t++]<<8,C=s[t++],T=C>>6&1,M=1<<1+(7&C),P=o,L=c,I=!1;C>>7&&(I=!0,P=t,L=M,t+=3*M);var O=t;for(t++;;){var $;if(!(($=s[t++])>=0))throw Error("Invalid block size");if($===0)break;t+=$}u.push({x:g,y:b,width:v,height:k,has_local_palette:I,palette_offset:P,palette_size:L,data_offset:O,data_length:t-O,transparent_index:m,interlaced:!!T,delay:h,disposal:p});break;case 59:d=!1;break;default:throw new Error("Unknown gif block: 0x"+s[t-1].toString(16))}this.numFrames=function(){return u.length},this.loopCount=function(){return x},this.frameInfo=function(q){if(q<0||q>=u.length)throw new Error("Frame index out of range.");return u[q]},this.decodeAndBlitFrameBGRA=function(q,W){var G=this.frameInfo(q),K=G.width*G.height;if(K>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var ee=new Uint8Array(K);wxt(s,G.data_offset,ee,K);var J=G.palette_offset,le=G.transparent_index;le===null&&(le=256);var ue=G.width,oe=n-ue,ie=ue,de=4*(G.y*n+G.x),we=4*((G.y+G.height)*n+G.x),je=de,xe=4*oe;G.interlaced===!0&&(xe+=4*n*7);for(var fe=8,Se=0,Ee=ee.length;Se=we&&(xe=4*oe+4*n*(fe-1),je=de+(ue+oe)*(fe<<1),fe>>=1)),Le===le)je+=4;else{var De=s[J+3*Le],Be=s[J+3*Le+1],Ne=s[J+3*Le+2];W[je++]=Ne,W[je++]=Be,W[je++]=De,W[je++]=255}--ie}},this.decodeAndBlitFrameRGBA=function(q,W){var G=this.frameInfo(q),K=G.width*G.height;if(K>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var ee=new Uint8Array(K);wxt(s,G.data_offset,ee,K);var J=G.palette_offset,le=G.transparent_index;le===null&&(le=256);var ue=G.width,oe=n-ue,ie=ue,de=4*(G.y*n+G.x),we=4*((G.y+G.height)*n+G.x),je=de,xe=4*oe;G.interlaced===!0&&(xe+=4*n*7);for(var fe=8,Se=0,Ee=ee.length;Se=we&&(xe=4*oe+4*n*(fe-1),je=de+(ue+oe)*(fe<<1),fe>>=1)),Le===le)je+=4;else{var De=s[J+3*Le],Be=s[J+3*Le+1],Ne=s[J+3*Le+2];W[je++]=De,W[je++]=Be,W[je++]=Ne,W[je++]=255}--ie}}}function wxt(s,t,n,r){for(var a=s[t++],i=1<>=c,u-=c,g!==i){if(g===l)break;for(var b=gi;)k=x[k]>>8,++v;var C=k;if(m+v+(b!==g?1:0)>r)return void gh.log("Warning, gif stream longer than expected.");n[m++]=C;var T=m+=v;for(b!==g&&(n[m++]=C),k=b;v--;)k=x[k],n[--T]=255&k,k>>=8;y!==null&&o<4096&&(x[o++]=y<<8|C,o>=d+1&&c<12&&(++c,d=d<<1|1)),y=g}else o=l+1,d=(1<<(c=a+1))-1,y=null}return m!==r&&gh.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 RIe(s){var t,n,r,a,i,l=Math.floor,o=new Array(64),c=new Array(64),d=new Array(64),u=new Array(64),h=new Array(65535),m=new Array(65535),p=new Array(64),x=new Array(64),y=[],g=0,b=7,v=new Array(64),k=new Array(64),C=new Array(64),T=new Array(256),M=new Array(2048),P=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],L=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],I=[0,1,2,3,4,5,6,7,8,9,10,11],O=[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],q=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],W=[0,1,2,3,4,5,6,7,8,9,10,11],G=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],K=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function ee(de,we){for(var je=0,xe=0,fe=new Array,Se=1;Se<=16;Se++){for(var Ee=1;Ee<=de[Se];Ee++)fe[we[xe]]=[],fe[we[xe]][0]=je,fe[we[xe]][1]=Se,xe++,je++;je*=2}return fe}function J(de){for(var we=de[0],je=de[1]-1;je>=0;)we&1<>8&255),le(255&de)}function oe(de,we,je,xe,fe){for(var Se,Ee=fe[0],Le=fe[240],De=function(Ze,Qe){var Ye,nt,rt,Fe,dt,Dt,pt,zt,Gt,qs,As=0;for(Gt=0;Gt<8;++Gt){Ye=Ze[As],nt=Ze[As+1],rt=Ze[As+2],Fe=Ze[As+3],dt=Ze[As+4],Dt=Ze[As+5],pt=Ze[As+6];var Bt=Ye+(zt=Ze[As+7]),At=Ye-zt,Is=nt+pt,jt=nt-pt,Qs=rt+Dt,cn=rt-Dt,qt=Fe+dt,Gs=Fe-dt,Ls=Bt+qt,sn=Bt-qt,Hs=Is+Qs,nn=Is-Qs;Ze[As]=Ls+Hs,Ze[As+4]=Ls-Hs;var tn=.707106781*(nn+sn);Ze[As+2]=sn+tn,Ze[As+6]=sn-tn;var _n=.382683433*((Ls=Gs+cn)-(nn=jt+At)),Cn=.5411961*Ls+_n,Un=1.306562965*nn+_n,Kr=.707106781*(Hs=cn+jt),jr=At+Kr,Xs=At-Kr;Ze[As+5]=Xs+Cn,Ze[As+3]=Xs-Cn,Ze[As+1]=jr+Un,Ze[As+7]=jr-Un,As+=8}for(As=0,Gt=0;Gt<8;++Gt){Ye=Ze[As],nt=Ze[As+8],rt=Ze[As+16],Fe=Ze[As+24],dt=Ze[As+32],Dt=Ze[As+40],pt=Ze[As+48];var Ba=Ye+(zt=Ze[As+56]),Hr=Ye-zt,mr=nt+pt,pr=nt-pt,rn=rt+Dt,Jn=rt-Dt,ea=Fe+dt,_s=Fe-dt,We=Ba+ea,it=Ba-ea,gt=mr+rn,St=mr-rn;Ze[As]=We+gt,Ze[As+32]=We-gt;var Ht=.707106781*(St+it);Ze[As+16]=it+Ht,Ze[As+48]=it-Ht;var ts=.382683433*((We=_s+Jn)-(St=pr+Hr)),Ms=.5411961*We+ts,js=1.306562965*St+ts,Zs=.707106781*(gt=Jn+pr),Tn=Hr+Zs,vn=Hr-Zs;Ze[As+40]=vn+Ms,Ze[As+24]=vn-Ms,Ze[As+8]=Tn+js,Ze[As+56]=Tn-js,As++}for(Gt=0;Gt<64;++Gt)qs=Ze[Gt]*Qe[Gt],p[Gt]=qs>0?qs+.5|0:qs-.5|0;return p}(de,we),Be=0;Be<64;++Be)x[P[Be]]=De[Be];var Ne=x[0]-je;je=x[0],Ne==0?J(xe[0]):(J(xe[m[Se=32767+Ne]]),J(h[Se]));for(var Ge=63;Ge>0&&x[Ge]==0;)Ge--;if(Ge==0)return J(Ee),je;for(var _e,Oe=1;Oe<=Ge;){for(var Ae=Oe;x[Oe]==0&&Oe<=Ge;)++Oe;var Xe=Oe-Ae;if(Xe>=16){_e=Xe>>4;for(var Ue=1;Ue<=_e;++Ue)J(Le);Xe&=15}Se=32767+x[Oe],J(fe[(Xe<<4)+m[Se]]),J(h[Se]),Oe++}return Ge!=63&&J(Ee),je}function ie(de){de=Math.min(Math.max(de,1),100),i!=de&&(function(we){for(var je=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],xe=0;xe<64;xe++){var fe=l((je[xe]*we+50)/100);fe=Math.min(Math.max(fe,1),255),o[P[xe]]=fe}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],Ee=0;Ee<64;Ee++){var Le=l((Se[Ee]*we+50)/100);Le=Math.min(Math.max(Le,1),255),c[P[Ee]]=Le}for(var De=[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[P[Be]]*De[Ne]*De[Ge]*8),u[Be]=1/(c[P[Be]]*De[Ne]*De[Ge]*8),Be++}(de<50?Math.floor(5e3/de):Math.floor(200-2*de)),i=de)}this.encode=function(de,we){we&&ie(we),y=new Array,g=0,b=7,ue(65496),ue(65504),ue(16),le(74),le(70),le(73),le(70),le(0),le(1),le(1),le(0),ue(1),ue(1),le(0),le(0),function(){ue(65499),ue(132),le(0);for(var nt=0;nt<64;nt++)le(o[nt]);le(1);for(var rt=0;rt<64;rt++)le(c[rt])}(),function(nt,rt){ue(65472),ue(17),le(8),ue(rt),ue(nt),le(3),le(1),le(17),le(0),le(2),le(17),le(1),le(3),le(17),le(1)}(de.width,de.height),function(){ue(65476),ue(418),le(0);for(var nt=0;nt<16;nt++)le(L[nt+1]);for(var rt=0;rt<=11;rt++)le(I[rt]);le(16);for(var Fe=0;Fe<16;Fe++)le(O[Fe+1]);for(var dt=0;dt<=161;dt++)le($[dt]);le(1);for(var Dt=0;Dt<16;Dt++)le(q[Dt+1]);for(var pt=0;pt<=11;pt++)le(W[pt]);le(17);for(var zt=0;zt<16;zt++)le(G[zt+1]);for(var Gt=0;Gt<=161;Gt++)le(K[Gt])}(),ue(65498),ue(12),le(3),le(1),le(0),le(2),le(17),le(3),le(17),le(0),le(63),le(0);var je=0,xe=0,fe=0;g=0,b=7,this.encode.displayName="_encode_";for(var Se,Ee,Le,De,Be,Ne,Ge,_e,Oe,Ae=de.data,Xe=de.width,Ue=de.height,Ze=4*Xe,Qe=0;Qe>3)*Ze+(Ge=4*(7&Oe)),Qe+_e>=Ue&&(Ne-=Ze*(Qe+1+_e-Ue)),Se+Ge>=Ze&&(Ne-=Se+Ge-Ze+4),Ee=Ae[Ne++],Le=Ae[Ne++],De=Ae[Ne++],v[Oe]=(M[Ee]+M[Le+256|0]+M[De+512|0]>>16)-128,k[Oe]=(M[Ee+768|0]+M[Le+1024|0]+M[De+1280|0]>>16)-128,C[Oe]=(M[Ee+1280|0]+M[Le+1536|0]+M[De+1792|0]>>16)-128;je=oe(v,d,je,t,r),xe=oe(k,u,xe,n,a),fe=oe(C,u,fe,n,a),Se+=32}Qe+=8}if(b>=0){var Ye=[];Ye[1]=b+1,Ye[0]=(1<q;q++)if(I[O+q]!=$.charCodeAt(q))return!0;return!1}function r(I,O,$,q,W){for(var G=0;GG+1?[]:new O),!(K.length>>0;Ce&ht;)ht>>>=1;return ht?(Ce&ht-1)+ht:Ce}function $(Ce,ze,ht,bt,Yt){t(!(bt%ht));do Ce[ze+(bt-=ht)]=Yt;while(0=Yt),512>=Yt)var ls=i(512);else if((ls=i(Yt))==null)return 0;return function(hs,Ss,Ts,Ws,Nn,Vn){var Ks,In,Xn=Ss,Cr=1<Ks;++Ks){if(hr[Ks]>1<(Zo-=hr[Ks]))return 0;for(;0=Ks;++Ks,Nn<<=1){if(fi+=Zo<<=1,0>(Zo-=hr[Ks]))return 0;for(;0ga&&!(0>=(Pr-=hr[ga]));)++ga,Pr<<=1;Cr+=Si=1<<(Pr=ga-Ts),hs[Ss+(ga=Li&ca)].g=Pr+Ts,hs[Ss+ga].value=Xn-Ss-ga}Ws.g=Ks-Ts,Ws.value=Vn[In++],$(hs,Xn+(Li>>Ts),Nn,Si,Ws),Li=O(Li,Ks)}}return fi!=2*On[15]-1?0:Cr}(Ce,ze,ht,bt,Yt,ls)}function W(){this.value=this.g=0}function G(){this.value=this.g=0}function K(){this.G=l(5,W),this.H=i(5),this.jc=this.Qb=this.qb=this.nd=0,this.pd=l(Fl,G)}function ee(Ce,ze,ht,bt){t(Ce!=null),t(ze!=null),t(2147483648>bt),Ce.Ca=254,Ce.I=0,Ce.b=-8,Ce.Ka=0,Ce.oa=ze,Ce.pa=ht,Ce.Jd=ze,Ce.Yc=ht+bt,Ce.Zc=4<=bt?ht+bt-4+1:ht,Ee(Ce)}function J(Ce,ze){for(var ht=0;0bt),Ce.Sb=bt,Ce.Ra=0,Ce.u=0,Ce.h=0,4>>=8,Ce.Ra+=Ce.oa[Ce.pa+Ce.bb]<>>0,++Ce.bb,Ce.u-=8;xe(Ce)&&(Ce.h=1,Ce.u=0)}function ie(Ce,ze){if(t(0<=ze),!Ce.h&&ze<=Nm){var ht=je(Ce)&Sa[ze];return Ce.u+=ze,oe(Ce),ht}return Ce.h=1,Ce.u=0}function de(){this.b=this.Ca=this.I=0,this.oa=[],this.pa=0,this.Jd=[],this.Yc=0,this.Zc=[],this.Ka=0}function we(){this.Ra=0,this.oa=[],this.h=this.u=this.bb=this.Sb=this.pa=0}function je(Ce){return Ce.Ra>>>(Ce.u&id-1)>>>0}function xe(Ce){return t(Ce.bb<=Ce.Sb),Ce.h||Ce.bb==Ce.Sb&&Ce.u>id}function fe(Ce,ze){Ce.u=ze,Ce.h=xe(Ce)}function Se(Ce){Ce.u>=la&&(t(Ce.u>=la),oe(Ce))}function Ee(Ce){t(Ce!=null&&Ce.oa!=null),Ce.pa>>0,Ce.b+=8):(t(Ce!=null&&Ce.oa!=null),Ce.paCe.b&&Ee(Ce);var bt=Ce.b,Yt=ht*ze>>>8,ls=(Ce.I>>>bt>Yt)+0;for(ls?(ht-=Yt,Ce.I-=Yt+1<>>0):ht=Yt+1,bt=ht,Yt=0;256<=bt;)Yt+=8,bt>>=8;return bt=7^Yt+Ox[bt],Ce.b-=bt,Ce.Ca=(ht<>24&255,Ce[ze+1]=ht>>16&255,Ce[ze+2]=ht>>8&255,Ce[ze+3]=255&ht}function Ne(Ce,ze){return Ce[ze+0]|Ce[ze+1]<<8}function Ge(Ce,ze){return Ne(Ce,ze)|Ce[ze+2]<<16}function _e(Ce,ze){return Ne(Ce,ze)|Ne(Ce,ze+2)<<16}function Oe(Ce,ze){var ht=1<=Yt||0>=ls?0:(ht[0]=Yt,bt[0]=ls,1)}function Ze(Ce,ze){return Ce+(1<>>ze}function Qe(Ce,ze){return((4278255360&Ce)+(4278255360&ze)>>>0&4278255360)+((16711935&Ce)+(16711935&ze)>>>0&16711935)>>>0}function Ye(Ce,ze){I[ze]=function(ht,bt,Yt,ls,hs,Ss,Ts){var Ws;for(Ws=0;Ws>>1)+(Ce&ze)>>>0}function Fe(Ce){return 0<=Ce&&256>Ce?Ce:0>Ce?0:255>1))}function Dt(Ce,ze,ht){return Math.abs(ze-ht)-Math.abs(Ce-ht)}function pt(Ce,ze,ht,bt,Yt,ls,hs){for(bt=ls[hs-1],ht=0;ht>8&255,Ts=16711935&(Ts=(Ts=16711935&hs)+((Ss<<16)+Ss));bt[Yt+ls]=(4278255360&hs)+Ts>>>0}}function Gt(Ce,ze){ze.jd=255&Ce,ze.hd=Ce>>8&255,ze.ud=Ce>>16&255}function qs(Ce,ze,ht,bt,Yt,ls){var hs;for(hs=0;hs>>8,Ws=Ss,Nn=255&(Nn=(Nn=Ss>>>16)+((Ce.jd<<24>>24)*(Ts<<24>>24)>>>5));Ws=255&(Ws=(Ws+=(Ce.hd<<24>>24)*(Ts<<24>>24)>>>5)+((Ce.ud<<24>>24)*(Nn<<24>>24)>>>5)),Yt[ls+hs]=(4278255360&Ss)+(Nn<<16)+Ws}}function As(Ce,ze,ht,bt,Yt){I[ze]=function(ls,hs,Ss,Ts,Ws,Nn,Vn,Ks,In){for(Ts=Vn;Ts>ls.b,In=ls.Ea,Xn=ls.K[0],Cr=ls.w;if(8>Ks)for(ls=(1<>=Ks}else I["VP8LMapColor"+ht](Ts,Ws,Xn,Cr,Nn,Vn,hs,Ss,In)}}function Bt(Ce,ze,ht,bt,Yt){for(ht=ze+ht;ze>16&255,bt[Yt++]=ls>>8&255,bt[Yt++]=255&ls}}function At(Ce,ze,ht,bt,Yt){for(ht=ze+ht;ze>16&255,bt[Yt++]=ls>>8&255,bt[Yt++]=255&ls,bt[Yt++]=ls>>24&255}}function Is(Ce,ze,ht,bt,Yt){for(ht=ze+ht;ze>16&240|hs>>12&15,hs=240&hs|hs>>28&15;bt[Yt++]=ls,bt[Yt++]=hs}}function jt(Ce,ze,ht,bt,Yt){for(ht=ze+ht;ze>16&248|hs>>13&7,hs=hs>>5&224|hs>>3&31;bt[Yt++]=ls,bt[Yt++]=hs}}function Qs(Ce,ze,ht,bt,Yt){for(ht=ze+ht;ze>8&255,bt[Yt++]=ls>>16&255}}function cn(Ce,ze,ht,bt,Yt,ls){if(ls==0)for(ht=ze+ht;ze>24|ls[1]>>8&65280|ls[2]<<8&16711680|ls[3]<<24)>>>0),Yt+=32;else r(bt,Yt,Ce,ze,ht)}function qt(Ce,ze){I[ze][0]=I[Ce+"0"],I[ze][1]=I[Ce+"1"],I[ze][2]=I[Ce+"2"],I[ze][3]=I[Ce+"3"],I[ze][4]=I[Ce+"4"],I[ze][5]=I[Ce+"5"],I[ze][6]=I[Ce+"6"],I[ze][7]=I[Ce+"7"],I[ze][8]=I[Ce+"8"],I[ze][9]=I[Ce+"9"],I[ze][10]=I[Ce+"10"],I[ze][11]=I[Ce+"11"],I[ze][12]=I[Ce+"12"],I[ze][13]=I[Ce+"13"],I[ze][14]=I[Ce+"0"],I[ze][15]=I[Ce+"0"]}function Gs(Ce){return Ce==fv||Ce==n2||Ce==fw||Ce==kg}function Ls(){this.eb=[],this.size=this.A=this.fb=0}function sn(){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 Hs(){this.Rd=this.height=this.width=this.S=0,this.f={},this.f.RGBA=new Ls,this.f.kb=new sn,this.sd=null}function nn(){this.width=[0],this.height=[0],this.Pd=[0],this.Qd=[0],this.format=[0]}function tn(){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 _n(Ce){return alert("todo:WebPSamplerProcessPlane"),Ce.T}function Cn(Ce,ze){var ht=Ce.T,bt=ze.ba.f.RGBA,Yt=bt.eb,ls=bt.fb+Ce.ka*bt.A,hs=Kp[ze.ba.S],Ss=Ce.y,Ts=Ce.O,Ws=Ce.f,Nn=Ce.N,Vn=Ce.ea,Ks=Ce.W,In=ze.cc,Xn=ze.dc,Cr=ze.Mc,hr=ze.Nc,On=Ce.ka,Pr=Ce.ka+Ce.T,ga=Ce.U,ca=ga+1>>1;for(On==0?hs(Ss,Ts,null,null,Ws,Nn,Vn,Ks,Ws,Nn,Vn,Ks,Yt,ls,null,null,ga):(hs(ze.ec,ze.fc,Ss,Ts,In,Xn,Cr,hr,Ws,Nn,Vn,Ks,Yt,ls-bt.A,Yt,ls,ga),++ht);On+2ht,Yt=ht==k1||ht==Wp||ht==vy||ht==k0||ht==12||Gs(ht);if(ze.memory=null,ze.Ib=null,ze.Jb=null,ze.Nd=null,!yl(ze.Oa,Ce,Yt?11:12))return 0;if(Yt&&Gs(ht)&&Qh(),Ce.da)alert("todo:use_scaling");else{if(bt){if(ze.Ib=_n,Ce.Kb){if(ht=Ce.U+1>>1,ze.memory=i(Ce.U+2*ht),ze.memory==null)return 0;ze.ec=ze.memory,ze.fc=0,ze.cc=ze.ec,ze.dc=ze.fc+Ce.U,ze.Mc=ze.cc,ze.Nc=ze.dc+ht,ze.Ib=Cn,Qh()}}else alert("todo:EmitYUV");Yt&&(ze.Jb=Un,bt&&bc())}if(bt&&!_w){for(Ce=0;256>Ce;++Ce)ww[Ce]=89858*(Ce-128)+vw>>by,JN[Ce]=-22014*(Ce-128)+vw,i2[Ce]=-45773*(Ce-128),Kb[Ce]=113618*(Ce-128)+vw>>by;for(Ce=bw;Ce>by,oC[Ce-bw]=ur(ze,255),Yb[Ce-bw]=ur(ze+8>>4,15);_w=1}return 1}function jr(Ce){var ze=Ce.ma,ht=Ce.U,bt=Ce.T;return t(!(1&Ce.ka)),0>=ht||0>=bt?0:(ht=ze.Ib(Ce,ze),ze.Jb!=null&&ze.Jb(Ce,ze,ht),ze.Dc+=ht,1)}function Xs(Ce){Ce.ma.memory=null}function Ba(Ce,ze,ht,bt){return ie(Ce,8)!=47?0:(ze[0]=ie(Ce,14)+1,ht[0]=ie(Ce,14)+1,bt[0]=ie(Ce,1),ie(Ce,3)!=0?0:!Ce.h)}function Hr(Ce,ze){if(4>Ce)return Ce+1;var ht=Ce-2>>1;return(2+(1&Ce)<>4)*Ce+(8-(15&ht)))?ht:1;var ht}function pr(Ce,ze,ht){var bt=je(ht),Yt=Ce[ze+=255&bt].g-8;return 0>>0,t(8>=ht.g),Ce.g}function Jn(Ce,ze,ht){var bt=Ce.xc;return t((ze=bt==0?0:Ce.vc[Ce.md*(ht>>bt)+(ze>>bt)])>Si.b)*fi;Crga&&(Ti=ga),(0,xu[Tl[Ad++]>>8&15])(Ks,In+ +Xo,On,Pr+Xo-ga,Ti-Xo,On,Pr+Xo),Xo=Ti}In+=ga,Pr+=ga,++Cr&Li||(Si+=fi)}Vn!=Ws.nc&&r(Ts,Ss-Xn,Ts,Ss+(Vn-Nn-1)*Xn,Xn);break;case 1:for(Xn=Ks,hr=In,ga=(Ks=Ws.Ea)-(Pr=Ks&~(On=(In=1<>Ws.b)*Cr;Nn=Yt),0ls.o&&(bt=ls.o),ht=bt?ht=0:(Yt[0]+=4*ls.v,ls.ka=ht-ls.j,ls.U=ls.va-ls.v,ls.T=bt-ht,ht=1),ht){if(Ss=Ss[0],11>(ht=Ce.ca).S){var Nn=ht.f.RGBA,Vn=(bt=ht.S,Yt=ls.U,ls=ls.T,Ws=Nn.eb,Nn.A),Ks=ls;for(Nn=Nn.fb+Ce.Ma*Nn.A;0bt){var Yt=Ce.l.width,ls=ht.ca,hs=ht.tb+Yt*bt,Ss=Ce.V,Ts=Ce.Ba+Ce.c*bt,Ws=Ce.gc;t(Ce.ab==1),t(Ws[0].hc==3),cp(Ws[0],bt,ze,Ss,Ts,ls,hs),it(ht,bt,ze,ls,hs,Yt)}Ce.C=Ce.Ma=ze}function St(Ce,ze,ht,bt,Yt,ls,hs){var Ss=Ce.$/bt,Ts=Ce.$%bt,Ws=Ce.m,Nn=Ce.s,Vn=ht+Ce.$,Ks=Vn;Yt=ht+bt*Yt;var In=ht+bt*ls,Xn=280+Nn.ua,Cr=Ce.Pb?Ss:16777216,hr=0=Cr){var Li=Vn-ht;t((Cr=Ce).Pb),Cr.wd=Cr.m,Cr.xd=Li,0Zo.g?(fe(ca,ca.u+Zo.g),Li[fi]=Zo.value,ca=0):(fe(ca,ca.u+Zo.g-256),t(256<=Zo.value),ca=Zo.value),ca==0&&(ga=!0)}else ca=pr(Pr.G[0],Pr.H[0],Ws);if(Ws.h)break;if(ga||256>ca){if(!ga)if(Pr.nd)ze[Vn]=(Pr.qb|ca<<8)>>>0;else{if(Se(Ws),ga=pr(Pr.G[1],Pr.H[1],Ws),Se(Ws),Li=pr(Pr.G[2],Pr.H[2],Ws),fi=pr(Pr.G[3],Pr.H[3],Ws),Ws.h)break;ze[Vn]=(fi<<24|ga<<16|ca<<8|Li)>>>0}if(ga=!1,++Vn,++Ts>=bt&&(Ts=0,++Ss,hs!=null&&Ss<=ls&&!(Ss%16)&&hs(Ce,Ss),hr!=null))for(;Ks>>hr.Mb]=ca}else if(280>ca){if(ca=Hr(ca-256,Ws),Li=pr(Pr.G[4],Pr.H[4],Ws),Se(Ws),Li=mr(bt,Li=Hr(Li,Ws)),Ws.h)break;if(Vn-ht=bt;)Ts-=bt,++Ss,hs!=null&&Ss<=ls&&!(Ss%16)&&hs(Ce,Ss);if(t(Vn<=Yt),Ts&On&&(Pr=Jn(Nn,Ts,Ss)),hr!=null)for(;Ks>>hr.Mb]=ca}else{if(!(ca>>hr.Mb]=ca;ca=Vn,t(!(ga>>>(Li=hr).Xa)),ze[ca]=Li.X[ga],ga=!0}ga||t(Ws.h==xe(Ws))}if(Ce.Pb&&Ws.h&&Vnls?ls:Ss),Ce.a=0,Ce.$=Vn-ht}return 1}return Ce.a=3,0}function Ht(Ce){t(Ce!=null),Ce.vc=null,Ce.yc=null,Ce.Ya=null;var ze=Ce.Wa;ze!=null&&(ze.X=null),Ce.vb=null,t(Ce!=null)}function ts(){var Ce=new xr;return Ce==null?null:(Ce.a=0,Ce.xb=kS,qt("Predictor","VP8LPredictors"),qt("Predictor","VP8LPredictors_C"),qt("PredictorAdd","VP8LPredictorsAdd"),qt("PredictorAdd","VP8LPredictorsAdd_C"),b0=zt,Kc=qs,dp=Bt,hv=At,mv=Is,_c=jt,Fx=Qs,I.VP8LMapColor32b=Oc,I.VP8LMapColor8b=ch,Ce)}function Ms(Ce,ze,ht,bt,Yt){var ls=1,hs=[Ce],Ss=[ze],Ts=bt.m,Ws=bt.s,Nn=null,Vn=0;e:for(;;){if(ht)for(;ls&&ie(Ts,1);){var Ks=hs,In=Ss,Xn=bt,Cr=1,hr=Xn.m,On=Xn.gc[Xn.ab],Pr=ie(hr,2);if(Xn.Oc&1<=Xn.ab),Pr){case 0:case 1:On.b=ie(hr,3)+2,Cr=Ms(Ze(On.Ea,On.b),Ze(On.nc,On.b),0,Xn,On.K),On.K=On.K[0];break;case 3:var ga,ca=ie(hr,8)+1,Li=16>Si.b),Ad=i(Tl);if(Ad==null)ga=0;else{var Xo=Si.K[0],Ti=Si.w;for(Ad[0]=Si.K[0][0],fi=1;fi<1*Zo;++fi)Ad[fi]=Qe(Xo[Ti+fi],Ad[fi-1]);for(;fi<4*Tl;++fi)Ad[fi]=0;Si.K[0]=null,Si.K[0]=Ad,ga=1}}Cr=ga;break;case 2:break;default:t(0)}ls=Cr}}if(hs=hs[0],Ss=Ss[0],ls&&ie(Ts,1)&&!(ls=1<=(Vn=ie(Ts,4))&&11>=Vn)){bt.a=3;break e}var Ya;if(Ya=ls)t:{var el,io,qo,yd=bt,Th=hs,vd=Ss,Qd=Vn,Wd=ht,Zp=yd.m,od=yd.s,uc=[null],Zc=1,vu=0,jc=iC[Qd];s:for(;;){if(Wd&&ie(Zp,1)){var Pu=ie(Zp,3)+2,km=Ze(Th,Pu),Fc=Ze(vd,Pu),Xu=km*Fc;if(!Ms(km,Fc,0,yd,uc))break s;for(uc=uc[0],od.xc=Pu,el=0;el>8&65535;uc[el]=Bl,Bl>=Zc&&(Zc=Bl+1)}}if(Zp.h)break s;for(io=0;5>io;++io){var Iu=WN[io];!io&&0=Td),Qp=Xp;var Cm=i(vu);if(Qp==null||Cm==null||Sm==null){yd.a=1;break s}var mh=Sm;for(el=qo=0;elio;++io){Iu=WN[io],gr[io]=mh,yo[io]=qo,!io&&0M1)break n}else jy=M1;for(dx=0;dxP1)Aw[dx++]=P1,P1!=0&&(A0=P1);else{var AS=P1==16,ek=P1-16,yv=oo[ek],vv=ie(bu,_S[ek])+yv;if(dx+vv>M1)break n;for(var TS=AS?A0:0;0=io){var bv,Tg=Cm[0];for(bv=1;bvTg&&(Tg=Cm[bv]);mc+=Tg}}if(hc.nd=ec,hc.Qb=0,ec&&(hc.qb=(gr[3][yo[3]+0].value<<24|gr[1][yo[1]+0].value<<16|gr[2][yo[2]+0].value)>>>0,Ec==0&&256>gr[0][yo[0]+0].value&&(hc.Qb=1,hc.qb+=gr[0][yo[0]+0].value<<8)),hc.jc=!hc.Qb&&6>mc,hc.jc){var o2,Ru=hc;for(o2=0;o2>=rn(tf,8,Ed),tm>>=rn(Ru.G[1][Ru.H[1]+tm],16,Ed),tm>>=rn(Ru.G[2][Ru.H[2]+tm],0,Ed),rn(Ru.G[3][Ru.H[3]+tm],24,Ed))}}}od.vc=uc,od.Wb=Zc,od.Ya=Qp,od.yc=Sm,Ya=1;break t}Ya=0}if(!(ls=Ya)){bt.a=3;break e}if(0bt+1?[]:0),!(Yt.lengthCe?0:Ce>ze?ze:Ce}function ao(){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 fo(){var Ce=new oa;return Ce!=null&&(Ce.a=0,Ce.sc="OK",Ce.cb=0,Ce.Xb=0,S1||(S1=Gr)),Ce}function Va(Ce,ze,ht){return Ce.a==0&&(Ce.a=ze,Ce.sc=ht,Ce.cb=0),0}function So(Ce,ze,ht){return 3<=ht&&Ce[ze+0]==157&&Ce[ze+1]==1&&Ce[ze+2]==42}function $a(Ce,ze){if(Ce==null)return 0;if(Ce.a=0,Ce.sc="OK",ze==null)return Va(Ce,2,"null VP8Io passed to VP8GetHeaders()");var ht=ze.data,bt=ze.w,Yt=ze.ha;if(4>Yt)return Va(Ce,7,"Truncated header.");var ls=ht[bt+0]|ht[bt+1]<<8|ht[bt+2]<<16,hs=Ce.Od;if(hs.Rb=!(1&ls),hs.td=ls>>1&7,hs.yd=ls>>4&1,hs.ub=ls>>5,3Yt)return Va(Ce,7,"cannot parse picture header");if(!So(ht,bt,Yt))return Va(Ce,3,"Bad code word");Ss.c=16383&(ht[bt+4]<<8|ht[bt+3]),Ss.Td=ht[bt+4]>>6,Ss.i=16383&(ht[bt+6]<<8|ht[bt+5]),Ss.Ud=ht[bt+6]>>6,bt+=7,Yt-=7,Ce.za=Ss.c+15>>4,Ce.Ub=Ss.i+15>>4,ze.width=Ss.c,ze.height=Ss.i,ze.Da=0,ze.j=0,ze.v=0,ze.va=ze.width,ze.o=ze.height,ze.da=0,ze.ib=ze.width,ze.hb=ze.height,ze.U=ze.width,ze.T=ze.height,a((ls=Ce.Pa).jb,0,255,ls.jb.length),t((ls=Ce.Qa)!=null),ls.Cb=0,ls.Bb=0,ls.Fb=1,a(ls.Zb,0,0,ls.Zb.length),a(ls.Lb,0,0,ls.Lb)}if(hs.ub>Yt)return Va(Ce,7,"bad partition length");ee(ls=Ce.m,ht,bt,hs.ub),bt+=hs.ub,Yt-=hs.ub,hs.Rb&&(Ss.Ld=Le(ls),Ss.Kd=Le(ls)),Ss=Ce.Qa;var Ts,Ws=Ce.Pa;if(t(ls!=null),t(Ss!=null),Ss.Cb=Le(ls),Ss.Cb){if(Ss.Bb=Le(ls),Le(ls)){for(Ss.Fb=Le(ls),Ts=0;4>Ts;++Ts)Ss.Zb[Ts]=Le(ls)?le(ls,7):0;for(Ts=0;4>Ts;++Ts)Ss.Lb[Ts]=Le(ls)?le(ls,6):0}if(Ss.Bb)for(Ts=0;3>Ts;++Ts)Ws.jb[Ts]=Le(ls)?J(ls,8):255}else Ss.Bb=0;if(ls.Ka)return Va(Ce,3,"cannot parse segment header");if((Ss=Ce.ed).zd=Le(ls),Ss.Tb=J(ls,6),Ss.wb=J(ls,3),Ss.Pc=Le(ls),Ss.Pc&&Le(ls)){for(Ws=0;4>Ws;++Ws)Le(ls)&&(Ss.vd[Ws]=le(ls,6));for(Ws=0;4>Ws;++Ws)Le(ls)&&(Ss.od[Ws]=le(ls,6))}if(Ce.L=Ss.Tb==0?0:Ss.zd?1:2,ls.Ka)return Va(Ce,3,"cannot parse filter header");var Nn=Yt;if(Yt=Ts=bt,bt=Ts+Nn,Ss=Nn,Ce.Xb=(1<Ss&&(Vn=Ss),ee(Ce.Jc[+Nn],ht,Ts,Vn),Ts+=Vn,Ss-=Vn,Yt+=3}ee(Ce.Jc[+Ws],ht,Ts,Ss),ht=TsVn;++Vn){if(Nn.Cb){var Ks=Nn.Zb[Vn];Nn.Fb||(Ks+=ht)}else{if(0>16,8>In.Eb[1]&&(In.Eb[1]=8),In.Qc[0]=Gb[ur(Ks+Ws,117)],In.Qc[1]=NS[ur(Ks+Ts,127)],In.lc=Ks+Ts}if(!hs.Rb)return Va(Ce,4,"Not a key frame.");for(Le(ls),hs=Ce.Pa,ht=0;4>ht;++ht){for(Yt=0;8>Yt;++Yt)for(bt=0;3>bt;++bt)for(Ss=0;11>Ss;++Ss)Ws=De(ls,C1[ht][Yt][bt][Ss])?J(ls,8):Wb[ht][Yt][bt][Ss],hs.Wc[ht][Yt].Yb[bt][Ss]=Ws;for(Yt=0;17>Yt;++Yt)hs.Xc[ht][Yt]=hs.Wc[ht][A1[Yt]]}return Ce.kc=Le(ls),Ce.kc&&(Ce.Bd=J(ls,8)),Ce.cb=1}function Gr(Ce,ze,ht,bt,Yt,ls,hs){var Ss=ze[Yt].Yb[ht];for(ht=0;16>Yt;++Yt){if(!De(Ce,Ss[ht+0]))return Yt;for(;!De(Ce,Ss[ht+1]);)if(Ss=ze[++Yt].Yb[0],ht=0,Yt==16)return 16;var Ts=ze[Yt+1].Yb;if(De(Ce,Ss[ht+2])){var Ws=Ce,Nn=0;if(De(Ws,(Ks=Ss)[(Vn=ht)+3]))if(De(Ws,Ks[Vn+6])){for(Ss=0,Vn=2*(Nn=De(Ws,Ks[Vn+8]))+(Ks=De(Ws,Ks[Vn+9+Nn])),Nn=0,Ks=M6[Vn];Ks[Ss];++Ss)Nn+=Nn+De(Ws,Ks[Ss]);Nn+=3+(8<(Ws=Ce).b&&Ee(Ws);var Vn,Ks=Ws.b,In=(Vn=Ws.Ca>>1)-(Ws.I>>Ks)>>31;--Ws.b,Ws.Ca+=In,Ws.Ca|=1,Ws.I-=(Vn+1&In)<>3),Ce[ze+ht+32*bt]=-256&Yt?0>Yt?0:255:Yt}function xo(Ce,ze,ht,bt,Yt,ls){qa(Ce,ze,0,ht,bt+Yt),qa(Ce,ze,1,ht,bt+ls),qa(Ce,ze,2,ht,bt-ls),qa(Ce,ze,3,ht,bt-Yt)}function Wo(Ce){return(20091*Ce>>16)+Ce}function Co(Ce,ze,ht,bt){var Yt,ls=0,hs=i(16);for(Yt=0;4>Yt;++Yt){var Ss=Ce[ze+0]+Ce[ze+8],Ts=Ce[ze+0]-Ce[ze+8],Ws=(35468*Ce[ze+4]>>16)-Wo(Ce[ze+12]),Nn=Wo(Ce[ze+4])+(35468*Ce[ze+12]>>16);hs[ls+0]=Ss+Nn,hs[ls+1]=Ts+Ws,hs[ls+2]=Ts-Ws,hs[ls+3]=Ss-Nn,ls+=4,ze++}for(Yt=ls=0;4>Yt;++Yt)Ss=(Ce=hs[ls+0]+4)+hs[ls+8],Ts=Ce-hs[ls+8],Ws=(35468*hs[ls+4]>>16)-Wo(hs[ls+12]),qa(ht,bt,0,0,Ss+(Nn=Wo(hs[ls+4])+(35468*hs[ls+12]>>16))),qa(ht,bt,1,0,Ts+Ws),qa(ht,bt,2,0,Ts-Ws),qa(ht,bt,3,0,Ss-Nn),ls++,bt+=32}function Ko(Ce,ze,ht,bt){var Yt=Ce[ze+0]+4,ls=35468*Ce[ze+4]>>16,hs=Wo(Ce[ze+4]),Ss=35468*Ce[ze+1]>>16;xo(ht,bt,0,Yt+hs,Ce=Wo(Ce[ze+1]),Ss),xo(ht,bt,1,Yt+ls,Ce,Ss),xo(ht,bt,2,Yt-ls,Ce,Ss),xo(ht,bt,3,Yt-hs,Ce,Ss)}function Ud(Ce,ze,ht,bt,Yt){Co(Ce,ze,ht,bt),Yt&&Co(Ce,ze+16,ht,bt+4)}function Mu(Ce,ze,ht,bt){dh(Ce,ze+0,ht,bt,1),dh(Ce,ze+32,ht,bt+128,1)}function Qm(Ce,ze,ht,bt){var Yt;for(Ce=Ce[ze+0]+4,Yt=0;4>Yt;++Yt)for(ze=0;4>ze;++ze)qa(ht,bt,ze,Yt,Ce)}function Gc(Ce,ze,ht,bt){Ce[ze+0]&&gu(Ce,ze+0,ht,bt),Ce[ze+16]&&gu(Ce,ze+16,ht,bt+4),Ce[ze+32]&&gu(Ce,ze+32,ht,bt+128),Ce[ze+48]&&gu(Ce,ze+48,ht,bt+128+4)}function lh(Ce,ze,ht,bt){var Yt,ls=i(16);for(Yt=0;4>Yt;++Yt){var hs=Ce[ze+0+Yt]+Ce[ze+12+Yt],Ss=Ce[ze+4+Yt]+Ce[ze+8+Yt],Ts=Ce[ze+4+Yt]-Ce[ze+8+Yt],Ws=Ce[ze+0+Yt]-Ce[ze+12+Yt];ls[0+Yt]=hs+Ss,ls[8+Yt]=hs-Ss,ls[4+Yt]=Ws+Ts,ls[12+Yt]=Ws-Ts}for(Yt=0;4>Yt;++Yt)hs=(Ce=ls[0+4*Yt]+3)+ls[3+4*Yt],Ss=ls[1+4*Yt]+ls[2+4*Yt],Ts=ls[1+4*Yt]-ls[2+4*Yt],Ws=Ce-ls[3+4*Yt],ht[bt+0]=hs+Ss>>3,ht[bt+16]=Ws+Ts>>3,ht[bt+32]=hs-Ss>>3,ht[bt+48]=Ws-Ts>>3,bt+=64}function qd(Ce,ze,ht){var bt,Yt=ze-32,ls=hh,hs=255-Ce[Yt-1];for(bt=0;btht;++ht)r(Ce,ze+32*ht,Ce,ze-32,16)}function xy(Ce,ze){var ht;for(ht=16;0bt;++bt)a(ze,ht+32*bt,Ce,16)}function Mf(Ce,ze){var ht,bt=16;for(ht=0;16>ht;++ht)bt+=Ce[ze-1+32*ht]+Ce[ze+ht-32];Ef(bt>>5,Ce,ze)}function pu(Ce,ze){var ht,bt=8;for(ht=0;16>ht;++ht)bt+=Ce[ze-1+32*ht];Ef(bt>>4,Ce,ze)}function Px(Ce,ze){var ht,bt=8;for(ht=0;16>ht;++ht)bt+=Ce[ze+ht-32];Ef(bt>>4,Ce,ze)}function Do(Ce,ze){Ef(128,Ce,ze)}function go(Ce,ze,ht){return Ce+2*ze+ht+2>>2}function ep(Ce,ze){var ht,bt=ze-32;for(bt=new Uint8Array([go(Ce[bt-1],Ce[bt+0],Ce[bt+1]),go(Ce[bt+0],Ce[bt+1],Ce[bt+2]),go(Ce[bt+1],Ce[bt+2],Ce[bt+3]),go(Ce[bt+2],Ce[bt+3],Ce[bt+4])]),ht=0;4>ht;++ht)r(Ce,ze+32*ht,bt,0,bt.length)}function _m(Ce,ze){var ht=Ce[ze-1],bt=Ce[ze-1+32],Yt=Ce[ze-1+64],ls=Ce[ze-1+96];Be(Ce,ze+0,16843009*go(Ce[ze-1-32],ht,bt)),Be(Ce,ze+32,16843009*go(ht,bt,Yt)),Be(Ce,ze+64,16843009*go(bt,Yt,ls)),Be(Ce,ze+96,16843009*go(Yt,ls,ls))}function Ix(Ce,ze){var ht,bt=4;for(ht=0;4>ht;++ht)bt+=Ce[ze+ht-32]+Ce[ze-1+32*ht];for(bt>>=3,ht=0;4>ht;++ht)a(Ce,ze+32*ht,bt,4)}function Ah(Ce,ze){var ht=Ce[ze-1+0],bt=Ce[ze-1+32],Yt=Ce[ze-1+64],ls=Ce[ze-1-32],hs=Ce[ze+0-32],Ss=Ce[ze+1-32],Ts=Ce[ze+2-32],Ws=Ce[ze+3-32];Ce[ze+0+96]=go(bt,Yt,Ce[ze-1+96]),Ce[ze+1+96]=Ce[ze+0+64]=go(ht,bt,Yt),Ce[ze+2+96]=Ce[ze+1+64]=Ce[ze+0+32]=go(ls,ht,bt),Ce[ze+3+96]=Ce[ze+2+64]=Ce[ze+1+32]=Ce[ze+0+0]=go(hs,ls,ht),Ce[ze+3+64]=Ce[ze+2+32]=Ce[ze+1+0]=go(Ss,hs,ls),Ce[ze+3+32]=Ce[ze+2+0]=go(Ts,Ss,hs),Ce[ze+3+0]=go(Ws,Ts,Ss)}function Vl(Ce,ze){var ht=Ce[ze+1-32],bt=Ce[ze+2-32],Yt=Ce[ze+3-32],ls=Ce[ze+4-32],hs=Ce[ze+5-32],Ss=Ce[ze+6-32],Ts=Ce[ze+7-32];Ce[ze+0+0]=go(Ce[ze+0-32],ht,bt),Ce[ze+1+0]=Ce[ze+0+32]=go(ht,bt,Yt),Ce[ze+2+0]=Ce[ze+1+32]=Ce[ze+0+64]=go(bt,Yt,ls),Ce[ze+3+0]=Ce[ze+2+32]=Ce[ze+1+64]=Ce[ze+0+96]=go(Yt,ls,hs),Ce[ze+3+32]=Ce[ze+2+64]=Ce[ze+1+96]=go(ls,hs,Ss),Ce[ze+3+64]=Ce[ze+2+96]=go(hs,Ss,Ts),Ce[ze+3+96]=go(Ss,Ts,Ts)}function tp(Ce,ze){var ht=Ce[ze-1+0],bt=Ce[ze-1+32],Yt=Ce[ze-1+64],ls=Ce[ze-1-32],hs=Ce[ze+0-32],Ss=Ce[ze+1-32],Ts=Ce[ze+2-32],Ws=Ce[ze+3-32];Ce[ze+0+0]=Ce[ze+1+64]=ls+hs+1>>1,Ce[ze+1+0]=Ce[ze+2+64]=hs+Ss+1>>1,Ce[ze+2+0]=Ce[ze+3+64]=Ss+Ts+1>>1,Ce[ze+3+0]=Ts+Ws+1>>1,Ce[ze+0+96]=go(Yt,bt,ht),Ce[ze+0+64]=go(bt,ht,ls),Ce[ze+0+32]=Ce[ze+1+96]=go(ht,ls,hs),Ce[ze+1+32]=Ce[ze+2+96]=go(ls,hs,Ss),Ce[ze+2+32]=Ce[ze+3+96]=go(hs,Ss,Ts),Ce[ze+3+32]=go(Ss,Ts,Ws)}function Cd(Ce,ze){var ht=Ce[ze+0-32],bt=Ce[ze+1-32],Yt=Ce[ze+2-32],ls=Ce[ze+3-32],hs=Ce[ze+4-32],Ss=Ce[ze+5-32],Ts=Ce[ze+6-32],Ws=Ce[ze+7-32];Ce[ze+0+0]=ht+bt+1>>1,Ce[ze+1+0]=Ce[ze+0+64]=bt+Yt+1>>1,Ce[ze+2+0]=Ce[ze+1+64]=Yt+ls+1>>1,Ce[ze+3+0]=Ce[ze+2+64]=ls+hs+1>>1,Ce[ze+0+32]=go(ht,bt,Yt),Ce[ze+1+32]=Ce[ze+0+96]=go(bt,Yt,ls),Ce[ze+2+32]=Ce[ze+1+96]=go(Yt,ls,hs),Ce[ze+3+32]=Ce[ze+2+96]=go(ls,hs,Ss),Ce[ze+3+64]=go(hs,Ss,Ts),Ce[ze+3+96]=go(Ss,Ts,Ws)}function g0(Ce,ze){var ht=Ce[ze-1+0],bt=Ce[ze-1+32],Yt=Ce[ze-1+64],ls=Ce[ze-1+96];Ce[ze+0+0]=ht+bt+1>>1,Ce[ze+2+0]=Ce[ze+0+32]=bt+Yt+1>>1,Ce[ze+2+32]=Ce[ze+0+64]=Yt+ls+1>>1,Ce[ze+1+0]=go(ht,bt,Yt),Ce[ze+3+0]=Ce[ze+1+32]=go(bt,Yt,ls),Ce[ze+3+32]=Ce[ze+1+64]=go(Yt,ls,ls),Ce[ze+3+64]=Ce[ze+2+64]=Ce[ze+0+96]=Ce[ze+1+96]=Ce[ze+2+96]=Ce[ze+3+96]=ls}function Bb(Ce,ze){var ht=Ce[ze-1+0],bt=Ce[ze-1+32],Yt=Ce[ze-1+64],ls=Ce[ze-1+96],hs=Ce[ze-1-32],Ss=Ce[ze+0-32],Ts=Ce[ze+1-32],Ws=Ce[ze+2-32];Ce[ze+0+0]=Ce[ze+2+32]=ht+hs+1>>1,Ce[ze+0+32]=Ce[ze+2+64]=bt+ht+1>>1,Ce[ze+0+64]=Ce[ze+2+96]=Yt+bt+1>>1,Ce[ze+0+96]=ls+Yt+1>>1,Ce[ze+3+0]=go(Ss,Ts,Ws),Ce[ze+2+0]=go(hs,Ss,Ts),Ce[ze+1+0]=Ce[ze+3+32]=go(ht,hs,Ss),Ce[ze+1+32]=Ce[ze+3+64]=go(bt,ht,hs),Ce[ze+1+64]=Ce[ze+3+96]=go(Yt,bt,ht),Ce[ze+1+96]=go(ls,Yt,bt)}function sp(Ce,ze){var ht;for(ht=0;8>ht;++ht)r(Ce,ze+32*ht,Ce,ze-32,8)}function ki(Ce,ze){var ht;for(ht=0;8>ht;++ht)a(Ce,ze,Ce[ze-1],8),ze+=32}function np(Ce,ze,ht){var bt;for(bt=0;8>bt;++bt)a(ze,ht+32*bt,Ce,8)}function gy(Ce,ze){var ht,bt=8;for(ht=0;8>ht;++ht)bt+=Ce[ze+ht-32]+Ce[ze-1+32*ht];np(bt>>4,Ce,ze)}function Yh(Ce,ze){var ht,bt=4;for(ht=0;8>ht;++ht)bt+=Ce[ze+ht-32];np(bt>>3,Ce,ze)}function Hp(Ce,ze){var ht,bt=4;for(ht=0;8>ht;++ht)bt+=Ce[ze-1+32*ht];np(bt>>3,Ce,ze)}function rp(Ce,ze){np(128,Ce,ze)}function wm(Ce,ze,ht){var bt=Ce[ze-ht],Yt=Ce[ze+0],ls=3*(Yt-bt)+Vb[1020+Ce[ze-2*ht]-Ce[ze+ht]],hs=up[112+(ls+4>>3)];Ce[ze-ht]=hh[255+bt+up[112+(ls+3>>3)]],Ce[ze+0]=hh[255+Yt-hs]}function ix(Ce,ze,ht,bt){var Yt=Ce[ze+0],ls=Ce[ze+ht];return nr[255+Ce[ze-2*ht]-Ce[ze-ht]]>bt||nr[255+ls-Yt]>bt}function _g(Ce,ze,ht,bt){return 4*nr[255+Ce[ze-ht]-Ce[ze+0]]+nr[255+Ce[ze-2*ht]-Ce[ze+ht]]<=bt}function ap(Ce,ze,ht,bt,Yt){var ls=Ce[ze-3*ht],hs=Ce[ze-2*ht],Ss=Ce[ze-ht],Ts=Ce[ze+0],Ws=Ce[ze+ht],Nn=Ce[ze+2*ht],Vn=Ce[ze+3*ht];return 4*nr[255+Ss-Ts]+nr[255+hs-Ws]>bt?0:nr[255+Ce[ze-4*ht]-ls]<=Yt&&nr[255+ls-hs]<=Yt&&nr[255+hs-Ss]<=Yt&&nr[255+Vn-Nn]<=Yt&&nr[255+Nn-Ws]<=Yt&&nr[255+Ws-Ts]<=Yt}function Zh(Ce,ze,ht,bt){var Yt=2*bt+1;for(bt=0;16>bt;++bt)_g(Ce,ze+bt,ht,Yt)&&wm(Ce,ze+bt,ht)}function Gp(Ce,ze,ht,bt){var Yt=2*bt+1;for(bt=0;16>bt;++bt)_g(Ce,ze+bt*ht,1,Yt)&&wm(Ce,ze+bt*ht,1)}function Rx(Ce,ze,ht,bt){var Yt;for(Yt=3;0>7,On=18*Pr+63>>7,Pr=9*Pr+63>>7;Ts[Ws-3*Nn]=hh[255+Ts[Ws-3*Nn]+Pr],Ts[Ws-2*Nn]=hh[255+Vn+On],Ts[Ws-Nn]=hh[255+Ks+hr],Ts[Ws+0]=hh[255+In-hr],Ts[Ws+Nn]=hh[255+Xn-On],Ts[Ws+2*Nn]=hh[255+Cr-Pr]}ze+=bt}}function Tc(Ce,ze,ht,bt,Yt,ls,hs,Ss){for(ls=2*ls+1;0>3)],Cr=up[112+(Cr+3>>3)],hr=Xn+1>>1;Ts[Ws-2*Nn]=hh[255+Ts[Ws-2*Nn]+hr],Ts[Ws-Nn]=hh[255+Vn+Cr],Ts[Ws+0]=hh[255+Ks-Xn],Ts[Ws+Nn]=hh[255+In-hr]}ze+=bt}}function ip(Ce,ze,ht,bt,Yt,ls){rd(Ce,ze,ht,1,16,bt,Yt,ls)}function Vd(Ce,ze,ht,bt,Yt,ls){rd(Ce,ze,1,ht,16,bt,Yt,ls)}function op(Ce,ze,ht,bt,Yt,ls){var hs;for(hs=3;0Ws?0:255:Ws)&255,Ws=Ts,Yt[ls+Ss]=Nn}}function Dc(Ce,ze,ht,bt){var Yt=ze.width,ls=ze.o;if(t(Ce!=null&&ze!=null),0>ht||0>=bt||ht+bt>ls)return null;if(!Ce.Cc){if(Ce.ga==null){var hs;if(Ce.ga=new Ha,(hs=Ce.ga==null)||(hs=ze.width*ze.o,t(Ce.Gb.length==0),Ce.Gb=i(hs),Ce.Uc=0,Ce.Gb==null?hs=0:(Ce.mb=Ce.Gb,Ce.nb=Ce.Uc,Ce.rc=null,hs=1),hs=!hs),!hs){hs=Ce.ga;var Ss=Ce.Fa,Ts=Ce.P,Ws=Ce.qc,Nn=Ce.mb,Vn=Ce.nb,Ks=Ts+1,In=Ws-1,Xn=hs.l;if(t(Ss!=null&&Nn!=null&&ze!=null),lx[0]=null,lx[1]=Zi,lx[2]=Hi,lx[3]=rl,hs.ca=Nn,hs.tb=Vn,hs.c=ze.width,hs.i=ze.height,t(0=Ws)ze=0;else if(hs.$a=3&Ss[Ts+0],hs.Z=Ss[Ts+0]>>2&3,hs.Lc=Ss[Ts+0]>>4&3,Ts=Ss[Ts+0]>>6&3,0>hs.$a||1=hs.c*hs.i;hs=!ze}if(hs)return null;Ce.ga.Lc!=1?Ce.Ga=0:bt=ls-ht}t(Ce.ga!=null),t(ht+bt<=ls);e:{if(ze=(Ss=Ce.ga).c,ls=Ss.l.o,Ss.$a==0){if(Ks=Ce.rc,In=Ce.Vc,Xn=Ce.Fa,Ts=Ce.P+1+ht*ze,Ws=Ce.mb,Nn=Ce.nb+ht*ze,t(Ts<=Ce.P+Ce.qc),Ss.Z!=0)for(t(lx[Ss.Z]!=null),hs=0;hs=ze)ze=1;else if(Ss.ic||bc(),Ss.ic){Ss=hs.V,Ks=hs.Ba,In=hs.c;var Cr=hs.i,hr=(Xn=1,Ts=hs.$/In,Ws=hs.$%In,Nn=hs.m,Vn=hs.s,hs.$),On=In*Cr,Pr=In*ze,ga=Vn.wc,ca=hr(Cr=pr(ca.G[0],ca.H[0],Nn)))Ss[Ks+hr]=Cr,++hr,++Ws>=In&&(Ws=0,++Ts<=ze&&!(Ts%16)&>(hs,Ts));else{if(!(280>Cr)){Xn=0;break t}Cr=Hr(Cr-256,Nn);var Li,fi=pr(ca.G[4],ca.H[4],Nn);if(Se(Nn),!(hr>=(fi=mr(In,fi=Hr(fi,Nn)))&&On-hr>=Cr)){Xn=0;break t}for(Li=0;Li=In;)Ws-=In,++Ts<=ze&&!(Ts%16)&>(hs,Ts);hrze?ze:Ts);break t}!Xn||Nn.h&&hr=ls&&(Ce.Cc=1),bt=1}if(!bt)return null;if(Ce.Cc&&((bt=Ce.ga)!=null&&(bt.mc=null),Ce.ga=null,0>23,Ss[Ts+4*hs+1]=Ss[Ts+4*hs+1]*Vn>>23,Ss[Ts+4*hs+2]=Ss[Ts+4*hs+2]*Vn>>23)}ze+=ls}}function ti(Ce,ze,ht,bt,Yt){for(;0>4)*Ts>>16;Ce[ze+2*ls+0]=(240&hs|hs>>4)*Ts>>16&240|(15&hs|hs<<4)*Ts>>16>>4&15,Ce[ze+2*ls+1]=240&Ws|Ss}ze+=Yt}}function ui(Ce,ze,ht,bt,Yt,ls,hs,Ss){var Ts,Ws,Nn=255;for(Ws=0;Ws>8}function bc(){j0=Lr,pw=ti,N0=ui,qb=Rl}function Gi(Ce,ze,ht){I[Ce]=function(bt,Yt,ls,hs,Ss,Ts,Ws,Nn,Vn,Ks,In,Xn,Cr,hr,On,Pr,ga){var ca,Li=ga-1>>1,fi=Ss[Ts+0]|Ws[Nn+0]<<16,Zo=Vn[Ks+0]|In[Xn+0]<<16;t(bt!=null);var Si=3*fi+Zo+131074>>2;for(ze(bt[Yt+0],255&Si,Si>>16,Cr,hr),ls!=null&&(Si=3*Zo+fi+131074>>2,ze(ls[hs+0],255&Si,Si>>16,On,Pr)),ca=1;ca<=Li;++ca){var Tl=Ss[Ts+ca]|Ws[Nn+ca]<<16,Ad=Vn[Ks+ca]|In[Xn+ca]<<16,Xo=fi+Tl+Zo+Ad+524296,Ti=Xo+2*(Tl+Zo)>>3;Si=Ti+fi>>1,fi=(Xo=Xo+2*(fi+Ad)>>3)+Tl>>1,ze(bt[Yt+2*ca-1],255&Si,Si>>16,Cr,hr+(2*ca-1)*ht),ze(bt[Yt+2*ca-0],255&fi,fi>>16,Cr,hr+(2*ca-0)*ht),ls!=null&&(Si=Xo+Zo>>1,fi=Ti+Ad>>1,ze(ls[hs+2*ca-1],255&Si,Si>>16,On,Pr+(2*ca-1)*ht),ze(ls[hs+2*ca+0],255&fi,fi>>16,On,Pr+(2*ca+0)*ht)),fi=Tl,Zo=Ad}1&ga||(Si=3*fi+Zo+131074>>2,ze(bt[Yt+ga-1],255&Si,Si>>16,Cr,hr+(ga-1)*ht),ls!=null&&(Si=3*Zo+fi+131074>>2,ze(ls[hs+ga-1],255&Si,Si>>16,On,Pr+(ga-1)*ht)))}}function Qh(){Kp[N1]=a2,Kp[k1]=gw,Kp[pv]=YN,Kp[Wp]=yw,Kp[vy]=Yp,Kp[k0]=hp,Kp[Hb]=SS,Kp[fv]=gw,Kp[n2]=yw,Kp[fw]=Yp,Kp[kg]=hp}function wg(Ce){return Ce&~QN?0>Ce?0:255:Ce>>XN}function jg(Ce,ze){return wg((19077*Ce>>8)+(26149*ze>>8)-14234)}function fu(Ce,ze,ht){return wg((19077*Ce>>8)-(6419*ze>>8)-(13320*ht>>8)+8708)}function Hl(Ce,ze){return wg((19077*Ce>>8)+(33050*ze>>8)-17685)}function b1(Ce,ze,ht,bt,Yt){bt[Yt+0]=jg(Ce,ht),bt[Yt+1]=fu(Ce,ze,ht),bt[Yt+2]=Hl(Ce,ze)}function Dx(Ce,ze,ht,bt,Yt){bt[Yt+0]=Hl(Ce,ze),bt[Yt+1]=fu(Ce,ze,ht),bt[Yt+2]=jg(Ce,ht)}function y0(Ce,ze,ht,bt,Yt){var ls=fu(Ce,ze,ht);ze=ls<<3&224|Hl(Ce,ze)>>3,bt[Yt+0]=248&jg(Ce,ht)|ls>>5,bt[Yt+1]=ze}function Hd(Ce,ze,ht,bt,Yt){var ls=240&Hl(Ce,ze)|15;bt[Yt+0]=240&jg(Ce,ht)|fu(Ce,ze,ht)>>4,bt[Yt+1]=ls}function lp(Ce,ze,ht,bt,Yt){bt[Yt+0]=255,b1(Ce,ze,ht,bt,Yt+1)}function v0(Ce,ze,ht,bt,Yt){Dx(Ce,ze,ht,bt,Yt),bt[Yt+3]=255}function yy(Ce,ze,ht,bt,Yt){b1(Ce,ze,ht,bt,Yt),bt[Yt+3]=255}function ad(Ce,ze,ht){I[Ce]=function(bt,Yt,ls,hs,Ss,Ts,Ws,Nn,Vn){for(var Ks=Nn+(-2&Vn)*ht;Nn!=Ks;)ze(bt[Yt+0],ls[hs+0],Ss[Ts+0],Ws,Nn),ze(bt[Yt+1],ls[hs+0],Ss[Ts+0],Ws,Nn+ht),Yt+=2,++hs,++Ts,Nn+=2*ht;1&Vn&&ze(bt[Yt+0],ls[hs+0],Ss[Ts+0],Ws,Nn)}}function gd(Ce,ze,ht){return ht==0?Ce==0?ze==0?6:5:ze==0?4:0:ht}function Lu(Ce,ze,ht,bt,Yt){switch(Ce>>>30){case 3:dh(ze,ht,bt,Yt,0);break;case 2:If(ze,ht,bt,Yt);break;case 1:gu(ze,ht,bt,Yt)}}function jm(Ce,ze){var ht,bt,Yt=ze.M,ls=ze.Nb,hs=Ce.oc,Ss=Ce.pc+40,Ts=Ce.oc,Ws=Ce.pc+584,Nn=Ce.oc,Vn=Ce.pc+600;for(ht=0;16>ht;++ht)hs[Ss+32*ht-1]=129;for(ht=0;8>ht;++ht)Ts[Ws+32*ht-1]=129,Nn[Vn+32*ht-1]=129;for(0ht;++ht)r(hs,Ss+32*ht-4,hs,Ss+32*ht+12,4);for(ht=-1;8>ht;++ht)r(Ts,Ws+32*ht-4,Ts,Ws+32*ht+4,4),r(Nn,Vn+32*ht-4,Nn,Vn+32*ht+4,4)}var In=Ce.Gd,Xn=Ce.Hd+bt,Cr=Ks.ad,hr=Ks.Hc;if(0=Ce.za-1?a(On,Pr,In[Xn].y[15],4):r(On,Pr,In[Xn+1].y,0,4)),ht=0;4>ht;ht++)On[Pr+128+ht]=On[Pr+256+ht]=On[Pr+384+ht]=On[Pr+0+ht];for(ht=0;16>ht;++ht,hr<<=2)On=hs,Pr=Ss+_y[ht],Xd[Ks.Ob[ht]](On,Pr),Lu(hr,Cr,16*+ht,On,Pr)}else if(On=gd(bt,Yt,Ks.Ob[0]),Rf[On](hs,Ss),hr!=0)for(ht=0;16>ht;++ht,hr<<=2)Lu(hr,Cr,16*+ht,hs,Ss+_y[ht]);for(ht=Ks.Gc,On=gd(bt,Yt,Ks.Dd),Cg[On](Ts,Ws),Cg[On](Nn,Vn),hr=Cr,On=Ts,Pr=Ws,255&(Ks=0|ht)&&(170&Ks?_1(hr,256,On,Pr):zl(hr,256,On,Pr)),Ks=Nn,hr=Vn,255&(ht>>=8)&&(170&ht?_1(Cr,320,Ks,hr):zl(Cr,320,Ks,hr)),Ytht;++ht)r(In,Xn+ht*Ce.R,hs,Ss+32*ht,16);for(ht=0;8>ht;++ht)r(Cr,Ks+ht*Ce.B,Ts,Ws+32*ht,8),r(hr,On+ht*Ce.B,Nn,Vn+32*ht,8)}}function Lf(Ce,ze,ht,bt,Yt,ls,hs,Ss,Ts){var Ws=[0],Nn=[0],Vn=0,Ks=Ts!=null?Ts.kd:0,In=Ts??new en;if(Ce==null||12>ht)return 7;In.data=Ce,In.w=ze,In.ha=ht,ze=[ze],ht=[ht],In.gb=[In.gb];e:{var Xn=ze,Cr=ht,hr=In.gb;if(t(Ce!=null),t(Cr!=null),t(hr!=null),hr[0]=0,12<=Cr[0]&&!n(Ce,Xn[0],"RIFF")){if(n(Ce,Xn[0]+8,"WEBP")){hr=3;break e}var On=_e(Ce,Xn[0]+4);if(12>On||4294967286Cr[0]-8){hr=7;break e}hr[0]=On,Xn[0]+=12,Cr[0]-=12}hr=0}if(hr!=0)return hr;for(On=0hr[0])hr=7;else{if(!n(Pr,Cr[0],"VP8X")){if(_e(Pr,Cr[0]+4)!=10){hr=3;break e}if(18>hr[0]){hr=7;break e}var fi=_e(Pr,Cr[0]+8),Zo=1+Ge(Pr,Cr[0]+12);if(2147483648<=Zo*(Pr=1+Ge(Pr,Cr[0]+15))){hr=3;break e}Li!=null&&(Li[0]=fi),ga!=null&&(ga[0]=Zo),ca!=null&&(ca[0]=Pr),Cr[0]+=18,hr[0]-=18,Si[0]=1}hr=0}}if(Vn=Vn[0],Xn=Xn[0],hr!=0)return hr;if(Cr=!!(2&Xn),!On&&Vn)return 3;if(ls!=null&&(ls[0]=!!(16&Xn)),hs!=null&&(hs[0]=Cr),Ss!=null&&(Ss[0]=0),hs=Ws[0],Xn=Nn[0],Vn&&Cr&&Ts==null){hr=0;break}if(4>ht){hr=7;break}if(On&&Vn||!On&&!Vn&&!n(Ce,ze[0],"ALPH")){ht=[ht],In.na=[In.na],In.P=[In.P],In.Sa=[In.Sa];e:{fi=Ce,hr=ze,On=ht;var Si=In.gb;ga=In.na,ca=In.P,Li=In.Sa,Zo=22,t(fi!=null),t(On!=null),Pr=hr[0];var Tl=On[0];for(t(ga!=null),t(Li!=null),ga[0]=null,ca[0]=null,Li[0]=0;;){if(hr[0]=Pr,On[0]=Tl,8>Tl){hr=7;break e}var Ad=_e(fi,Pr+4);if(4294967286Si){hr=3;break e}if(!n(fi,Pr,"VP8 ")||!n(fi,Pr,"VP8L")){hr=0;break e}if(Tl[0]On[0])hr=7;else{if(Pr||Zo){if(Si=_e(Si,fi+4),12<=ga&&Si>ga-12){hr=3;break e}if(Ks&&Si>On[0]-8){hr=7;break e}ca[0]=Si,hr[0]+=8,On[0]-=8,Li[0]=Zo}else Li[0]=5<=On[0]&&Si[fi+0]==47&&!(Si[fi+4]>>5),ca[0]=On[0];hr=0}if(ht=ht[0],In.Ja=In.Ja[0],In.xa=In.xa[0],ze=ze[0],hr!=0)break;if(4294967286ht){hr=7;break}Ss=hs,Ks=Xn,Cr=ls,Ce==null||5>ht?Ce=0:5<=ht&&Ce[ze+0]==47&&!(Ce[ze+4]>>5)?(On=[0],Si=[0],ga=[0],ue(ca=new we,Ce,ze,ht),Ba(ca,On,Si,ga)?(Ss!=null&&(Ss[0]=On[0]),Ks!=null&&(Ks[0]=Si[0]),Cr!=null&&(Cr[0]=ga[0]),Ce=1):Ce=0):Ce=0}else{if(10>ht){hr=7;break}Ss=Xn,Ce==null||10>ht||!So(Ce,ze+3,ht-3)?Ce=0:(Ks=Ce[ze+0]|Ce[ze+1]<<8|Ce[ze+2]<<16,Cr=16383&(Ce[ze+7]<<8|Ce[ze+6]),Ce=16383&(Ce[ze+9]<<8|Ce[ze+8]),1&Ks||3<(Ks>>1&7)||!(Ks>>4&1)||Ks>>5>=In.Ja||!Cr||!Ce?Ce=0:(hs&&(hs[0]=Cr),Ss&&(Ss[0]=Ce),Ce=1))}if(!Ce||(hs=hs[0],Xn=Xn[0],Vn&&(Ws[0]!=hs||Nn[0]!=Xn)))return 3;Ts!=null&&(Ts[0]=In,Ts.offset=ze-Ts.w,t(4294967286>ze-Ts.w),t(Ts.offset==Ts.ha-ht));break}return hr==0||hr==7&&Vn&&Ts==null?(ls!=null&&(ls[0]|=In.na!=null&&0ht||(ls&=-2,hs&=-2),0>ls||0>hs||0>=Ss||0>=Ts||ls+Ss>bt||hs+Ts>Yt))return 0;if(ze.v=ls,ze.j=hs,ze.va=ls+Ss,ze.o=hs+Ts,ze.U=Ss,ze.T=Ts,ze.da=Ce!=null&&0Ce.S){var ze=Ce.f.RGBA;ze.fb+=(Ce.height-1)*ze.A,ze.A=-ze.A}else ze=Ce.f.kb,Ce=Ce.height,ze.O+=(Ce-1)*ze.fa,ze.fa=-ze.fa,ze.N+=(Ce-1>>1)*ze.Ab,ze.Ab=-ze.Ab,ze.W+=(Ce-1>>1)*ze.Db,ze.Db=-ze.Db,ze.F!=null&&(ze.J+=(Ce-1)*ze.lb,ze.lb=-ze.lb);return 0}function Ir(Ce,ze,ht,bt){if(bt==null||0>=Ce||0>=ze)return 2;if(ht!=null){if(ht.Da){var Yt=ht.cd,ls=ht.bd,hs=-2&ht.v,Ss=-2&ht.j;if(0>hs||0>Ss||0>=Yt||0>=ls||hs+Yt>Ce||Ss+ls>ze)return 2;Ce=Yt,ze=ls}if(ht.da){if(!Ue(Ce,ze,Yt=[ht.ib],ls=[ht.hb]))return 2;Ce=Yt[0],ze=ls[0]}}bt.width=Ce,bt.height=ze;e:{var Ts=bt.width,Ws=bt.height;if(Ce=bt.S,0>=Ts||0>=Ws||!(Ce>=N1&&13>Ce))Ce=2;else{if(0>=bt.Rd&&bt.sd==null){hs=ls=Yt=ze=0;var Nn=(Ss=Ts*Zb[Ce])*Ws;if(11>Ce||(ls=(Ws+1)/2*(ze=(Ts+1)/2),Ce==12&&(hs=(Yt=Ts)*Ws)),(Ws=i(Nn+2*ls+hs))==null){Ce=1;break e}bt.sd=Ws,11>Ce?((Ts=bt.f.RGBA).eb=Ws,Ts.fb=0,Ts.A=Ss,Ts.size=Nn):((Ts=bt.f.kb).y=Ws,Ts.O=0,Ts.fa=Ss,Ts.Fd=Nn,Ts.f=Ws,Ts.N=0+Nn,Ts.Ab=ze,Ts.Cd=ls,Ts.ea=Ws,Ts.W=0+Nn+ls,Ts.Db=ze,Ts.Ed=ls,Ce==12&&(Ts.F=Ws,Ts.J=0+Nn+2*ls),Ts.Tc=hs,Ts.lb=Yt)}if(ze=1,Yt=bt.S,ls=bt.width,hs=bt.height,Yt>=N1&&13>Yt)if(11>Yt)Ce=bt.f.RGBA,ze&=(Ss=Math.abs(Ce.A))*(hs-1)+ls<=Ce.size,ze&=Ss>=ls*Zb[Yt],ze&=Ce.eb!=null;else{Ce=bt.f.kb,Ss=(ls+1)/2,Nn=(hs+1)/2,Ts=Math.abs(Ce.fa),Ws=Math.abs(Ce.Ab);var Vn=Math.abs(Ce.Db),Ks=Math.abs(Ce.lb),In=Ks*(hs-1)+ls;ze&=Ts*(hs-1)+ls<=Ce.Fd,ze&=Ws*(Nn-1)+Ss<=Ce.Cd,ze=(ze&=Vn*(Nn-1)+Ss<=Ce.Ed)&Ts>=ls&Ws>=Ss&Vn>=Ss,ze&=Ce.y!=null,ze&=Ce.f!=null,ze&=Ce.ea!=null,Yt==12&&(ze&=Ks>=ls,ze&=In<=Ce.Tc,ze&=Ce.F!=null)}else ze=0;Ce=ze?0:2}}return Ce!=0||ht!=null&&ht.fd&&(Ce=ka(bt)),Ce}var Fl=64,Sa=[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],Nm=24,id=32,la=8,Ox=[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];Ye("Predictor0","PredictorAdd0"),I.Predictor0=function(){return 4278190080},I.Predictor1=function(Ce){return Ce},I.Predictor2=function(Ce,ze,ht){return ze[ht+0]},I.Predictor3=function(Ce,ze,ht){return ze[ht+1]},I.Predictor4=function(Ce,ze,ht){return ze[ht-1]},I.Predictor5=function(Ce,ze,ht){return rt(rt(Ce,ze[ht+1]),ze[ht+0])},I.Predictor6=function(Ce,ze,ht){return rt(Ce,ze[ht-1])},I.Predictor7=function(Ce,ze,ht){return rt(Ce,ze[ht+0])},I.Predictor8=function(Ce,ze,ht){return rt(ze[ht-1],ze[ht+0])},I.Predictor9=function(Ce,ze,ht){return rt(ze[ht+0],ze[ht+1])},I.Predictor10=function(Ce,ze,ht){return rt(rt(Ce,ze[ht-1]),rt(ze[ht+0],ze[ht+1]))},I.Predictor11=function(Ce,ze,ht){var bt=ze[ht+0];return 0>=Dt(bt>>24&255,Ce>>24&255,(ze=ze[ht-1])>>24&255)+Dt(bt>>16&255,Ce>>16&255,ze>>16&255)+Dt(bt>>8&255,Ce>>8&255,ze>>8&255)+Dt(255&bt,255&Ce,255&ze)?bt:Ce},I.Predictor12=function(Ce,ze,ht){var bt=ze[ht+0];return(Fe((Ce>>24&255)+(bt>>24&255)-((ze=ze[ht-1])>>24&255))<<24|Fe((Ce>>16&255)+(bt>>16&255)-(ze>>16&255))<<16|Fe((Ce>>8&255)+(bt>>8&255)-(ze>>8&255))<<8|Fe((255&Ce)+(255&bt)-(255&ze)))>>>0},I.Predictor13=function(Ce,ze,ht){var bt=ze[ht-1];return(dt((Ce=rt(Ce,ze[ht+0]))>>24&255,bt>>24&255)<<24|dt(Ce>>16&255,bt>>16&255)<<16|dt(Ce>>8&255,bt>>8&255)<<8|dt(255&Ce,255&bt))>>>0};var Ng=I.PredictorAdd0;I.PredictorAdd1=pt,Ye("Predictor2","PredictorAdd2"),Ye("Predictor3","PredictorAdd3"),Ye("Predictor4","PredictorAdd4"),Ye("Predictor5","PredictorAdd5"),Ye("Predictor6","PredictorAdd6"),Ye("Predictor7","PredictorAdd7"),Ye("Predictor8","PredictorAdd8"),Ye("Predictor9","PredictorAdd9"),Ye("Predictor10","PredictorAdd10"),Ye("Predictor11","PredictorAdd11"),Ye("Predictor12","PredictorAdd12"),Ye("Predictor13","PredictorAdd13");var ox=I.PredictorAdd2;As("ColorIndexInverseTransform","MapARGB","32b",function(Ce){return Ce>>8&255},function(Ce){return Ce}),As("VP8LColorIndexInverseTransformAlpha","MapAlpha","8b",function(Ce){return Ce},function(Ce){return Ce>>8&255});var b0,Pf=I.ColorIndexInverseTransform,Oc=I.MapARGB,cp=I.VP8LColorIndexInverseTransformAlpha,ch=I.MapAlpha,xu=I.VP8LPredictorsAdd=[];xu.length=16,(I.VP8LPredictors=[]).length=16,(I.VP8LPredictorsAdd_C=[]).length=16,(I.VP8LPredictors_C=[]).length=16;var Kc,dp,hv,mv,_c,Fx,_0,dh,If,_1,gu,zl,Yo,$o,Gd,Yc,zx,w0,uh,$b,mw,Ub,Bx,yu,j0,pw,N0,qb,e2=i(511),t2=i(2041),w1=i(225),j1=i(767),s2=0,Vb=t2,up=w1,hh=j1,nr=e2,N1=0,k1=1,pv=2,Wp=3,vy=4,k0=5,Hb=6,fv=7,n2=8,fw=9,kg=10,_S=[2,3,7],oo=[3,3,11],WN=[280,256,256,256,40],wS=[0,1,1,1,0],E6=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],jS=[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],iC=[2954,2956,2958,2962,2970,2986,3018,3082,3212,3468,3980,5004],wc=8,Gb=[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],NS=[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],S1=null,M6=[[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]],Sg=[0,1,4,8,5,2,3,6,9,12,13,10,7,11,14,15],xw=[-0,1,-1,2,-2,3,4,6,-3,5,-4,-5,-6,7,-7,8,-8,-9],Wb=[[[[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]]]],KN=[[[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]]],C1=[[[[255,255,255,255,255,255,255,255,255,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]]]],A1=[0,1,2,3,6,4,5,6,6,6,6,6,6,6,6,7,0],Rf=[],Xd=[],Cg=[],r2=1,kS=2,lx=[],Kp=[];Gi("UpsampleRgbLinePair",b1,3),Gi("UpsampleBgrLinePair",Dx,3),Gi("UpsampleRgbaLinePair",yy,4),Gi("UpsampleBgraLinePair",v0,4),Gi("UpsampleArgbLinePair",lp,4),Gi("UpsampleRgba4444LinePair",Hd,2),Gi("UpsampleRgb565LinePair",y0,2);var a2=I.UpsampleRgbLinePair,YN=I.UpsampleBgrLinePair,gw=I.UpsampleRgbaLinePair,yw=I.UpsampleBgraLinePair,Yp=I.UpsampleArgbLinePair,hp=I.UpsampleRgba4444LinePair,SS=I.UpsampleRgb565LinePair,by=16,vw=1<bt.ca.S||(alert("todo:WebPInitConvertARGBToYUV"),bt.ca.f.kb.F!=null&&bc()),bt.Pb&&0(Ts=ht.Md)?0:100Ws;++Ws)12>(Vn=Yt.pb[Ws]).lc&&(Vn.ia=Ts*Jh[0>Vn.lc?0:Vn.lc]>>3),Nn|=Vn.ia;Nn&&(alert("todo:VP8InitRandom"),Yt.ia=1)}Yt.Ga=ht.Id,100Yt.Ga&&(Yt.Ga=0)}(function(Ks,In){if(Ks==null)return 0;if(In==null)return Va(Ks,2,"NULL VP8Io parameter in VP8Decode().");if(!Ks.cb&&!$a(Ks,In))return 0;if(t(Ks.cb),In.ac==null||In.ac(In)){In.ob&&(Ks.L=0);var Xn=jw[Ks.L];if(Ks.L==2?(Ks.yb=0,Ks.zb=0):(Ks.yb=In.v-Xn>>4,Ks.zb=In.j-Xn>>4,0>Ks.yb&&(Ks.yb=0),0>Ks.zb&&(Ks.zb=0)),Ks.Va=In.o+15+Xn>>4,Ks.Hb=In.va+15+Xn>>4,Ks.Hb>Ks.za&&(Ks.Hb=Ks.za),Ks.Va>Ks.Ub&&(Ks.Va=Ks.Ub),0Xn;++Xn){var hr;if(Ks.Qa.Cb){var On=Ks.Qa.Lb[Xn];Ks.Qa.Fb||(On+=Cr.Tb)}else On=Cr.Tb;for(hr=0;1>=hr;++hr){var Pr=Ks.gd[Xn][hr],ga=On;if(Cr.Pc&&(ga+=Cr.vd[0],hr&&(ga+=Cr.od[0])),0<(ga=0>ga?0:63>2:ca>>1)>9-Cr.wb&&(ca=9-Cr.wb),1>ca&&(ca=1),Pr.dd=ca,Pr.tc=2*ga+ca,Pr.ld=40<=ga?2:15<=ga?1:0}else Pr.tc=0;Pr.La=hr}}}Xn=0}else Va(Ks,6,"Frame setup failed"),Xn=Ks.a;if(Xn=Xn==0){if(Xn){Ks.$c=0,0Ks.Vb){if(Ks.Vb=0,Ks.Ec=i(Pr),Ks.Fc=0,Ks.Ec==null){Xn=Va(Ks,1,"no memory during frame initialization.");break t}Ks.Vb=Pr}Pr=Ks.Ec,ga=Ks.Fc,Ks.Ac=Pr,Ks.Bc=ga,ga+=Cr,Ks.Gd=l(Li,Na),Ks.Hd=0,Ks.rb=l(fi+1,Qt),Ks.sb=1,Ks.wa=Zo?l(Zo,Xr):null,Ks.Y=0,Ks.D.Nb=0,Ks.D.wa=Ks.wa,Ks.D.Y=Ks.Y,0=Xn;++Xn)e2[255+Xn]=0>Xn?-Xn:Xn;for(Xn=-1020;1020>=Xn;++Xn)t2[1020+Xn]=-128>Xn?-128:127=Xn;++Xn)w1[112+Xn]=-16>Xn?-16:15=Xn;++Xn)j1[255+Xn]=0>Xn?0:255qo;++qo){var od,uc=vd[0+qo];for(od=0;4>od;++od){uc=KN[yd[Th+od]][uc];for(var Zc=xw[De(io,uc[0])];0>3;for(Zc=0;256>Zc;Zc+=16)qo[Wd+Zc]=Xu}Pu=1,km=Th[0]}var Bl=15&io.la,Iu=15&Zp.la;for(Zc=0;4>Zc;++Zc){var Sm=1&Iu;for(Xu=jc=0;4>Xu;++Xu)Bl=Bl>>1|(Sm=(Fc=S1(yd,km,Fc=Sm+(1&Bl),Qd.Sc,Pu,qo,Wd))>Pu)<<7,jc=jc<<2|(3>=4,Iu=Iu>>1|Sm<<7,od=(od<<8|jc)>>>0}for(km=Bl,Pu=Iu>>4,vu=0;4>vu;vu+=2){for(jc=0,Bl=io.la>>4+vu,Iu=Zp.la>>4+vu,Zc=0;2>Zc;++Zc){for(Sm=1&Iu,Xu=0;2>Xu;++Xu)Fc=Sm+(1&Bl),Bl=Bl>>1|(Sm=0<(Fc=S1(yd,Th[2],Fc,Qd.Qc,0,qo,Wd)))<<3,jc=jc<<2|(3>=2,Iu=Iu>>1|Sm<<5}uc|=jc<<4*vu,km|=Bl<<4<=Ti.zb&&Ti.M<=Ti.Va,Ti.Aa==0)t:{if(Xo.M=Ti.M,Xo.uc=io,jm(Ti,Xo),el=1,Xo=(jc=Ti.D).Nb,io=(uc=jw[Ti.L])*Ti.R,yd=uc/2*Ti.B,Zc=16*Xo*Ti.R,Xu=8*Xo*Ti.B,Th=Ti.sa,vd=Ti.ta-io+Zc,Qd=Ti.qa,qo=Ti.ra-yd+Xu,Wd=Ti.Ha,Zp=Ti.Ia-yd+Xu,Iu=(Bl=jc.M)==0,od=Bl>=Ti.Va-1,Ti.Aa==2&&jm(Ti,jc),jc.uc)for(Sm=(Fc=Ti).D.M,t(Fc.D.uc),jc=Fc.yb;jcYa.o&&(Bl=Ya.o),Ya.F=null,Ya.J=null,Ti.Fa!=null&&0>1),Ya.W+=Ti.B*(uc>>1),Ya.F!=null&&(Ya.J+=Ya.width*uc)),jc>1,Ya.W+=Ya.v>>1,Ya.F!=null&&(Ya.J+=Ya.v),Ya.ka=jc-Ya.j,Ya.U=Ya.va-Ya.v,Ya.T=Bl-jc,el=Ya.put(Ya))}Xo+1!=Ti.Ic||od||(r(Ti.sa,Ti.ta-io,Th,vd+16*Ti.R,io),r(Ti.qa,Ti.ra-yd,Qd,qo+8*Ti.B,yd),r(Ti.Ha,Ti.Ia-yd,Wd,Zp+8*Ti.B,yd))}if(!el)return Va(Tl,6,"Output aborted.")}return 1}(Ks,In)),In.bc!=null&&In.bc(In),Xn&=1}return Xn?(Ks.cb=0,Xn):0})(Ce,bt)||(ze=Ce.a)}}else ze=Ce.a}ze==0&&hs.Oa!=null&&hs.Oa.fd&&(ze=ka(hs.ba))}hs=ze}ls=hs!=0?null:11>ls?Ss.f.RGBA.eb:Ss.f.kb.y}else ls=null;return ls};var Zb=[3,4,3,4,4,2,2,4,4,4,2,1,1]};function d(I,O){for(var $="",q=0;q<4;q++)$+=String.fromCharCode(I[O++]);return $}function u(I,O){return I[O+0]|I[O+1]<<8}function h(I,O){return(I[O+0]|I[O+1]<<8|I[O+2]<<16)>>>0}function m(I,O){return(I[O+0]|I[O+1]<<8|I[O+2]<<16|I[O+3]<<24)>>>0}new c;var p=[0],x=[0],y=[],g=new c,b=s,v=function(I,O){var $={},q=0,W=!1,G=0,K=0;if($.frames=[],!function(de,we){for(var je=0;je<4;je++)if(de[we+je]!="RIFF".charCodeAt(je))return!0;return!1}(I,O)){for(m(I,O+=4),O+=8;O>1&1}ee!="ANMF"&&(O+=le)}return $}}(b,0);v.response=b,v.rgbaoutput=!0,v.dataurl=!1;var k=v.header?v.header:null,C=v.frames?v.frames:null;if(k){k.loop_counter=k.loop_count,p=[k.canvas_height],x=[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 Hwn(){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(de){return de=de||{},this.isStrokeTransparent=de.isStrokeTransparent||!1,this.strokeOpacity=de.strokeOpacity||1,this.strokeStyle=de.strokeStyle||"#000000",this.fillStyle=de.fillStyle||"#000000",this.isFillTransparent=de.isFillTransparent||!1,this.fillOpacity=de.fillOpacity||1,this.font=de.font||"10px sans-serif",this.textBaseline=de.textBaseline||"alphabetic",this.textAlign=de.textAlign||"left",this.lineWidth=de.lineWidth||1,this.lineJoin=de.lineJoin||"miter",this.lineCap=de.lineCap||"butt",this.path=de.path||[],this.transform=de.transform!==void 0?de.transform.clone():new c,this.globalCompositeOperation=de.globalCompositeOperation||"normal",this.globalAlpha=de.globalAlpha||1,this.clip_path=de.clip_path||[],this.currentPoint=de.currentPoint||new l,this.miterLimit=de.miterLimit||10,this.lastPoint=de.lastPoint||new l,this.lineDashOffset=de.lineDashOffset||0,this.lineDash=de.lineDash||[],this.margin=de.margin||[0,0,0,0],this.prevPageLastElemOffset=de.prevPageLastElemOffset||0,this.ignoreClearRect=typeof de.ignoreClearRect!="boolean"||de.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(de){Object.defineProperty(this,"canvas",{get:function(){return{parentNode:!1,style:!1}}});var we=de;Object.defineProperty(this,"pdf",{get:function(){return we}});var je=!1;Object.defineProperty(this,"pageWrapXEnabled",{get:function(){return je},set:function(Oe){je=!!Oe}});var xe=!1;Object.defineProperty(this,"pageWrapYEnabled",{get:function(){return xe},set:function(Oe){xe=!!Oe}});var fe=0;Object.defineProperty(this,"posX",{get:function(){return fe},set:function(Oe){isNaN(Oe)||(fe=Oe)}});var Se=0;Object.defineProperty(this,"posY",{get:function(){return Se},set:function(Oe){isNaN(Oe)||(Se=Oe)}}),Object.defineProperty(this,"margin",{get:function(){return d.margin},set:function(Oe){var Ae;typeof Oe=="number"?Ae=[Oe,Oe,Oe,Oe]:((Ae=new Array(4))[0]=Oe[0],Ae[1]=Oe.length>=2?Oe[1]:Ae[0],Ae[2]=Oe.length>=3?Oe[2]:Ae[0],Ae[3]=Oe.length>=4?Oe[3]:Ae[1]),d.margin=Ae}});var Ee=!1;Object.defineProperty(this,"autoPaging",{get:function(){return Ee},set:function(Oe){Ee=Oe}});var Le=0;Object.defineProperty(this,"lastBreak",{get:function(){return Le},set:function(Oe){Le=Oe}});var De=[];Object.defineProperty(this,"pageBreaks",{get:function(){return De},set:function(Oe){De=Oe}}),Object.defineProperty(this,"ctx",{get:function(){return d},set:function(Oe){Oe instanceof u&&(d=Oe)}}),Object.defineProperty(this,"path",{get:function(){return d.path},set:function(Oe){d.path=Oe}});var Be=[];Object.defineProperty(this,"ctxStack",{get:function(){return Be},set:function(Oe){Be=Oe}}),Object.defineProperty(this,"fillStyle",{get:function(){return this.ctx.fillStyle},set:function(Oe){var Ae;Ae=m(Oe),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(Oe){var Ae=m(Oe);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(Oe){["butt","round","square"].indexOf(Oe)!==-1&&(this.ctx.lineCap=Oe,this.pdf.setLineCap(Oe))}}),Object.defineProperty(this,"lineWidth",{get:function(){return this.ctx.lineWidth},set:function(Oe){isNaN(Oe)||(this.ctx.lineWidth=Oe,this.pdf.setLineWidth(Oe))}}),Object.defineProperty(this,"lineJoin",{get:function(){return this.ctx.lineJoin},set:function(Oe){["bevel","round","miter"].indexOf(Oe)!==-1&&(this.ctx.lineJoin=Oe,this.pdf.setLineJoin(Oe))}}),Object.defineProperty(this,"miterLimit",{get:function(){return this.ctx.miterLimit},set:function(Oe){isNaN(Oe)||(this.ctx.miterLimit=Oe,this.pdf.setMiterLimit(Oe))}}),Object.defineProperty(this,"textBaseline",{get:function(){return this.ctx.textBaseline},set:function(Oe){this.ctx.textBaseline=Oe}}),Object.defineProperty(this,"textAlign",{get:function(){return this.ctx.textAlign},set:function(Oe){["right","end","center","left","start"].indexOf(Oe)!==-1&&(this.ctx.textAlign=Oe)}});var Ne=null,Ge=null,_e=null;Object.defineProperty(this,"fontFaces",{get:function(){return _e},set:function(Oe){Ne=null,Ge=null,_e=Oe}}),Object.defineProperty(this,"font",{get:function(){return this.ctx.font},set:function(Oe){var Ae;if(this.ctx.font=Oe,(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(Oe))!==null){var Xe=Ae[1];Ae[2];var Ue=Ae[3],Ze=Ae[4];Ae[5];var Qe=Ae[6],Ye=/^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec(Ze)[2];Ze=Math.floor(Ye==="px"?parseFloat(Ze)*this.pdf.internal.scaleFactor:Ye==="em"?parseFloat(Ze)*this.pdf.getFontSize():parseFloat(Ze)*this.pdf.internal.scaleFactor),this.pdf.setFontSize(Ze);var nt=function(As){var Bt,At,Is=[],jt=As.trim();if(jt==="")return PIe;if(jt in dxt)return[dxt[jt]];for(;jt!=="";){switch(At=null,Bt=(jt=hxt(jt)).charAt(0)){case'"':case"'":At=Fwn(jt.substring(1),Bt);break;default:At=zwn(jt)}if(At===null||(Is.push(At[0]),(jt=hxt(At[1]))!==""&&jt.charAt(0)!==","))return PIe;jt=jt.replace(/^,/,"")}return Is}(Qe);if(this.fontFaces){var rt=function(As,Bt){var At=As.getFontList(),Is=JSON.stringify(At);if(Ne===null||Ge!==Is){var jt=function(Qs){var cn=[];return Object.keys(Qs).forEach(function(qt){Qs[qt].forEach(function(Gs){var Ls=null;switch(Gs){case"bold":Ls={family:qt,weight:"bold"};break;case"italic":Ls={family:qt,style:"italic"};break;case"bolditalic":Ls={family:qt,weight:"bold",style:"italic"};break;case"":case"normal":Ls={family:qt}}Ls!==null&&(Ls.ref={name:qt,style:Gs},cn.push(Ls))})}),cn}(At);Ne=function(Qs){for(var cn={},qt=0;qt=700||Xe==="bold")&&(Dt="bold"),Xe==="italic"&&(Dt+="italic"),Dt.length===0&&(Dt="normal");for(var pt="",zt={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"},Gt=0;Gt=2*Math.PI&&(xe=0,fe=2*Math.PI),this.path.push({type:"arc",x:de,y:we,radius:je,startAngle:xe,endAngle:fe,counterclockwise:Se})},h.prototype.arcTo=function(de,we,je,xe,fe){throw new Error("arcTo not implemented.")},h.prototype.rect=function(de,we,je,xe){if(isNaN(de)||isNaN(we)||isNaN(je)||isNaN(xe))throw gh.error("jsPDF.context2d.rect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rect");this.moveTo(de,we),this.lineTo(de+je,we),this.lineTo(de+je,we+xe),this.lineTo(de,we+xe),this.lineTo(de,we),this.lineTo(de+je,we),this.lineTo(de,we)},h.prototype.fillRect=function(de,we,je,xe){if(isNaN(de)||isNaN(we)||isNaN(je)||isNaN(xe))throw gh.error("jsPDF.context2d.fillRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.fillRect");if(!p.call(this)){var fe={};this.lineCap!=="butt"&&(fe.lineCap=this.lineCap,this.lineCap="butt"),this.lineJoin!=="miter"&&(fe.lineJoin=this.lineJoin,this.lineJoin="miter"),this.beginPath(),this.rect(de,we,je,xe),this.fill(),fe.hasOwnProperty("lineCap")&&(this.lineCap=fe.lineCap),fe.hasOwnProperty("lineJoin")&&(this.lineJoin=fe.lineJoin)}},h.prototype.strokeRect=function(de,we,je,xe){if(isNaN(de)||isNaN(we)||isNaN(je)||isNaN(xe))throw gh.error("jsPDF.context2d.strokeRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.strokeRect");x.call(this)||(this.beginPath(),this.rect(de,we,je,xe),this.stroke())},h.prototype.clearRect=function(de,we,je,xe){if(isNaN(de)||isNaN(we)||isNaN(je)||isNaN(xe))throw gh.error("jsPDF.context2d.clearRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.clearRect");this.ignoreClearRect||(this.fillStyle="#ffffff",this.fillRect(de,we,je,xe))},h.prototype.save=function(de){de=typeof de!="boolean"||de;for(var we=this.pdf.internal.getCurrentPageInfo().pageNumber,je=0;je0||this.margin[1]>0||this.margin[2]>0||this.margin[3]>0};h.prototype.drawImage=function(de,we,je,xe,fe,Se,Ee,Le,De){var Be=this.pdf.getImageProperties(de),Ne=1,Ge=1,_e=1,Oe=1;xe!==void 0&&Le!==void 0&&(_e=Le/xe,Oe=De/fe,Ne=Be.width/xe*Le/xe,Ge=Be.height/fe*De/fe),Se===void 0&&(Se=we,Ee=je,we=0,je=0),xe!==void 0&&Le===void 0&&(Le=xe,De=fe),xe===void 0&&Le===void 0&&(Le=Be.width,De=Be.height);var Ae=this.ctx.transform.decompose(),Xe=le(Ae.rotate.shx),Ue=new c,Ze=(Ue=(Ue=(Ue=Ue.multiply(Ae.translate)).multiply(Ae.skew)).multiply(Ae.scale)).applyToRectangle(new o(Se-we*_e,Ee-je*Oe,xe*Ne,fe*Ge));if(this.autoPaging){for(var Qe,Ye=g.call(this,Ze),nt=[],rt=0;rtFe||DtZe||Ye0)){for(;De>=0;De--)if(fe[De-1].close!==!0&&fe[De-1].begin!==!0){fe[De-1].deltas.push(je),fe[De-1].abs.push(Le);break}}break;case"bct":je=[Le.x1-Se[Ee-1].x,Le.y1-Se[Ee-1].y,Le.x2-Se[Ee-1].x,Le.y2-Se[Ee-1].y,Le.x-Se[Ee-1].x,Le.y-Se[Ee-1].y],fe[fe.length-1].deltas.push(je);break;case"qct":var Be=Se[Ee-1].x+2/3*(Le.x1-Se[Ee-1].x),Ne=Se[Ee-1].y+2/3*(Le.y1-Se[Ee-1].y),Ge=Le.x+2/3*(Le.x1-Le.x),_e=Le.y+2/3*(Le.y1-Le.y),Oe=Le.x,Ae=Le.y;je=[Be-Se[Ee-1].x,Ne-Se[Ee-1].y,Ge-Se[Ee-1].x,_e-Se[Ee-1].y,Oe-Se[Ee-1].x,Ae-Se[Ee-1].y],fe[fe.length-1].deltas.push(je);break;case"arc":fe.push({deltas:[],abs:[],arc:!0}),Array.isArray(fe[fe.length-1].abs)&&fe[fe.length-1].abs.push(Le)}}xe=we?null:de==="stroke"?"stroke":"fill";for(var Xe=!1,Ue=0;Ue=.01&&(xe=this.pdf.internal.getFontSize(),this.pdf.setFontSize(xe*de.scale),fe=this.lineWidth,this.lineWidth=fe*de.scale);var qs=this.autoPaging!=="text";if(qs||Gt.y+Gt.h<=rt){if(qs||Gt.y>=Ye&&Gt.x<=dt){var As=qs?de.text:this.pdf.splitTextToSize(de.text,de.maxWidth||dt-Gt.x)[0],Bt=v([JSON.parse(JSON.stringify(Ge))],this.posX+this.margin[3],-pt+Ye+this.ctx.prevPageLastElemOffset)[0],At=qs&&(Qe>Ue||Qe=.01&&(this.pdf.setFontSize(xe),this.lineWidth=fe)}}else de.scale>=.01&&(xe=this.pdf.internal.getFontSize(),this.pdf.setFontSize(xe*de.scale),fe=this.lineWidth,this.lineWidth=fe*de.scale),this.pdf.text(de.text,De.x+this.posX,De.y+this.posY,{angle:de.angle,align:we,renderingMode:de.renderingMode,maxWidth:de.maxWidth}),de.scale>=.01&&(this.pdf.setFontSize(xe),this.lineWidth=fe)},W=function(de,we,je,xe){je=je||0,xe=xe||0,this.pdf.internal.out(n(de+je)+" "+r(we+xe)+" l")},G=function(de,we,je){return this.pdf.lines(de,we,je,null,null)},K=function(de,we,je,xe,fe,Se,Ee,Le){this.pdf.internal.out([t(a(je+de)),t(i(xe+we)),t(a(fe+de)),t(i(Se+we)),t(a(Ee+de)),t(i(Le+we)),"c"].join(" "))},ee=function(de,we,je,xe){for(var fe=2*Math.PI,Se=Math.PI/2;we>je;)we-=fe;var Ee=Math.abs(je-we);Ee1e-5;){var Ne=Be+De*Math.min(Ee,Se);Le.push(J.call(this,de,Be,Ne)),Ee-=Math.abs(Ne-Be),Be=Ne}return Le},J=function(de,we,je){var xe=(je-we)/2,fe=de*Math.cos(xe),Se=de*Math.sin(xe),Ee=fe,Le=-Se,De=Ee*Ee+Le*Le,Be=De+Ee*fe+Le*Se,Ne=4/3*(Math.sqrt(2*De*Be)-Be)/(Ee*Se-Le*fe),Ge=Ee-Ne*Le,_e=Le+Ne*Ee,Oe=Ge,Ae=-_e,Xe=xe+we,Ue=Math.cos(Xe),Ze=Math.sin(Xe);return{x1:de*Math.cos(we),y1:de*Math.sin(we),x2:Ge*Ue-_e*Ze,y2:Ge*Ze+_e*Ue,x3:Oe*Ue-Ae*Ze,y3:Oe*Ze+Ae*Ue,x4:de*Math.cos(je),y4:de*Math.sin(je)}},le=function(de){return 180*de/Math.PI},ue=function(de,we,je,xe,fe,Se){var Ee=de+.5*(je-de),Le=we+.5*(xe-we),De=fe+.5*(je-fe),Be=Se+.5*(xe-Se),Ne=Math.min(de,fe,Ee,De),Ge=Math.max(de,fe,Ee,De),_e=Math.min(we,Se,Le,Be),Oe=Math.max(we,Se,Le,Be);return new o(Ne,_e,Ge-Ne,Oe-_e)},oe=function(de,we,je,xe,fe,Se,Ee,Le){var De,Be,Ne,Ge,_e,Oe,Ae,Xe,Ue,Ze,Qe,Ye,nt,rt,Fe=je-de,dt=xe-we,Dt=fe-je,pt=Se-xe,zt=Ee-fe,Gt=Le-Se;for(Be=0;Be<41;Be++)Ue=(Ae=(Ne=de+(De=Be/40)*Fe)+De*((_e=je+De*Dt)-Ne))+De*(_e+De*(fe+De*zt-_e)-Ae),Ze=(Xe=(Ge=we+De*dt)+De*((Oe=xe+De*pt)-Ge))+De*(Oe+De*(Se+De*Gt-Oe)-Xe),Be==0?(Qe=Ue,Ye=Ze,nt=Ue,rt=Ze):(Qe=Math.min(Qe,Ue),Ye=Math.min(Ye,Ze),nt=Math.max(nt,Ue),rt=Math.max(rt,Ze));return new o(Math.round(Qe),Math.round(Ye),Math.round(nt-Qe),Math.round(rt-Ye))},ie=function(){if(this.prevLineDash||this.ctx.lineDash.length||this.ctx.lineDashOffset){var de,we,je=(de=this.ctx.lineDash,we=this.ctx.lineDashOffset,JSON.stringify({lineDash:de,lineDashOffset:we}));this.prevLineDash!==je&&(this.pdf.setLineDash(this.ctx.lineDash,this.ctx.lineDashOffset),this.prevLineDash=je)}}})(ho.API),function(s){var t=function(l){var o,c,d,u,h,m,p,x,y,g;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-(g=h%85))/85)-(y=h%85))/85)-(x=h%85))/85)-(p=h%85))/85)%85,c.push(m+33,p+33,x+33,y+33,g+33)):c.push(122);return function(b,v){for(var k=v;k>0;k--)b.pop()}(c,o.length),String.fromCharCode.apply(String,c)+"~>"},n=function(l){var o,c,d,u,h,m=String,p="length",x=255,y="charCodeAt",g="slice",b="replace";for(l[g](-2),l=l[g](0,-2)[b](/\s/g,"")[b]("z","!!!!!"),d=[],u=0,h=(l+=o="uuuuu"[g](l[p]%5||5))[p];h>u;u+=5)c=52200625*(l[y](u)-33)+614125*(l[y](u+1)-33)+7225*(l[y](u+2)-33)+85*(l[y](u+3)-33)+(l[y](u+4)-33),d.push(x&c>>24,x&c>>16,x&c>>8,x&c);return function(v,k){for(var C=k;C>0;C--)v.pop()}(d,o[p]),m.fromCharCode.apply(m,d)},r=function(l){return l.split("").map(function(o){return("0"+o.charCodeAt().toString(16)).slice(-2)}).join("")+">"},a=function(l){var o=new RegExp(/^([0-9A-Fa-f]{2})+$/);if((l=l.replace(/\s/g,"")).indexOf(">")!==-1&&(l=l.substr(0,l.indexOf(">"))),l.length%2&&(l+="0"),o.test(l)===!1)return"";for(var c="",d=0;dimport("./html2canvas.esm-CBrSDip1.js"),[])).catch(function(o){return Promise.reject(new Error("Could not load html2canvas: "+o))}).then(function(o){return o.default?o.default:o})}function n(){return(wl.DOMPurify?Promise.resolve(wl.DOMPurify):Mi(()=>import("./purify.es-dhnUglUx.js"),[])).catch(function(o){return Promise.reject(new Error("Could not load dompurify: "+o))}).then(function(o){return o.default?o.default:o})}var r=function(o){var c=Gu(o);return c==="undefined"?"undefined":c==="string"||o instanceof String?"string":c==="number"||o instanceof Number?"number":c==="function"||o instanceof Function?"function":o&&o.constructor===Array?"array":o&&o.nodeType===1?"element":c==="object"?"object":"unknown"},a=function(o,c){var d=document.createElement(o);for(var u in c.className&&(d.className=c.className),c.innerHTML&&c.dompurify&&(d.innerHTML=c.dompurify.sanitize(c.innerHTML)),c.style)d.style[u]=c.style[u];return d},i=function o(c,d){for(var u=c.nodeType===3?document.createTextNode(c.nodeValue):c.cloneNode(!1),h=c.firstChild;h;h=h.nextSibling)d!==!0&&h.nodeType===1&&h.nodeName==="SCRIPT"||u.appendChild(o(h,d));return c.nodeType===1&&(c.nodeName==="CANVAS"?(u.width=c.width,u.height=c.height,u.getContext("2d").drawImage(c,0,0)):c.nodeName!=="TEXTAREA"&&c.nodeName!=="SELECT"||(u.value=c.value),u.addEventListener("load",function(){u.scrollTop=c.scrollTop,u.scrollLeft=c.scrollLeft},!0)),u},l=function o(c){var d=Object.assign(o.convert(Promise.resolve()),JSON.parse(JSON.stringify(o.template))),u=o.convert(Promise.resolve(),d);return(u=u.setProgress(1,o,1,[o])).set(c)};(l.prototype=Object.create(Promise.prototype)).constructor=l,l.convert=function(o,c){return o.__proto__=c||l.prototype,o},l.template={prop:{src:null,container:null,overlay:null,canvas:null,img:null,pdf:null,pageSize:null,callback:function(){}},progress:{val:0,state:null,n:0,stack:[]},opt:{filename:"file.pdf",margin:[0,0,0,0],enableLinks:!0,x:0,y:0,html2canvas:{},jsPDF:{},backgroundColor:"transparent"}},l.prototype.from=function(o,c){return this.then(function(){switch(c=c||function(d){switch(r(d)){case"string":return"string";case"element":return d.nodeName.toLowerCase()==="canvas"?"canvas":"element";default:return"unknown"}}(o),c){case"string":return this.then(n).then(function(d){return this.set({src:a("div",{innerHTML:o,dompurify:d})})});case"element":return this.set({src:o});case"canvas":return this.set({canvas:o});case"img":return this.set({img:o});default:return this.error("Unknown source type.")}})},l.prototype.to=function(o){switch(o){case"container":return this.toContainer();case"canvas":return this.toCanvas();case"img":return this.toImg();case"pdf":return this.toPdf();default:return this.error("Invalid target.")}},l.prototype.toContainer=function(){return this.thenList([function(){return this.prop.src||this.error("Cannot duplicate - no source HTML.")},function(){return this.prop.pageSize||this.setPageSize()}]).then(function(){var o={position:"relative",display:"inline-block",width:(typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?Math.max(this.prop.src.clientWidth,this.prop.src.scrollWidth,this.prop.src.offsetWidth):this.opt.windowWidth)+"px",left:0,right:0,top:0,margin:"auto",backgroundColor:this.opt.backgroundColor},c=i(this.prop.src,this.opt.html2canvas.javascriptEnabled);c.tagName==="BODY"&&(o.height=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)+"px"),this.prop.overlay=a("div",{className:"html2pdf__overlay",style:{position:"fixed",overflow:"hidden",zIndex:1e3,left:"-100000px",right:0,bottom:0,top:0}}),this.prop.container=a("div",{className:"html2pdf__container",style:o}),this.prop.container.appendChild(c),this.prop.container.firstChild.appendChild(a("div",{style:{clear:"both",border:"0 none transparent",margin:0,padding:0,height:0}})),this.prop.container.style.float="none",this.prop.overlay.appendChild(this.prop.container),document.body.appendChild(this.prop.overlay),this.prop.container.firstChild.style.position="relative",this.prop.container.height=Math.max(this.prop.container.firstChild.clientHeight,this.prop.container.firstChild.scrollHeight,this.prop.container.firstChild.offsetHeight)+"px"})},l.prototype.toCanvas=function(){var o=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(o).then(t).then(function(c){var d=Object.assign({},this.opt.html2canvas);return delete d.onrendered,c(this.prop.container,d)}).then(function(c){(this.opt.html2canvas.onrendered||function(){})(c),this.prop.canvas=c,document.body.removeChild(this.prop.overlay)})},l.prototype.toContext2d=function(){var o=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(o).then(t).then(function(c){var d=this.opt.jsPDF,u=this.opt.fontFaces,h=typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?1:this.opt.width/this.opt.windowWidth,m=Object.assign({async:!0,allowTaint:!0,scale:h,scrollX:this.opt.scrollX||0,scrollY:this.opt.scrollY||0,backgroundColor:"#ffffff",imageTimeout:15e3,logging:!0,proxy:null,removeContainer:!0,foreignObjectRendering:!1,useCORS:!1},this.opt.html2canvas);if(delete m.onrendered,d.context2d.autoPaging=this.opt.autoPaging===void 0||this.opt.autoPaging,d.context2d.posX=this.opt.x,d.context2d.posY=this.opt.y,d.context2d.margin=this.opt.margin,d.context2d.fontFaces=u,u)for(var p=0;py&&(x=g,g=y,y=x);else{if(o!=="l"&&o!=="landscape")throw"Invalid orientation: "+o;o="l",y>g&&(x=g,g=y,y=x)}return{width:g,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(LIe):null;var d=new l(c);return c.worker?d:d.from(o).doCallback()}}(ho.API),ho.API.addJS=function(s){var t,n,r=function(a){for(var i="",l=0;l=0&&a[d]==="\\";d--)c++;i+=c%2==0?"\\"+o:o}else i+=o}return i}(s);return this.internal.events.subscribe("postPutResources",function(){t=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/Names [(EmbeddedJS) "+(t+1)+" 0 R]"),this.internal.out(">>"),this.internal.out("endobj"),n=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/S /JavaScript"),this.internal.out("/JS ("+r+")"),this.internal.out(">>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){t!==void 0&&n!==void 0&&this.internal.out("/Names <>")}),this},function(s){var t;s.events.push(["postPutResources",function(){var n=this,r=/^(\d+) 0 obj$/;if(this.outline.root.children.length>0)for(var a=n.outline.render().split(/\r\n/),i=0;i> endobj")}var p=n.internal.newObject();for(n.internal.write("<< /Names [ "),i=0;i>","endobj"),t=n.internal.newObject(),n.internal.write("<< /Dests "+p+" 0 R"),n.internal.write(">>","endobj")}}]),s.events.push(["putCatalog",function(){var n=this;n.outline.root.children.length>0&&(n.internal.write("/Outlines",this.outline.makeRef(this.outline.root)),this.outline.createNamedDestinations&&n.internal.write("/Names "+t+" 0 R"))}]),s.events.push(["initialized",function(){var n=this;n.outline={createNamedDestinations:!1,root:{children:[]}},n.outline.add=function(r,a,i){var l={title:a,options:i,children:[]};return r==null&&(r=this.root),r.children.push(l),l},n.outline.render=function(){return this.ctx={},this.ctx.val="",this.ctx.pdf=n,this.genIds_r(this.root),this.renderRoot(this.root),this.renderItems(this.root),this.ctx.val},n.outline.genIds_r=function(r){r.id=n.internal.newObjectDeferred();for(var a=0;a0&&(this.line("/First "+this.makeRef(r.children[0])),this.line("/Last "+this.makeRef(r.children[r.children.length-1]))),this.line("/Count "+this.count_r({count:0},r)),this.objEnd()},n.outline.renderItems=function(r){for(var a=this.ctx.pdf.internal.getVerticalCoordinateString,i=0;i0&&this.line("/Prev "+this.makeRef(r.children[i-1])),i0&&(this.line("/First "+this.makeRef(l.children[0])),this.line("/Last "+this.makeRef(l.children[l.children.length-1])));var o=this.count=this.count_r({count:0},l);if(o>0&&this.line("/Count "+o),l.options&&l.options.pageNumber){var c=n.internal.getPageInfo(l.options.pageNumber);this.line("/Dest ["+c.objId+" 0 R /XYZ 0 "+a(0)+" 0]")}this.objEnd()}for(var d=0;d> \r endobj\r `},n.outline.count_r=function(r,a){for(var i=0;i1){G=!0,ee=void 0;var fe=I*O;J=new Uint8Array(fe);for(var Se=new DataView($.buffer),Ee=0;Ee536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");this.data=new Uint8Array(t);try{this[s]()}catch(n){gh.log("bit decode error:"+n)}},N2.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)}},N2.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)}},N2.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}},N2.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}},N2.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},fxt=function(s,t,n){n||(n={});var r,a,i,l,o,c,d,u=[],h=[u],m=n.textIndent||0,p=0,x=0,y=s.split(" "),g=sre.apply(this,[" ",n])[0];if(c=n.lineIndent===-1?y[0].length+2:n.lineIndent||0){var b=Array(c).join(" "),v=[];y.map(function(C){(C=C.split(/\s*\n/)).length>1?v=v.concat(C.map(function(T,M){return(M&&T.length?` `:"")+T})):v.push(C[0])}),y=v,c=mxt.apply(this,[b,n])}for(i=0,l=y.length;it||k){if(x>t){for(o=pxt.apply(this,[r,a,t-(m+p),t]),u.push(o.shift()),u=[o.pop()];o.length;)h.push([o.shift()]);x=a.slice(r.length-(u[0]?u[0].length:0)).reduce(function(C,T){return C+T},0)}else u=[r];h.push(u),m=x+c,p=g}else u.push(r),m+=p+x,p=g}return d=c?function(C,T){return(T?b:"")+C.join(" ")}:function(C){return C.join(" ")},h.map(d)},l7.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-DvJ7cBD5.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)})},ho.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},ho.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",Hwn),this.internal.events.subscribe("postPutResources",Vwn)),this},function(s){var t=s.API,n=t.pdfEscape16=function(i,l){for(var o,c=l.metadata.Unicode.widths,d=["","0","00","000","0000"],u=[""],h=0,m=i.length;h> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange`,c=[],h=0,m=(o=Object.keys(i).sort(function(p,x){return p-x})).length;h=100&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar`,c=[]),i[l]!==void 0&&i[l]!==null&&typeof i[l].toString=="function"&&(d=("0000"+i[l].toString(16)).slice(-4),l=("0000"+(+l).toString(16)).slice(-4),c.push("<"+l+"><"+d+">"));return c.length&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar `),u+`endcmap CMapName currentdict /CMap defineresource pop end end`};t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="Identity-H"){for(var h=o.metadata.Unicode.widths,m=o.metadata.subset.encode(o.metadata.glyIdsUsed,1),p="",x=0;x>"),c("endobj");var v=d();c("<<"),c("/Type /Font"),c("/BaseFont /"+O7(o.fontName)),c("/FontDescriptor "+b+" 0 R"),c("/W "+s.API.PDFObject.convert(h)),c("/CIDToGIDMap /Identity"),c("/DW 1000"),c("/Subtype /CIDFontType2"),c("/CIDSystemInfo"),c("<<"),c("/Supplement 0"),c("/Registry (Adobe)"),c("/Ordering ("+o.encoding+")"),c(">>"),c(">>"),c("endobj"),o.objectNumber=d(),c("<<"),c("/Type /Font"),c("/Subtype /Type0"),c("/ToUnicode "+g+" 0 R"),c("/BaseFont /"+O7(o.fontName)),c("/Encoding /"+o.encoding),c("/DescendantFonts ["+v+" 0 R]"),c(">>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]),t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="WinAnsiEncoding"){for(var h=o.metadata.rawData,m="",p=0;p>"),c("endobj"),o.objectNumber=d();for(var b=0;b>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]);var a=function(i){var l,o=i.text||"",c=i.x,d=i.y,u=i.options||{},h=i.mutex||{},m=h.pdfEscape,p=h.activeFontKey,x=h.fonts,y=p,g="",b=0,v="",k=x[y].encoding;if(x[y].encoding!=="Identity-H")return{text:o,x:c,y:d,options:u,mutex:h};for(v=o,y=p,Array.isArray(o)&&(v=o[0]),b=0;b","<","[","]","[","{","}","{","«","»","«","‹","›","‹","⁅","⁆","⁅","⁽","⁾","⁽","₍","₎","₍","≤","≥","≤","〈","〉","〈","﹙","﹚","﹙","﹛","﹜","﹛","﹝","﹞","﹝","﹤","﹥","﹤"],b=new RegExp(/^([1-4|9]|1[0-9]|2[0-9]|3[0168]|4[04589]|5[012]|7[78]|159|16[0-9]|17[0-2]|21[569]|22[03489]|250)$/),v=!1,k=0;this.__bidiEngine__={};var C=function($){var q=$.charCodeAt(),W=q>>8,G=y[W];return G!==void 0?h[256*G+(255&q)]:W===252||W===253?"AL":b.test(W)?"L":W===8?"R":"N"},T=function($){for(var q,W=0;W<$.length;W++){if((q=C($.charAt(W)))==="L")return!1;if(q==="R")return!0}return!1},M=function($,q,W,G){var K,ee,J,le,ue=q[G];switch(ue){case"L":case"R":case"LRE":case"RLE":case"LRO":case"RLO":case"PDF":v=!1;break;case"N":case"AN":break;case"EN":v&&(ue="AN");break;case"AL":v=!0,ue="R";break;case"WS":case"BN":ue="N";break;case"CS":G<1||G+1>=q.length||(K=W[G-1])!=="EN"&&K!=="AN"||(ee=q[G+1])!=="EN"&&ee!=="AN"?ue="N":v&&(ee="AN"),ue=ee===K?ee:"N";break;case"ES":ue=(K=G>0?W[G-1]:"B")==="EN"&&G+10&&W[G-1]==="EN"){ue="EN";break}if(v){ue="N";break}for(J=G+1,le=q.length;J=1425&&oe<=2303||oe===64286;if(K=q[J],ie&&(K==="R"||K==="AL")){ue="R";break}}}ue=G<1||(K=q[G-1])==="B"?"N":W[G-1];break;case"B":v=!1,a=!0,ue=k;break;case"S":i=!0,ue="N"}return ue},P=function($,q,W){var G=$.split("");return W&&L(G,W,{hiLevel:k}),G.reverse(),q&&q.reverse(),G.join("")},L=function($,q,W){var G,K,ee,J,le,ue=-1,oe=$.length,ie=0,de=[],we=k?p:m,je=[];for(v=!1,a=!1,i=!1,K=0;K0)if(G===16){for(K=ue;K-1){for(K=ue;K=0&&xe[Le]==="WS";Le--)fe[Le]=k}}(je,q,oe)},I=function($,q,W,G,K){if(!(K.hiLevel<$)){if($===1&&k===1&&!a)return q.reverse(),void(W&&W.reverse());for(var ee,J,le,ue,oe=q.length,ie=0;ie=$){for(le=ie+1;le=$;)le++;for(ue=ie,J=le-1;ue=0&&(ee[oe]=g[ue+1])}(G,W,K),I(2,G,q,W,K),I(1,G,q,W,K),G.join("")};return this.__bidiEngine__.doBidiReorder=function($,q,W){if(function(K,ee){if(ee)for(var J=0;J>16)&&(n=-(1+(65535^n))),this.italicAngle=+(n+"."+r)):this.italicAngle=0,this.ascender=Math.round(this.ascender*this.scaleFactor),this.decender=Math.round(this.decender*this.scaleFactor),this.lineGap=Math.round(this.lineGap*this.scaleFactor),this.capHeight=this.os2.exists&&this.os2.capHeight||this.ascender,this.xHeight=this.os2.exists&&this.os2.xHeight||0,this.familyClass=(this.os2.exists&&this.os2.familyClass||0)>>8,this.isSerif=(i=this.familyClass)===1||i===2||i===3||i===4||i===5||i===7,this.isScript=this.familyClass===10,this.flags=0,this.post.isFixedPitch&&(this.flags|=1),this.isSerif&&(this.flags|=2),this.isScript&&(this.flags|=8),this.italicAngle!==0&&(this.flags|=64),this.flags|=32,!this.cmap.unicode)throw new Error("No unicode cmap for font")},s.prototype.characterToGlyph=function(t){var n;return((n=this.cmap.unicode)!=null?n.codeMap[t]:void 0)||0},s.prototype.widthOfGlyph=function(t){var n;return n=1e3/this.head.unitsPerEm,this.hmtx.forGlyph(t).advance*n},s.prototype.widthOfString=function(t,n,r){var a,i,l,o;for(l=0,i=0,o=(t=""+t).length;0<=o?io;i=0<=o?++i:--i)a=t.charCodeAt(i),l+=this.widthOfGlyph(this.characterToGlyph(a))+r*(1e3/n)||0;return l*(n/1e3)},s.prototype.lineHeight=function(t,n){var r;return n==null&&(n=!1),r=n?this.lineGap:0,(this.ascender+r-this.decender)/1e3*t},s}();var GN,zE=function(){function s(t){this.data=t??[],this.pos=0,this.length=this.data.length}return s.prototype.readByte=function(){return this.data[this.pos++]},s.prototype.writeByte=function(t){return this.data[this.pos++]=t},s.prototype.readUInt32=function(){return 16777216*this.readByte()+(this.readByte()<<16)+(this.readByte()<<8)+this.readByte()},s.prototype.writeUInt32=function(t){return this.writeByte(t>>>24&255),this.writeByte(t>>16&255),this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt32=function(){var t;return(t=this.readUInt32())>=2147483648?t-4294967296:t},s.prototype.writeInt32=function(t){return t<0&&(t+=4294967296),this.writeUInt32(t)},s.prototype.readUInt16=function(){return this.readByte()<<8|this.readByte()},s.prototype.writeUInt16=function(t){return this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt16=function(){var t;return(t=this.readUInt16())>=32768?t-65536:t},s.prototype.writeInt16=function(t){return t<0&&(t+=65536),this.writeUInt16(t)},s.prototype.readString=function(t){var n,r;for(r=[],n=0;0<=t?nt;n=0<=t?++n:--n)r[n]=String.fromCharCode(this.readByte());return r.join("")},s.prototype.writeString=function(t){var n,r,a;for(a=[],n=0,r=t.length;0<=r?nr;n=0<=r?++n:--n)a.push(this.writeByte(t.charCodeAt(n)));return a},s.prototype.readShort=function(){return this.readInt16()},s.prototype.writeShort=function(t){return this.writeInt16(t)},s.prototype.readLongLong=function(){var t,n,r,a,i,l,o,c;return t=this.readByte(),n=this.readByte(),r=this.readByte(),a=this.readByte(),i=this.readByte(),l=this.readByte(),o=this.readByte(),c=this.readByte(),128&t?-1*(72057594037927940*(255^t)+281474976710656*(255^n)+1099511627776*(255^r)+4294967296*(255^a)+16777216*(255^i)+65536*(255^l)+256*(255^o)+(255^c)+1):72057594037927940*t+281474976710656*n+1099511627776*r+4294967296*a+16777216*i+65536*l+256*o+c},s.prototype.writeLongLong=function(t){var n,r;return n=Math.floor(t/4294967296),r=4294967295&t,this.writeByte(n>>24&255),this.writeByte(n>>16&255),this.writeByte(n>>8&255),this.writeByte(255&n),this.writeByte(r>>24&255),this.writeByte(r>>16&255),this.writeByte(r>>8&255),this.writeByte(255&r)},s.prototype.readInt=function(){return this.readInt32()},s.prototype.writeInt=function(t){return this.writeInt32(t)},s.prototype.read=function(t){var n,r;for(n=[],r=0;0<=t?rt;r=0<=t?++r:--r)n.push(this.readByte());return n},s.prototype.write=function(t){var n,r,a,i;for(i=[],r=0,a=t.length;ri;a=0<=i?++a:--a)r={tag:n.readString(4),checksum:n.readInt(),offset:n.readInt(),length:n.readInt()},this.tables[r.tag]=r}return t.prototype.encode=function(n){var r,a,i,l,o,c,d,u,h,m,p,x,y;for(y in p=Object.keys(n).length,c=Math.log(2),h=16*Math.floor(Math.log(p)/c),l=Math.floor(h/c),u=16*p-h,(a=new zE).writeInt(this.scalarType),a.writeShort(p),a.writeShort(h),a.writeShort(l),a.writeShort(u),i=16*p,d=a.pos+i,o=null,x=[],n)for(m=n[y],a.writeString(y),a.writeInt(s(m)),a.writeInt(d),a.writeInt(m.length),x=x.concat(m),y==="head"&&(o=d),d+=m.length;d%4;)x.push(0),d++;return a.write(x),r=2981146554-s(a.data),a.pos=o+8,a.writeUInt32(r),a.data},s=function(n){var r,a,i,l;for(n=e7t.call(n);n.length%4;)n.push(0);for(i=new zE(n),a=0,r=0,l=n.length;rm;c=0<=m?++C:--C)T.push(t.readUInt16());return T}(),t.pos+=2,y=function(){var C,T;for(T=[],c=C=0;0<=m?Cm;c=0<=m?++C:--C)T.push(t.readUInt16());return T}(),d=function(){var C,T;for(T=[],c=C=0;0<=m?Cm;c=0<=m?++C:--C)T.push(t.readUInt16());return T}(),u=function(){var C,T;for(T=[],c=C=0;0<=m?Cm;c=0<=m?++C:--C)T.push(t.readUInt16());return T}(),a=(this.length-t.pos+this.offset)/2,o=function(){var C,T;for(T=[],c=C=0;0<=a?Ca;c=0<=a?++C:--C)T.push(t.readUInt16());return T}(),c=b=0,k=i.length;b=g;r=x<=g?++v:--v)u[c]===0?l=r+d[c]:(l=o[u[c]/2+(r-x)-(m-c)]||0)!==0&&(l+=d[c]),this.codeMap[r]=65535&l}t.pos=h}return s.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,p,x,y,g,b,v,k,C,T,M,P,L,I,O,$,q,W,G,K,ee,J,le,ue,oe,ie,de,we,je,xe,fe,Se,Ee,Le,De,Be,Ne;switch(G=new zE,l=Object.keys(t).sort(function(Ge,_e){return Ge-_e}),n){case"macroman":for(y=0,g=function(){var Ge=[];for(x=0;x<256;++x)Ge.push(0);return Ge}(),v={0:0},i={},K=0,ue=l.length;K=32768)for(c.push(0),M.push(2*(p.length+I-x)),a=le=$;$<=u?le<=u:le>=u;a=$<=u?++le:--le)p.push(r[a].new);else c.push(W-$),M.push(0)}for(G.writeUInt16(3),G.writeUInt16(1),G.writeUInt32(12),G.writeUInt16(4),G.writeUInt16(16+8*I+2*p.length),G.writeUInt16(0),G.writeUInt16(O),G.writeUInt16(L),G.writeUInt16(m),G.writeUInt16(P),Se=0,de=h.length;Sea;r=0<=a?++r:--r)n=new Nxt(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=Nxt.encode(t,n),(a=new zE).writeUInt16(0),a.writeUInt16(1),r.table=a.data.concat(r.subtable),r},s}(),Ywn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return yS(s,GN),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}(),Zwn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return yS(s,GN),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}(),Xwn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return yS(s,GN),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}(),Qwn=function(s,t){this.raw=s,this.length=s.length,this.platformID=t.platformID,this.encodingID=t.encodingID,this.languageID=t.languageID},Jwn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return yS(s,GN),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}(),e7t=[].slice,sjn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return yS(s,GN),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 zE(n.read(a))).readShort(),d=o.readShort(),h=o.readShort(),c=o.readShort(),u=o.readShort(),this.cache[t]=l===-1?new rjn(o,d,h,c,u):new njn(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}(),ijn=function(){function s(t){this.font=t,this.subset={},this.unicodes={},this.next=33}return s.prototype.generateCmap=function(){var t,n,r,a,i;for(n in a=this.font.cmap.tables[0].codeMap,t={},i=this.subset)r=i[n],t[n]=a[r];return t},s.prototype.glyphsFor=function(t){var n,r,a,i,l,o,c;for(a={},l=0,o=t.length;l0)for(i in c=this.glyphsFor(n))r=c[i],a[i]=r;return a},s.prototype.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,p,x,y,g,b;for(a in r=JFt.encode(this.generateCmap(),"unicode"),l=this.glyphsFor(t),p={0:0},b=r.charMap)p[(c=b[a]).old]=c.new;for(x in m=r.maxGlyphID,l)x in p||(p[x]=m++);return u=function(v){var k,C;for(k in C={},v)C[v[k]]=k;return C}(p),h=Object.keys(u).sort(function(v,k){return v-k}),y=function(){var v,k,C;for(C=[],v=0,k=h.length;v>"),i.join(` `)}return""+n},t}();const nze=[{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}],ojn="signature";function ljn(s){return nze.find(t=>t.id===s)||nze[0]}const Ul=792,Bh=612,Wr=52;function c7(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 Rp(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 vS=[22,24,28],l1=[124,128,136],uo=[255,255,255];function cjn(s){return s==null||!Number.isFinite(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Number(s))}const DIe="https://relzejiswnotikjgvjhz.supabase.co";function djn(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(DIe).origin?s:`${DIe}/functions/v1/image-proxy?url=${encodeURIComponent(t.toString())}`}catch{return s}}async function ZH(s,t=2e3){if(!s)return null;try{const n=await fetch(djn(s),{mode:"cors"});if(!n.ok)return null;const r=await n.blob(),a=URL.createObjectURL(r),i=await new Promise((y,g)=>{const b=new Image;b.crossOrigin="anonymous",b.onload=()=>y(b),b.onerror=g,b.src=a}),l=Math.min(1,t/i.naturalWidth),o=Math.max(1,Math.round(i.naturalWidth*l)),c=Math.max(1,Math.round(i.naturalHeight*l)),d=document.createElement("canvas");d.width=o,d.height=c,d.getContext("2d").drawImage(i,0,0,o,c),URL.revokeObjectURL(a);const h=r.type.includes("png"),m=h?"PNG":"JPEG",p=d.toDataURL(h?"image/png":"image/jpeg",.92);return{el:await new Promise(y=>{const g=new Image;g.onload=()=>y(g),g.onerror=()=>y(g),g.src=p}),dataUrl:p,w:o,h:c,format:m}}catch{return null}}let t7t={x:.5,y:.5};function ujn(s){t7t={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 uee(s,t,n,r,a,i,l={}){const o=l.dpi??2,c=Math.max(1,Math.round(a*o)),d=Math.max(1,Math.round(i*o)),u=document.createElement("canvas");u.width=c,u.height=d;const h=u.getContext("2d"),m=t.w/t.h,p=a/i;let x=0,y=0,g=t.w,b=t.h;const v=l.focal??t7t;if(m>p?(g=t.h*p,x=Math.min(Math.max(0,t.w*v.x-g/2),t.w-g)):(b=t.w/p,y=Math.min(Math.max(0,t.h*v.y-b/2),t.h-b)),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,x,y,g,b,0,0,c,d)}catch{h.fillStyle="#e9e6e0",h.fillRect(0,0,c,d)}if(h.filter="none",l.tint&&l.tint.amount>0){const[T,M,P]=l.tint.color;h.globalCompositeOperation="multiply",h.fillStyle=`rgba(${T},${M},${P},${Math.min(1,l.tint.amount)})`,h.fillRect(0,0,c,d),h.globalCompositeOperation="source-over"}if(l.darken&&l.darken>0&&(h.fillStyle=`rgba(0,0,0,${Math.min(.9,l.darken)})`,h.fillRect(0,0,c,d)),l.gradient==="bottom"){const 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 C=u.toDataURL("image/jpeg",.92);s.addImage(C,"JPEG",n,r,a,i,void 0,"FAST")}function xD(s,t,n,r,a,i=3){const l=a*2,o=Math.max(1,Math.round(l*i)),c=document.createElement("canvas");c.width=o,c.height=o;const d=c.getContext("2d");d.fillStyle="#ffffff",d.fillRect(0,0,o,o),d.save(),d.beginPath(),d.arc(o/2,o/2,o/2,0,Math.PI*2),d.closePath(),d.clip();const u=t.w/t.h;let h=0,m=0,p=t.w,x=t.h;u>1?(p=t.h,h=(t.w-p)/2):(x=t.w,m=(t.h-x)/2);try{d.drawImage(t.el,h,m,p,x,0,0,o,o)}catch{}d.restore(),s.addImage(c.toDataURL("image/jpeg",.92),"JPEG",n-a,r-a,l,l,void 0,"FAST")}function PKe(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 tb(s,t){const n=s.GState;n&&s.setGState(new n({opacity:t}))}function hjn(s,t,n,r,a,i={font:"helvetica",size:10,color:vS}){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 Gq(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=hjn(s,c,n+13,l,a-13,{font:i.font,size:i.size,color:i.color,leading:o})+(i.gap??7)}),l}function nv(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 FO='',zO='',mjn={title:"Facebook",slug:"facebook",get svg(){return FO+"Facebook"+zO+this.path+BO},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"},pjn={title:"Instagram",slug:"instagram",get svg(){return FO+"Instagram"+zO+this.path+BO},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"},fjn={title:"Pinterest",slug:"pinterest",get svg(){return FO+"Pinterest"+zO+this.path+BO},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"},xjn={title:"TikTok",slug:"tiktok",get svg(){return FO+"TikTok"+zO+this.path+BO},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"},gjn={title:"trulia",slug:"trulia",get svg(){return FO+"trulia"+zO+this.path+BO},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"},yjn={title:"YouTube",slug:"youtube",get svg(){return FO+"YouTube"+zO+this.path+BO},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"},vjn={title:"Zillow",slug:"zillow",get svg(){return FO+"Zillow"+zO+this.path+BO},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"},bjn={facebook:mjn,instagram:pjn,youtube:yjn,tiktok:xjn,pinterest:fjn,zillow:vjn,trulia:gjn},kxt=new Map;function _jn(s,t,n){return`${s}|${t}|${n}`}function wjn(s,t,n=128){const r=s.toLowerCase().replace(/[^a-z]/g,""),a=bjn[r];if(!a)return null;const i=_jn(r,t,n),l=kxt.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 kxt.set(i,d),d}catch{return null}}const td="helvetica";let _U="helvetica";function s7t(s,t,n,r,a,i){const l=`#${n.map(d=>Math.round(d).toString(16).padStart(2,"0")).join("")}`,o=wjn(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(td,"bold"),s.setFontSize(c*1.15),s.setTextColor(...uo),s.text(t.charAt(0).toUpperCase(),r,a+c*.42,{align:"center"})}let hee=[252,251,248],sO=[244,247,250],kb=[223,228,234],py=[72,78,88];function mee(s,t){return $Ot(s.data.pages,t)}function IKe(s){var n;const t=s.coAgent;return t!=null&&t.enabled&&((n=t.name)!=null&&n.trim())?t:null}function n7t(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 jjn(s){return[s.agent.brokerageName,s.agent.phone,s.agent.email].filter(Boolean).join(" | ")}function Kf(s,t,n,r,a,i,l){const o=l.font||td,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 hu(s,t,n,r,a,i){s.setFont(td,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 Wq(s,t,n,r,a,i){const{doc:l}=s;l.setFont(td,"bold"),l.setFontSize(7.5),l.setTextColor(...a||s.accent),l.text(t.toUpperCase(),n,r,{charSpace:1.8,align:i})}function p0(s,t=hee){s.doc.addPage("letter","landscape"),s.pageNo+=1,s.doc.setFillColor(...t),s.doc.rect(0,0,Ul,Bh,"F")}function fy(s,t,n,r,a={}){const{doc:i}=s,l=!!a.dark,o=a.width??Ul-Wr*2-60;Wq(s,t,Wr,62,s.accent),i.setFont(_U,"bold"),i.setFontSize(_U==="times"?25:23);const c=i.splitTextToSize(n,o).slice(0,3);i.setTextColor(...l?uo:s.brand),c.forEach((u,h)=>i.text(u,Wr,96+h*29));let d=96+(c.length-1)*29;return r&&(d=hu(i,r,Wr,d+26,Math.min(o+40,Ul-Wr*2),{size:10,color:l?Rp(uo,s.deep,.28):l1,leading:15,maxLines:2})),d+34}function f0(s,t=!1){const{doc:n,data:r}=s,a=t?Rp(uo,s.deep,.7):kb;n.setDrawColor(...a),n.setLineWidth(.6),n.line(Wr,Bh-46,Ul-Wr,Bh-46);const i=Bh-30;n.setFont(td,"bold"),n.setFontSize(7),n.setTextColor(...t?uo:s.brand),t&&tb(n,.9),n.text((r.agent.name||"").toUpperCase(),Wr,i,{charSpace:1.4});const l=jjn(r);l&&(n.setFont(td,"normal"),n.setFontSize(7),n.setTextColor(...t?uo:l1),Kf(n,l,Ul/2,i,Ul/2-Wr-40,7,{color:t?uo:l1,align:"center"})),n.setFont(td,"normal"),n.setFontSize(7),n.setTextColor(...t?uo:l1),n.text(String(s.pageNo).padStart(2,"0"),Ul-Wr,i,{align:"right"}),t&&tb(n,1)}function r7t(s,t,n,r,a){const{doc:i}=s;i.setFont(td,"bold"),i.setFontSize(8);const l=i.splitTextToSize(t,a-28),o=16+l.length*12;return nv(i,n,r,a,o,6,Rp(s.accent,uo,.86)),i.setTextColor(...Rp(s.brand,vS,.2)),l.forEach((c,d)=>i.text(c,n+14,r+20+d*12)),r+o}function RKe(s,t,n,r,a,i={}){const{doc:l}=s;s.hero?uee(l,s.hero,t,n,r,a,{radius:10,dpi:s.dpi,tint:i.tint?{color:s.deep,amount:i.tint}:void 0}):nv(l,t,n,r,a,10,Rp(s.deep,uo,.12))}function Njn(s){const{doc:t,data:n}=s,{line1:r,line2:a}=n7t(n),i=336;s.hero?uee(t,s.hero,0,0,Ul,Bh,{dpi:s.dpi,darken:.12}):(t.setFillColor(...s.deep),t.rect(0,0,Ul,Bh,"F")),t.setFillColor(...s.deep),t.rect(0,0,i,Bh,"F"),t.setFillColor(...s.accent),t.rect(i-3,0,3,Bh,"F");const l=mee(s,"cover");Wq(s,l.kicker,Wr,66),t.setFont(_U,"bold"),t.setFontSize(_U==="times"?29:26),t.setTextColor(...uo);const o=t.splitTextToSize(r,i-Wr*2).slice(0,3);o.forEach((g,b)=>t.text(g,Wr,102+b*30));let c=102+(o.length-1)*30;a&&(t.setFont(td,"normal"),t.setFontSize(9),tb(t,.9),Kf(t,a.toUpperCase(),Wr,c+22,i-Wr*2,9,{color:uo,charSpace:1.4}),tb(t,1),c+=22),c=hu(t,l.body,Wr,c+34,i-Wr*2,{size:10,color:Rp(uo,s.deep,.22),leading:16});const d=[cjn(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(Wr,c+30,Wr+40,c+30),Kf(t,d.join(" · "),Wr,c+54,i-Wr*2,10,{style:"bold",color:uo,charSpace:1}));const u=IKe(n),h=Bh-(u?152:128);let m=Wr;s.headshot&&(xD(t,s.headshot,Wr+22,h+18,22),u&&s.coHeadshot?(xD(t,s.coHeadshot,Wr+56,h+18,22),m=Wr+90):m=Wr+56),Kf(t,u?`${n.agent.name} + ${u.name}`:n.agent.name,m,h+12,i-m-24,14,{style:"bold",color:uo}),t.setFont(td,"normal"),t.setFontSize(8),tb(t,.85);const p=[n.agent.brokerageName].filter(Boolean).join("");p&&Kf(t,p,m,h+26,i-m-24,8,{color:uo});const x=[n.agent.phone,n.agent.email].filter(Boolean).join(" · ");if(x&&Kf(t,x,m,h+38,i-m-24,8,{color:uo}),u){const g=[u.title||"Co-listing agent",u.phone].filter(Boolean).join(" · ");g&&Kf(t,g,Wr,h+56,i-Wr-24,8,{color:uo})}tb(t,1),s.logo&&(tb(t,.95),PKe(t,s.logo,Wr,Bh-74,132,30,"left"),tb(t,1));const y=n.sellerName?`PREPARED FOR ${n.sellerName.toUpperCase()}`:"PREPARED FOR YOUR HOME";t.setFont(td,"bold"),t.setFontSize(7.5),t.setTextColor(...uo),tb(t,.9),t.text(y,Ul-Wr,Bh-34,{align:"right",charSpace:1.6}),tb(t,1)}function kjn(s){p0(s);const{doc:t}=s,n=mee(s,"welcome"),r=fy(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(...Rp(s.accent,uo,.85)),t.circle(Wr+13,i-3,13,"F"),t.setFont(td,"bold"),t.setFontSize(9),t.setTextColor(...s.brand),t.text(String(c+1).padStart(2,"0"),Wr+13,i,{align:"center"});const d=Wr+44,u=Ul-d-Wr-40;t.setFont(td,"bold"),t.setFontSize(11.5),t.setTextColor(...vS),t.text(l,d,i),hu(t,o,d,i+18,u,{size:9.5,color:py,leading:14,maxLines:2}),i+=88}),f0(s)}function Sjn(s){p0(s,uo);const{doc:t,data:n}=s,r=mee(s,"agent"),a=fy(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=IKe(n),l=Ul-Wr-260,o=a-6,c=262;if(i){const x=(y,g,b,v)=>{nv(t,l,y,260,124,10,sO,"FD",kb),t.setFillColor(...s.accent),t.rect(l,y,260,3,"F");let k=l+18;b&&(xD(t,b,l+48,y+62+2,30),k=l+90);const C=260-(k-l)-18;Kf(t,g,k,y+40,C,13,{style:"bold",color:s.brand});let T=y+56;v.filter(Boolean).slice(0,4).forEach(M=>{Kf(t,String(M),k,T,C,8,{color:l1}),T+=13})};x(o,n.agent.name,s.headshot,[n.agent.brokerageName,n.agent.phone,n.agent.email]),x(o+124+14,i.name,s.coHeadshot,[i.title||"Co-listing agent",i.brokerageName||n.agent.brokerageName,i.phone,i.email])}else{nv(t,l,o,260,c,10,sO,"FD",kb),t.setFillColor(...s.accent),t.rect(l,o,260,3,"F"),s.headshot&&xD(t,s.headshot,l+130,o+72,42),Kf(t,n.agent.name,l+130,o+(s.headshot?138:70),216,16,{style:"bold",color:s.brand,align:"center"});let m=o+(s.headshot?158:92);[n.agent.brokerageName,n.agent.phone,n.agent.email,n.agent.website].filter(Boolean).slice(0,4).forEach(p=>{Kf(t,String(p),l+130,m,220,8.5,{color:l1,align:"center"}),m+=14}),s.logo&&PKe(t,s.logo,l+80,o+c-44,100,28,"left")}const d=l-Wr-44;let u=hu(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.",Wr,a+4,d,{size:10,color:py,leading:16,maxLines:5});u+=34,[["Phone",n.agent.phone],["Email",n.agent.email],["Website",n.agent.website],["Brokerage",n.agent.brokerageName],["License",n.agent.licenseNumber?`${n.agent.licenseNumber}${n.agent.licenseState?` · ${n.agent.licenseState}`:""}`:null],i?["Co-listing",[i.name,i.licenseNumber].filter(Boolean).join(" · ")]:["",null]].filter(([m,p])=>!!m&&!!p).forEach(([m,p])=>{t.setFont(td,"bold"),t.setFontSize(7),t.setTextColor(...l1),t.text(m.toUpperCase(),Wr,u,{charSpace:1.4}),Kf(t,p,Wr+86,u,d-86,10.5,{color:vS}),t.setDrawColor(...kb),t.setLineWidth(.5),t.line(Wr,u+11,Wr+d,u+11),u+=36}),f0(s)}function Cjn(s,t){p0(s);const{doc:n}=s,r=mee(s,"overview"),a=fy(s,r.kicker,r.headline,r.subhead||null),i=4,l=14,o=(Ul-Wr*2-l*(i-1))/i,c=96;t.slice(0,8).forEach((d,u)=>{const h=Wr+u%i*(o+l),m=a+Math.floor(u/i)*(c+l);nv(n,h,m,o,c,8,uo,"FD",kb),n.setFillColor(...s.accent),n.rect(h,m,3,c,"F"),n.setFont(td,"bold"),n.setFontSize(15),n.setTextColor(...Rp(s.brand,uo,.55)),n.text(String(u+1).padStart(2,"0"),h+16,m+30),hu(n,d.title,h+16,m+52,o-30,{size:9.5,style:"bold",color:vS,leading:13,maxLines:3})}),f0(s)}function S6(s,t=5){var n;return(((n=s.options)==null?void 0:n.filter(r=>r.enabled).map(r=>r.label))??s1n[s.key]??[]).slice(0,t)}function Sxt(s,t,n){p0(s,n.dark?s.deep:hee);const{doc:r}=s,a=fy(s,n.kicker,n.headline,n.sub,{dark:n.dark}),i=404,l=272,o=!!n.flip,c=o?Ul-Wr-i:Wr,d=o?Wr:Wr+i+40,u=Ul-Wr*2-i-40;RKe(s,c,a,i,l,{tint:n.dark?.1:0}),Wq(s,t.title,d,a+12);let h=hu(r,t.body,d,a+32,u,{size:9.5,color:n.dark?Rp(uo,s.deep,.2):py,leading:15,maxLines:4});const m=S6(t,5);if(m.length&&(h=Gq(r,m,d,h+28,u,{font:td,size:9.5,color:n.dark?uo:vS,accent:s.accent,gap:7})),n.note&&!n.dark){const p=Math.min(h+14,Bh-120);r7t(s,n.note,d,p,u)}else n.note&&(r.setFont(td,"bold"),r.setFontSize(9.5),r.setTextColor(...uo),tb(r,.9),hu(r,n.note,Wr,Bh-78,Ul-Wr*2,{size:9.5,style:"bold",color:uo,leading:13,maxLines:1}),tb(r,1));f0(s,n.dark)}function Ajn(s,t){p0(s);const{doc:n}=s,r=fy(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=(Ul-Wr*2-o*(l-1))/l,d=176;(a.length?a:i).forEach((u,h)=>{const m=Wr+h*(c+o);nv(n,m,r,c,d,8,uo,"FD",kb),n.setFont(td,"bold"),n.setFontSize(16),n.setTextColor(...s.accent),n.text(String(h+1),m+16,r+34),n.setFont(td,"bold"),n.setFontSize(7.5),n.setTextColor(...l1),n.text((i[h]||`STEP ${h+1}`).toUpperCase(),m+16,r+56,{charSpace:1.2}),hu(n,u,m+16,r+76,c-32,{size:9,color:py,leading:13,maxLines:5})}),hu(n,t.body,Wr,r+d+34,Ul-Wr*2-120,{size:10,style:"bold",color:s.brand,leading:15,maxLines:2}),f0(s)}function Tjn(s,t){p0(s);const{doc:n}=s,r=fy(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=(Ul-Wr*2-l*(i-1))/i,c=68;a.forEach(([u,h],m)=>{const p=Wr+m%i*(o+l),x=r+Math.floor(m/i)*(c+l);nv(n,p,x,o,c,8,uo,"FD",kb),s7t(n,u,h,p+28,x+c/2,20),Kf(n,u,p+48,x+c/2+4,o-64,13,{style:"bold",color:h})});const d=r+2*(c+l)+22;hu(n,t.body,Wr,d,Ul-Wr*2-140,{size:9.5,color:py,leading:14,maxLines:3}),n.setFont(td,"normal"),n.setFontSize(7.5),n.setTextColor(...l1),n.text("Distribution varies by MLS, market, and portal policies.",Wr,Bh-62),f0(s)}function Ejn(s,t){p0(s,sO);const{doc:n,data:r}=s,{line1:a}=n7t(r),i=fy(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;nv(n,Wr,i,l,o,10,uo,"FD",kb),nv(n,Wr,i,l,22,10,s.deep),n.setFillColor(...s.deep),n.rect(Wr,i+12,l,10,"F"),n.setFont(td,"bold"),n.setFontSize(7),n.setTextColor(...uo);const c=(r.agent.website||`${a}`).replace(/^https?:\/\//,"").toUpperCase();Kf(n,c,Wr+14,i+15,l-28,7,{style:"bold",color:uo,charSpace:1}),RKe(s,Wr+14,i+36,186,142);const d=Wr+214,u=l-228;Kf(n,a,d,i+54,u,12,{style:"bold",color:s.brand}),hu(n,"Welcome home.",d,i+72,u,{size:9,color:s.accent,leading:12,maxLines:1}),hu(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:py,leading:12,maxLines:5}),r7t(s,"Shareable. Trackable. Memorable.",Wr+14,i+o-46,l-28);const h=Wr+l+40,m=Ul-h-Wr;Wq(s,t.title,h,i+12);let p=hu(n,t.body,h,i+32,m,{size:9.5,color:py,leading:15,maxLines:5});const x=S6(t,5);x.length&&Gq(n,x,h,p+26,m,{font:td,size:9,color:vS,accent:s.accent,gap:7}),f0(s)}function Mjn(s,t){p0(s,s.deep);const{doc:n}=s,r=fy(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=Wr+h*(i+l);nv(n,m,r,i,i,12,uo),s7t(n,d,u,m+i/2,r+i/2-4,30),n.setFont(td,"bold"),n.setFontSize(6.5),n.setTextColor(...l1),n.text(d.toUpperCase(),m+i/2,r+i-8,{align:"center",charSpace:.6})});const o=Wr+5*(i+l)+14,c=Ul-o-Wr;Wq(s,"The campaign can include",o,r+12),Gq(n,S6(t,5),o,r+32,c,{font:td,size:9,color:uo,accent:s.accent,gap:7}),hu(n,t.body,Wr,r+i+44,420,{size:9.5,color:Rp(uo,s.deep,.2),leading:15,maxLines:4}),hu(n,"Every post sends attention back to the property.",Wr,Bh-84,460,{size:11,style:"bold",color:uo,leading:14,maxLines:1}),f0(s,!0)}function Ljn(s,t){p0(s);const{doc:n}=s,r=fy(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)=>{nv(n,Wr,l-14,34,34,8,Rp(s.accent,uo,.85)),n.setFont(td,"bold"),n.setFontSize(11),n.setTextColor(...s.brand),n.text(String(c+1),Wr+17,l+7,{align:"center"});const d=Wr+52,u=Ul-d-Wr-20;n.setFont(td,"bold"),n.setFontSize(8),n.setTextColor(...s.brand),n.text((i[c]||t.title).toUpperCase(),d,l-2,{charSpace:1.2}),hu(n,o,d,l+14,u,{size:9.5,color:py,leading:14,maxLines:2}),l+=76}),hu(n,t.body,Wr,Math.min(l+8,Bh-92),Ul-Wr*2-120,{size:9.5,color:l1,leading:14,maxLines:2}),f0(s)}function Pjn(s,t){p0(s);const{doc:n}=s,r=fy(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=(Ul-Wr*2-o)/l,d=112;a.forEach((u,h)=>{const m=Wr+h%l*(c+o),p=r+Math.floor(h/l)*(d+o);nv(n,m,p,c,d,8,sO,"FD",kb),n.setFont(td,"bold"),n.setFontSize(7.5),n.setTextColor(...s.brand),n.text((i[h]||t.title).toUpperCase(),m+16,p+24,{charSpace:1.2}),hu(n,u,m+16,p+46,c-32,{size:9.5,color:py,leading:14,maxLines:3})}),f0(s)}function Ijn(s,t){p0(s,sO);const{doc:n}=s,r=fy(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(td,"bold"),n.setFontSize(11),n.setTextColor(...s.accent),n.text(String(c+1).padStart(2,"0"),Wr,l),n.setFont(td,"bold"),n.setFontSize(9),n.setTextColor(...s.brand),n.text((i[c]||"").toUpperCase(),Wr+48,l,{charSpace:1.2}),hu(n,o,Wr+250,l-1,Ul-Wr-250-Wr,{size:9.5,color:py,leading:13,maxLines:2}),n.setDrawColor(...kb),n.setLineWidth(.5),n.line(Wr,l+22,Ul-Wr,l+22),l+=62}),hu(n,"Marketing creates opportunity. Communication helps us act on it.",Wr,Math.min(l+18,Bh-84),520,{size:11,style:"bold",color:s.brand,leading:14,maxLines:1}),f0(s)}function Rjn(s){p0(s,s.deep);const{doc:t,data:n}=s;s.hero&&uee(t,s.hero,0,0,Ul,Bh,{tint:{color:s.deep,amount:.92},darken:.25,dpi:s.dpi});const r=mee(s,"closing"),a=fy(s,r.kicker,r.headline,r.subhead||null,{dark:!0,width:520}),i=420;let l=hu(t,r.body,Wr,a,i,{size:10.5,color:Rp(uo,s.deep,.18),leading:17});l+=30,Gq(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"],Wr,l,i,{font:td,size:9.5,color:uo,accent:s.accent,gap:8});const o=IKe(n),c=250,d=Ul-Wr-c,u=a-20,h=o?300:258;nv(t,d,u,c,h,10,uo),t.setFillColor(...s.accent),t.rect(d,u,c,3,"F"),s.headshot&&(o&&s.coHeadshot?(xD(t,s.headshot,d+c/2-34,u+70,32),xD(t,s.coHeadshot,d+c/2+34,u+70,32)):xD(t,s.headshot,d+c/2,u+70,38)),Kf(t,o?`${n.agent.name} + ${o.name}`:n.agent.name,d+c/2,u+(s.headshot?132:68),c-30,16,{style:"bold",color:s.brand,align:"center"});let m=u+(s.headshot?152:90);[n.agent.brokerageName,n.agent.phone,n.agent.email,n.agent.website,n.agent.licenseNumber?`License ${n.agent.licenseNumber}${n.agent.licenseState?` · ${n.agent.licenseState}`:""}`:null].filter(Boolean).slice(0,5).forEach(p=>{Kf(t,String(p),d+c/2,m,c-30,8.5,{color:l1,align:"center"}),m+=14}),o?(m+=6,t.setDrawColor(...kb),t.setLineWidth(.5),t.line(d+24,m-8,d+c-24,m-8),Kf(t,o.name,d+c/2,m+8,c-30,10,{style:"bold",color:s.brand,align:"center"}),m+=22,[o.title||"Co-listing agent",o.phone,o.email].filter(Boolean).slice(0,3).forEach(p=>{Kf(t,String(p),d+c/2,m,c-30,8.5,{color:l1,align:"center"}),m+=13})):s.logo&&PKe(t,s.logo,d+c/2-50,u+h-44,100,28,"left"),t.setFont(td,"bold"),t.setFontSize(9),t.setTextColor(...uo),tb(t,.9),t.text("LET'S MAKE YOUR HOME THE ONE BUYERS REMEMBER.",Wr,Bh-72,{charSpace:1.4}),tb(t,1),f0(s,!0)}function DKe(s,t){return s.customImages[t.id]||null}function a7t(s,t,n,r,a,i){const l=DKe(s,t);l?uee(s.doc,l,n,r,a,i,{radius:10,dpi:s.dpi}):RKe(s,n,r,a,i)}function Djn(s,t){p0(s,t.dark?s.deep:hee);const{doc:n}=s,r=fy(s,t.kicker||"About",t.headline,t.subhead||null,{dark:t.dark}),a=300,i=t.imageSide!=="left",l=i?Ul-Wr-a:Wr,o=i?Wr:Wr+a+40,c=Ul-Wr*2-a-40;a7t(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=hu(n,h,o,u,c,{size:10,color:t.dark?Rp(uo,s.deep,.2):py,leading:16,maxLines:7}),u+=26}),t.bullets.length&&Gq(n,t.bullets.slice(0,5),o,Math.min(u,Bh-150),c,{font:td,size:9.5,color:t.dark?uo:vS,accent:s.accent,gap:7}),f0(s,t.dark)}function Ojn(s,t){p0(s,t.dark?s.deep:sO);const{doc:n}=s,r=fy(s,t.kicker||"What others are saying",t.headline,t.subhead||null,{dark:t.dark}),a=t.testimonials.filter(m=>{var p;return(p=m.quote)==null?void 0:p.trim()}).slice(0,6),i=a.length<=2?a.length||1:a.length>4?3:2,l=18,o=(Ul-Wr*2-l*(i-1))/i,c=Math.ceil(a.length/i)||1,d=Bh-72-r,u=c>1?Math.min(150,(d-l*(c-1))/c):Math.min(200,d),h=c>1?i===3?4:3:7;a.forEach((m,p)=>{const x=Wr+p%i*(o+l),y=r+Math.floor(p/i)*(u+l);nv(n,x,y,o,u,10,t.dark?Rp(s.deep,uo,.08):uo,"FD",kb),n.setFillColor(...s.accent),n.rect(x,y,3,u,"F"),n.setFont(_U,"bold"),n.setFontSize(30),n.setTextColor(...Rp(s.accent,t.dark?s.deep:uo,.4)),n.text("“",x+18,y+40),hu(n,m.quote,x+18,y+56,o-40,{size:9.5,color:t.dark?Rp(uo,s.deep,.2):py,leading:14,maxLines:h}),n.setDrawColor(...s.accent),n.setLineWidth(1.2),n.line(x+18,y+u-32,x+42,y+u-32),n.setFont(td,"bold"),n.setFontSize(8),n.setTextColor(...s.brand);const g=[m.name,m.detail].filter(Boolean).join(" · ");g&&Kf(n,g.toUpperCase(),x+18,y+u-16,o-36,8,{style:"bold",color:t.dark?uo:s.brand,charSpace:1.1})}),t.body&&hu(n,t.body,Wr,Math.min(r+c*(u+l)+14,Bh-88),Ul-Wr*2-120,{size:9.5,color:t.dark?Rp(uo,s.deep,.2):l1,leading:14,maxLines:2}),f0(s,t.dark)}function Fjn(s,t){p0(s,t.dark?s.deep:hee);const{doc:n}=s,r=fy(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=(Ul-Wr*2-18*(a.length-1))/a.length,o=150;a.forEach((c,d)=>{const u=Wr+d*(l+18);nv(n,u,r,l,o,10,t.dark?Rp(s.deep,uo,.1):uo,"FD",kb),n.setFillColor(...s.accent),n.rect(u,r,l,3,"F"),Kf(n,c.value||"—",u+l/2,r+76,l-28,34,{style:"bold",color:t.dark?uo:s.brand,align:"center"}),hu(n,c.label||"",u+20,r+100,l-40,{size:9,color:t.dark?Rp(uo,s.deep,.3):l1,leading:12,maxLines:2,align:"center"})}),t.body&&hu(n,t.body,Wr,r+o+40,Ul-Wr*2-140,{size:10,color:t.dark?Rp(uo,s.deep,.2):py,leading:15,maxLines:3})}else t.body&&hu(n,t.body,Wr,r,Ul-Wr*2-140,{size:10.5,color:t.dark?uo:py,leading:16});f0(s,t.dark)}function zjn(s,t){p0(s,t.dark?s.deep:uo);const{doc:n}=s,r=fy(s,t.kicker||"Our promise",t.headline,t.subhead||null,{dark:t.dark}),i=!!DKe(s,t)||!!s.hero,l=i?Ul-Wr*2-280:Ul-Wr*2-140;let o=r;t.body&&(o=hu(n,t.body,Wr,o,l,{size:10,color:t.dark?Rp(uo,s.deep,.2):py,leading:15,maxLines:3})+28),t.bullets.filter(d=>d==null?void 0:d.trim()).slice(0,7).forEach(d=>{nv(n,Wr,o-9,14,14,4,s.accent),n.setFont(td,"bold"),n.setFontSize(8),n.setTextColor(...uo),n.text("✓",Wr+7,o+1,{align:"center"}),o=hu(n,d,Wr+26,o,l-26,{size:10,color:t.dark?uo:vS,leading:14,maxLines:2})+22}),i&&a7t(s,t,Ul-Wr-240,r,240,250),f0(s,t.dark)}function Bjn(s,t){p0(s,s.deep);const{doc:n}=s,r=DKe(s,t)||s.hero;r&&uee(n,r,0,0,Ul,Bh,{tint:{color:s.deep,amount:.82},darken:.28,dpi:s.dpi}),Wq(s,t.kicker||"Our approach",Wr,Bh/2-84),n.setFont(td,"bold"),n.setFontSize(30),n.setTextColor(...uo);const a=n.splitTextToSize(t.headline||"",Ul-Wr*2-140).slice(0,4);a.forEach((i,l)=>n.text(i,Wr,Bh/2-44+l*38)),t.body&&hu(n,t.body,Wr,Bh/2+a.length*38-24,480,{size:10.5,color:Rp(uo,s.deep,.2),leading:16,maxLines:4}),f0(s,!0)}function Cxt(s,t){switch(t.layout){case"testimonials":return Ojn(s,t);case"stats":return Fjn(s,t);case"checklist":return zjn(s,t);case"statement":return Bjn(s,t);case"story":default:return Djn(s,t)}}async function $jn(s,t,n){var P,L,I,O;const r=n==="print"?4:2,a=n==="print"?2600:1600,i=ljn((P=t.pages)==null?void 0:P.theme);hee=c7(i.paper),sO=c7(i.paperCool),kb=c7(i.softLine),py=c7(i.bodyInk),_U=i.headFont;const l=c7((i.useAgentColors?t.agent.brandColor:i.brand)||i.brand||"#0E1B2C"),o=c7((i.useAgentColors?t.agent.accentColor:i.accent)||i.accent||"#B8965A"),c=Rp(l,[0,0,0],i.id==="luxury"?.35:.2),d=(L=t.coAgent)!=null&&L.enabled&&((I=t.coAgent.name)!=null&&I.trim())?t.coAgent:null,u=(t.customPages||[]).filter($=>$.enabled).sort(($,q)=>$.order-q.order),[h,m,p,x,...y]=await Promise.all([ZH(t.property.photoUrl,a),ZH(t.agent.headshotUrl,700),ZH(t.agent.brokerageLogoUrl,800),ZH((d==null?void 0:d.headshotUrl)||null,700),...u.map($=>ZH($.imageUrl||null,a))]),g={};u.forEach(($,q)=>{g[$.id]=y[q]??null}),ujn(t.focal);const b={doc:s,data:t,brand:l,accent:o,deep:c,hero:h,headshot:m,coHeadshot:x,logo:p,customImages:g,dpi:r,pageNo:1},v=new Set(((O=t.pages)==null?void 0:O.hidden)||[]),k=[...t.services].filter($=>$.enabled).sort(($,q)=>$.order-q.order),C=$=>k.find(q=>q.key===$);Njn(b),v.has("welcome")||kjn(b),v.has("agent")||Sjn(b),u.filter($=>$.placement!=="end").forEach($=>Cxt(b,$)),v.has("overview")||Cjn(b,k);const T=new Set,M=($,q)=>{const W=C($);W&&(T.add($),q(W))};M("photography",$=>Sxt(b,$,{kicker:"First impressions",headline:"Buyers will see your home at its absolute best.",sub:"Strong presentation earns the click before a showing is ever scheduled.",note:"Every image has one job: earn the next click."})),M("video",$=>Sxt(b,$,{kicker:"More ways to experience it",headline:"Photos introduce the home. Video helps buyers feel it.",sub:"A cinematic walk-through gives the listing movement, emotion, and shareability.",note:"The right format for every screen.",dark:!0,flip:!0})),M("mls",$=>Ajn(b,$)),M("syndication",$=>Tjn(b,$)),M("website",$=>Ejn(b,$)),M("social",$=>Mjn(b,$)),M("email",$=>Ljn(b,$)),M("openhouse",$=>Pjn(b,$)),M("communication",$=>Ijn(b,$)),k.filter($=>!T.has($.key)).forEach($=>{p0(b);const q=fy(b,"Marketing",$.title,null),W=S6($,6),G=hu(s,$.body,Wr,q,Ul-Wr*2-160,{size:10.5,color:py,leading:16});W.length&&Gq(s,W,Wr,G+30,Ul-Wr*2-160,{font:td,size:9.5,color:vS,accent:b.accent,gap:8}),f0(b)}),u.filter($=>$.placement==="end").forEach($=>Cxt(b,$)),v.has("closing")||Rjn(b)}const Axt=[{id:"signature",name:"Signature",description:"Editorial full-bleed cover with a brand-tinted photo motif throughout.",render:$jn}];function Ujn(s){return Axt.find(t=>t.id===s)||Axt[0]}async function i7t(s,t,n="screen"){const r=new ho({unit:"pt",format:"letter",orientation:"landscape",compress:!0});return await Ujn(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 qjn(s){return`${(s.property.addressLine1||s.title||"listing-presentation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing-presentation"}-presentation.pdf`}const Vjn={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 _Se(s){if(!s)return null;const{data:t}=await U.storage.from(FE).createSignedUrl(s,3600);return(t==null?void 0:t.signedUrl)??null}function wSe(s,t,n){const r=s.agent_snapshot||{},a={...Vjn,...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:qOt(s.co_agent),customPages:HOt(s.custom_pages),services:z9e(s.services),pages:s.page_settings&&Object.keys(s.page_settings).length?s.page_settings:O9e,focal:s.photo_focal||F9e}}async function o7t(s,t){if(s.property.photoUrl||!t)return s;const n=await _Se(t);return{...s,property:{...s.property,photoUrl:n}}}async function l7t(s,t,n){const r=await o7t(s,n);return(await i7t(r,t,"screen")).output("blob")}async function c7t(s,t,n="print",r){const a=await o7t(s,r),l=(await i7t(a,t,n)).output("blob"),o=URL.createObjectURL(l),c=document.createElement("a");return c.href=o,c.download=qjn(a),document.body.appendChild(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(o),4e3),l}async function d7t(s,t,n){const r=`${s}/${t}/presentation.pdf`,{error:a}=await U.storage.from(FE).upload(r,n,{upsert:!0,contentType:"application/pdf"});return a?null:(await U.from("listing_presentations").update({pdf_path:r,last_generated_at:new Date().toISOString(),status:"final"}).eq("id",t),r)}async function u7t(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 Hjn(s,t,n){const r=await u7t(n),a=`${s}/${t}/photo.jpg`,{error:i}=await U.storage.from(FE).upload(a,r,{upsert:!0,contentType:"image/jpeg"});if(i)throw i;return a}async function Gjn(s,t,n="presentation",r=1800){const a=await u7t(t,r),i=`${s}/${n}-${Date.now()}.jpg`,{error:l}=await U.storage.from("avatars").upload(i,a,{upsert:!0,contentType:"image/jpeg"});if(l)throw l;const{data:o}=U.storage.from("avatars").getPublicUrl(i);return o.publicUrl}function Wjn({path:s,alt:t}){const[n,r]=j.useState(null),[a,i]=j.useState(!1);return j.useEffect(()=>{let l=!0;if(r(null),i(!1),!!s)return Qvn(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(ia,{className:"h-8 w-8 text-primary/50"})})}const Txt=60*60*24*30;function h7t({open:s,onOpenChange:t,row:n,brand:r,photoUrl:a}){const{user:i}=Ns(),[l,o]=j.useState([]),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,p]=j.useState(!1),[x,y]=j.useState(""),[g,b]=j.useState(""),[v,k]=j.useState(!1),C=j.useRef(null),T=(n==null?void 0:n.property_address_line1)||(n==null?void 0:n.title)||"your home";j.useEffect(()=>{!s||!n||(o([]),d(""),h([]),y(`Your listing presentation for ${T}`),b(`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]),j.useEffect(()=>{C.current&&clearTimeout(C.current);const O=c.trim();if(!i||O.length<2||/\S+@\S+\.\S+/.test(O)){h([]);return}return C.current=setTimeout(async()=>{p(!0);const $=`%${O}%`,q=U,{data:W}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i.id).not("email","is",null).or(`first_name.ilike.${$},last_name.ilike.${$},email.ilike.${$}`).order("first_name",{ascending:!0}).limit(6);p(!1),h(W||[])},200),()=>{C.current&&clearTimeout(C.current)}},[c,i==null?void 0:i.id]);const M=O=>{O.email&&(o($=>$.some(q=>q.email.toLowerCase()===O.email.toLowerCase())?$:[...$,O]),d(""),h([]))},P=()=>{const O=c.trim();if(!/\S+@\S+\.\S+/.test(O)){re.error("Enter a valid email address");return}M({email:O})},L=j.useMemo(()=>!!n&&l.length>0&&x.trim().length>0&&!v,[n,l,x,v]),I=async()=>{if(!(!n||!i)){if(!n.property_photo_path){re.error("Add the primary exterior photo before emailing the presentation");return}k(!0);try{const O=await l7t(wSe(n,r,a??null),n.template_id,n.property_photo_path),$=await d7t(i.id,n.id,O)||n.pdf_path;if(!$)throw new Error("Could not save the presentation PDF");const{data:q,error:W}=await U.storage.from(FE).createSignedUrl($,Txt);if(W||!(q!=null&&q.signedUrl))throw new Error("Could not create a share link");const G=await _Se(n.property_photo_path).then(le=>le).catch(()=>null),{data:K}=await U.storage.from(FE).createSignedUrl(n.property_photo_path,Txt),{data:ee,error:J}=await U.functions.invoke("listing-presentation-email",{body:{presentation_id:n.id,subject:x,message:g,pdf_url:q.signedUrl,photo_url:(K==null?void 0:K.signedUrl)||G,recipients:l}});if(J)throw J;if(!(ee!=null&&ee.success))throw new Error((ee==null?void 0:ee.error)||"Could not send the email");re.success(ee.failed?`Sent to ${ee.sent} · ${ee.failed} failed`:`Presentation emailed to ${ee.sent} ${ee.sent===1?"contact":"contacts"}`),t(!1)}catch(O){re.error((O==null?void 0:O.message)||"Could not send the presentation")}finally{k(!1)}}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4"})," Email this presentation"]}),e.jsxs(kr,{children:["Sends a branded email with a secure link to the PDF. Use ",e.jsx("code",{children:"{{first_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"To"}),l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map(O=>e.jsxs(qe,{variant:"secondary",className:"gap-1 py-1",children:[[O.first_name,O.last_name].filter(Boolean).join(" ")||O.email,e.jsx("button",{type:"button",onClick:()=>o($=>$.filter(q=>q.email!==O.email)),"aria-label":`Remove ${O.email}`,children:e.jsx(dr,{className:"h-3 w-3"})})]},O.email))}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:c,onChange:O=>d(O.target.value),onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),P())},placeholder:"Search contacts or type an email"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:P,children:e.jsx(Js,{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(Wt,{className:"h-3 w-3 animate-spin"})," Searching…"]}),u.map(O=>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:()=>M({email:O.email,first_name:O.first_name,last_name:O.last_name,contact_id:O.id}),children:[e.jsx(Eo,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:[O.first_name,O.last_name].filter(Boolean).join(" ")||O.email}),e.jsx("span",{className:"ml-auto truncate text-xs text-muted-foreground",children:O.email})]},O.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"pres-subject",children:"Subject"}),e.jsx(ye,{id:"pres-subject",value:x,onChange:O=>y(O.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"pres-message",children:"Message"}),e.jsx(Ds,{id:"pres-message",rows:7,value:g,onChange:O=>b(O.target.value)})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:v,children:"Cancel"}),e.jsxs(B,{onClick:I,disabled:!L,className:"gap-2",children:[v?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"}),v?"Sending…":`Send${l.length?` (${l.length})`:""}`]})]})]})})}const Kjn=()=>{const s=Hn(),{presentations:t,isLoading:n,create:r,duplicate:a,remove:i,update:l}=zOt(),{data:o}=Zvn(),{data:c}=BOt(),{savedTemplates:d,remove:u}=FOt(),[h,m]=j.useState(null),[p,x]=j.useState(""),[y,g]=j.useState(null),[b,v]=j.useState(null),[k,C]=j.useState(null),T=j.useMemo(()=>{var I,O;return(O=(I=o==null?void 0:o[0])==null?void 0:I.default_services)!=null&&O.length?o[0].default_services:pSe},[o]),M=async()=>{var O;if(!c)return;const I=await r.mutateAsync({title:"Untitled Presentation",template_id:((O=o==null?void 0:o[0])==null?void 0:O.slug)||"signature",agent_snapshot:c,services:T});s(`/apps/listing-presentation-studio/${I.id}`)},P=async I=>{var $;const O=await r.mutateAsync({title:`${I.name} — new listing`,template_id:I.template_id||"signature",agent_snapshot:I.agent_snapshot,co_agent:I.co_agent,custom_pages:I.custom_pages,services:($=I.services)!=null&&$.length?I.services:T,page_settings:I.page_settings});s(`/apps/listing-presentation-studio/${O.id}`)},L=async I=>{try{v(I.id),await c7t(wSe(I,c),I.template_id,"print",I.property_photo_path)}catch(O){re.error((O==null?void 0:O.message)||"Could not build the PDF")}finally{v(null)}};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/10 via-background to-accent/10 p-8",children:e.jsxs("div",{className:"flex flex-col gap-6 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(yn,{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:M,disabled:r.isPending||!c,className:"gap-2",children:[r.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Js,{className:"h-4 w-4"}),"New presentation"]}),d.length>0&&e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsxs(B,{size:"lg",variant:"outline",className:"gap-2",children:[e.jsx(s1,{className:"h-4 w-4"})," From template",e.jsx(Po,{className:"h-4 w-4"})]})}),e.jsx(xd,{align:"end",className:"w-64",children:d.map(I=>e.jsxs(wa,{onClick:()=>P(I),children:[e.jsx(s1,{className:"mr-2 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:I.name})]},I.id))})]})]})]})}),d.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:"Your saved templates"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Start a new presentation from a saved setup — just add the address and photo."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:d.map(I=>e.jsx(be,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Re,{className:"flex items-start justify-between gap-3 p-4",children:[e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>P(I),disabled:r.isPending,children:[e.jsxs("p",{className:"flex items-center gap-2 truncate font-medium",children:[e.jsx(s1,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),I.name]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:I.description||"Branding, theme, page wording, and marketing plan saved."})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>u.mutate(I.id),children:e.jsx(Rn,{className:"h-4 w-4"})})]})},I.id))})]}),n?e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(I=>e.jsx(gn,{className:"h-56 rounded-xl"},I))}):t.length===0?e.jsx(be,{className:"border-dashed",children:e.jsxs(Re,{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($r,{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:M,disabled:r.isPending||!c,className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"})," New presentation"]})]})}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(I=>{const O=I.property_address_line1||"No address yet",$=[I.city,I.state].filter(Boolean).join(", ");return e.jsxs(be,{className:"group overflow-hidden transition-shadow hover:shadow-lg",children:[e.jsx("button",{className:"block w-full text-left",onClick:()=>s(`/apps/listing-presentation-studio/${I.id}`),children:e.jsx(Wjn,{path:I.property_photo_path,alt:`${O} property photo`})}),e.jsxs(Re,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-medium",children:I.title}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[O,$?` · ${$}`:""]})]}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(W0,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[e.jsxs(wa,{onClick:()=>s(`/apps/listing-presentation-studio/${I.id}`),children:[e.jsx(Za,{className:"mr-2 h-4 w-4"})," Open"]}),e.jsxs(wa,{onClick:()=>{m(I),x(I.title)},children:[e.jsx($r,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(wa,{onClick:()=>a.mutate(I),children:[e.jsx(ja,{className:"mr-2 h-4 w-4"})," Duplicate"]}),e.jsxs(wa,{onClick:()=>L(I),children:[e.jsx(ii,{className:"mr-2 h-4 w-4"})," Download PDF"]}),e.jsxs(wa,{onClick:()=>C(I),children:[e.jsx(on,{className:"mr-2 h-4 w-4"})," Email to a contact"]}),e.jsx(uy,{}),e.jsxs(wa,{className:"text-destructive",onClick:()=>g(I),children:[e.jsx(Rn,{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 ",Bs(new Date(I.updated_at),"MMM d, yyyy")]}),I.last_generated_at?e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:"PDF ready"}):e.jsx(qe,{variant:"outline",className:"text-[10px]",children:"Draft"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-2",disabled:b===I.id,onClick:()=>L(I),children:[b===I.id?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(ii,{className:"h-4 w-4"}),"Download PDF"]})]})]},I.id)})})]}),e.jsx(Fs,{open:!!h,onOpenChange:I=>!I&&m(null),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{children:"Rename presentation"})}),e.jsx(ye,{value:p,onChange:I=>x(I.target.value),autoFocus:!0}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx(B,{onClick:async()=>{h&&(await l.mutateAsync({id:h.id,title:p.trim()||"Untitled Presentation"}),m(null),re.success("Renamed"))},children:"Save"})]})]})}),e.jsx(Nl,{open:!!y,onOpenChange:I=>!I&&g(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete this presentation?"}),e.jsx(xl,{children:"This permanently removes the presentation, its property photo, and the generated PDF."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{y&&i.mutate(y),g(null)},children:"Delete"})]})]})}),e.jsx(h7t,{open:!!k,onOpenChange:I=>!I&&C(null),row:k,brand:c})]})};var mY={};mY.d=(s,t)=>{for(var n in t)mY.o(t,n)&&!mY.o(s,n)&&Object.defineProperty(s,n,{enumerable:!0,get:t[n]})};mY.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var Ol=globalThis.pdfjsLib={};mY.d(Ol,{AbortException:()=>UO,AnnotationEditorLayer:()=>pBe,AnnotationEditorParamsType:()=>Ll,AnnotationEditorType:()=>rc,AnnotationEditorUIManager:()=>rO,AnnotationLayer:()=>GNn,AnnotationMode:()=>PA,ColorPicker:()=>SSe,DOMSVGFactory:()=>KKe,DrawLayer:()=>yBe,FeatureTest:()=>c1,GlobalWorkerOptions:()=>s3,ImageKind:()=>Kje,InvalidPDFException:()=>p7t,MissingPDFException:()=>$O,OPS:()=>L2,OutputScale:()=>lze,PDFDataRangeTransport:()=>d9t,PDFDateString:()=>$Ke,PDFWorker:()=>$z,PasswordResponses:()=>Qjn,PermissionFlag:()=>Xjn,PixelsPerInch:()=>BE,RenderingCancelledException:()=>zKe,TextLayer:()=>vX,UnexpectedResponseException:()=>hTe,Util:()=>vo,VerbosityLevel:()=>cTe,XfaLayer:()=>h9t,build:()=>SNn,createValidAbsoluteUrl:()=>s2n,fetchData:()=>pTe,getDocument:()=>gNn,getFilenameFromUrl:()=>u2n,getPdfFilenameFromUrl:()=>h2n,getXfaPageViewport:()=>m2n,isDataScheme:()=>fTe,isPdfFile:()=>BKe,noContextMenu:()=>qj,normalizeUnicode:()=>l2n,setLayerDimensions:()=>nO,shadow:()=>md,version:()=>kNn});const Xy=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),m7t=[1,0,0,1,0,0],rze=[.001,0,0,.001,0,0],Yjn=1e7,OIe=1.35,S_={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},PA={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Zjn="pdfjs_internal_editor_",rc={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},Ll={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},Xjn={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Iy={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},Kje={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Hx={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},XH={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},cTe={ERRORS:0,WARNINGS:1,INFOS:5},L2={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},Qjn={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let dTe=cTe.WARNINGS;function Jjn(s){Number.isInteger(s)&&(dTe=s)}function e2n(){return dTe}function uTe(s){dTe>=cTe.INFOS&&console.log(`Info: ${s}`)}function Sc(s){dTe>=cTe.WARNINGS&&console.log(`Warning: ${s}`)}function pm(s){throw new Error(s)}function ig(s,t){s||pm(t)}function t2n(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function s2n(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=o2n(s)}catch{}}const r=t?new URL(s,t):new URL(s);if(t2n(r))return r}catch{}return null}function md(s,t,n,r=!1){return Object.defineProperty(s,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}const C6=function(){function t(n,r){this.message=n,this.name=r}return t.prototype=new Error,t.constructor=t,t}();class aze extends C6{constructor(t,n){super(t,"PasswordException"),this.code=n}}class ize extends C6{constructor(t,n){super(t,"UnknownErrorException"),this.details=n}}class p7t extends C6{constructor(t){super(t,"InvalidPDFException")}}class $O extends C6{constructor(t){super(t,"MissingPDFException")}}class hTe extends C6{constructor(t,n){super(t,"UnexpectedResponseException"),this.status=n}}class n2n extends C6{constructor(t){super(t,"FormatError")}}class UO extends C6{constructor(t){super(t,"AbortException")}}function f7t(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&pm("Invalid argument for bytesToString");const t=s.length,n=8192;if(t>24&255,s>>16&255,s>>8&255,s&255)}function OKe(s){const t=Object.create(null);for(const[n,r]of s)t[n]=r;return t}function a2n(){const s=new Uint8Array(4);return s[0]=1,new Uint32Array(s.buffer,0,1)[0]===1}function i2n(){try{return new Function(""),!0}catch{return!1}}class c1{static get isLittleEndian(){return md(this,"isLittleEndian",a2n())}static get isEvalSupported(){return md(this,"isEvalSupported",i2n())}static get isOffscreenCanvasSupported(){return md(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?md(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")}):md(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,n;return md(this,"isCSSRoundSupported",(n=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:n.call(t,"width: round(1.5px, 1px)"))}}const FIe=Array.from(Array(256).keys(),s=>s.toString(16).padStart(2,"0"));var M3,Yje,oze;class vo{static makeHexColor(t,n,r){return`#${FIe[t]}${FIe[n]}${FIe[r]}`}static scaleMinMax(t,n){let r;t[0]?(t[0]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=t[0],n[2]*=t[0],t[3]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=t[3],n[3]*=t[3]):(r=n[0],n[0]=n[1],n[1]=r,r=n[2],n[2]=n[3],n[3]=r,t[1]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=t[1],n[3]*=t[1],t[2]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=t[2],n[2]*=t[2]),n[0]+=t[4],n[1]+=t[5],n[2]+=t[4],n[3]+=t[5]}static transform(t,n){return[t[0]*n[0]+t[2]*n[1],t[1]*n[0]+t[3]*n[1],t[0]*n[2]+t[2]*n[3],t[1]*n[2]+t[3]*n[3],t[0]*n[4]+t[2]*n[5]+t[4],t[1]*n[4]+t[3]*n[5]+t[5]]}static applyTransform(t,n){const r=t[0]*n[0]+t[1]*n[2]+n[4],a=t[0]*n[1]+t[1]*n[3]+n[5];return[r,a]}static applyInverseTransform(t,n){const r=n[0]*n[3]-n[1]*n[2],a=(t[0]*n[3]-t[1]*n[2]+n[2]*n[5]-n[4]*n[3])/r,i=(-t[0]*n[1]+t[1]*n[0]+n[4]*n[1]-n[5]*n[0])/r;return[a,i]}static getAxialAlignedBoundingBox(t,n){const r=this.applyTransform(t,n),a=this.applyTransform(t.slice(2,4),n),i=this.applyTransform([t[0],t[3]],n),l=this.applyTransform([t[2],t[1]],n);return[Math.min(r[0],a[0],i[0],l[0]),Math.min(r[1],a[1],i[1],l[1]),Math.max(r[0],a[0],i[0],l[0]),Math.max(r[1],a[1],i[1],l[1])]}static inverseTransform(t){const n=t[0]*t[3]-t[1]*t[2];return[t[3]/n,-t[1]/n,-t[2]/n,t[0]/n,(t[2]*t[5]-t[4]*t[3])/n,(t[4]*t[1]-t[5]*t[0])/n]}static singularValueDecompose2dScale(t){const n=[t[0],t[2],t[1],t[3]],r=t[0]*n[0]+t[1]*n[2],a=t[0]*n[1]+t[1]*n[3],i=t[2]*n[0]+t[3]*n[2],l=t[2]*n[1]+t[3]*n[3],o=(r+l)/2,c=Math.sqrt((r+l)**2-4*(r*l-i*a))/2,d=o+c||1,u=o-c||1;return[Math.sqrt(d),Math.sqrt(u)]}static normalizeRect(t){const n=t.slice(0);return t[0]>t[2]&&(n[0]=t[2],n[2]=t[0]),t[1]>t[3]&&(n[1]=t[3],n[3]=t[1]),n}static intersect(t,n){const r=Math.max(Math.min(t[0],t[2]),Math.min(n[0],n[2])),a=Math.min(Math.max(t[0],t[2]),Math.max(n[0],n[2]));if(r>a)return null;const i=Math.max(Math.min(t[1],t[3]),Math.min(n[1],n[3])),l=Math.min(Math.max(t[1],t[3]),Math.max(n[1],n[3]));return i>l?null:[r,i,a,l]}static bezierBoundingBox(t,n,r,a,i,l,o,c,d){return d?(d[0]=Math.min(d[0],t,o),d[1]=Math.min(d[1],n,c),d[2]=Math.max(d[2],t,o),d[3]=Math.max(d[3],n,c)):d=[Math.min(t,o),Math.min(n,c),Math.max(t,o),Math.max(n,c)],Kt(this,M3,oze).call(this,t,r,i,o,n,a,l,c,3*(-t+3*(r-i)+o),6*(t-2*r+i),3*(r-t),d),Kt(this,M3,oze).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}}M3=new WeakSet,Yje=function(t,n,r,a,i,l,o,c,d,u){if(d<=0||d>=1)return;const h=1-d,m=d*d,p=m*d,x=h*(h*(h*t+3*d*n)+3*m*r)+p*a,y=h*(h*(h*i+3*d*l)+3*m*o)+p*c;u[0]=Math.min(u[0],x),u[1]=Math.min(u[1],y),u[2]=Math.max(u[2],x),u[3]=Math.max(u[3],y)},oze=function(t,n,r,a,i,l,o,c,d,u,h,m){if(Math.abs(d)<1e-12){Math.abs(u)>=1e-12&&Kt(this,M3,Yje).call(this,t,n,r,a,i,l,o,c,-h/u,m);return}const p=u**2-4*h*d;if(p<0)return;const x=Math.sqrt(p),y=2*d;Kt(this,M3,Yje).call(this,t,n,r,a,i,l,o,c,(-u+x)/y,m),Kt(this,M3,Yje).call(this,t,n,r,a,i,l,o,c,(-u-x)/y,m)},rs(vo,M3);function o2n(s){return decodeURIComponent(escape(s))}let zIe=null,Ext=null;function l2n(s){return zIe||(zIe=/([\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,Ext=new Map([["ſt","ſt"]])),s.replaceAll(zIe,(t,n,r)=>n?n.normalize("NFKC"):Ext.get(r))}function c2n(){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 f7t(s)}const FKe="pdfjs_internal_id_",s4={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 d2n(s){return Uint8Array.prototype.toBase64?s.toBase64():btoa(f7t(s))}const h4="http://www.w3.org/2000/svg",YI=class YI{};Ar(YI,"CSS",96),Ar(YI,"PDF",72),Ar(YI,"PDF_TO_CSS_UNITS",YI.CSS/YI.PDF);let BE=YI;async function pTe(s,t="text"){if(ZG(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 pee{constructor({viewBox:t,scale:n,rotation:r,offsetX:a=0,offsetY:i=0,dontFlip:l=!1}){this.viewBox=t,this.scale=n,this.rotation=r,this.offsetX=a,this.offsetY=i;const o=(t[2]+t[0])/2,c=(t[3]+t[1])/2;let d,u,h,m;switch(r%=360,r<0&&(r+=360),r){case 180:d=-1,u=0,h=0,m=1;break;case 90:d=0,u=1,h=1,m=0;break;case 270:d=0,u=-1,h=-1,m=0;break;case 0:d=1,u=0,h=0,m=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}l&&(h=-h,m=-m);let p,x,y,g;d===0?(p=Math.abs(c-t[1])*n+a,x=Math.abs(o-t[0])*n+i,y=(t[3]-t[1])*n,g=(t[2]-t[0])*n):(p=Math.abs(o-t[0])*n+a,x=Math.abs(c-t[1])*n+i,y=(t[2]-t[0])*n,g=(t[3]-t[1])*n),this.transform=[d*n,u*n,h*n,m*n,p-d*n*o-h*n*c,x-u*n*o-m*n*c],this.width=y,this.height=g}get rawDims(){const{viewBox:t}=this;return md(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 pee({viewBox:this.viewBox.slice(),scale:t,rotation:n,offsetX:r,offsetY:a,dontFlip:i})}convertToViewportPoint(t,n){return vo.applyTransform([t,n],this.transform)}convertToViewportRectangle(t){const n=vo.applyTransform([t[0],t[1]],this.transform),r=vo.applyTransform([t[2],t[3]],this.transform);return[n[0],n[1],r[0],r[1]]}convertToPdfPoint(t,n){return vo.applyInverseTransform([t,n],this.transform)}}class zKe extends C6{constructor(t,n=0){super(t,"RenderingCancelledException"),this.extraDelay=n}}function fTe(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))}}PX=new WeakMap,rs($Ke,PX);function m2n(s,{scale:t=1,rotation:n=0}){const{width:r,height:a}=s.attributes.style,i=[0,0,parseInt(r),parseInt(a)];return new pee({viewBox:i,scale:t,rotation:n})}function UKe(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):(Sc(`Not a valid color format: "${s}"`),[0,0,0])}function p2n(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,UKe(r))}t.remove()}function wp(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform();return[t,n,r,a,i,l]}function n4(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 nO(s,t,n=!1,r=!0){if(t instanceof pee){const{pageWidth:a,pageHeight:i}=t.rawDims,{style:l}=s,o=c1.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 lze{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 VA,M8,R2,L8,IX,RX,KSe,x7t,d1,g7t,y7t,Zje,v7t,dze;const b4=class b4{constructor(t){rs(this,d1);rs(this,VA,null);rs(this,M8,null);rs(this,R2);rs(this,L8,null);rs(this,IX,null);Ot(this,R2,t),me(b4,RX)||Ot(b4,RX,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=Ot(this,VA,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const n=me(this,R2)._uiManager._signal;t.addEventListener("contextmenu",qj,{signal:n}),t.addEventListener("pointerdown",Kt(b4,KSe,x7t),{signal:n});const r=Ot(this,L8,document.createElement("div"));r.className="buttons",t.append(r);const a=me(this,R2).toolbarPosition;if(a){const{style:i}=t,l=me(this,R2)._uiManager.direction==="ltr"?1-a[0]:a[0];i.insetInlineEnd=`${100*l}%`,i.top=`calc(${100*a[1]}% + var(--editor-toolbar-vert-offset))`}return Kt(this,d1,v7t).call(this),t}get div(){return me(this,VA)}hide(){var t;me(this,VA).classList.add("hidden"),(t=me(this,M8))==null||t.hideDropdown()}show(){var t;me(this,VA).classList.remove("hidden"),(t=me(this,IX))==null||t.shown()}async addAltText(t){const n=await t.render();Kt(this,d1,Zje).call(this,n),me(this,L8).prepend(n,me(this,d1,dze)),Ot(this,IX,t)}addColorPicker(t){Ot(this,M8,t);const n=t.renderButton();Kt(this,d1,Zje).call(this,n),me(this,L8).prepend(n,me(this,d1,dze))}remove(){var t;me(this,VA).remove(),(t=me(this,M8))==null||t.destroy(),Ot(this,M8,null)}};VA=new WeakMap,M8=new WeakMap,R2=new WeakMap,L8=new WeakMap,IX=new WeakMap,RX=new WeakMap,KSe=new WeakSet,x7t=function(t){t.stopPropagation()},d1=new WeakSet,g7t=function(t){me(this,R2)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},y7t=function(t){me(this,R2)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},Zje=function(t){const n=me(this,R2)._uiManager._signal;t.addEventListener("focusin",Kt(this,d1,g7t).bind(this),{capture:!0,signal:n}),t.addEventListener("focusout",Kt(this,d1,y7t).bind(this),{capture:!0,signal:n}),t.addEventListener("contextmenu",qj,{signal:n})},v7t=function(){const{editorType:t,_uiManager:n}=me(this,R2),r=document.createElement("button");r.className="delete",r.tabIndex=0,r.setAttribute("data-l10n-id",me(b4,RX)[t]),Kt(this,d1,Zje).call(this,r),r.addEventListener("click",a=>{n.delete()},{signal:n._signal}),me(this,L8).append(r)},dze=function(){const t=document.createElement("div");return t.className="divider",t},rs(b4,KSe),rs(b4,RX,null);let cze=b4;var DX,P8,I8,HE,b7t,_7t,w7t;class f2n{constructor(t){rs(this,HE);rs(this,DX,null);rs(this,P8,null);rs(this,I8);Ot(this,I8,t)}show(t,n,r){const[a,i]=Kt(this,HE,_7t).call(this,n,r),{style:l}=me(this,P8)||Ot(this,P8,Kt(this,HE,b7t).call(this));t.append(me(this,P8)),l.insetInlineEnd=`${100*a}%`,l.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){me(this,P8).remove()}}DX=new WeakMap,P8=new WeakMap,I8=new WeakMap,HE=new WeakSet,b7t=function(){const t=Ot(this,P8,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",qj,{signal:me(this,I8)._signal});const n=Ot(this,DX,document.createElement("div"));return n.className="buttons",t.append(n),Kt(this,HE,w7t).call(this),t},_7t=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{me(this,I8).highlightSelection("floating_button")},{signal:r}),me(this,DX).append(t)};function jSe(s,t,n){for(const r of n)t.addEventListener(r,s[r].bind(s))}function x2n(s){return Math.round(Math.min(255,Math.max(1,255*s))).toString(16).padStart(2,"0")}var YSe;class g2n{constructor(){rs(this,YSe,0)}get id(){return`${Zjn}${Ig(this,YSe)._++}`}}YSe=new WeakMap;var oB,OX,Oy,lB,Xje;const oZe=class oZe{constructor(){rs(this,lB);rs(this,oB,c2n());rs(this,OX,0);rs(this,Oy,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 md(this,"_isSVGFittingCanvas",i)}async getFromFile(t){const{lastModified:n,name:r,size:a,type:i}=t;return Kt(this,lB,Xje).call(this,`${n}_${r}_${a}_${i}`,t)}async getFromUrl(t){return Kt(this,lB,Xje).call(this,t,t)}async getFromBlob(t,n){const r=await n;return Kt(this,lB,Xje).call(this,t,r)}async getFromId(t){me(this,Oy)||Ot(this,Oy,new Map);const n=me(this,Oy).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){me(this,Oy)||Ot(this,Oy,new Map);let r=me(this,Oy).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_${me(this,oB)}_${Ig(this,OX)._++}`,refCounter:1,isSvg:!1},me(this,Oy).set(t,r),me(this,Oy).set(r.id,r),r}getSvgUrl(t){const n=me(this,Oy).get(t);return n!=null&&n.isSvg?n.svgUrl:null}deleteId(t){var a;me(this,Oy)||Ot(this,Oy,new Map);const n=me(this,Oy).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_${me(this,oB)}_`)}};oB=new WeakMap,OX=new WeakMap,Oy=new WeakMap,lB=new WeakSet,Xje=async function(t,n){me(this,Oy)||Ot(this,Oy,new Map);let r=me(this,Oy).get(t);if(r===null)return null;if(r!=null&&r.bitmap)return r.refCounter+=1,r;try{r||(r={bitmap:null,id:`image_${me(this,oB)}_${Ig(this,OX)._++}`,refCounter:0,isSvg:!1});let a;if(typeof n=="string"?(r.url=n,a=await pTe(n,"blob")):n instanceof File?a=r.file=n:n instanceof Blob&&(a=n),a.type==="image/svg+xml"){const i=oZe._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 me(this,Oy).set(t,r),r&&me(this,Oy).set(r.id,r),r};let uze=oZe;var zg,HA,FX,Bg;class y2n{constructor(t=128){rs(this,zg,[]);rs(this,HA,!1);rs(this,FX);rs(this,Bg,-1);Ot(this,FX,t)}add({cmd:t,undo:n,post:r,mustExec:a,type:i=NaN,overwriteIfSameType:l=!1,keepUndo:o=!1}){if(a&&t(),me(this,HA))return;const c={cmd:t,undo:n,post:r,type:i};if(me(this,Bg)===-1){me(this,zg).length>0&&(me(this,zg).length=0),Ot(this,Bg,0),me(this,zg).push(c);return}if(l&&me(this,zg)[me(this,Bg)].type===i){o&&(c.undo=me(this,zg)[me(this,Bg)].undo),me(this,zg)[me(this,Bg)]=c;return}const d=me(this,Bg)+1;d===me(this,FX)?me(this,zg).splice(0,1):(Ot(this,Bg,d),di===n[l]))return XSe._colorsMapping.get(r);return n}getHexCode(t){const n=this._colors.get(t);return n?vo.makeHexColor(...n):t}};Ar(XSe,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let hze=XSe;var cB,g_,Kx,O0,dB,E4,uB,D2,GA,hB,R8,Hk,O2,D8,zX,BX,mB,$X,Gk,WA,pB,KA,Wk,QSe,YA,UX,ZA,O8,qX,VX,$g,Fu,M4,F8,HX,GX,XA,Kk,L4,WX,Xw,vi,Qje,mze,N7t,k7t,Jje,S7t,C7t,A7t,pze,T7t,fze,xze,E7t,Iv,rA,M7t,L7t,gze,P7t,XG,yze;const C9=class C9{constructor(t,n,r,a,i,l,o,c,d,u,h){rs(this,vi);rs(this,cB,new AbortController);rs(this,g_,null);rs(this,Kx,new Map);rs(this,O0,new Map);rs(this,dB,null);rs(this,E4,null);rs(this,uB,null);rs(this,D2,new y2n);rs(this,GA,null);rs(this,hB,0);rs(this,R8,new Set);rs(this,Hk,null);rs(this,O2,null);rs(this,D8,new Set);rs(this,zX,!1);rs(this,BX,!1);rs(this,mB,!1);rs(this,$X,null);rs(this,Gk,null);rs(this,WA,null);rs(this,pB,null);rs(this,KA,!1);rs(this,Wk,null);rs(this,QSe,new g2n);rs(this,YA,!1);rs(this,UX,!1);rs(this,ZA,null);rs(this,O8,null);rs(this,qX,null);rs(this,VX,null);rs(this,$g,rc.NONE);rs(this,Fu,new Set);rs(this,M4,null);rs(this,F8,null);rs(this,HX,null);rs(this,GX,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});rs(this,XA,[0,0]);rs(this,Kk,null);rs(this,L4,null);rs(this,WX,null);rs(this,Xw,null);const m=this._signal=me(this,cB).signal;Ot(this,L4,t),Ot(this,WX,n),Ot(this,dB,r),this._eventBus=a,a._on("editingaction",this.onEditingAction.bind(this),{signal:m}),a._on("pagechanging",this.onPageChanging.bind(this),{signal:m}),a._on("scalechanging",this.onScaleChanging.bind(this),{signal:m}),a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:m}),a._on("setpreference",this.onSetPreference.bind(this),{signal:m}),a._on("switchannotationeditorparams",p=>this.updateParams(p.type,p.value),{signal:m}),Kt(this,vi,S7t).call(this),Kt(this,vi,E7t).call(this),Kt(this,vi,pze).call(this),Ot(this,E4,i.annotationStorage),Ot(this,$X,i.filterFactory),Ot(this,F8,l),Ot(this,pB,o||null),Ot(this,zX,c),Ot(this,BX,d),Ot(this,mB,u),Ot(this,VX,h||null),this.viewParameters={realScale:BE.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=C9.prototype,n=l=>me(l,L4).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 md(this,"_keyboardManager",new fee([[["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)&&me(l,L4).contains(o)&&!l.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&me(l,L4).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=me(this,Xw))==null||t.resolve(),Ot(this,Xw,null),(n=me(this,cB))==null||n.abort(),Ot(this,cB,null),this._signal=null;for(const i of me(this,O0).values())i.destroy();me(this,O0).clear(),me(this,Kx).clear(),me(this,D8).clear(),Ot(this,g_,null),me(this,Fu).clear(),me(this,D2).destroy(),(r=me(this,dB))==null||r.destroy(),(a=me(this,Wk))==null||a.hide(),Ot(this,Wk,null),me(this,Gk)&&(clearTimeout(me(this,Gk)),Ot(this,Gk,null)),me(this,Kk)&&(clearTimeout(me(this,Kk)),Ot(this,Kk,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return me(this,VX)}get useNewAltTextFlow(){return me(this,BX)}get useNewAltTextWhenAddingImage(){return me(this,mB)}get hcmFilter(){return md(this,"hcmFilter",me(this,F8)?me(this,$X).addHCMFilter(me(this,F8).foreground,me(this,F8).background):"none")}get direction(){return md(this,"direction",getComputedStyle(me(this,L4)).direction)}get highlightColors(){return md(this,"highlightColors",me(this,pB)?new Map(me(this,pB).split(",").map(t=>t.split("=").map(n=>n.trim()))):null)}get highlightColorNames(){return md(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){Ot(this,qX,t)}editAltText(t,n=!1){var r;(r=me(this,dB))==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":Ot(this,mB,n);break}}onPageChanging({pageNumber:t}){Ot(this,hB,t-1)}focusMainContainer(){me(this,L4).focus()}findParent(t,n){for(const r of me(this,O0).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){me(this,WX).classList.toggle("noUserSelect",t)}addShouldRescale(t){me(this,D8).add(t)}removeShouldRescale(t){me(this,D8).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*BE.PDF_TO_CSS_UNITS;for(const n of me(this,D8))n.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}highlightSelection(t=""){const n=document.getSelection();if(!n||n.isCollapsed)return;const{anchorNode:r,anchorOffset:a,focusNode:i,focusOffset:l}=n,o=n.toString(),d=Kt(this,vi,Qje).call(this,n).closest(".textLayer"),u=this.getSelectionBoxes(d);if(!u)return;n.empty();const h=Kt(this,vi,mze).call(this,d),m=me(this,$g)===rc.NONE,p=()=>{h==null||h.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:u,anchorNode:r,anchorOffset:a,focusNode:i,focusOffset:l,text:o}),m&&this.showAllEditors("highlight",!0,!0)};if(m){this.switchToMode(rc.HIGHLIGHT,p);return}p()}addToAnnotationStorage(t){!t.isEmpty()&&me(this,E4)&&!me(this,E4).has(t.id)&&me(this,E4).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,me(this,KA)&&(Ot(this,KA,!1),Kt(this,vi,Jje).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const n of me(this,Fu))if(n.div.contains(t)){Ot(this,O8,[n,t]),n._focusEventsAllowed=!1;break}}focus(){if(!me(this,O8))return;const[t,n]=me(this,O8);Ot(this,O8,null),n.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),n.focus()}addEditListeners(){Kt(this,vi,pze).call(this),Kt(this,vi,fze).call(this)}removeEditListeners(){Kt(this,vi,T7t).call(this),Kt(this,vi,xze).call(this)}dragOver(t){for(const{type:n}of t.dataTransfer.items)for(const r of me(this,O2))if(r.isHandlingMimeForPasting(n)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const n of t.dataTransfer.items)for(const r of me(this,O2))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer),t.preventDefault();return}}copy(t){var r;if(t.preventDefault(),(r=me(this,g_))==null||r.commitOrRemove(),!this.hasSelection)return;const n=[];for(const a of me(this,Fu)){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 me(this,O2))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){Sc(`paste: "${i.message}".`);return}if(!Array.isArray(r))return;this.unselectAll();const a=this.currentLayer;try{const i=[];for(const c of r){const d=await a.deserialize(c);if(!d)return;i.push(d)}const l=()=>{for(const c of i)Kt(this,vi,gze).call(this,c);Kt(this,vi,yze).call(this,i)},o=()=>{for(const c of i)c.remove()};this.addCommands({cmd:l,undo:o,mustExec:!0})}catch(i){Sc(`paste: "${i.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),me(this,$g)!==rc.NONE&&!this.isEditorHandlingKeyboard&&C9._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,me(this,KA)&&(Ot(this,KA,!1),Kt(this,vi,Jje).call(this,"main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}setEditingState(t){t?(Kt(this,vi,C7t).call(this),Kt(this,vi,fze).call(this),Kt(this,vi,Iv).call(this,{isEditing:me(this,$g)!==rc.NONE,isEmpty:Kt(this,vi,XG).call(this),hasSomethingToUndo:me(this,D2).hasSomethingToUndo(),hasSomethingToRedo:me(this,D2).hasSomethingToRedo(),hasSelectedEditor:!1})):(Kt(this,vi,A7t).call(this),Kt(this,vi,xze).call(this),Kt(this,vi,Iv).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!me(this,O2)){Ot(this,O2,t);for(const n of me(this,O2))Kt(this,vi,rA).call(this,n.defaultPropertiesToUpdate)}}getId(){return me(this,QSe).id}get currentLayer(){return me(this,O0).get(me(this,hB))}getLayer(t){return me(this,O0).get(t)}get currentPageIndex(){return me(this,hB)}addLayer(t){me(this,O0).set(t.pageIndex,t),me(this,YA)?t.enable():t.disable()}removeLayer(t){me(this,O0).delete(t.pageIndex)}async updateMode(t,n=null,r=!1){if(me(this,$g)!==t&&!(me(this,Xw)&&(await me(this,Xw).promise,!me(this,Xw)))){if(Ot(this,Xw,Promise.withResolvers()),Ot(this,$g,t),t===rc.NONE){this.setEditingState(!1),Kt(this,vi,L7t).call(this),me(this,Xw).resolve();return}this.setEditingState(!0),await Kt(this,vi,M7t).call(this),this.unselectAll();for(const a of me(this,O0).values())a.updateMode(t);if(!n){r&&this.addNewEditorFromKeyboard(),me(this,Xw).resolve();return}for(const a of me(this,Kx).values())a.annotationElementId===n?(this.setSelected(a),a.enterInEditMode()):a.unselect();me(this,Xw).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==me(this,$g)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,n){var r;if(me(this,O2)){switch(t){case Ll.CREATE:this.currentLayer.addNewEditor();return;case Ll.HIGHLIGHT_DEFAULT_COLOR:(r=me(this,qX))==null||r.updateColor(n);break;case Ll.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(me(this,HX)||Ot(this,HX,new Map)).set(t,n),this.showAllEditors("highlight",n);break}for(const a of me(this,Fu))a.updateParams(t,n);for(const a of me(this,O2))a.updateDefaultParams(t,n)}}showAllEditors(t,n,r=!1){var i;for(const l of me(this,Kx).values())l.editorType===t&&l.show(n);(((i=me(this,HX))==null?void 0:i.get(Ll.HIGHLIGHT_SHOW_ALL))??!0)!==n&&Kt(this,vi,rA).call(this,[[Ll.HIGHLIGHT_SHOW_ALL,n]])}enableWaiting(t=!1){if(me(this,UX)!==t){Ot(this,UX,t);for(const n of me(this,O0).values())t?n.disableClick():n.enableClick(),n.div.classList.toggle("waiting",t)}}getEditors(t){const n=[];for(const r of me(this,Kx).values())r.pageIndex===t&&n.push(r);return n}getEditor(t){return me(this,Kx).get(t)}addEditor(t){me(this,Kx).set(t.id,t)}removeEditor(t){var n;t.div.contains(document.activeElement)&&(me(this,Gk)&&clearTimeout(me(this,Gk)),Ot(this,Gk,setTimeout(()=>{this.focusMainContainer(),Ot(this,Gk,null)},0))),me(this,Kx).delete(t.id),this.unselect(t),(!t.annotationElementId||!me(this,R8).has(t.annotationElementId))&&((n=me(this,E4))==null||n.remove(t.id))}addDeletedAnnotationElement(t){me(this,R8).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return me(this,R8).has(t)}removeDeletedAnnotationElement(t){me(this,R8).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){me(this,g_)!==t&&(Ot(this,g_,t),t&&Kt(this,vi,rA).call(this,t.propertiesToUpdate))}updateUI(t){me(this,vi,P7t)===t&&Kt(this,vi,rA).call(this,t.propertiesToUpdate)}toggleSelected(t){if(me(this,Fu).has(t)){me(this,Fu).delete(t),t.unselect(),Kt(this,vi,Iv).call(this,{hasSelectedEditor:this.hasSelection});return}me(this,Fu).add(t),t.select(),Kt(this,vi,rA).call(this,t.propertiesToUpdate),Kt(this,vi,Iv).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const n of me(this,Fu))n!==t&&n.unselect();me(this,Fu).clear(),me(this,Fu).add(t),t.select(),Kt(this,vi,rA).call(this,t.propertiesToUpdate),Kt(this,vi,Iv).call(this,{hasSelectedEditor:!0})}isSelected(t){return me(this,Fu).has(t)}get firstSelectedEditor(){return me(this,Fu).values().next().value}unselect(t){t.unselect(),me(this,Fu).delete(t),Kt(this,vi,Iv).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return me(this,Fu).size!==0}get isEnterHandled(){return me(this,Fu).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){me(this,D2).undo(),Kt(this,vi,Iv).call(this,{hasSomethingToUndo:me(this,D2).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:Kt(this,vi,XG).call(this)})}redo(){me(this,D2).redo(),Kt(this,vi,Iv).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:me(this,D2).hasSomethingToRedo(),isEmpty:Kt(this,vi,XG).call(this)})}addCommands(t){me(this,D2).add(t),Kt(this,vi,Iv).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:Kt(this,vi,XG).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...me(this,Fu)],n=()=>{for(const a of t)a.remove()},r=()=>{for(const a of t)Kt(this,vi,gze).call(this,a)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){var t;(t=me(this,g_))==null||t.commitOrRemove()}hasSomethingToControl(){return me(this,g_)||this.hasSelection}selectAll(){for(const t of me(this,Fu))t.commit();Kt(this,vi,yze).call(this,me(this,Kx).values())}unselectAll(){if(!(me(this,g_)&&(me(this,g_).commitOrRemove(),me(this,$g)!==rc.NONE))&&this.hasSelection){for(const t of me(this,Fu))t.unselect();me(this,Fu).clear(),Kt(this,vi,Iv).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,n,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;me(this,XA)[0]+=t,me(this,XA)[1]+=n;const[a,i]=me(this,XA),l=[...me(this,Fu)],o=1e3;me(this,Kk)&&clearTimeout(me(this,Kk)),Ot(this,Kk,setTimeout(()=>{Ot(this,Kk,null),me(this,XA)[0]=me(this,XA)[1]=0,this.addCommands({cmd:()=>{for(const c of l)me(this,Kx).has(c.id)&&c.translateInPage(a,i)},undo:()=>{for(const c of l)me(this,Kx).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),Ot(this,Hk,new Map);for(const t of me(this,Fu))me(this,Hk).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!me(this,Hk))return!1;this.disableUserSelect(!1);const t=me(this,Hk);Ot(this,Hk,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(me(this,Kx).has(a.id)){const c=me(this,O0).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(me(this,Hk))for(const r of me(this,Hk).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())||me(this,Fu).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return me(this,g_)===t}getActive(){return me(this,g_)}getMode(){return me(this,$g)}get imageManager(){return md(this,"imageManager",new uze)}getSelectionBoxes(t){if(!t)return null;const n=document.getSelection();for(let d=0,u=n.rangeCount;d({x:(u-a)/l,y:1-(d+h-r)/i,width:m/l,height:h/i});break;case"180":o=(d,u,h,m)=>({x:1-(d+h-r)/i,y:1-(u+m-a)/l,width:h/i,height:m/l});break;case"270":o=(d,u,h,m)=>({x:1-(u+m-a)/l,y:(d-r)/i,width:m/l,height:h/i});break;default:o=(d,u,h,m)=>({x:(d-r)/i,y:(u-a)/l,width:h/i,height:m/l});break}const c=[];for(let d=0,u=n.rangeCount;d{m.type==="pointerup"&&m.button!==0||(d.abort(),c==null||c.toggleDrawing(!0),m.type==="pointerup"&&Kt(this,vi,Jje).call(this,"main_toolbar"))};window.addEventListener("pointerup",h,{signal:u}),window.addEventListener("blur",h,{signal:u})}},Jje=function(t=""){me(this,$g)===rc.HIGHLIGHT?this.highlightSelection(t):me(this,zX)&&Kt(this,vi,N7t).call(this)},S7t=function(){document.addEventListener("selectionchange",Kt(this,vi,k7t).bind(this),{signal:this._signal})},C7t=function(){if(me(this,WA))return;Ot(this,WA,new AbortController);const t=this.combinedSignal(me(this,WA));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},A7t=function(){var t;(t=me(this,WA))==null||t.abort(),Ot(this,WA,null)},pze=function(){if(me(this,ZA))return;Ot(this,ZA,new AbortController);const t=this.combinedSignal(me(this,ZA));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},T7t=function(){var t;(t=me(this,ZA))==null||t.abort(),Ot(this,ZA,null)},fze=function(){if(me(this,GA))return;Ot(this,GA,new AbortController);const t=this.combinedSignal(me(this,GA));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})},xze=function(){var t;(t=me(this,GA))==null||t.abort(),Ot(this,GA,null)},E7t=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},Iv=function(t){Object.entries(t).some(([r,a])=>me(this,GX)[r]!==a)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(me(this,GX),t)}),me(this,$g)===rc.HIGHLIGHT&&t.hasSelectedEditor===!1&&Kt(this,vi,rA).call(this,[[Ll.HIGHLIGHT_FREE,!0]]))},rA=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},M7t=async function(){if(!me(this,YA)){Ot(this,YA,!0);const t=[];for(const n of me(this,O0).values())t.push(n.enable());await Promise.all(t);for(const n of me(this,Kx).values())n.enable()}},L7t=function(){if(this.unselectAll(),me(this,YA)){Ot(this,YA,!1);for(const t of me(this,O0).values())t.disable();for(const t of me(this,Kx).values())t.disable()}},gze=function(t){const n=me(this,O0).get(t.pageIndex);n?n.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},P7t=function(){let t=null;for(t of me(this,Fu));return t},XG=function(){if(me(this,Kx).size===0)return!0;if(me(this,Kx).size===1)for(const t of me(this,Kx).values())return t.isEmpty();return!1},yze=function(t){for(const n of me(this,Fu))n.unselect();me(this,Fu).clear();for(const n of t)n.isEmpty()||(me(this,Fu).add(n),n.select());Kt(this,vi,Iv).call(this,{hasSelectedEditor:this.hasSelection})},Ar(C9,"TRANSLATE_SMALL",1),Ar(C9,"TRANSLATE_BIG",10);let rO=C9;var Ug,Yk,F2,fB,Zk,y_,xB,Xk,Y1,P4,z8,Qk,QA,cN,QG,e2e;const Dv=class Dv{constructor(t){rs(this,cN);rs(this,Ug,null);rs(this,Yk,!1);rs(this,F2,null);rs(this,fB,null);rs(this,Zk,null);rs(this,y_,null);rs(this,xB,!1);rs(this,Xk,null);rs(this,Y1,null);rs(this,P4,null);rs(this,z8,null);rs(this,Qk,!1);Ot(this,Y1,t),Ot(this,Qk,t._uiManager.useNewAltTextFlow),me(Dv,QA)||Ot(Dv,QA,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){Dv._l10n??(Dv._l10n=t)}async render(){const t=Ot(this,F2,document.createElement("button"));t.className="altText",t.tabIndex="0";const n=Ot(this,fB,document.createElement("span"));t.append(n),me(this,Qk)?(t.classList.add("new"),t.setAttribute("data-l10n-id",me(Dv,QA).missing),n.setAttribute("data-l10n-id",me(Dv,QA)["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=me(this,Y1)._uiManager._signal;t.addEventListener("contextmenu",qj,{signal:r}),t.addEventListener("pointerdown",i=>i.stopPropagation(),{signal:r});const a=i=>{i.preventDefault(),me(this,Y1)._uiManager.editAltText(me(this,Y1)),me(this,Qk)&&me(this,Y1)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:me(this,cN,QG)}})};return t.addEventListener("click",a,{capture:!0,signal:r}),t.addEventListener("keydown",i=>{i.target===t&&i.key==="Enter"&&(Ot(this,xB,!0),a(i))},{signal:r}),await Kt(this,cN,e2e).call(this),t}finish(){me(this,F2)&&(me(this,F2).focus({focusVisible:me(this,xB)}),Ot(this,xB,!1))}isEmpty(){return me(this,Qk)?me(this,Ug)===null:!me(this,Ug)&&!me(this,Yk)}hasData(){return me(this,Qk)?me(this,Ug)!==null||!!me(this,P4):this.isEmpty()}get guessedText(){return me(this,P4)}async setGuessedText(t){me(this,Ug)===null&&(Ot(this,P4,t),Ot(this,z8,await Dv._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),Kt(this,cN,e2e).call(this))}toggleAltTextBadge(t=!1){var n;if(!me(this,Qk)||me(this,Ug)){(n=me(this,Xk))==null||n.remove(),Ot(this,Xk,null);return}if(!me(this,Xk)){const r=Ot(this,Xk,document.createElement("div"));r.className="noAltTextBadge",me(this,Y1).div.append(r)}me(this,Xk).classList.toggle("hidden",!t)}serialize(t){let n=me(this,Ug);return!t&&me(this,P4)===n&&(n=me(this,z8)),{altText:n,decorative:me(this,Yk),guessedText:me(this,P4),textWithDisclaimer:me(this,z8)}}get data(){return{altText:me(this,Ug),decorative:me(this,Yk)}}set data({altText:t,decorative:n,guessedText:r,textWithDisclaimer:a,cancel:i=!1}){r&&(Ot(this,P4,r),Ot(this,z8,a)),!(me(this,Ug)===t&&me(this,Yk)===n)&&(i||(Ot(this,Ug,t),Ot(this,Yk,n)),Kt(this,cN,e2e).call(this))}toggle(t=!1){me(this,F2)&&(!t&&me(this,y_)&&(clearTimeout(me(this,y_)),Ot(this,y_,null)),me(this,F2).disabled=!t)}shown(){me(this,Y1)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:me(this,cN,QG)}})}destroy(){var t,n;(t=me(this,F2))==null||t.remove(),Ot(this,F2,null),Ot(this,fB,null),Ot(this,Zk,null),(n=me(this,Xk))==null||n.remove(),Ot(this,Xk,null)}};Ug=new WeakMap,Yk=new WeakMap,F2=new WeakMap,fB=new WeakMap,Zk=new WeakMap,y_=new WeakMap,xB=new WeakMap,Xk=new WeakMap,Y1=new WeakMap,P4=new WeakMap,z8=new WeakMap,Qk=new WeakMap,QA=new WeakMap,cN=new WeakSet,QG=function(){return me(this,Ug)&&"added"||me(this,Ug)===null&&this.guessedText&&"review"||"missing"},e2e=async function(){var a,i,l;const t=me(this,F2);if(!t)return;if(me(this,Qk)){if(t.classList.toggle("done",!!me(this,Ug)),t.setAttribute("data-l10n-id",me(Dv,QA)[me(this,cN,QG)]),(a=me(this,fB))==null||a.setAttribute("data-l10n-id",me(Dv,QA)[`${me(this,cN,QG)}-label`]),!me(this,Ug)){(i=me(this,Zk))==null||i.remove();return}}else{if(!me(this,Ug)&&!me(this,Yk)){t.classList.remove("done"),(l=me(this,Zk))==null||l.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let n=me(this,Zk);if(!n){Ot(this,Zk,n=document.createElement("span")),n.className="tooltip",n.setAttribute("role","tooltip"),n.id=`alt-text-tooltip-${me(this,Y1).id}`;const o=100,c=me(this,Y1)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(me(this,y_)),Ot(this,y_,null)},{once:!0}),t.addEventListener("mouseenter",()=>{Ot(this,y_,setTimeout(()=>{Ot(this,y_,null),me(this,Zk).classList.add("show"),me(this,Y1)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:c}),t.addEventListener("mouseleave",()=>{var d;me(this,y_)&&(clearTimeout(me(this,y_)),Ot(this,y_,null)),(d=me(this,Zk))==null||d.classList.remove("show")},{signal:c})}me(this,Yk)?n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(n.removeAttribute("data-l10n-id"),n.textContent=me(this,Ug)),n.parentNode||t.append(n);const r=me(this,Y1).getImageForAltText();r==null||r.setAttribute("aria-describedby",n.id)},rs(Dv,QA,null),Ar(Dv,"_l10n",null);let NSe=Dv;var B8,z2,bp,gB,$8,F0,U8,JA,KX,q8,eT,YX,V8,I4,Jk,yB,vB,Qw,ZX,JSe,yc,vze,XX,bze,_ze,I7t,R7t,wze,jze,Nze,D7t,kze,O7t,F7t,z7t,Sze,JG;const ku=class ku{constructor(t){rs(this,yc);rs(this,B8,null);rs(this,z2,null);rs(this,bp,null);rs(this,gB,!1);rs(this,$8,!1);rs(this,F0,null);rs(this,U8,null);rs(this,JA,null);rs(this,KX,"");rs(this,q8,!1);rs(this,eT,null);rs(this,YX,!1);rs(this,V8,!1);rs(this,I4,!1);rs(this,Jk,null);rs(this,yB,0);rs(this,vB,0);rs(this,Qw,null);Ar(this,"_editToolbar",null);Ar(this,"_initialOptions",Object.create(null));Ar(this,"_initialData",null);Ar(this,"_isVisible",!0);Ar(this,"_uiManager",null);Ar(this,"_focusEventsAllowed",!0);rs(this,ZX,!1);rs(this,JSe,ku._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=ku.prototype._resizeWithKeyboard,n=rO.TRANSLATE_SMALL,r=rO.TRANSLATE_BIG;return md(this,"_resizerKeyboardManager",new fee([[["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"],ku.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return md(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const n=new v2n({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(ku._l10n??(ku._l10n=t),ku._l10nResizer||(ku._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"})),ku._borderLineWidth!==-1)return;const r=getComputedStyle(document.documentElement);ku._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,n){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,n){pm("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return me(this,ZX)}set _isDraggable(t){var n;Ot(this,ZX,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=me(this,JSe)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):Kt(this,yc,JG).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(me(this,q8)?Ot(this,q8,!1):this.parent.setSelected(this))}focusout(t){var r;if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;const n=t.relatedTarget;n!=null&&n.closest(`#${this.id}`)||(t.preventDefault(),(r=this.parent)!=null&&r.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,n,r,a){const[i,l]=this.parentDimensions;[r,a]=this.screenToPageTranslation(r,a),this.x=(t+r)/i,this.y=(n+a)/l,this.fixAndSetPosition()}translate(t,n){Kt(this,yc,vze).call(this,this.parentDimensions,t,n)}translateInPage(t,n){me(this,eT)||Ot(this,eT,[this.x,this.y]),Kt(this,yc,vze).call(this,this.pageDimensions,t,n),this.div.scrollIntoView({block:"nearest"})}drag(t,n){me(this,eT)||Ot(this,eT,[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!!me(this,eT)&&(me(this,eT)[0]!==this.x||me(this,eT)[1]!==this.y)}getBaseTranslation(){const[t,n]=this.parentDimensions,{_borderLineWidth:r}=ku,a=r/t,i=r/n;switch(this.rotation){case 90:return[-a,i];case 180:return[a,i];case 270:return[a,-i];default:return[-a,-i]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const[n,r]=this.pageDimensions;let{x:a,y:i,width:l,height:o}=this;if(l*=n,o*=r,a*=n,i*=r,this._mustFixPosition)switch(t){case 0:a=Math.max(0,Math.min(n-l,a)),i=Math.max(0,Math.min(r-o,i));break;case 90:a=Math.max(0,Math.min(n-o,a)),i=Math.min(r,Math.max(l,i));break;case 180:a=Math.min(n,Math.max(l,a)),i=Math.min(r,Math.max(o,i));break;case 270:a=Math.min(n,Math.max(o,a)),i=Math.max(0,Math.min(r-l,i));break}this.x=a/=n,this.y=i/=r;const[c,d]=this.getBaseTranslation();a+=c,i+=d;const{style:u}=this.div;u.left=`${(100*a).toFixed(2)}%`,u.top=`${(100*i).toFixed(2)}%`,this.moveInDOM()}screenToPageTranslation(t,n){var r;return Kt(r=ku,XX,bze).call(r,t,n,this.parentRotation)}pageTranslationToScreen(t,n){var r;return Kt(r=ku,XX,bze).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)}%`,me(this,$8)||(this.div.style.height=`${(100*n/a).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:n,width:r}=t,a=r.endsWith("%"),i=!me(this,$8)&&n.endsWith("%");if(a&&i)return;const[l,o]=this.parentDimensions;a||(t.width=`${(100*parseFloat(r)/l).toFixed(2)}%`),!me(this,$8)&&!i&&(t.height=`${(100*parseFloat(n)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=me(this,bp))==null||t.finish()}async addEditToolbar(){return this._editToolbar||me(this,V8)?this._editToolbar:(this._editToolbar=new cze(this),this.div.append(this._editToolbar.render()),me(this,bp)&&await this._editToolbar.addAltText(me(this,bp)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=me(this,bp))==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(){me(this,bp)||(NSe.initialize(ku._l10n),Ot(this,bp,new NSe(this)),me(this,B8)&&(me(this,bp).data=me(this,B8),Ot(this,B8,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=me(this,bp))==null?void 0:t.data}set altTextData(t){me(this,bp)&&(me(this,bp).data=t)}get guessedAltText(){var t;return(t=me(this,bp))==null?void 0:t.guessedText}async setGuessedAltText(t){var n;await((n=me(this,bp))==null?void 0:n.setGuessedText(t))}serializeAltText(t){var n;return(n=me(this,bp))==null?void 0:n.serialize(t)}hasAltText(){return!!me(this,bp)&&!me(this,bp).isEmpty()}hasAltTextData(){var t;return((t=me(this,bp))==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=me(this,gB)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),Kt(this,yc,kze).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),jSe(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:n}=c1.platform;if(t.button!==0||t.ctrlKey&&n){t.preventDefault();return}if(Ot(this,q8,!0),this._isDraggable){Kt(this,yc,D7t).call(this,t);return}Kt(this,yc,Nze).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){me(this,Jk)&&clearTimeout(me(this,Jk)),Ot(this,Jk,setTimeout(()=>{var t;Ot(this,Jk,null),(t=this.parent)==null||t.moveEditorInDOM(this)},0))}_setParentAndPosition(t,n,r){t.changeParent(this),this.x=n,this.y=r,this.fixAndSetPosition()}getRect(t,n,r=this.rotation){const a=this.parentScale,[i,l]=this.pageDimensions,[o,c]=this.pageTranslation,d=t/a,u=n/a,h=this.x*i,m=this.y*l,p=this.width*i,x=this.height*l;switch(r){case 0:return[h+d+o,l-m-u-x+c,h+d+p+o,l-m-u+c];case 90:return[h+u+o,l-m+d+c,h+u+x+o,l-m+d+p+c];case 180:return[h-d-p+o,l-m+u+c,h-d+o,l-m+u+x+c];case 270:return[h-u-x+o,l-m-d-p+c,h-u+o,l-m-d+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,n){const[r,a,i,l]=t,o=i-r,c=l-a;switch(this.rotation){case 0:return[r,n-l,o,c];case 90:return[r,n-a,c,o];case 180:return[i,n-a,o,c];case 270:return[i,n-l,c,o];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){Ot(this,V8,!0)}disableEditMode(){Ot(this,V8,!1)}isInEditMode(){return me(this,V8)}shouldGetKeyboardEvents(){return me(this,I4)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){Kt(this,yc,kze).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){pm("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,Ot(a,B8,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=me(this,JA))==null||t.abort(),Ot(this,JA,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),me(this,Jk)&&(clearTimeout(me(this,Jk)),Ot(this,Jk,null)),Kt(this,yc,JG).call(this),this.removeEditToolbar(),me(this,Qw)){for(const n of me(this,Qw).values())clearTimeout(n);Ot(this,Qw,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(Kt(this,yc,I7t).call(this),me(this,F0).classList.remove("hidden"),jSe(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),Ot(this,U8,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const n=me(this,F0).children;if(!me(this,z2)){Ot(this,z2,Array.from(n));const l=Kt(this,yc,O7t).bind(this),o=Kt(this,yc,F7t).bind(this),c=this._uiManager._signal;for(const d of me(this,z2)){const u=d.getAttribute("data-resizer-name");d.setAttribute("role","spinbutton"),d.addEventListener("keydown",l,{signal:c}),d.addEventListener("blur",o,{signal:c}),d.addEventListener("focus",Kt(this,yc,z7t).bind(this,u),{signal:c}),d.setAttribute("data-l10n-id",ku._l10nResizer[u])}}const r=me(this,z2)[0];let a=0;for(const l of n){if(l===r)break;a++}const i=(360-this.rotation+this.parentRotation)%360/90*(me(this,z2).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=me(this,bp))==null||r.toggleAltTextBadge(!1)}unselect(){var t,n,r,a,i;(t=me(this,F0))==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=me(this,bp))==null||i.toggleAltTextBadge(!0)}updateParams(t,n){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return me(this,YX)}set isEditing(t){Ot(this,YX,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,n){Ot(this,$8,!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){me(this,Qw)||Ot(this,Qw,new Map);const{action:r}=t;let a=me(this,Qw).get(r);a&&clearTimeout(a),a=setTimeout(()=>{this._reportTelemetry(t),me(this,Qw).delete(r),me(this,Qw).size===0&&Ot(this,Qw,null)},ku._telemetryTimeout),me(this,Qw).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),Ot(this,gB,!1)}disable(){this.div&&(this.div.tabIndex=-1),Ot(this,gB,!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()}};B8=new WeakMap,z2=new WeakMap,bp=new WeakMap,gB=new WeakMap,$8=new WeakMap,F0=new WeakMap,U8=new WeakMap,JA=new WeakMap,KX=new WeakMap,q8=new WeakMap,eT=new WeakMap,YX=new WeakMap,V8=new WeakMap,I4=new WeakMap,Jk=new WeakMap,yB=new WeakMap,vB=new WeakMap,Qw=new WeakMap,ZX=new WeakMap,JSe=new WeakMap,yc=new WeakSet,vze=function([t,n],r,a){[r,a]=this.screenToPageTranslation(r,a),this.x+=r/t,this.y+=a/n,this.fixAndSetPosition()},XX=new WeakSet,bze=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]}},_ze=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]}},I7t=function(){if(me(this,F0))return;Ot(this,F0,document.createElement("div")),me(this,F0).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");me(this,F0).append(a),a.classList.add("resizer",r),a.setAttribute("data-resizer-name",r),a.addEventListener("pointerdown",Kt(this,yc,R7t).bind(this,r),{signal:n}),a.addEventListener("contextmenu",qj,{signal:n}),a.tabIndex=-1}this.div.prepend(me(this,F0))},R7t=function(t,n){var x;n.preventDefault();const{isMac:r}=c1.platform;if(n.button!==0||n.ctrlKey&&r)return;(x=me(this,bp))==null||x.toggle(!1);const a=this._isDraggable;this._isDraggable=!1;const i=new AbortController,l=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",Kt(this,yc,jze).bind(this,t),{passive:!0,capture:!0,signal:l}),window.addEventListener("contextmenu",qj,{signal:l});const o=this.x,c=this.y,d=this.width,u=this.height,h=this.parent.div.style.cursor,m=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(n.target).cursor;const p=()=>{var y;i.abort(),this.parent.togglePointerEvents(!0),(y=me(this,bp))==null||y.toggle(!0),this._isDraggable=a,this.parent.div.style.cursor=h,this.div.style.cursor=m,Kt(this,yc,wze).call(this,o,c,d,u)};window.addEventListener("pointerup",p,{signal:l}),window.addEventListener("blur",p,{signal:l})},wze=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})},jze=function(t,n){const[r,a]=this.parentDimensions,i=this.x,l=this.y,o=this.width,c=this.height,d=ku.MIN_SIZE/r,u=ku.MIN_SIZE/a,h=J=>Math.round(J*1e4)/1e4,m=Kt(this,yc,_ze).call(this,this.rotation),p=(J,le)=>[m[0]*J+m[2]*le,m[1]*J+m[3]*le],x=Kt(this,yc,_ze).call(this,360-this.rotation),y=(J,le)=>[x[0]*J+x[2]*le,x[1]*J+x[3]*le];let g,b,v=!1,k=!1;switch(t){case"topLeft":v=!0,g=(J,le)=>[0,0],b=(J,le)=>[J,le];break;case"topMiddle":g=(J,le)=>[J/2,0],b=(J,le)=>[J/2,le];break;case"topRight":v=!0,g=(J,le)=>[J,0],b=(J,le)=>[0,le];break;case"middleRight":k=!0,g=(J,le)=>[J,le/2],b=(J,le)=>[0,le/2];break;case"bottomRight":v=!0,g=(J,le)=>[J,le],b=(J,le)=>[0,0];break;case"bottomMiddle":g=(J,le)=>[J/2,le],b=(J,le)=>[J/2,0];break;case"bottomLeft":v=!0,g=(J,le)=>[0,le],b=(J,le)=>[J,0];break;case"middleLeft":k=!0,g=(J,le)=>[0,le/2],b=(J,le)=>[J,le/2];break}const C=g(o,c),T=b(o,c);let M=p(...T);const P=h(i+M[0]),L=h(l+M[1]);let I=1,O=1,[$,q]=this.screenToPageTranslation(n.movementX,n.movementY);if([$,q]=y($/r,q/a),v){const J=Math.hypot(o,c);I=O=Math.max(Math.min(Math.hypot(T[0]-C[0]-$,T[1]-C[1]-q)/J,1/o,1/c),d/o,u/c)}else k?I=Math.max(d,Math.min(1,Math.abs(T[0]-C[0]-$)))/o:O=Math.max(u,Math.min(1,Math.abs(T[1]-C[1]-q)))/c;const W=h(o*I),G=h(c*O);M=p(...b(W,G));const K=P-M[0],ee=L-M[1];this.width=W,this.height=G,this.x=K,this.y=ee,this.setDims(r*W,a*G),this.fixAndSetPosition()},Nze=function(t){const{isMac:n}=c1.platform;t.ctrlKey&&!n||t.shiftKey||t.metaKey&&n?this.parent.toggleSelected(this):this.parent.setSelected(this)},D7t=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"),Ot(this,yB,t.clientX),Ot(this,vB,t.clientY);const l=o=>{const{clientX:c,clientY:d}=o,[u,h]=this.screenToPageTranslation(c-me(this,yB),d-me(this,vB));Ot(this,yB,c),Ot(this,vB,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"),Ot(this,q8,!1),this._uiManager.endDragSession()||Kt(this,yc,Nze).call(this,t)};window.addEventListener("pointerup",i,{signal:a}),window.addEventListener("blur",i,{signal:a})},kze=function(){if(me(this,JA)||!this.div)return;Ot(this,JA,new AbortController);const t=this._uiManager.combinedSignal(me(this,JA));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},O7t=function(t){ku._resizerKeyboardManager.exec(this,t)},F7t=function(t){var n;me(this,I4)&&((n=t.relatedTarget)==null?void 0:n.parentNode)!==me(this,F0)&&Kt(this,yc,JG).call(this)},z7t=function(t){Ot(this,KX,me(this,I4)?t:"")},Sze=function(t){if(me(this,z2))for(const n of me(this,z2))n.tabIndex=t},JG=function(){if(Ot(this,I4,!1),Kt(this,yc,Sze).call(this,-1),me(this,U8)){const{savedX:t,savedY:n,savedWidth:r,savedHeight:a}=me(this,U8);Kt(this,yc,wze).call(this,t,n,r,a),Ot(this,U8,null)}},rs(ku,XX),Ar(ku,"_l10n",null),Ar(ku,"_l10nResizer",null),Ar(ku,"_borderLineWidth",-1),Ar(ku,"_colorManager",new hze),Ar(ku,"_zIndex",1),Ar(ku,"_telemetryTimeout",1e3);let qu=ku;class v2n extends qu{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Pxt=3285377520,Vw=4294901760,Nk=65535;class B7t{constructor(t){this.h1=t?t&4294967295:Pxt,this.h2=t?t&4294967295:Pxt}update(t){let n,r;if(typeof t=="string"){n=new Uint8Array(t.length*2),r=0;for(let y=0,g=t.length;y>>8,n[r++]=b&255)}}else if(ArrayBuffer.isView(t))n=t.slice(),r=n.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const a=r>>2,i=r-a*4,l=new Uint32Array(n.buffer,0,a);let o=0,c=0,d=this.h1,u=this.h2;const h=3432918353,m=461845907,p=h&Nk,x=m&Nk;for(let y=0;y>>17,o=o*m&Vw|o*x&Nk,d^=o,d=d<<13|d>>>19,d=d*5+3864292196):(c=l[y],c=c*h&Vw|c*p&Nk,c=c<<15|c>>>17,c=c*m&Vw|c*x&Nk,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&Vw|o*p&Nk,o=o<<15|o>>>17,o=o*m&Vw|o*x&Nk,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&Vw|t*36045&Nk,n=n*4283543511&Vw|((n<<16|t>>>16)*2950163797&Vw)>>>16,t^=n>>>1,t=t*444984403&Vw|t*60499&Nk,n=n*3301882366&Vw|((n<<16|t>>>16)*3120437893&Vw)>>>16,t^=n>>>1,(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}}const Cze=Object.freeze({map:null,hash:"",transfer:void 0});var H8,G8,qg,e4e,$7t;class qKe{constructor(){rs(this,e4e);rs(this,H8,!1);rs(this,G8,null);rs(this,qg,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,n){const r=me(this,qg).get(t);return r===void 0?n:Object.assign(n,r)}getRawValue(t){return me(this,qg).get(t)}remove(t){if(me(this,qg).delete(t),me(this,qg).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const n of me(this,qg).values())if(n instanceof qu)return;this.onAnnotationEditor(null)}}setValue(t,n){const r=me(this,qg).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,me(this,qg).set(t,n);a&&Kt(this,e4e,$7t).call(this),n instanceof qu&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(n.constructor._type)}has(t){return me(this,qg).has(t)}getAll(){return me(this,qg).size>0?OKe(me(this,qg)):null}setAll(t){for(const[n,r]of Object.entries(t))this.setValue(n,r)}get size(){return me(this,qg).size}resetModified(){me(this,H8)&&(Ot(this,H8,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new U7t(this)}get serializable(){if(me(this,qg).size===0)return Cze;const t=new Map,n=new B7t,r=[],a=Object.create(null);let i=!1;for(const[l,o]of me(this,qg)){const c=o instanceof qu?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}:Cze}get editorStats(){let t=null;const n=new Map;for(const r of me(this,qg).values()){if(!(r instanceof qu))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(){Ot(this,G8,null)}get modifiedIds(){if(me(this,G8))return me(this,G8);const t=[];for(const n of me(this,qg).values())!(n instanceof qu)||!n.annotationElementId||!n.serialize()||t.push(n.annotationElementId);return Ot(this,G8,{ids:new Set(t),hash:t.join(",")})}}H8=new WeakMap,G8=new WeakMap,qg=new WeakMap,e4e=new WeakSet,$7t=function(){me(this,H8)||(Ot(this,H8,!0),typeof this.onSetModified=="function"&&this.onSetModified())};var QX;class U7t extends qKe{constructor(n){super();rs(this,QX);const{map:r,hash:a,transfer:i}=n.serializable,l=structuredClone(r,i?{transfer:i}:null);Ot(this,QX,{map:l,hash:a,transfer:i})}get print(){pm("Should not call PrintAnnotationStorage.print")}get serializable(){return me(this,QX)}get modifiedIds(){return md(this,"modifiedIds",{ids:new Set,hash:""})}}QX=new WeakMap;var bB;class b2n{constructor({ownerDocument:t=globalThis.document,styleElement:n=null}){rs(this,bB,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(),me(this,bB).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:n}){if(!(!t||me(this,bB).has(t.loadedName))){if(ig(!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(),me(this,bB).add(r),n==null||n(t)}catch{Sc(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}pm("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 Sc(`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 md(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Xy||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),md(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function n(){for(ig(!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 md(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,n){function r(C,T){return C.charCodeAt(T)<<24|C.charCodeAt(T+1)<<16|C.charCodeAt(T+2)<<8|C.charCodeAt(T+3)&255}function a(C,T,M,P){const L=C.substring(0,T),I=C.substring(T+M);return L+P+I}let i,l;const o=this._document.createElement("canvas");o.width=1,o.height=1;const c=o.getContext("2d");let d=0;function u(C,T){if(++d>30){Sc("Load test font never loaded."),T();return}if(c.font="30px "+C,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){T();return}setTimeout(u.bind(null,C,T))}const h=`lt${Date.now()}${this.loadTestFontId++}`;let m=this._loadTestFont;m=a(m,976,h.length,h);const x=16,y=1482184792;let g=r(m,x);for(i=0,l=h.length-3;i{k.remove(),n.complete()})}}bB=new WeakMap;class _2n{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,${d2n(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){Sc(`getPathGenerator - ignoring character: "${i}".`)}if(!Array.isArray(r)||r.length===0)return this.compiledGlyphs[n]=function(i,l){};const a=[];for(let i=0,l=r.length;ip.bezierCurveTo(o,c,d,u,h,m)),i+=6}break;case s4.MOVE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.moveTo(o,c)),i+=2}break;case s4.LINE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.lineTo(o,c)),i+=2}break;case s4.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 s4.RESTORE:a.push(o=>o.restore());break;case s4.SAVE:a.push(o=>o.save());break;case s4.SCALE:ig(a.length===2,"Scale command is only valid at the third position.");break;case s4.TRANSFORM:{const[o,c,d,u,h,m]=r.slice(i,i+6);a.push(p=>p.transform(o,c,d,u,h,m)),i+=6}break;case s4.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){pm("Abstract method `_fetch` called.")}}class H7t extends V7t{async _fetch(t){const n=await pTe(t,this.isCompressed?"arraybuffer":"text");return n instanceof ArrayBuffer?new Uint8Array(n):mTe(n)}}class G7t{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 W8,K8,e5,R4,Fy,t4e,Y8,Oi,Ry,F7,z7,t2e,B7,W7t,Aze,$7,eW,tW,Tze,sW;class j2n extends G7t{constructor({docId:n,ownerDocument:r=globalThis.document}){super();rs(this,Oi);rs(this,W8);rs(this,K8);rs(this,e5);rs(this,R4);rs(this,Fy);rs(this,t4e);rs(this,Y8,0);Ot(this,R4,n),Ot(this,Fy,r)}addFilter(n){if(!n)return"none";let r=me(this,Oi,Ry).get(n);if(r)return r;const[a,i,l]=Kt(this,Oi,t2e).call(this,n),o=n.length===1?a:`${a}${i}${l}`;if(r=me(this,Oi,Ry).get(o),r)return me(this,Oi,Ry).set(n,r),r;const c=`g_${me(this,R4)}_transfer_map_${Ig(this,Y8)._++}`,d=Kt(this,Oi,B7).call(this,c);me(this,Oi,Ry).set(n,d),me(this,Oi,Ry).set(o,d);const u=Kt(this,Oi,$7).call(this,c);return Kt(this,Oi,tW).call(this,a,i,l,u),d}addHCMFilter(n,r){var x;const a=`${n}-${r}`,i="base";let l=me(this,Oi,F7).get(i);if((l==null?void 0:l.key)===a||(l?((x=l.filter)==null||x.remove(),l.key=a,l.url="none",l.filter=null):(l={key:a,url:"none",filter:null},me(this,Oi,F7).set(i,l)),!n||!r))return l.url;const o=Kt(this,Oi,sW).call(this,n);n=vo.makeHexColor(...o);const c=Kt(this,Oi,sW).call(this,r);if(r=vo.makeHexColor(...c),me(this,Oi,z7).style.color="",n==="#000000"&&r==="#ffffff"||n===r)return l.url;const d=new Array(256);for(let y=0;y<=255;y++){const g=y/255;d[y]=g<=.03928?g/12.92:((g+.055)/1.055)**2.4}const u=d.join(","),h=`g_${me(this,R4)}_hcm_filter`,m=l.filter=Kt(this,Oi,$7).call(this,h);Kt(this,Oi,tW).call(this,u,u,u,m),Kt(this,Oi,Aze).call(this,m);const p=(y,g)=>{const b=o[y]/255,v=c[y]/255,k=new Array(g+1);for(let C=0;C<=g;C++)k[C]=b+C/g*(v-b);return k.join(",")};return Kt(this,Oi,tW).call(this,p(0,5),p(1,5),p(2,5),m),l.url=Kt(this,Oi,B7).call(this,h),l.url}addAlphaFilter(n){let r=me(this,Oi,Ry).get(n);if(r)return r;const[a]=Kt(this,Oi,t2e).call(this,[n]),i=`alpha_${a}`;if(r=me(this,Oi,Ry).get(i),r)return me(this,Oi,Ry).set(n,r),r;const l=`g_${me(this,R4)}_alpha_map_${Ig(this,Y8)._++}`,o=Kt(this,Oi,B7).call(this,l);me(this,Oi,Ry).set(n,o),me(this,Oi,Ry).set(i,o);const c=Kt(this,Oi,$7).call(this,l);return Kt(this,Oi,Tze).call(this,a,c),o}addLuminosityFilter(n){let r=me(this,Oi,Ry).get(n||"luminosity");if(r)return r;let a,i;if(n?([a]=Kt(this,Oi,t2e).call(this,[n]),i=`luminosity_${a}`):i="luminosity",r=me(this,Oi,Ry).get(i),r)return me(this,Oi,Ry).set(n,r),r;const l=`g_${me(this,R4)}_luminosity_map_${Ig(this,Y8)._++}`,o=Kt(this,Oi,B7).call(this,l);me(this,Oi,Ry).set(n,o),me(this,Oi,Ry).set(i,o);const c=Kt(this,Oi,$7).call(this,l);return Kt(this,Oi,W7t).call(this,c),n&&Kt(this,Oi,Tze).call(this,a,c),o}addHighlightHCMFilter(n,r,a,i,l){var v;const o=`${r}-${a}-${i}-${l}`;let c=me(this,Oi,F7).get(n);if((c==null?void 0:c.key)===o||(c?((v=c.filter)==null||v.remove(),c.key=o,c.url="none",c.filter=null):(c={key:o,url:"none",filter:null},me(this,Oi,F7).set(n,c)),!r||!a))return c.url;const[d,u]=[r,a].map(Kt(this,Oi,sW).bind(this));let h=Math.round(.2126*d[0]+.7152*d[1]+.0722*d[2]),m=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[p,x]=[i,l].map(Kt(this,Oi,sW).bind(this));m{const M=new Array(256),P=(m-h)/T,L=k/255,I=(C-k)/(255*T);let O=0;for(let $=0;$<=T;$++){const q=Math.round(h+$*P),W=L+$*I;for(let G=O;G<=q;G++)M[G]=W;O=q+1}for(let $=O;$<256;$++)M[$]=M[O-1];return M.join(",")},g=`g_${me(this,R4)}_hcm_${n}_filter`,b=c.filter=Kt(this,Oi,$7).call(this,g);return Kt(this,Oi,Aze).call(this,b),Kt(this,Oi,tW).call(this,y(p[0],x[0],5),y(p[1],x[1],5),y(p[2],x[2],5),b),c.url=Kt(this,Oi,B7).call(this,g),c.url}destroy(n=!1){n&&me(this,Oi,F7).size!==0||(me(this,e5)&&(me(this,e5).parentNode.parentNode.remove(),Ot(this,e5,null)),me(this,K8)&&(me(this,K8).clear(),Ot(this,K8,null)),Ot(this,Y8,0))}}W8=new WeakMap,K8=new WeakMap,e5=new WeakMap,R4=new WeakMap,Fy=new WeakMap,t4e=new WeakMap,Y8=new WeakMap,Oi=new WeakSet,Ry=function(){return me(this,K8)||Ot(this,K8,new Map)},F7=function(){return me(this,t4e)||Ot(this,t4e,new Map)},z7=function(){if(!me(this,e5)){const n=me(this,Fy).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=me(this,Fy).createElementNS(h4,"svg");a.setAttribute("width",0),a.setAttribute("height",0),Ot(this,e5,me(this,Fy).createElementNS(h4,"defs")),n.append(a),a.append(me(this,e5)),me(this,Fy).body.append(n)}return me(this,e5)},t2e=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(",")]},B7=function(n){if(me(this,W8)===void 0){Ot(this,W8,"");const r=me(this,Fy).URL;r!==me(this,Fy).baseURI&&(fTe(r)?Sc('#createUrl: ignore "data:"-URL for performance reasons.'):Ot(this,W8,r.split("#",1)[0]))}return`url(${me(this,W8)}#${n})`},W7t=function(n){const r=me(this,Fy).createElementNS(h4,"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)},Aze=function(n){const r=me(this,Fy).createElementNS(h4,"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)},$7=function(n){const r=me(this,Fy).createElementNS(h4,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",n),me(this,Oi,z7).append(r),r},eW=function(n,r,a){const i=me(this,Fy).createElementNS(h4,r);i.setAttribute("type","discrete"),i.setAttribute("tableValues",a),n.append(i)},tW=function(n,r,a,i){const l=me(this,Fy).createElementNS(h4,"feComponentTransfer");i.append(l),Kt(this,Oi,eW).call(this,l,"feFuncR",n),Kt(this,Oi,eW).call(this,l,"feFuncG",r),Kt(this,Oi,eW).call(this,l,"feFuncB",a)},Tze=function(n,r){const a=me(this,Fy).createElementNS(h4,"feComponentTransfer");r.append(a),Kt(this,Oi,eW).call(this,a,"feFuncA",n)},sW=function(n){return me(this,Oi,z7).style.color=n,UKe(getComputedStyle(me(this,Oi,z7)).getPropertyValue("color"))};class K7t{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){pm("Abstract method `_fetch` called.")}}class Y7t extends K7t{async _fetch(t){const n=await pTe(t,"arraybuffer");return new Uint8Array(n)}}if(Xy){var Eze=Promise.withResolvers(),pY=null;(async()=>{const t=await Mi(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),n=await Mi(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),r=await Mi(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),a=await Mi(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]);let i,l;return new Map(Object.entries({fs:t,http:n,https:r,url:a,canvas:i,path2d:l}))})().then(t=>{pY=t,Eze.resolve()},t=>{Sc(`loadPackages: ${t}`),pY=new Map,Eze.resolve()})}class $E{static get promise(){return Eze.promise}static get(t){return pY==null?void 0:pY.get(t)}}async function Z7t(s){const n=await $E.get("fs").promises.readFile(s);return new Uint8Array(n)}class N2n extends G7t{}class k2n extends q7t{_createCanvas(t,n){return $E.get("canvas").createCanvas(t,n)}}class S2n extends V7t{async _fetch(t){return Z7t(t)}}class C2n extends K7t{async _fetch(t){return Z7t(t)}}const Vv={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Mze(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 VKe{getPattern(){pm("Abstract method `getPattern` called.")}}class A2n extends VKe{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===Vv.STROKE||a===Vv.FILL){const l=n.current.getClippedPathBoundingBox(a,wp(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=vo.transform(r,[1,0,0,1,l[0],l[1]]),u.transform(...n.baseTransform),this.matrix&&u.transform(...this.matrix),Mze(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 Mze(t,this._bbox),i=this._createGradient(t);return i}}function BIe(s,t,n,r,a,i,l,o){const c=t.coords,d=t.colors,u=s.data,h=s.width*4;let m;c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m),c[r+1]>c[a+1]&&(m=r,r=a,a=m,m=l,l=o,o=m),c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m);const p=(c[n]+t.offsetX)*t.scaleX,x=(c[n+1]+t.offsetY)*t.scaleY,y=(c[r]+t.offsetX)*t.scaleX,g=(c[r+1]+t.offsetY)*t.scaleY,b=(c[a]+t.offsetX)*t.scaleX,v=(c[a+1]+t.offsetY)*t.scaleY;if(x>=v)return;const k=d[i],C=d[i+1],T=d[i+2],M=d[l],P=d[l+1],L=d[l+2],I=d[o],O=d[o+1],$=d[o+2],q=Math.round(x),W=Math.round(v);let G,K,ee,J,le,ue,oe,ie;for(let de=q;de<=W;de++){if(dev?Se=1:g===v?Se=0:Se=(g-de)/(g-v),G=y-(y-b)*Se,K=M-(M-I)*Se,ee=P-(P-O)*Se,J=L-(L-$)*Se}let we;dev?we=1:we=(x-de)/(x-v),le=p-(p-b)*we,ue=k-(k-I)*we,oe=C-(C-O)*we,ie=T-(T-$)*we;const je=Math.round(Math.min(G,le)),xe=Math.round(Math.max(G,le));let fe=h*de+je*4;for(let Se=je;Se<=xe;Se++)we=(G-Se)/(G-le),we<0?we=0:we>1&&(we=1),u[fe++]=K-(K-ue)*we|0,u[fe++]=ee-(ee-oe)*we|0,u[fe++]=J-(J-ie)*we|0,u[fe++]=255}}function T2n(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=O?C=c:M=!0,I>=$?T=d:P=!0;const q=this.getSizeAndScale(C,this.ctx.canvas.width,v),W=this.getSizeAndScale(T,this.ctx.canvas.height,k),G=t.cachedCanvases.getCanvas("pattern",q.size,W.size),K=G.context,ee=o.createCanvasGraphics(K);if(ee.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(ee,a,l),K.translate(-q.scale*u,-W.scale*h),ee.transform(q.scale,0,0,W.scale,0,0),K.save(),this.clipBbox(ee,u,h,m,p),ee.baseTransform=wp(ee.ctx),ee.executeOperatorList(r),ee.endDrawing(),K.restore(),M||P){const J=G.canvas;M&&(C=c),P&&(T=d);const le=this.getSizeAndScale(C,this.ctx.canvas.width,v),ue=this.getSizeAndScale(T,this.ctx.canvas.height,k),oe=le.size,ie=ue.size,de=t.cachedCanvases.getCanvas("pattern-workaround",oe,ie),we=de.context,je=M?Math.floor(x/c):0,xe=P?Math.floor(y/d):0;for(let fe=0;fe<=je;fe++)for(let Se=0;Se<=xe;Se++)we.drawImage(J,oe*fe,ie*Se,oe,ie,0,0,oe,ie);return{canvas:de.canvas,scaleX:le.scale,scaleY:ue.scale,offsetX:u,offsetY:h}}return{canvas:G.canvas,scaleX:q.scale,scaleY:W.scale,offsetX:u,offsetY:h}}getSizeAndScale(t,n,r){const a=Math.max(s4e.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(wp(t.ctx),[n,r,a,i]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,n,r){const a=t.ctx,i=t.current;switch(n){case Ixt.COLORED:const l=this.ctx;a.fillStyle=l.fillStyle,a.strokeStyle=l.strokeStyle,i.fillColor=l.fillStyle,i.strokeColor=l.strokeStyle;break;case Ixt.UNCOLORED:const o=vo.makeHexColor(r[0],r[1],r[2]);a.fillStyle=o,a.strokeStyle=o,i.fillColor=o,i.strokeColor=o;break;default:throw new n2n(`Unsupported paint type: ${n}`)}}getPattern(t,n,r,a){let i=r;a!==Vv.SHADING&&(i=vo.transform(i,n.baseTransform),this.matrix&&(i=vo.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}};Ar(s4e,"MAX_PATTERN_SIZE",3e3);let Lze=s4e;function P2n({src:s,srcPos:t=0,dest:n,width:r,height:a,nonBlackColor:i=4294967295,inverseDecode:l=!1}){const o=c1.isLittleEndian?4278190080:255,[c,d]=l?[i,o]:[o,i],u=r>>3,h=r&7,m=s.length;n=new Uint32Array(n.buffer);let p=0;for(let x=0;x{s.save=s.__originalSave,s.restore=s.__originalRestore,s.rotate=s.__originalRotate,s.scale=s.__originalScale,s.translate=s.__originalTranslate,s.transform=s.__originalTransform,s.setTransform=s.__originalSetTransform,s.resetTransform=s.__originalResetTransform,s.clip=s.__originalClip,s.moveTo=s.__originalMoveTo,s.lineTo=s.__originalLineTo,s.bezierCurveTo=s.__originalBezierCurveTo,s.rect=s.__originalRect,s.closePath=s.__originalClosePath,s.beginPath=s.__originalBeginPath,delete s._removeMirroring},s.save=function(){t.save(),this.__originalSave()},s.restore=function(){t.restore(),this.__originalRestore()},s.translate=function(r,a){t.translate(r,a),this.__originalTranslate(r,a)},s.scale=function(r,a){t.scale(r,a),this.__originalScale(r,a)},s.transform=function(r,a,i,l,o,c){t.transform(r,a,i,l,o,c),this.__originalTransform(r,a,i,l,o,c)},s.setTransform=function(r,a,i,l,o,c){t.setTransform(r,a,i,l,o,c),this.__originalSetTransform(r,a,i,l,o,c)},s.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},s.rotate=function(r){t.rotate(r),this.__originalRotate(r)},s.clip=function(r){t.clip(r),this.__originalClip(r)},s.moveTo=function(n,r){t.moveTo(n,r),this.__originalMoveTo(n,r)},s.lineTo=function(n,r){t.lineTo(n,r),this.__originalLineTo(n,r)},s.bezierCurveTo=function(n,r,a,i,l,o){t.bezierCurveTo(n,r,a,i,l,o),this.__originalBezierCurveTo(n,r,a,i,l,o)},s.rect=function(n,r,a,i){t.rect(n,r,a,i),this.__originalRect(n,r,a,i)},s.closePath=function(){t.closePath(),this.__originalClosePath()},s.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class D2n{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 nre(s,t,n,r,a,i,l,o,c,d){const[u,h,m,p,x,y]=wp(s);if(h===0&&m===0){const v=l*u+x,k=Math.round(v),C=o*p+y,T=Math.round(C),M=(l+c)*u+x,P=Math.abs(Math.round(M)-k)||1,L=(o+d)*p+y,I=Math.abs(Math.round(L)-T)||1;return s.setTransform(Math.sign(u),0,0,Math.sign(p),k,T),s.drawImage(t,n,r,a,i,0,0,P,I),s.setTransform(u,h,m,p,x,y),[P,I]}if(u===0&&p===0){const v=o*m+x,k=Math.round(v),C=l*h+y,T=Math.round(C),M=(o+d)*m+x,P=Math.abs(Math.round(M)-k)||1,L=(l+c)*h+y,I=Math.abs(Math.round(L)-T)||1;return s.setTransform(0,Math.sign(h),Math.sign(m),0,k,T),s.drawImage(t,n,r,a,i,0,0,I,P),s.setTransform(u,h,m,p,x,y),[I,P]}s.drawImage(t,n,r,a,i,l,o,c,d);const g=Math.hypot(u,h),b=Math.hypot(m,p);return[g*c,b*d]}function O2n(s){const{width:t,height:n}=s;if(t>Fxt||n>Fxt)return null;const r=1e3,a=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),i=t+1;let l=new Uint8Array(i*(n+1)),o,c,d;const u=t+7&-8;let h=new Uint8Array(u*n),m=0;for(const b of s.data){let v=128;for(;v>0;)h[m++]=b&v?0:255,v>>=1}let p=0;for(m=0,h[m]!==0&&(l[0]=1,++p),c=1;c>2)+(h[m+1]?4:0)+(h[m-u+1]?8:0),a[b]&&(l[d+c]=a[b],++p),m++;if(h[m-u]!==h[m]&&(l[d+c]=h[m]?2:4,++p),p>r)return null}for(m=u*(n-1),d=o*i,h[m]!==0&&(l[d]=8,++p),c=1;cr)return null;const x=new Int32Array([0,i,-1,0,-i,0,0,0,1]),y=new Path2D;for(o=0;p&&o<=n;o++){let b=o*i;const v=b+t;for(;b>4,l[b]&=C>>2|C<<2),y.lineTo(b%i,b/i|0),l[b]||--p}while(k!==b);--o}return h=null,l=null,function(b){b.save(),b.scale(1/t,-1/n),b.translate(0,-n),b.fill(y),b.beginPath(),b.restore()}}class zxt{constructor(t,n){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=m7t,this.textMatrixScale=1,this.fontMatrix=rze,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=Iy.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]=vo.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=vo.applyTransform(n,t),a=vo.applyTransform(n.slice(2),t),i=vo.applyTransform([n[0],n[3]],t),l=vo.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){vo.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=vo.bezierBoundingBox(n,r,a,i,l,o,c,d,u);u||this.updateRectMinMax(t,h)}getPathBoundingBox(t=Vv.FILL,n=null){const r=[this.minX,this.minY,this.maxX,this.maxY];if(t===Vv.STROKE){n||pm("Stroke bounding box must include transform.");const a=vo.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=vo.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=Vv.FILL,n=null){return vo.intersect(this.clipBox,this.getPathBoundingBox(t,n))}}function Bxt(s,t){if(typeof ImageData<"u"&&t instanceof ImageData){s.putImageData(t,0,0);return}const n=t.height,r=t.width,a=n%eb,i=(n-a)/eb,l=a===0?i:i+1,o=s.createImageData(r,eb);let c=0,d;const u=t.data,h=o.data;let m,p,x,y;if(t.kind===Kje.GRAYSCALE_1BPP){const g=u.byteLength,b=new Uint32Array(h.buffer,0,h.byteLength>>2),v=b.length,k=r+7>>3,C=4294967295,T=c1.isLittleEndian?4278190080:255;for(m=0;mk?r:M*8-7,I=L&-8;let O=0,$=0;for(;P>=1}for(;d=i&&(x=a,y=r*x),d=0,p=y;p--;)h[d++]=u[c++],h[d++]=u[c++],h[d++]=u[c++],h[d++]=255;s.putImageData(o,0,m*eb)}else throw new Error(`bad image kind: ${t.kind}`)}function $xt(s,t){if(t.bitmap){s.drawImage(t.bitmap,0,0);return}const n=t.height,r=t.width,a=n%eb,i=(n-a)/eb,l=a===0?i:i+1,o=s.createImageData(r,eb);let c=0;const d=t.data,u=o.data;for(let h=0;hOxt&&typeof r=="function",u=d?Date.now()+I2n:0;let h=0;const m=this.commonObjs,p=this.objs;let x;for(;;){if(a!==void 0&&o===a.nextBreakPoint)return a.breakIt(o,r),o;if(x=l[o],x!==L2.dependency)this[x].apply(this,i[o]);else for(const y of i[o]){const g=y.startsWith("g_")?m:p;if(!g.has(y))return g.get(y,r),o}if(o++,o===c)return o;if(d&&++h>Oxt){if(Date.now()>u)return r(),o;h=0}}}endDrawing(){Kt(this,GE,Pze).call(this),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const n of t.values())typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement&&(n.width=n.height=0);t.clear()}this._cachedBitmapsMap.clear(),Kt(this,GE,Ize).call(this)}_scaleImage(t,n){const r=t.width??t.displayWidth,a=t.height??t.displayHeight;let i=Math.max(Math.hypot(n[0],n[1]),1),l=Math.max(Math.hypot(n[2],n[3]),1),o=r,c=a,d="prescale1",u,h;for(;i>2&&o>1||l>2&&c>1;){let m=o,p=c;i>2&&o>1&&(m=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),i/=o/m),l>2&&c>1&&(p=c>=16384?Math.floor(c/2)-1||1:Math.ceil(c)/2,l/=c/p),u=this.cachedCanvases.getCanvas(d,m,p),h=u.context,h.clearRect(0,0,m,p),h.drawImage(t,0,0,o,c,0,0,m,p),t=u.canvas,o=m,c=p,d=d==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:c}}_createMaskCanvas(t){const n=this.ctx,{width:r,height:a}=t,i=this.current.fillColor,l=this.current.patternFill,o=wp(n);let c,d,u,h;if((t.bitmap||t.data)&&t.count>1){const L=t.bitmap||t.data.buffer;d=JSON.stringify(l?o:[o.slice(0,4),i]),c=this._cachedBitmapsMap.get(L),c||(c=new Map,this._cachedBitmapsMap.set(L,c));const I=c.get(d);if(I&&!l){const O=Math.round(Math.min(o[0],o[2])+o[4]),$=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:I,offsetX:O,offsetY:$}}u=I}u||(h=this.cachedCanvases.getCanvas("maskCanvas",r,a),$xt(h.context,t));let m=vo.transform(o,[1/r,0,0,-1/a,0,0]);m=vo.transform(m,[1,0,0,1,0,-a]);const[p,x,y,g]=vo.getAxialAlignedBoundingBox([0,0,r,a],m),b=Math.round(y-p)||1,v=Math.round(g-x)||1,k=this.cachedCanvases.getCanvas("fillCanvas",b,v),C=k.context,T=p,M=x;C.translate(-T,-M),C.transform(...m),u||(u=this._scaleImage(h.canvas,n4(C)),u=u.img,c&&l&&c.set(d,u)),C.imageSmoothingEnabled=Uxt(wp(C),t.interpolate),nre(C,u,0,0,u.width,u.height,0,0,r,a),C.globalCompositeOperation="source-in";const P=vo.transform(n4(C),[1,0,0,1,-T,-M]);return C.fillStyle=l?i.getPattern(n,this,P,Vv.FILL):i,C.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(M)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=F2n[t]}setLineJoin(t){this.ctx.lineJoin=z2n[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(...wp(this.suspendedCtx)),QH(this.suspendedCtx,i),R2n(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(),QH(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const n=this.current.activeSMask,r=this.suspendedCtx;this.composeSMask(r,n,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,n,r,a){const i=a[0],l=a[1],o=a[2]-i,c=a[3]-l;o===0||c===0||(this.genericComposeSMask(n.context,r,o,c,n.subtype,n.backdrop,n.transferMap,i,l,n.offsetX,n.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(r.canvas,0,0),t.restore())}genericComposeSMask(t,n,r,a,i,l,o,c,d,u,h){let m=t.canvas,p=c-u,x=d-h;if(l){const g=vo.makeHexColor(...l);if(p<0||x<0||p+r>m.width||x+a>m.height){const b=this.cachedCanvases.getCanvas("maskExtension",r,a),v=b.context;v.drawImage(m,-p,-x),v.globalCompositeOperation="destination-atop",v.fillStyle=g,v.fillRect(0,0,r,a),v.globalCompositeOperation="source-over",m=b.canvas,p=x=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const b=new Path2D;b.rect(p,x,r,a),t.clip(b),t.globalCompositeOperation="destination-atop",t.fillStyle=g,t.fillRect(p,x,r,a),t.restore()}}n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0),i==="Alpha"&&o?n.filter=this.filterFactory.addAlphaFilter(o):i==="Luminosity"&&(n.filter=this.filterFactory.addLuminosityFilter(o));const y=new Path2D;y.rect(c,d,r,a),n.clip(y),n.globalCompositeOperation="destination-in",n.drawImage(m,p,x,r,a,c,d,r,a),n.restore()}save(){this.inSMaskMode?(QH(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(),QH(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=wp(a),h=u[0]===0&&u[3]===0||u[1]===0&&u[2]===0,m=h?r.slice(0):null;for(let p=0,x=0,y=t.length;pDxt&&(d=Dxt),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&Iy.FILL_STROKE_MASK,h=!!(c&Iy.ADD_TO_PATH_FLAG),m=l.patternFill&&!o.missingFile;let p;(o.disableFontFace||h||m)&&(p=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||m?(i.save(),i.translate(n,r),i.beginPath(),p(i,d),a&&i.setTransform(...a),(u===Iy.FILL||u===Iy.FILL_STROKE)&&i.fill(),(u===Iy.STROKE||u===Iy.FILL_STROKE)&&i.stroke(),i.restore()):((u===Iy.FILL||u===Iy.FILL_STROKE)&&i.fillText(t,n,r),(u===Iy.STROKE||u===Iy.FILL_STROKE)&&i.strokeText(t,n,r)),h&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:wp(i),x:n,y:r,fontSize:d,addToPath:p})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const n=t.getImageData(0,0,10,10).data;let r=!1;for(let a=3;a0&&n[a]<255){r=!0;break}return md(this,"isFontSubpixelAAEnabled",r)}showText(t){const n=this.current,r=n.font;if(r.isType3Font)return this.showType3Text(t);const a=n.fontSize;if(a===0)return;const i=this.ctx,l=n.fontSizeScale,o=n.charSpacing,c=n.wordSpacing,d=n.fontDirection,u=n.textHScale*d,h=t.length,m=r.vertical,p=m?1:-1,x=r.defaultVMetrics,y=a*n.fontMatrix[0],g=n.textRenderingMode===Iy.FILL&&!r.disableFontFace&&!n.patternFill;i.save(),i.transform(...n.textMatrix),i.translate(n.x,n.y+n.textRise),d>0?i.scale(u,-1):i.scale(u,1);let b;if(n.patternFill){i.save();const M=n.fillColor.getPattern(i,this,n4(i),Vv.FILL);b=wp(i),i.restore(),i.fillStyle=M}let v=n.lineWidth;const k=n.textMatrixScale;if(k===0||v===0){const M=n.textRenderingMode&Iy.FILL_STROKE_MASK;(M===Iy.STROKE||M===Iy.FILL_STROKE)&&(v=this.getSinglePixelWidth())}else v/=k;if(l!==1&&(i.scale(l,l),v/=l),i.lineWidth=v,r.isInvalidPDFjsFont){const M=[];let P=0;for(const L of t)M.push(L.unicode),P+=L.width;i.fillText(M.join(""),0,0),n.x+=P*y*u,i.restore(),this.compose();return}let C=0,T;for(T=0;T0){const K=i.measureText(I).width*1e3/a*l;if(Wnew lZe(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};n=new Lze(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=vo.makeHexColor(t,n,r)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,n,r){this.ctx.fillStyle=this.current.fillColor=vo.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=L2n(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,n4(n),Vv.SHADING);const a=n4(n);if(a){const{width:i,height:l}=n.canvas,[o,c,d,u]=vo.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(){pm("Should not call beginInlineImage")}beginImageData(){pm("Should not call beginImageData")}paintFormXObjectBegin(t,n){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=wp(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(wp(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||uTe("TODO: Support non-isolated groups."),t.knockout&&Sc("Knockout groups not supported.");const r=wp(n);if(t.matrix&&n.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let a=vo.getAxialAlignedBoundingBox(t.bbox,wp(n));const i=[0,0,n.canvas.width,n.canvas.height];a=vo.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()),QH(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=wp(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...a);const i=vo.getAxialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],a);this.ctx.drawImage(n.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,n,r,a,i){if(Kt(this,GE,Pze).call(this),rre(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]=vo.singularValueDecompose2dScale(wp(this.ctx)),{viewportScale:u}=this,h=Math.ceil(l*this.outputScaleX*u),m=Math.ceil(o*this.outputScaleY*u);this.annotationCanvas=this.canvasFactory.create(h,m);const{canvas:p,context:x}=this.annotationCanvas;this.annotationCanvasMap.set(t,p),this.annotationCanvas.savedCtx=this.ctx,this.ctx=x,this.ctx.save(),this.ctx.setTransform(c,0,0,-d,0,o*d),rre(this.ctx)}else rre(this.ctx),this.endPath(),this.ctx.rect(n[0],n[1],l,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new zxt(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...r),this.transform(...a)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),Kt(this,GE,Ize).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=O2n(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=wp(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}};GE=new WeakSet,Pze=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)},Ize=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 Bz=lZe;for(const s in L2)Bz.prototype[s]!==void 0&&(Bz.prototype[L2[s]]=Bz.prototype[s]);var eQ,tQ;class s3{static get workerPort(){return me(this,eQ)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");Ot(this,eQ,t)}static get workerSrc(){return me(this,tQ)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");Ot(this,tQ,t)}}eQ=new WeakMap,tQ=new WeakMap,rs(s3,eQ,null),rs(s3,tQ,"");const are={UNKNOWN:0,DATA:1,ERROR:2},mx={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function l_(s){switch(s instanceof Error||typeof s=="object"&&s!==null||pm('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new UO(s.message);case"MissingPDFException":return new $O(s.message);case"PasswordException":return new aze(s.message,s.code);case"UnexpectedResponseException":return new hTe(s.message,s.status);case"UnknownErrorException":return new ize(s.message,s.details);default:return new ize(s.message,s.toString())}}var _B,Rj,X7t,Q7t,J7t,s2e;class nW{constructor(t,n,r){rs(this,Rj);rs(this,_B,new AbortController);this.sourceName=t,this.targetName=n,this.comObj=r,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),r.addEventListener("message",Kt(this,Rj,X7t).bind(this),{signal:me(this,_B).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:mx.PULL,streamId:i,desiredSize:d.desiredSize}),u.promise},cancel:d=>{ig(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:mx.CANCEL,streamId:i,reason:l_(d)}),u.promise}},r)}destroy(){var t;(t=me(this,_B))==null||t.abort(),Ot(this,_B,null)}}_B=new WeakMap,Rj=new WeakSet,X7t=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){Kt(this,Rj,J7t).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===are.DATA)a.resolve(t.data);else if(t.callback===are.ERROR)a.reject(l_(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:are.DATA,callbackId:t.callbackId,data:l})},function(l){i.postMessage({sourceName:r,targetName:a,callback:are.ERROR,callbackId:t.callbackId,reason:l_(l)})});return}if(t.streamId){Kt(this,Rj,Q7t).call(this,t);return}n(t.data)},Q7t=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:mx.ENQUEUE,streamId:n,chunk:d},h)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:mx.CLOSE,streamId:n}),delete l.streamSinks[n])},error(d){ig(d instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:mx.ERROR,streamId:n,reason:l_(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:mx.START_COMPLETE,streamId:n,success:!0})},function(d){i.postMessage({sourceName:r,targetName:a,stream:mx.START_COMPLETE,streamId:n,reason:l_(d)})})},J7t=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 mx.START_COMPLETE:t.success?l.startCall.resolve():l.startCall.reject(l_(t.reason));break;case mx.PULL_COMPLETE:t.success?l.pullCall.resolve():l.pullCall.reject(l_(t.reason));break;case mx.PULL:if(!o){i.postMessage({sourceName:r,targetName:a,stream:mx.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:mx.PULL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:mx.PULL_COMPLETE,streamId:n,reason:l_(c)})});break;case mx.ENQUEUE:if(ig(l,"enqueue should have stream controller"),l.isClosed)break;l.controller.enqueue(t.chunk);break;case mx.CLOSE:if(ig(l,"close should have stream controller"),l.isClosed)break;l.isClosed=!0,l.controller.close(),Kt(this,Rj,s2e).call(this,l,n);break;case mx.ERROR:ig(l,"error should have stream controller"),l.controller.error(l_(t.reason)),Kt(this,Rj,s2e).call(this,l,n);break;case mx.CANCEL_COMPLETE:t.success?l.cancelCall.resolve():l.cancelCall.reject(l_(t.reason)),Kt(this,Rj,s2e).call(this,l,n);break;case mx.CANCEL:if(!o)break;new Promise(function(c){var d;c((d=o.onCancel)==null?void 0:d.call(o,l_(t.reason)))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:mx.CANCEL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:mx.CANCEL_COMPLETE,streamId:n,reason:l_(c)})}),o.sinkCapability.reject(l_(t.reason)),o.isCancelled=!0,delete this.streamSinks[n];break;default:throw new Error("Unexpected stream case")}},s2e=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 Z8,sQ;class $2n{constructor({parsedData:t,rawData:n}){rs(this,Z8);rs(this,sQ);Ot(this,Z8,t),Ot(this,sQ,n)}getRaw(){return me(this,sQ)}get(t){return me(this,Z8).get(t)??null}getAll(){return OKe(me(this,Z8))}has(t){return me(this,Z8).has(t)}}Z8=new WeakMap,sQ=new WeakMap;const U7=Symbol("INTERNAL");var nQ,rQ,aQ,wB;class U2n{constructor(t,{name:n,intent:r,usage:a,rbGroups:i}){rs(this,nQ,!1);rs(this,rQ,!1);rs(this,aQ,!1);rs(this,wB,!0);Ot(this,nQ,!!(t&S_.DISPLAY)),Ot(this,rQ,!!(t&S_.PRINT)),this.name=n,this.intent=r,this.usage=a,this.rbGroups=i}get visible(){if(me(this,aQ))return me(this,wB);if(!me(this,wB))return!1;const{print:t,view:n}=this.usage;return me(this,nQ)?(n==null?void 0:n.viewState)!=="OFF":me(this,rQ)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,n,r=!1){t!==U7&&pm("Internal method `_setVisible` called."),Ot(this,aQ,r),Ot(this,wB,n)}}nQ=new WeakMap,rQ=new WeakMap,aQ=new WeakMap,wB=new WeakMap;var tT,zu,jB,NB,iQ,Rze;class q2n{constructor(t,n=S_.DISPLAY){rs(this,iQ);rs(this,tT,null);rs(this,zu,new Map);rs(this,jB,null);rs(this,NB,null);if(this.renderingIntent=n,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,Ot(this,NB,t.order);for(const r of t.groups)me(this,zu).set(r.id,new U2n(n,r));if(t.baseState==="OFF")for(const r of me(this,zu).values())r._setVisible(U7,!1);for(const r of t.on)me(this,zu).get(r)._setVisible(U7,!0);for(const r of t.off)me(this,zu).get(r)._setVisible(U7,!1);Ot(this,jB,this.getHash())}}isVisible(t){if(me(this,zu).size===0)return!0;if(!t)return uTe("Optional content group not defined."),!0;if(t.type==="OCG")return me(this,zu).has(t.id)?me(this,zu).get(t.id).visible:(Sc(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return Kt(this,iQ,Rze).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const n of t.ids){if(!me(this,zu).has(n))return Sc(`Optional content group not found: ${n}`),!0;if(me(this,zu).get(n).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const n of t.ids){if(!me(this,zu).has(n))return Sc(`Optional content group not found: ${n}`),!0;if(!me(this,zu).get(n).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const n of t.ids){if(!me(this,zu).has(n))return Sc(`Optional content group not found: ${n}`),!0;if(!me(this,zu).get(n).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const n of t.ids){if(!me(this,zu).has(n))return Sc(`Optional content group not found: ${n}`),!0;if(me(this,zu).get(n).visible)return!1}return!0}return Sc(`Unknown optional content policy ${t.policy}.`),!0}return Sc(`Unknown group type ${t.type}.`),!0}setVisibility(t,n=!0,r=!0){var i;const a=me(this,zu).get(t);if(!a){Sc(`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=me(this,zu).get(o))==null||i._setVisible(U7,!1,!0));a._setVisible(U7,!!n,!0),Ot(this,tT,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=me(this,zu).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}}Ot(this,tT,null)}get hasInitialVisibility(){return me(this,jB)===null||this.getHash()===me(this,jB)}getOrder(){return me(this,zu).size?me(this,NB)?me(this,NB).slice():[...me(this,zu).keys()]:null}getGroups(){return me(this,zu).size>0?OKe(me(this,zu)):null}getGroup(t){return me(this,zu).get(t)||null}getHash(){if(me(this,tT)!==null)return me(this,tT);const t=new B7t;for(const[n,r]of me(this,zu))t.update(`${n}:${r.visible}`);return Ot(this,tT,t.hexdigest())}}tT=new WeakMap,zu=new WeakMap,jB=new WeakMap,NB=new WeakMap,iQ=new WeakSet,Rze=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)});ig(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(){ig(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new H2n(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=new G2n(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 H2n{constructor(t,n,r=!1,a=null){this._stream=t,this._done=r||!1,this._filename=BKe(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 G2n{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 W2n(s){let t=!0,n=r("filename\\*","i").exec(s);if(n){n=n[1];let u=o(n);return u=unescape(u),u=c(u),u=d(u),i(u)}if(n=l(s),n){const u=d(n);return i(u)}if(n=r("filename","i").exec(s),n){n=n[1];let u=o(n);return u=d(u),i(u)}function r(u,h){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',h)}function a(u,h){if(u){if(!/^[\x00-\xFF]+$/.test(h))return h;try{const m=new TextDecoder(u,{fatal:!0}),p=mTe(h);h=m.decode(p),t=!1}catch{}}return h}function i(u){return t&&/[\x80-\xff]/.test(u)&&(u=a("utf-8",u),t&&(u=a("iso-8859-1",u))),u}function l(u){const h=[];let m;const p=r("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(m=p.exec(u))!==null;){let[,y,g,b]=m;if(y=parseInt(y,10),y in h){if(y===0)break;continue}h[y]=[g,b]}const x=[];for(let y=0;y{if(!e9t(i.status))throw xTe(i.status,a);this._reader=i.body.getReader(),this._headersCapability.resolve();const l=i.headers,{allowRangeRequests:o,suggestedLength:c}=GKe({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=c||this._contentLength,this._filename=WKe(l),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new UO("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:s9t(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class Y2n{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,t9t(i,this._withCredentials,this._abortController)).then(o=>{if(!e9t(o.status))throw xTe(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:s9t(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}const $Ie=200,UIe=206;function Z2n(s){const t=s.response;return typeof t!="string"?t:mTe(t).buffer}class X2n{constructor({url:t,httpHeaders:n,withCredentials:r}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=HKe(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=UIe):a.expectedStatus=$Ie,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||$Ie;if(!(i===$Ie&&r.expectedStatus===UIe)&&i!==r.expectedStatus){(d=r.onError)==null||d.call(r,a.status);return}const o=Z2n(a);if(i===UIe){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 Q2n{constructor(t){this._source=t,this._manager=new X2n(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 ig(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new J2n(this._manager,this._source),this._fullRequestReader}getRangeReader(t,n){const r=new eNn(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 J2n{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}=GKe({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});a&&(this._isRangeSupported=!0),this._contentLength=i||this._contentLength,this._filename=WKe(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=xTe(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 eNn{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=xTe(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 tNn=/^[a-z][a-z0-9\-+.]+:/i;function sNn(s){if(tNn.test(s))return new URL(s);const t=$E.get("url");return new URL(t.pathToFileURL(s))}function n9t(s,t,n){return s.protocol==="http:"?$E.get("http").request(s,{headers:t},n):$E.get("https").request(s,{headers:t},n)}class nNn{constructor(t){this.source=t,this.url=sNn(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=HKe(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 ig(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new iNn(this):new rNn(this),this._fullRequestReader}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=this.isFsUrl?new oNn(this,t,n):new aNn(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 r9t{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 UO("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class a9t{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 rNn extends r9t{constructor(t){super(t);const n=Object.fromEntries(t.headers),r=a=>{if(a.statusCode===404){const c=new $O(`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}=GKe({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=o||this._contentLength,this._filename=WKe(i)};this._request=n9t(this._url,n,r),this._request.on("error",a=>{this._storedError=a,this._headersCapability.reject(a)}),this._request.end()}}class aNn extends a9t{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 $O(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(l)};this._request=n9t(this._url,a,i),this._request.on("error",l=>{this._storedError=l}),this._request.end()}}class iNn extends r9t{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 $O(`Missing PDF "${this._url}".`)),this._storedError=r,this._headersCapability.reject(r)})}}class oNn extends a9t{constructor(t,n,r){super(t);const a=$E.get("fs");this._setReadableStream(a.createReadStream(this._url,{start:n,end:r-1}))}}const lNn=1e5,U1=30,cNn=.8;var s1t,sT,Z1,oQ,lQ,X8,D4,cQ,dQ,Q8,kB,SB,nT,CB,uQ,AB,J8,hQ,mQ,eR,tR,pQ,rT,TB,K3,i9t,o9t,Dze,ew,n2e,Oze,l9t,c9t;const Wx=class Wx{constructor({textContentSource:t,container:n,viewport:r}){rs(this,K3);rs(this,sT,Promise.withResolvers());rs(this,Z1,null);rs(this,oQ,!1);rs(this,lQ,!!((s1t=globalThis.FontInspector)!=null&&s1t.enabled));rs(this,X8,null);rs(this,D4,null);rs(this,cQ,0);rs(this,dQ,0);rs(this,Q8,null);rs(this,kB,null);rs(this,SB,0);rs(this,nT,0);rs(this,CB,Object.create(null));rs(this,uQ,[]);rs(this,AB,null);rs(this,J8,[]);rs(this,hQ,new WeakMap);rs(this,mQ,null);var c;if(t instanceof ReadableStream)Ot(this,AB,t);else if(typeof t=="object")Ot(this,AB,new ReadableStream({start(d){d.enqueue(t),d.close()}}));else throw new Error('No "textContentSource" parameter specified.');Ot(this,Z1,Ot(this,kB,n)),Ot(this,nT,r.scale*(globalThis.devicePixelRatio||1)),Ot(this,SB,r.rotation),Ot(this,D4,{div:null,properties:null,ctx:null});const{pageWidth:a,pageHeight:i,pageX:l,pageY:o}=r.rawDims;Ot(this,mQ,[1,0,0,-1,-l,o+i]),Ot(this,dQ,a),Ot(this,cQ,i),Kt(c=Wx,ew,l9t).call(c),nO(n,r),me(this,sT).promise.finally(()=>{me(Wx,TB).delete(this),Ot(this,D4,null),Ot(this,CB,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:n}=c1.platform;return md(this,"fontFamilyMap",new Map([["sans-serif",`${t&&n?"Calibri, ":""}sans-serif`],["monospace",`${t&&n?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{me(this,Q8).read().then(({value:n,done:r})=>{if(r){me(this,sT).resolve();return}me(this,X8)??Ot(this,X8,n.lang),Object.assign(me(this,CB),n.styles),Kt(this,K3,i9t).call(this,n.items),t()},me(this,sT).reject)};return Ot(this,Q8,me(this,AB).getReader()),me(Wx,TB).add(this),t(),me(this,sT).promise}update({viewport:t,onBefore:n=null}){var i;const r=t.scale*(globalThis.devicePixelRatio||1),a=t.rotation;if(a!==me(this,SB)&&(n==null||n(),Ot(this,SB,a),nO(me(this,kB),{rotation:a})),r!==me(this,nT)){n==null||n(),Ot(this,nT,r);const l={div:null,properties:null,ctx:Kt(i=Wx,ew,n2e).call(i,me(this,X8))};for(const o of me(this,J8))l.properties=me(this,hQ).get(o),l.div=o,Kt(this,K3,Dze).call(this,l)}}cancel(){var n;const t=new UO("TextLayer task cancelled.");(n=me(this,Q8))==null||n.cancel(t).catch(()=>{}),Ot(this,Q8,null),me(this,sT).reject(t)}get textDivs(){return me(this,J8)}get textContentItemsStr(){return me(this,uQ)}static cleanup(){if(!(me(this,TB).size>0)){me(this,eR).clear();for(const{canvas:t}of me(this,tR).values())t.remove();me(this,tR).clear()}}};sT=new WeakMap,Z1=new WeakMap,oQ=new WeakMap,lQ=new WeakMap,X8=new WeakMap,D4=new WeakMap,cQ=new WeakMap,dQ=new WeakMap,Q8=new WeakMap,kB=new WeakMap,SB=new WeakMap,nT=new WeakMap,CB=new WeakMap,uQ=new WeakMap,AB=new WeakMap,J8=new WeakMap,hQ=new WeakMap,mQ=new WeakMap,eR=new WeakMap,tR=new WeakMap,pQ=new WeakMap,rT=new WeakMap,TB=new WeakMap,K3=new WeakSet,i9t=function(t){var a,i;if(me(this,oQ))return;(i=me(this,D4)).ctx??(i.ctx=Kt(a=Wx,ew,n2e).call(a,me(this,X8)));const n=me(this,J8),r=me(this,uQ);for(const l of t){if(n.length>lNn){Sc("Ignoring additional textDivs for performance reasons."),Ot(this,oQ,!0);return}if(l.str===void 0){if(l.type==="beginMarkedContentProps"||l.type==="beginMarkedContent"){const o=me(this,Z1);Ot(this,Z1,document.createElement("span")),me(this,Z1).classList.add("markedContent"),l.id!==null&&me(this,Z1).setAttribute("id",`${l.id}`),o.append(me(this,Z1))}else l.type==="endMarkedContent"&&Ot(this,Z1,me(this,Z1).parentNode);continue}r.push(l.str),Kt(this,K3,o9t).call(this,l)}},o9t=function(t){var y;const n=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};me(this,J8).push(n);const a=vo.transform(me(this,mQ),t.transform);let i=Math.atan2(a[1],a[0]);const l=me(this,CB)[t.fontName];l.vertical&&(i+=Math.PI/2);let o=me(this,lQ)&&l.fontSubstitution||l.fontFamily;o=Wx.fontFamilyMap.get(o)||o;const c=Math.hypot(a[2],a[3]),d=c*Kt(y=Wx,ew,c9t).call(y,o,me(this,X8));let u,h;i===0?(u=a[4],h=a[5]-d):(u=a[4]+d*Math.sin(i),h=a[5]-d*Math.cos(i));const m="calc(var(--scale-factor)*",p=n.style;me(this,Z1)===me(this,kB)?(p.left=`${(100*u/me(this,dQ)).toFixed(2)}%`,p.top=`${(100*h/me(this,cQ)).toFixed(2)}%`):(p.left=`${m}${u.toFixed(2)}px)`,p.top=`${m}${h.toFixed(2)}px)`),p.fontSize=`${m}${(me(Wx,rT)*c).toFixed(2)}px)`,p.fontFamily=o,r.fontSize=c,n.setAttribute("role","presentation"),n.textContent=t.str,n.dir=t.dir,me(this,lQ)&&(n.dataset.fontName=l.fontSubstitutionLoadedName||t.fontName),i!==0&&(r.angle=i*(180/Math.PI));let x=!1;if(t.str.length>1)x=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const g=Math.abs(t.transform[0]),b=Math.abs(t.transform[3]);g!==b&&Math.max(g,b)/Math.min(g,b)>1.5&&(x=!0)}if(x&&(r.canvasWidth=l.vertical?t.height:t.width),me(this,hQ).set(n,r),me(this,D4).div=n,me(this,D4).properties=r,Kt(this,K3,Dze).call(this,me(this,D4)),r.hasText&&me(this,Z1).append(n),r.hasEOL){const g=document.createElement("br");g.setAttribute("role","presentation"),me(this,Z1).append(g)}},Dze=function(t){var o;const{div:n,properties:r,ctx:a}=t,{style:i}=n;let l="";if(me(Wx,rT)>1&&(l=`scale(${1/me(Wx,rT)})`),r.canvasWidth!==0&&r.hasText){const{fontFamily:c}=i,{canvasWidth:d,fontSize:u}=r;Kt(o=Wx,ew,Oze).call(o,a,u*me(this,nT),c);const{width:h}=a.measureText(n.textContent);h>0&&(l=`scaleX(${d*me(this,nT)/h}) ${l}`)}r.angle!==0&&(l=`rotate(${r.angle}deg) ${l}`),l.length>0&&(i.transform=l)},ew=new WeakSet,n2e=function(t=null){let n=me(this,tR).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}),me(this,tR).set(t,n),me(this,pQ).set(n,{size:0,family:""})}return n},Oze=function(t,n,r){const a=me(this,pQ).get(t);n===a.size&&r===a.family||(t.font=`${n}px ${r}`,a.size=n,a.family=r)},l9t=function(){if(me(this,rT)!==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),Ot(this,rT,t.getBoundingClientRect().height),t.remove()},c9t=function(t,n){const r=me(this,eR).get(t);if(r)return r;const a=Kt(this,ew,n2e).call(this,n);a.canvas.width=a.canvas.height=U1,Kt(this,ew,Oze).call(this,a,U1,t);const i=a.measureText("");let l=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(l){const u=l/(l+o);return me(this,eR).set(t,u),a.canvas.width=a.canvas.height=0,u}a.strokeStyle="red",a.clearRect(0,0,U1,U1),a.strokeText("g",0,0);let c=a.getImageData(0,0,U1,U1).data;o=0;for(let u=c.length-1-3;u>=0;u-=4)if(c[u]>0){o=Math.ceil(u/4/U1);break}a.clearRect(0,0,U1,U1),a.strokeText("A",0,U1),c=a.getImageData(0,0,U1,U1).data,l=0;for(let u=0,h=c.length;u0){l=U1-Math.floor(u/4/U1);break}a.canvas.width=a.canvas.height=0;const d=l?l/(l+o):cNn;return me(this,eR).set(t,d),d},rs(Wx,ew),rs(Wx,eR,new Map),rs(Wx,tR,new Map),rs(Wx,pQ,new WeakMap),rs(Wx,rT,null),rs(Wx,TB,new Set);let vX=Wx;class bX{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(bX.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 dNn=65536,uNn=100,hNn=5e3,mNn=Xy?k2n:w2n,pNn=Xy?S2n:H7t,fNn=Xy?N2n:j2n,xNn=Xy?C2n:Y7t;function gNn(s={}){typeof s=="string"||s instanceof URL?s={url:s}:(s instanceof ArrayBuffer||ArrayBuffer.isView(s))&&(s={data:s});const t=new Fze,{docId:n}=t,r=s.url?yNn(s.url):null,a=s.data?vNn(s.data):null,i=s.httpHeaders||null,l=s.withCredentials===!0,o=s.password??null,c=s.range instanceof d9t?s.range:null,d=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:dNn;let u=s.worker instanceof $z?s.worker:null;const h=s.verbosity,m=typeof s.docBaseUrl=="string"&&!fTe(s.docBaseUrl)?s.docBaseUrl:null,p=typeof s.cMapUrl=="string"?s.cMapUrl:null,x=s.cMapPacked!==!1,y=s.CMapReaderFactory||pNn,g=typeof s.standardFontDataUrl=="string"?s.standardFontDataUrl:null,b=s.StandardFontDataFactory||xNn,v=s.stopAtErrors!==!0,k=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,C=s.isEvalSupported!==!1,T=typeof s.isOffscreenCanvasSupported=="boolean"?s.isOffscreenCanvasSupported:!Xy,M=typeof s.isChrome=="boolean"?s.isChrome:!c1.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),P=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,L=typeof s.disableFontFace=="boolean"?s.disableFontFace:Xy,I=s.fontExtraProperties===!0,O=s.enableXfa===!0,$=s.ownerDocument||globalThis.document,q=s.disableRange===!0,W=s.disableStream===!0,G=s.disableAutoFetch===!0,K=s.pdfBug===!0,ee=s.CanvasFactory||mNn,J=s.FilterFactory||fNn,le=s.enableHWA===!0,ue=c?c.length:s.length??NaN,oe=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!Xy&&!L,ie=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:y===H7t&&b===Y7t&&p&&g&&ZG(p,document.baseURI)&&ZG(g,document.baseURI);s.canvasFactory&&Lxt("`canvasFactory`-instance option, please use `CanvasFactory` instead."),s.filterFactory&&Lxt("`filterFactory`-instance option, please use `FilterFactory` instead.");const de=null;Jjn(h);const we={canvasFactory:new ee({ownerDocument:$,enableHWA:le}),filterFactory:new J({docId:n,ownerDocument:$}),cMapReaderFactory:ie?null:new y({baseUrl:p,isCompressed:x}),standardFontDataFactory:ie?null:new b({baseUrl:g})};if(!u){const fe={verbosity:h,port:s3.workerPort};u=fe.port?$z.fromPort(fe):new $z(fe),t._worker=u}const je={docId:n,apiVersion:"4.8.69",data:a,password:o,disableAutoFetch:G,rangeChunkSize:d,length:ue,docBaseUrl:m,enableXfa:O,evaluatorOptions:{maxImageSize:k,disableFontFace:L,ignoreErrors:v,isEvalSupported:C,isOffscreenCanvasSupported:T,isChrome:M,canvasMaxAreaInBytes:P,fontExtraProperties:I,useSystemFonts:oe,cMapUrl:ie?p:null,standardFontDataUrl:ie?g:null}},xe={disableFontFace:L,fontExtraProperties:I,ownerDocument:$,pdfBug:K,styleElement:de,loadingParams:{disableAutoFetch:G,enableXfa:O}};return u.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const fe=u.messageHandler.sendWithPromise("GetDocRequest",je,a?[a.buffer]:null);let Se;if(c)Se=new V2n(c,{disableRange:q,disableStream:W});else if(!a){if(!r)throw new Error("getDocument - no `url` parameter provided.");let Ee;Xy?Ee=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&ZG(r)?Vxt:nNn:Ee=ZG(r)?Vxt:Q2n,Se=new Ee({url:r,length:ue,httpHeaders:i,withCredentials:l,rangeChunkSize:d,disableRange:q,disableStream:W})}return fe.then(Ee=>{if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const Le=new nW(n,Ee,u.port),De=new jNn(Le,t,Se,xe,we);t._transport=De,Le.send("Ready",null)})}).catch(t._capability.reject),t}function yNn(s){if(s instanceof URL)return s.href;try{return new URL(s,window.location).href}catch{if(Xy&&typeof s=="string")return s}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function vNn(s){if(Xy&&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 mTe(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 Hxt(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 n4e;const r4e=class r4e{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Ig(r4e,n4e)._++}`,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)}};n4e=new WeakMap,rs(r4e,n4e,0);let Fze=r4e;class d9t{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){pm("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class bNn{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 md(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 aT,O4,pj,q7,r2e;class _Nn{constructor(t,n,r,a=!1){rs(this,pj);rs(this,aT,null);rs(this,O4,!1);this._pageIndex=t,this._pageInfo=n,this._transport=r,this._stats=a?new Mxt:null,this._pdfBug=a,this.commonObjs=r.commonObjs,this.objs=new u9t,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 pee({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 md(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=PA.ENABLE,transform:i=null,background:l=null,optionalContentConfigPromise:o=null,annotationCanvasMap:c=null,pageColors:d=null,printAnnotationStorage:u=null,isEditing:h=!1}){var C,T;(C=this._stats)==null||C.time("Overall");const m=this._transport.getRenderingIntent(r,a,u,h),{renderingIntent:p,cacheKey:x}=m;Ot(this,O4,!1),Kt(this,pj,r2e).call(this),o||(o=this._transport.getOptionalContentConfig(p));let y=this._intentStates.get(x);y||(y=Object.create(null),this._intentStates.set(x,y)),y.streamReaderCancelTimeout&&(clearTimeout(y.streamReaderCancelTimeout),y.streamReaderCancelTimeout=null);const g=!!(p&S_.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 b=M=>{var P;y.renderTasks.delete(v),(this._maybeCleanupAfterRender||g)&&Ot(this,O4,!0),Kt(this,pj,q7).call(this,!g),M?(v.capability.reject(M),this._abortOperatorList({intentState:y,reason:M instanceof Error?M:new Error(M)})):v.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(P=globalThis.Stats)!=null&&P.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},v=new Bze({callback:b,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:!g,pdfBug:this._pdfBug,pageColors:d});(y.renderTasks||(y.renderTasks=new Set)).add(v);const k=v.task;return Promise.all([y.displayReadyCapability.promise,o]).then(([M,P])=>{var L;if(this.destroyed){b();return}if((L=this._stats)==null||L.time("Rendering"),!(P.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");v.initializeGraphics({transparency:M,optionalContentConfig:P}),v.operatorListChanged()}).catch(b),k}getOperatorList({intent:t="display",annotationMode:n=PA.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=>bX.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(),Ot(this,O4,!1),Kt(this,pj,r2e).call(this),Promise.all(t)}cleanup(t=!1){Ot(this,O4,!0);const n=Kt(this,pj,q7).call(this,!1);return t&&n&&this._stats&&(this._stats=new Mxt),n}_startRenderPage(t,n){var a,i;const r=this._intentStates.get(n);r&&((a=this._stats)==null||a.timeEnd("Page Request"),(i=r.displayReadyCapability)==null||i.resolve(t))}_renderPageChunk(t,n){for(let r=0,a=t.length;r{c.read().then(({value:h,done:m})=>{if(m){d.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(h,d),u())},h=>{if(d.streamReader=null,!this._transport.destroyed){if(d.operatorList){d.operatorList.lastChunk=!0;for(const m of d.renderTasks)m.operatorListChanged();Kt(this,pj,q7).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 zKe){let a=uNn;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 UO(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}}aT=new WeakMap,O4=new WeakMap,pj=new WeakSet,q7=function(t=!1){if(Kt(this,pj,r2e).call(this),!me(this,O4)||this.destroyed)return!1;if(t)return Ot(this,aT,setTimeout(()=>{Ot(this,aT,null),Kt(this,pj,q7).call(this,!1)},hNn)),!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(),Ot(this,O4,!1),!0},r2e=function(){me(this,aT)&&(clearTimeout(me(this,aT)),Ot(this,aT,null))};var F4,a4e;class wNn{constructor(){rs(this,F4,new Map);rs(this,a4e,Promise.resolve())}postMessage(t,n){const r={data:structuredClone(t,n?{transfer:n}:null)};me(this,a4e).then(()=>{for(const[a]of me(this,F4))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){Sc("LoopbackPort - cannot use an `aborted` signal.");return}const l=()=>this.removeEventListener(t,n);a=()=>i.removeEventListener("abort",l),i.addEventListener("abort",l)}me(this,F4).set(n,a)}removeEventListener(t,n){const r=me(this,F4).get(n);r==null||r(),me(this,F4).delete(n)}terminate(){for(const[,t]of me(this,F4))t==null||t();me(this,F4).clear()}}F4=new WeakMap,a4e=new WeakMap;var i4e,sR,nR,EB,a2e,MB,i2e;const Fm=class Fm{constructor({name:t=null,port:n=null,verbosity:r=e2n()}={}){rs(this,EB);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=me(Fm,nR))!=null&&a.has(n))throw new Error("Cannot use more than one PDFWorker per port.");(me(Fm,nR)||Ot(Fm,nR,new WeakMap)).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return Xy?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 nW("main","worker",t),this._messageHandler.on("ready",function(){}),Kt(this,EB,a2e).call(this)}_initialize(){if(me(Fm,sR)||me(Fm,MB,i2e)){this._setupFakeWorker();return}let{workerSrc:t}=Fm;try{Fm._isSameOrigin(window.location.href,t)||(t=Fm._createCDNWrapper(new URL(t,window.location).href));const n=new Worker(t,{type:"module"}),r=new nW("main","worker",n),a=()=>{i.abort(),r.destroy(),n.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},i=new AbortController;n.addEventListener("error",()=>{this._webWorker||a()},{signal:i.signal}),r.on("test",o=>{if(i.abort(),this.destroyed||!o){a();return}this._messageHandler=r,this._port=n,this._webWorker=n,Kt(this,EB,a2e).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{uTe("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){me(Fm,sR)||(Sc("Setting up fake worker."),Ot(Fm,sR,!0)),Fm._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const n=new wNn;this._port=n;const r=`fake${Ig(Fm,i4e)._++}`,a=new nW(r+"_worker",r,n);t.setup(a,n),this._messageHandler=new nW(r,r+"_worker",n),Kt(this,EB,a2e).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=me(Fm,nR))==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=me(this,nR))==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 Fm(t)}static get workerSrc(){if(s3.workerSrc)return s3.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return md(this,"_setupFakeWorkerGlobal",(async()=>me(this,MB,i2e)?me(this,MB,i2e):(await import(this.workerSrc)).WorkerMessageHandler)())}};i4e=new WeakMap,sR=new WeakMap,nR=new WeakMap,EB=new WeakSet,a2e=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},MB=new WeakSet,i2e=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},rs(Fm,MB),rs(Fm,i4e,0),rs(Fm,sR,!1),rs(Fm,nR),Xy&&(Ot(Fm,sR,!0),s3.workerSrc||(s3.workerSrc="./pdf.worker.mjs")),Fm._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},Fm._createCDNWrapper=t=>{const n=`await import("${t}");`;return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))};let $z=Fm;var z4,t5,LB,PB,s5,rR,rW;class jNn{constructor(t,n,r,a,i){rs(this,rR);rs(this,z4,new Map);rs(this,t5,new Map);rs(this,LB,new Map);rs(this,PB,new Map);rs(this,s5,null);this.messageHandler=t,this.loadingTask=n,this.commonObjs=new u9t,this.fontLoader=new b2n({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 md(this,"annotationStorage",new qKe)}getRenderingIntent(t,n=PA.ENABLE,r=null,a=!1,i=!1){let l=S_.DISPLAY,o=Cze;switch(t){case"any":l=S_.ANY;break;case"display":break;case"print":l=S_.PRINT;break;default:Sc(`getRenderingIntent - invalid intent: ${t}`)}const c=l&S_.PRINT&&r instanceof U7t?r:this.annotationStorage;switch(n){case PA.DISABLE:l+=S_.ANNOTATIONS_DISABLE;break;case PA.ENABLE:break;case PA.ENABLE_FORMS:l+=S_.ANNOTATIONS_FORMS;break;case PA.ENABLE_STORAGE:l+=S_.ANNOTATIONS_STORAGE,o=c.serializable;break;default:Sc(`getRenderingIntent - invalid annotationMode: ${n}`)}a&&(l+=S_.IS_EDITING),i&&(l+=S_.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=me(this,s5))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const a of me(this,t5).values())t.push(a._destroy());me(this,t5).clear(),me(this,LB).clear(),me(this,PB).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(),me(this,z4).clear(),this.filterFactory.destroy(),vX.cleanup(),(a=this._networkStream)==null||a.cancelAllRequests(new UO("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)=>{ig(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}ig(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)=>{ig(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}ig(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 bNn(r,this))}),t.on("DocException",function(r){let a;switch(r.name){case"PasswordException":a=new aze(r.message,r.code);break;case"InvalidPDFException":a=new p7t(r.message);break;case"MissingPDFException":a=new $O(r.message);break;case"UnexpectedResponseException":a=new hTe(r.message,r.status);break;case"UnknownErrorException":a=new ize(r.message,r.details);break;default:pm("DocException - expected a valid Error.")}n._capability.reject(a)}),t.on("PasswordRequest",r=>{if(Ot(this,s5,Promise.withResolvers()),n.onPassword){const a=i=>{i instanceof Error?me(this,s5).reject(i):me(this,s5).resolve({password:i})};try{n.onPassword(a,r.code)}catch(i){me(this,s5).reject(i)}}else me(this,s5).reject(new aze(r.message,r.code));return me(this,s5).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;me(this,t5).get(r.pageIndex)._startRenderPage(r.transparency,r.cacheKey)}),t.on("commonobj",([r,a,i])=>{var l;if(this.destroyed||this.commonObjs.has(r))return null;switch(a){case"Font":const{disableFontFace:o,fontExtraProperties:c,pdfBug:d}=this._params;if("error"in i){const p=i.error;Sc(`Error during font loading: ${p}`),this.commonObjs.resolve(r,p);break}const u=d&&((l=globalThis.FontInspector)!=null&&l.enabled)?(p,x)=>globalThis.FontInspector.fontAdded(p,x):null,h=new _2n(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;ig(m,"The imageRef must be defined.");for(const p of me(this,t5).values())for(const[,x]of p.objs)if((x==null?void 0:x.ref)===m)return x.dataLen?(this.commonObjs.resolve(r,structuredClone(x)),x.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(r,i);break;default:throw new Error(`Got unknown common object type ${a}`)}return null}),t.on("obj",([r,a,i,l])=>{var c;if(this.destroyed)return;const o=me(this,t5).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)>Yjn&&(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&&Sc("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=me(this,LB).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&&me(this,PB).set(i.refStr,t);const l=new _Nn(n,i,this,this._params.pdfBug);return me(this,t5).set(n,l),l});return me(this,LB).set(n,a),a}getPageIndex(t){return Hxt(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,n){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:n})}getFieldObjects(){return Kt(this,rR,rW).call(this,"GetFieldObjects")}hasJSActions(){return Kt(this,rR,rW).call(this,"HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return Kt(this,rR,rW).call(this,"GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return Kt(this,rR,rW).call(this,"GetOptionalContentConfig").then(n=>new q2n(n,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",n=me(this,z4).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 $2n(a[1]):null,contentDispositionFilename:((i=this._fullReader)==null?void 0:i.filename)??null,contentLength:((l=this._fullReader)==null?void 0:l.contentLength)??null}});return me(this,z4).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 me(this,t5).values())if(!n.cleanup())throw new Error(`startCleanup: Page ${n.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),me(this,z4).clear(),this.filterFactory.destroy(!0),vX.cleanup()}}cachedPageNumber(t){if(!Hxt(t))return null;const n=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return me(this,PB).get(n)??null}}z4=new WeakMap,t5=new WeakMap,LB=new WeakMap,PB=new WeakMap,s5=new WeakMap,rR=new WeakSet,rW=function(t,n=null){const r=me(this,z4).get(t);if(r)return r;const a=this.messageHandler.sendWithPromise(t,n);return me(this,z4).set(t,a),a};const ire=Symbol("INITIAL_DATA");var B2,fQ,zze;class u9t{constructor(){rs(this,fQ);rs(this,B2,Object.create(null))}get(t,n=null){if(n){const a=Kt(this,fQ,zze).call(this,t);return a.promise.then(()=>n(a.data)),null}const r=me(this,B2)[t];if(!r||r.data===ire)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return r.data}has(t){const n=me(this,B2)[t];return!!n&&n.data!==ire}resolve(t,n=null){const r=Kt(this,fQ,zze).call(this,t);r.data=n,r.resolve()}clear(){var t;for(const n in me(this,B2)){const{data:r}=me(this,B2)[n];(t=r==null?void 0:r.bitmap)==null||t.close()}Ot(this,B2,Object.create(null))}*[Symbol.iterator](){for(const t in me(this,B2)){const{data:n}=me(this,B2)[t];n!==ire&&(yield[t,n])}}}B2=new WeakMap,fQ=new WeakSet,zze=function(t){var n;return(n=me(this,B2))[t]||(n[t]={...Promise.withResolvers(),data:ire})};var iT;class NNn{constructor(t){rs(this,iT,null);Ot(this,iT,t),this.onContinue=null}get promise(){return me(this,iT).capability.promise}cancel(t=0){me(this,iT).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=me(this,iT).operatorList;if(!t)return!1;const{annotationCanvasMap:n}=me(this,iT);return t.form||t.canvas&&(n==null?void 0:n.size)>0}}iT=new WeakMap;var oT,aR;const ZI=class ZI{constructor({callback:t,params:n,objs:r,commonObjs:a,annotationCanvasMap:i,operatorList:l,pageIndex:o,canvasFactory:c,filterFactory:d,useRequestAnimationFrame:u=!1,pdfBug:h=!1,pageColors:m=null}){rs(this,oT,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 NNn(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(me(ZI,aR).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.");me(ZI,aR).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 Bz(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(),me(this,oT)&&(window.cancelAnimationFrame(me(this,oT)),Ot(this,oT,null)),me(ZI,aR).delete(this._canvas),this.callback(t||new zKe(`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?Ot(this,oT,window.requestAnimationFrame(()=>{Ot(this,oT,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(),me(ZI,aR).delete(this._canvas),this.callback())))}};oT=new WeakMap,aR=new WeakMap,rs(ZI,aR,new WeakSet);let Bze=ZI;const kNn="4.8.69",SNn="3634dab10";function Gxt(s){return Math.floor(Math.max(0,Math.min(1,s))*255).toString(16).padStart(2,"0")}function JH(s){return Math.max(0,Math.min(255,255*s))}class Wxt{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=JH(t),[t,t,t]}static G_HTML([t]){const n=Gxt(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(JH)}static RGB_HTML(t){return`#${t.map(Gxt).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[JH(1-Math.min(1,t+a)),JH(1-Math.min(1,r+a)),JH(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 CNn{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){pm("Abstract method `_createSVG` called.")}}class KKe extends CNn{_createSVG(t){return document.createElementNS(h4,t)}}class h9t{static setupStorage(t,n,r,a,i){const l=a.getValue(n,{value:null});switch(r.name){case"textarea":if(l.value!==null&&(t.textContent=l.value),i==="print")break;t.addEventListener("input",o=>{a.setValue(n,{value:o.target.value})});break;case"input":if(r.attributes.type==="radio"||r.attributes.type==="checkbox"){if(l.value===r.attributes.xfaOn?t.setAttribute("checked",!0):l.value===r.attributes.xfaOff&&t.removeAttribute("checked"),i==="print")break;t.addEventListener("change",o=>{a.setValue(n,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(l.value!==null&&t.setAttribute("value",l.value),i==="print")break;t.addEventListener("input",o=>{a.setValue(n,{value:o.target.value})})}break;case"select":if(l.value!==null){t.setAttribute("value",l.value);for(const o of r.children)o.attributes.value===l.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const c=o.target.options,d=c.selectedIndex===-1?"":c[c.selectedIndex].value;a.setValue(n,{value:d})});break}}static setAttributes({html:t,element:n,storage:r=null,intent:a,linkService:i}){const{attributes:l}=n,o=t instanceof HTMLAnchorElement;l.type==="radio"&&(l.name=`${l.name}-${a}`);for(const[c,d]of Object.entries(l))if(d!=null)switch(c){case"class":d.length&&t.setAttribute(c,d.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",d);break;case"style":Object.assign(t.style,d);break;case"textContent":t.textContent=d;break;default:(!o||c!=="href"&&c!=="newWindow")&&t.setAttribute(c,d)}o&&i.addLinkAttributes(t,l.href,l.newWindow),r&&l.dataId&&this.setupStorage(t,l.dataId,n,r)}static render(t){var h,m;const n=t.annotationStorage,r=t.linkService,a=t.xfaHtml,i=t.intent||"display",l=document.createElement(a.name);a.attributes&&this.setAttributes({html:l,element:a,intent:i,linkService:r});const o=i!=="richText",c=t.div;if(c.append(l),t.viewport){const p=`matrix(${t.viewport.transform.join(",")})`;c.style.transform=p}o&&c.setAttribute("class","xfaLayer xfaFont");const d=[];if(a.children.length===0){if(a.value){const p=document.createTextNode(a.value);l.append(p),o&&bX.shouldBuildText(a.name)&&d.push(p)}return{textDivs:d}}const u=[[a,-1,l]];for(;u.length>0;){const[p,x,y]=u.at(-1);if(x+1===p.children.length){u.pop();continue}const g=p.children[++u.at(-1)[1]];if(g===null)continue;const{name:b}=g;if(b==="#text"){const k=document.createTextNode(g.value);d.push(k),y.append(k);continue}const v=(h=g==null?void 0:g.attributes)!=null&&h.xmlns?document.createElementNS(g.attributes.xmlns,b):document.createElement(b);if(y.append(v),g.attributes&&this.setAttributes({html:v,element:g,storage:n,intent:i,linkService:r}),((m=g.children)==null?void 0:m.length)>0)u.push([g,-1,v]);else if(g.value){const k=document.createTextNode(g.value);o&&bX.shouldBuildText(b)&&d.push(k),v.append(k)}}for(const p of c.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))p.setAttribute("readOnly",!0);return{textDivs:d}}static update(t){const n=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=n,t.div.hidden=!1}}const xee=1e3,ANn=9,aO=new WeakSet;function A3(s){return{width:s[2]-s[0],height:s[3]-s[1]}}class TNn{static create(t){switch(t.data.annotationType){case Hx.LINK:return new m9t(t);case Hx.TEXT:return new ENn(t);case Hx.WIDGET:switch(t.data.fieldType){case"Tx":return new MNn(t);case"Btn":return t.data.radioButton?new x9t(t):t.data.checkBox?new PNn(t):new INn(t);case"Ch":return new RNn(t);case"Sig":return new LNn(t)}return new qO(t);case Hx.POPUP:return new Uze(t);case Hx.FREETEXT:return new _9t(t);case Hx.LINE:return new ONn(t);case Hx.SQUARE:return new FNn(t);case Hx.CIRCLE:return new zNn(t);case Hx.POLYLINE:return new w9t(t);case Hx.CARET:return new $Nn(t);case Hx.INK:return new YKe(t);case Hx.POLYGON:return new BNn(t);case Hx.HIGHLIGHT:return new j9t(t);case Hx.UNDERLINE:return new UNn(t);case Hx.SQUIGGLY:return new qNn(t);case Hx.STRIKEOUT:return new VNn(t);case Hx.STAMP:return new N9t(t);case Hx.FILEATTACHMENT:return new HNn(t);default:return new rx(t)}}}var iR,IB,RB,xQ,$ze;const cZe=class cZe{constructor(t,{isRenderable:n=!1,ignoreBorder:r=!1,createQuadrilaterals:a=!1}={}){rs(this,xQ);rs(this,iR,null);rs(this,IB,!1);rs(this,RB,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 cZe._hasPopupData(this.data)}updateEdited(t){var r;if(!this.container)return;me(this,iR)||Ot(this,iR,{rect:this.data.rect.slice(0)});const{rect:n}=t;n&&Kt(this,xQ,$ze).call(this,n),(r=me(this,RB))==null||r.popup.updateEdited(t)}resetEdited(){var t;me(this,iR)&&(Kt(this,xQ,$ze).call(this,me(this,iR).rect),(t=me(this,RB))==null||t.popup.resetEdited(),Ot(this,iR,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 qO||(i.tabIndex=xee);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 Uze){const{rotation:y}=n;return!n.hasOwnCanvas&&y!==0&&this.setRotation(y,i),i}const{width:o,height:c}=A3(n.rect);if(!t&&n.borderStyle.width>0){l.borderWidth=`${n.borderStyle.width}px`;const y=n.borderStyle.horizontalCornerRadius,g=n.borderStyle.verticalCornerRadius;if(y>0||g>0){const v=`calc(${y}px * var(--scale-factor)) / calc(${g}px * var(--scale-factor))`;l.borderRadius=v}else if(this instanceof x9t){const v=`calc(${o}px * var(--scale-factor)) / calc(${c}px * var(--scale-factor))`;l.borderRadius=v}switch(n.borderStyle.style){case XH.SOLID:l.borderStyle="solid";break;case XH.DASHED:l.borderStyle="dashed";break;case XH.BEVELED:Sc("Unimplemented border style: beveled");break;case XH.INSET:Sc("Unimplemented border style: inset");break;case XH.UNDERLINE:l.borderBottomStyle="solid";break}const b=n.borderColor||null;b?(Ot(this,IB,!0),l.borderColor=vo.makeHexColor(b[0]|0,b[1]|0,b[2]|0)):l.borderWidth=0}const d=vo.normalizeRect([n.rect[0],r.view[3]-n.rect[1]+r.view[1],n.rect[2],r.view[3]-n.rect[3]+r.view[1]]),{pageWidth:u,pageHeight:h,pageX:m,pageY:p}=a.rawDims;l.left=`${100*(d[0]-m)/u}%`,l.top=`${100*(d[1]-p)/h}%`;const{rotation:x}=n;return n.hasOwnCanvas||x===0?(l.width=`${100*o/u}%`,l.height=`${100*c/h}%`):this.setRotation(x,i),i}setRotation(t,n=this.container){if(!this.data.rect)return;const{pageWidth:r,pageHeight:a}=this.parent.viewport.rawDims,{width:i,height:l}=A3(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]=Wxt[`${l}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[r]:Wxt[`${l}_rgb`](o)})};return md(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,g,b,v]=t.subarray(2,6);if(a===y&&i===g&&n===b&&r===v)return}const{style:l}=this.container;let o;if(me(this,IB)){const{borderColor:y,borderWidth:g}=l;l.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const c=a-n,d=i-r,{svgFactory:u}=this,h=u.createElement("svg");h.classList.add("quadrilateralsContainer"),h.setAttribute("width",0),h.setAttribute("height",0);const m=u.createElement("defs");h.append(m);const p=u.createElement("clipPath"),x=`clippath_${this.data.id}`;p.setAttribute("id",x),p.setAttribute("clipPathUnits","objectBoundingBox"),m.append(p);for(let y=2,g=t.length;y`)}me(this,IB)&&(o.push("')"),l.backgroundImage=o.join("")),this.container.append(h),this.container.style.clipPath=`url(#${x})`}_createPopup(){const{data:t}=this,n=Ot(this,RB,new Uze({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(){pm("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&&!aO.has(d)){Sc(`_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&&aO.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})})}};iR=new WeakMap,IB=new WeakMap,RB=new WeakMap,xQ=new WeakSet,$ze=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}=A3(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 rx=cZe;var P_,OI,p9t,f9t;class m9t extends rx{constructor(n,r=null){super(n,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});rs(this,P_);this.isTooltipOnly=n.data.isTooltipOnly}render(){const{data:n,linkService:r}=this,a=document.createElement("a");a.setAttribute("data-element-id",n.id);let i=!1;return n.url?(r.addLinkAttributes(a,n.url,n.newWindow),i=!0):n.action?(this._bindNamedAction(a,n.action),i=!0):n.attachment?(Kt(this,P_,p9t).call(this,a,n.attachment,n.attachmentDest),i=!0):n.setOCGState?(Kt(this,P_,f9t).call(this,a,n.setOCGState),i=!0):n.dest?(this._bindLink(a,n.dest),i=!0):(n.actions&&(n.actions.Action||n.actions["Mouse Up"]||n.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(a,n),i=!0),n.resetForm?(this._bindResetFormAction(a,n.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(a,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(a),this.container}_bindLink(n,r){n.href=this.linkService.getDestinationHash(r),n.onclick=()=>(r&&this.linkService.goToDestination(r),!1),(r||r==="")&&Kt(this,P_,OI).call(this)}_bindNamedAction(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeNamedAction(r),!1),Kt(this,P_,OI).call(this)}_bindJSAction(n,r){n.href=this.linkService.getAnchorUrl("");const a=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(r.actions)){const l=a.get(i);l&&(n[l]=()=>{var o;return(o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:r.id,name:i}}),!1})}n.onclick||(n.onclick=()=>!1),Kt(this,P_,OI).call(this)}_bindResetFormAction(n,r){const a=n.onclick;if(a||(n.href=this.linkService.getAnchorUrl("")),Kt(this,P_,OI).call(this),!this._fieldObjects){Sc('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),a||(n.onclick=()=>!1);return}n.onclick=()=>{var h;a==null||a();const{fields:i,refs:l,include:o}=r,c=[];if(i.length!==0||l.length!==0){const m=new Set(l);for(const p of i){const x=this._fieldObjects[p]||[];for(const{id:y}of x)m.add(y)}for(const p of Object.values(this._fieldObjects))for(const x of p)m.has(x.id)===o&&c.push(x)}else for(const m of Object.values(this._fieldObjects))c.push(...m);const d=this.annotationStorage,u=[];for(const m of c){const{id:p}=m;switch(u.push(p),m.type){case"text":{const y=m.defaultValue||"";d.setValue(p,{value:y});break}case"checkbox":case"radiobutton":{const y=m.defaultValue===m.exportValues;d.setValue(p,{value:y});break}case"combobox":case"listbox":{const y=m.defaultValue||"";d.setValue(p,{value:y});break}default:continue}const x=document.querySelector(`[data-element-id="${p}"]`);if(x){if(!aO.has(x)){Sc(`_bindResetFormAction - element not allowed: ${p}`);continue}}else continue;x.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((h=this.linkService.eventBus)==null||h.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}P_=new WeakSet,OI=function(){this.container.setAttribute("data-internal-link","")},p9t=function(n,r,a=null){n.href=this.linkService.getAnchorUrl(""),r.description&&(n.title=r.description),n.onclick=()=>{var i;return(i=this.downloadManager)==null||i.openOrDownloadData(r.content,r.filename,a),!1},Kt(this,P_,OI).call(this)},f9t=function(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeSetOCGState(r),!1),Kt(this,P_,OI).call(this)};class ENn extends rx{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 qO extends rx{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 c1.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":vo.makeHexColor(n[0],n[1],n[2])}_setTextStyle(t){const n=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,a=this.data.defaultAppearanceData.fontSize||ANn,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/(OIe*a))||1,h=d/u;l=Math.min(a,c(h/OIe))}else{const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o);l=Math.min(a,c(d/OIe))}i.fontSize=`calc(${l}px * var(--scale-factor))`,i.color=vo.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 MNn extends qO{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),aO.add(r),r.setAttribute("data-element-id",n),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=xee,this._setRequired(r,this.data.required),c&&(r.maxLength=c),r.addEventListener("input",m=>{t.setValue(n,{value:m.target.value}),this.setPropertyOnSiblings(r,"value",m.target.value,"value"),u.formattedValue=null}),r.addEventListener("resetform",m=>{const p=this.data.defaultFieldValue??"";r.value=u.userValue=p,u.formattedValue=null});let h=m=>{const{formattedValue:p}=u;p!=null&&(m.target.value=p),m.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){r.addEventListener("focus",p=>{var y;if(u.focused)return;const{target:x}=p;u.userValue&&(x.value=u.userValue),u.lastCommittedValue=x.value,u.commitKey=1,(y=this.data.actions)!=null&&y.Focus||(u.focused=!0)}),r.addEventListener("updatefromsandbox",p=>{this.showElementAndHideCanvas(p.target);const x={value(y){u.userValue=y.detail.value??"",t.setValue(n,{value:u.userValue.toString()}),y.target.value=u.userValue},formattedValue(y){const{formattedValue:g}=y.detail;u.formattedValue=g,g!=null&&y.target!==document.activeElement&&(y.target.value=g),t.setValue(n,{formattedValue:g})},selRange(y){y.target.setSelectionRange(...y.detail.selRange)},charLimit:y=>{var k;const{charLimit:g}=y.detail,{target:b}=y;if(g===0){b.removeAttribute("maxLength");return}b.setAttribute("maxLength",g);let v=u.userValue;!v||v.length<=g||(v=v.slice(0,g),b.value=u.userValue=v,t.setValue(n,{value:v}),(k=this.linkService.eventBus)==null||k.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:v,willCommit:!0,commitKey:1,selStart:b.selectionStart,selEnd:b.selectionEnd}}))}};this._dispatchEventFromSandbox(x,p)}),r.addEventListener("keydown",p=>{var g;u.commitKey=1;let x=-1;if(p.key==="Escape"?x=0:p.key==="Enter"&&!this.data.multiLine?x=2:p.key==="Tab"&&(u.commitKey=3),x===-1)return;const{value:y}=p.target;u.lastCommittedValue!==y&&(u.lastCommittedValue=y,u.userValue=y,(g=this.linkService.eventBus)==null||g.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:y,willCommit:!0,commitKey:x,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}}))});const m=h;h=null,r.addEventListener("blur",p=>{var y,g;if(!u.focused||!p.relatedTarget)return;(y=this.data.actions)!=null&&y.Blur||(u.focused=!1);const{value:x}=p.target;u.userValue=x,u.lastCommittedValue!==x&&((g=this.linkService.eventBus)==null||g.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:x,willCommit:!0,commitKey:u.commitKey,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}})),m(p)}),(i=this.data.actions)!=null&&i.Keystroke&&r.addEventListener("beforeinput",p=>{var T;u.lastCommittedValue=null;const{data:x,target:y}=p,{value:g,selectionStart:b,selectionEnd:v}=y;let k=b,C=v;switch(p.inputType){case"deleteWordBackward":{const M=g.substring(0,b).match(/\w*[^\w]*$/);M&&(k-=M[0].length);break}case"deleteWordForward":{const M=g.substring(b).match(/^[^\w]*\w*/);M&&(C+=M[0].length);break}case"deleteContentBackward":b===v&&(k-=1);break;case"deleteContentForward":b===v&&(C+=1);break}p.preventDefault(),(T=this.linkService.eventBus)==null||T.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:g,change:x||"",willCommit:!1,selStart:k,selEnd:C}})}),this._setEventListeners(r,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],p=>p.target.value)}if(h&&r.addEventListener("blur",h),this.data.comb){const p=(this.data.rect[2]-this.data.rect[0])/c;r.classList.add("comb"),r.style.letterSpacing=`calc(${p}px * var(--scale-factor) - 1ch)`}}else r=document.createElement("div"),r.textContent=this.data.fieldValue,r.style.verticalAlign="middle",r.style.display="table-cell",this.data.hasOwnCanvas&&(r.hidden=!0);return this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class LNn extends qO{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class PNn extends qO{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 aO.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=xee,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 x9t extends qO{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(aO.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=xee,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 INn extends m9t{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 RNn extends qO{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");aO.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=xee;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(a.size=this.data.options.length,this.data.multiSelect&&(a.multiple=!0)),a.addEventListener("resetform",u=>{const h=this.data.defaultFieldValue;for(const m of a.options)m.selected=m.value===h});for(const u of this.data.options){const h=document.createElement("option");h.textContent=u.displayValue,h.value=u.exportValue,r.value.includes(u.exportValue)&&(h.setAttribute("selected",!0),i=!1),a.append(h)}let l=null;if(i){const u=document.createElement("option");u.value=" ",u.setAttribute("hidden",!0),u.setAttribute("selected",!0),a.prepend(u),l=()=>{u.remove(),a.removeEventListener("input",l),l=null},a.addEventListener("input",l)}const o=u=>{const h=u?"value":"textContent",{options:m,multiple:p}=a;return p?Array.prototype.filter.call(m,x=>x.selected).map(x=>x[h]):m.selectedIndex===-1?null:m[m.selectedIndex][h]};let c=o(!1);const d=u=>{const h=u.target.options;return Array.prototype.map.call(h,m=>({displayValue:m.textContent,exportValue:m.value}))};return this.enableScripting&&this.hasJSActions?(a.addEventListener("updatefromsandbox",u=>{const h={value(m){l==null||l();const p=m.detail.value,x=new Set(Array.isArray(p)?p:[p]);for(const y of a.options)y.selected=x.has(y.value);t.setValue(n,{value:o(!0)}),c=o(!1)},multipleSelection(m){a.multiple=!0},remove(m){const p=a.options,x=m.detail.remove;p[x].selected=!1,a.remove(x),p.length>0&&Array.prototype.findIndex.call(p,g=>g.selected)===-1&&(p[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},clear(m){for(;a.length!==0;)a.remove(0);t.setValue(n,{value:null,items:[]}),c=o(!1)},insert(m){const{index:p,displayValue:x,exportValue:y}=m.detail.insert,g=a.children[p],b=document.createElement("option");b.textContent=x,b.value=y,g?g.before(b):a.append(b),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},items(m){const{items:p}=m.detail;for(;a.length!==0;)a.remove(0);for(const x of p){const{displayValue:y,exportValue:g}=x,b=document.createElement("option");b.textContent=y,b.value=g,a.append(b)}a.options.length>0&&(a.options[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},indices(m){const p=new Set(m.detail.indices);for(const x of m.target.options)x.selected=p.has(x.index);t.setValue(n,{value:o(!0)}),c=o(!1)},editable(m){m.target.disabled=!m.detail.editable}};this._dispatchEventFromSandbox(h,u)}),a.addEventListener("input",u=>{var p;const h=o(!0),m=o(!1);t.setValue(n,{value:h}),u.preventDefault(),(p=this.linkService.eventBus)==null||p.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:c,change:m,changeEx:h,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(a,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],u=>u.target.value)):a.addEventListener("input",function(u){t.setValue(n,{value:o(!0)})}),this.data.combo&&this._setTextStyle(a),this._setBackgroundColor(a),this._setDefaultPropertiesFromJS(a),this.container.append(a),this.container}}class Uze extends rx{constructor(t){const{data:n,elements:r}=t;super(t,{isRenderable:rx._hasPopupData(n)}),this.elements=r,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new DNn({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=>`${FKe}${r}`).join(",")),this.container}}var DB,o4e,l4e,OB,oR,cf,B4,FB,gQ,yQ,zB,$4,$2,U4,vQ,q4,bQ,lR,cR,ih,o2e,qze,g9t,y9t,v9t,b9t,l2e,c2e,Vze;class DNn{constructor({container:t,color:n,elements:r,titleObj:a,modificationDate:i,contentsObj:l,richText:o,parent:c,rect:d,parentRect:u,open:h}){rs(this,ih);rs(this,DB,Kt(this,ih,v9t).bind(this));rs(this,o4e,Kt(this,ih,Vze).bind(this));rs(this,l4e,Kt(this,ih,c2e).bind(this));rs(this,OB,Kt(this,ih,l2e).bind(this));rs(this,oR,null);rs(this,cf,null);rs(this,B4,null);rs(this,FB,null);rs(this,gQ,null);rs(this,yQ,null);rs(this,zB,null);rs(this,$4,!1);rs(this,$2,null);rs(this,U4,null);rs(this,vQ,null);rs(this,q4,null);rs(this,bQ,null);rs(this,lR,null);rs(this,cR,!1);var m;Ot(this,cf,t),Ot(this,bQ,a),Ot(this,B4,l),Ot(this,q4,o),Ot(this,yQ,c),Ot(this,oR,n),Ot(this,vQ,d),Ot(this,zB,u),Ot(this,gQ,r),Ot(this,FB,$Ke.toDateObject(i)),this.trigger=r.flatMap(p=>p.getElementsToTriggerPopup());for(const p of this.trigger)p.addEventListener("click",me(this,OB)),p.addEventListener("mouseenter",me(this,l4e)),p.addEventListener("mouseleave",me(this,o4e)),p.classList.add("popupTriggerArea");for(const p of r)(m=p.container)==null||m.addEventListener("keydown",me(this,DB));me(this,cf).hidden=!0,h&&Kt(this,ih,l2e).call(this)}render(){if(me(this,$2))return;const t=Ot(this,$2,document.createElement("div"));if(t.className="popup",me(this,oR)){const i=t.style.outlineColor=vo.makeHexColor(...me(this,oR));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${i} 30%, white)`:t.style.backgroundColor=vo.makeHexColor(...me(this,oR).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}=me(this,bQ),t.append(n),me(this,FB)){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:me(this,FB).valueOf()})),n.append(i)}const a=me(this,ih,o2e);if(a)h9t.render({xfaHtml:a,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const i=this._formatContents(me(this,B4));t.append(i)}me(this,cf).append(t)}_formatContents({str:t,dir:n}){const r=document.createElement("p");r.classList.add("popupContent"),r.dir=n;const a=t.split(/(?:\r\n?|\n)/);for(let i=0,l=a.length;i{l.key==="Enter"&&(i?l.metaKey:l.ctrlKey)&&Kt(this,CQ,Hze).call(this)}),!r.popupRef&&this.hasPopupData?this._createPopup():a.classList.add("popupTriggerArea"),n.append(a),n}getElementsToTriggerPopup(){return me(this,SQ)}addHighlightArea(){this.container.classList.add("highlightArea")}}SQ=new WeakMap,CQ=new WeakSet,Hze=function(){var n;(n=this.downloadManager)==null||n.openOrDownloadData(this.content,this.filename)};var AQ,dR,uR,TQ,lO,k9t,Gze;class GNn{constructor({div:t,accessibilityManager:n,annotationCanvasMap:r,annotationEditorUIManager:a,page:i,viewport:l,structTreeLayer:o}){rs(this,lO);rs(this,AQ,null);rs(this,dR,null);rs(this,uR,new Map);rs(this,TQ,null);this.div=t,Ot(this,AQ,n),Ot(this,dR,r),Ot(this,TQ,o||null),this.page=i,this.viewport=l,this.zIndex=0,this._annotationEditorUIManager=a}hasEditableAnnotations(){return me(this,uR).size>0}async render(t){var l;const{annotations:n}=t,r=this.div;nO(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 KKe,annotationStorage:t.annotationStorage||new qKe,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===Hx.POPUP;if(c){const h=a.get(o.id);if(!h)continue;i.elements=h}else{const{width:h,height:m}=A3(o.rect);if(h<=0||m<=0)continue}i.data=o;const d=TNn.create(i);if(!d.isRenderable)continue;if(!c&&o.popupRef){const h=a.get(o.popupRef);h?h.push(d):a.set(o.popupRef,[d])}const u=d.render();o.hidden&&(u.style.visibility="hidden"),await Kt(this,lO,k9t).call(this,u,o.id),d._isEditable&&(me(this,uR).set(d.data.id,d),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(d))}Kt(this,lO,Gze).call(this)}update({viewport:t}){const n=this.div;this.viewport=t,nO(n,{rotation:t.rotation}),Kt(this,lO,Gze).call(this),n.hidden=!1}getEditableAnnotations(){return Array.from(me(this,uR).values())}getEditableAnnotation(t){return me(this,uR).get(t)}}AQ=new WeakMap,dR=new WeakMap,uR=new WeakMap,TQ=new WeakMap,lO=new WeakSet,k9t=async function(t,n){var l,o;const r=t.firstChild||t,a=r.id=`${FKe}${n}`,i=await((l=me(this,TQ))==null?void 0:l.getAriaAttributes(a));if(i)for(const[c,d]of i)r.setAttribute(c,d);this.div.append(t),(o=me(this,AQ))==null||o.moveElementInDOM(this.div,t,r,!1)},Gze=function(){if(!me(this,dR))return;const t=this.div;for(const[n,r]of me(this,dR)){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)}me(this,dR).clear()};const ore=/\r\n?|\n/g;var U2,v_,EQ,hR,b_,Ex,S9t,C9t,A9t,d2e,L3,u2e,h2e,T9t,Kze,E9t;const Rh=class Rh extends qu{constructor(n){super({...n,name:"freeTextEditor"});rs(this,Ex);rs(this,U2);rs(this,v_,"");rs(this,EQ,`${this.id}-editor`);rs(this,hR,null);rs(this,b_);Ot(this,U2,n.color||Rh._defaultColor||qu._defaultLineColor),Ot(this,b_,n.fontSize||Rh._defaultFontSize)}static get _keyboardManager(){const n=Rh.prototype,r=l=>l.isEmpty(),a=rO.TRANSLATE_SMALL,i=rO.TRANSLATE_BIG;return md(this,"_keyboardManager",new fee([[["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){qu.initialize(n,r);const a=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(a.getPropertyValue("--freetext-padding"))}static updateDefaultParams(n,r){switch(n){case Ll.FREETEXT_SIZE:Rh._defaultFontSize=r;break;case Ll.FREETEXT_COLOR:Rh._defaultColor=r;break}}updateParams(n,r){switch(n){case Ll.FREETEXT_SIZE:Kt(this,Ex,S9t).call(this,r);break;case Ll.FREETEXT_COLOR:Kt(this,Ex,C9t).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[Ll.FREETEXT_SIZE,Rh._defaultFontSize],[Ll.FREETEXT_COLOR,Rh._defaultColor||qu._defaultLineColor]]}get propertiesToUpdate(){return[[Ll.FREETEXT_SIZE,me(this,b_)],[Ll.FREETEXT_COLOR,me(this,U2)]]}_translateEmpty(n,r){this._uiManager.translateSelectedEditors(n,r,!0)}getInitialTranslation(){const n=this.parentScale;return[-Rh._internalPadding*n,-(Rh._internalPadding+me(this,b_))*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(rc.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),Ot(this,hR,new AbortController);const n=this._uiManager.combinedSignal(me(this,hR));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",me(this,EQ)),this._isDraggable=!0,(n=me(this,hR))==null||n.abort(),Ot(this,hR,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=me(this,v_),r=Ot(this,v_,Kt(this,Ex,A9t).call(this).trimEnd());if(n===r)return;const a=i=>{if(Ot(this,v_,i),!i){this.remove();return}Kt(this,Ex,h2e).call(this),this._uiManager.rebuild(this),Kt(this,Ex,d2e).call(this)};this.addCommands({cmd:()=>{a(r)},undo:()=>{a(n)},mustExec:!1}),Kt(this,Ex,d2e).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){Rh._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",me(this,EQ)),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(${me(this,b_)}px * var(--scale-factor))`,a.color=me(this,U2),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),jSe(this,this.div,["dblclick","keydown"]),this.width){const[i,l]=this.parentDimensions;if(this.annotationElementId){const{position:o}=this._initialData;let[c,d]=this.getInitialTranslation();[c,d]=this.pageTranslationToScreen(c,d);const[u,h]=this.pageDimensions,[m,p]=this.pageTranslation;let x,y;switch(this.rotation){case 0:x=n+(o[0]-m)/u,y=r+this.height-(o[1]-p)/h;break;case 90:x=n+(o[0]-m)/u,y=r-(o[1]-p)/h,[c,d]=[d,-c];break;case 180:x=n-this.width+(o[0]-m)/u,y=r-(o[1]-p)/h,[c,d]=[-c,-d];break;case 270:x=n+(o[0]-m-this.height*h)/u,y=r+(o[1]-p-this.width*u)/h,[c,d]=[-d,c];break}this.setAt(x*i,y*l,c,d)}else this.setAt(n*i,r*l,this.width*i,this.height*l);Kt(this,Ex,h2e).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(n){var x,y,g;const r=n.clipboardData||window.clipboardData,{types:a}=r;if(a.length===1&&a[0]==="text/plain")return;n.preventDefault();const i=Kt(x=Rh,L3,Kze).call(x,r.getData("text")||"").replaceAll(ore,` `);if(!i)return;const l=window.getSelection();if(!l.rangeCount)return;this.editorDiv.normalize(),l.deleteFromDocument();const o=l.getRangeAt(0);if(!i.includes(` `)){o.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),l.collapseToStart();return}const{startContainer:c,startOffset:d}=o,u=[],h=[];if(c.nodeType===Node.TEXT_NODE){const b=c.parentElement;if(h.push(c.nodeValue.slice(d).replaceAll(ore,"")),b!==this.editorDiv){let v=u;for(const k of this.editorDiv.childNodes){if(k===b){v=h;continue}v.push(Kt(y=Rh,L3,u2e).call(y,k))}}u.push(c.nodeValue.slice(0,d).replaceAll(ore,""))}else if(c===this.editorDiv){let b=u,v=0;for(const k of this.editorDiv.childNodes)v++===d&&(b=h),b.push(Kt(g=Rh,L3,u2e).call(g,k))}Ot(this,v_,`${u.join(` `)}${i}${h.join(` `)}`),Kt(this,Ex,h2e).call(this);const m=new Range;let p=u.reduce((b,v)=>b+v.length,0);for(const{firstChild:b}of this.editorDiv.childNodes)if(b.nodeType===Node.TEXT_NODE){const v=b.nodeValue.length;if(p<=v){m.setStart(b,p),m.setEnd(b,p);break}p-=v}l.removeAllRanges(),l.addRange(m)}get contentDiv(){return this.editorDiv}static async deserialize(n,r,a){var o;let i=null;if(n instanceof _9t){const{data:{defaultAppearanceData:{fontSize:c,fontColor:d},rect:u,rotation:h,id:m,popupRef:p},textContent:x,textPosition:y,parent:{page:{pageNumber:g}}}=n;if(!x||x.length===0)return null;i=n={annotationType:rc.FREETEXT,color:Array.from(d),fontSize:c,value:x.join(` `),position:y,pageIndex:g-1,rect:u.slice(0),rotation:h,id:m,deleted:!1,popupRef:p}}const l=await super.deserialize(n,r,a);return Ot(l,b_,n.fontSize),Ot(l,U2,vo.makeHexColor(...n.color)),Ot(l,v_,Kt(o=Rh,L3,Kze).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=Rh._internalPadding*this.parentScale,a=this.getRect(r,r),i=qu._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:me(this,U2)),l={annotationType:rc.FREETEXT,color:i,fontSize:me(this,b_),value:Kt(this,Ex,T9t).call(this),pageIndex:this.pageIndex,rect:a,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return n?l:this.annotationElementId&&!Kt(this,Ex,E9t).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(${me(this,b_)}px * var(--scale-factor))`,a.color=me(this,U2),r.replaceChildren();for(const l of me(this,v_).split(` `)){const o=document.createElement("div");o.append(l?document.createTextNode(l):document.createElement("br")),r.append(o)}const i=Rh._internalPadding*this.parentScale;return n.updateEdited({rect:this.getRect(i,i),popupContent:me(this,v_)}),r}resetAnnotationElement(n){super.resetAnnotationElement(n),n.resetEdited()}};U2=new WeakMap,v_=new WeakMap,EQ=new WeakMap,hR=new WeakMap,b_=new WeakMap,Ex=new WeakSet,S9t=function(n){const r=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-me(this,b_))*this.parentScale),Ot(this,b_,i),Kt(this,Ex,d2e).call(this)},a=me(this,b_);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Ll.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},C9t=function(n){const r=i=>{Ot(this,U2,this.editorDiv.style.color=i)},a=me(this,U2);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Ll.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},A9t=function(){var a;const n=[];this.editorDiv.normalize();let r=null;for(const i of this.editorDiv.childNodes)(r==null?void 0:r.nodeType)===Node.TEXT_NODE&&i.nodeName==="BR"||(n.push(Kt(a=Rh,L3,u2e).call(a,i)),r=i);return n.join(` `)},d2e=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()},L3=new WeakSet,u2e=function(n){return(n.nodeType===Node.TEXT_NODE?n.nodeValue:n.innerText).replaceAll(ore,"")},h2e=function(){if(this.editorDiv.replaceChildren(),!!me(this,v_))for(const n of me(this,v_).split(` `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),this.editorDiv.append(r)}},T9t=function(){return me(this,v_).replaceAll(" "," ")},Kze=function(n){return n.replaceAll(" "," ")},E9t=function(n){const{value:r,fontSize:a,color:i,pageIndex:l}=this._initialData;return this._hasBeenMoved||n.value!==r||n.fontSize!==a||n.color.some((o,c)=>o!==i[c])||n.pageIndex!==l},rs(Rh,L3),Ar(Rh,"_freeTextDefaultContent",""),Ar(Rh,"_internalPadding",0),Ar(Rh,"_defaultColor",null),Ar(Rh,"_defaultFontSize",10),Ar(Rh,"_type","freetext"),Ar(Rh,"_editorType",rc.FREETEXT);let Wze=Rh;class M9t{toSVGPath(){pm("Abstract method `toSVGPath` must be implemented.")}get box(){pm("Abstract getter `box` must be implemented.")}serialize(t,n){pm("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){pm("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){pm("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}var __,q2,BB,$B,n5,Lc,mR,pR,MQ,LQ,UB,qB,lT,PQ,c4e,d4e,dg,aW,L9t,P9t,I9t,R9t,D9t,O9t;const _4=class _4{constructor({x:t,y:n},r,a,i,l,o=0){rs(this,dg);rs(this,__);rs(this,q2,[]);rs(this,BB);rs(this,$B);rs(this,n5,[]);rs(this,Lc,new Float64Array(18));rs(this,mR);rs(this,pR);rs(this,MQ);rs(this,LQ);rs(this,UB);rs(this,qB);rs(this,lT,[]);Ot(this,__,r),Ot(this,qB,i*a),Ot(this,$B,l),me(this,Lc).set([NaN,NaN,NaN,NaN,t,n],6),Ot(this,BB,o),Ot(this,LQ,me(_4,PQ)*a),Ot(this,MQ,me(_4,d4e)*a),Ot(this,UB,a),me(this,lT).push(t,n)}isEmpty(){return isNaN(me(this,Lc)[8])}add({x:t,y:n}){var I;Ot(this,mR,t),Ot(this,pR,n);const[r,a,i,l]=me(this,__);let[o,c,d,u]=me(this,Lc).subarray(8,12);const h=t-d,m=n-u,p=Math.hypot(h,m);if(p=6;a-=6)isNaN(n[a])?r.push(`L${n[a+4]} ${n[a+5]}`):r.push(`C${n[a]} ${n[a+1]} ${n[a+2]} ${n[a+3]} ${n[a+4]} ${n[a+5]}`);return Kt(this,dg,P9t).call(this,r),r.join(" ")}newFreeDrawOutline(t,n,r,a,i,l){return new F9t(t,n,r,a,i,l)}getOutlines(){var h;const t=me(this,n5),n=me(this,q2),r=me(this,Lc),[a,i,l,o]=me(this,__),c=new Float64Array((((h=me(this,lT))==null?void 0:h.length)??0)+2);for(let m=0,p=c.length-2;m=6;m-=6)for(let p=0;p<6;p+=2){if(isNaN(n[m+p])){d[u]=d[u+1]=NaN,u+=2;continue}d[u]=n[m+p],d[u+1]=n[m+p+1],u+=2}return Kt(this,dg,D9t).call(this,d,u),this.newFreeDrawOutline(d,c,me(this,__),me(this,UB),me(this,BB),me(this,$B))}};__=new WeakMap,q2=new WeakMap,BB=new WeakMap,$B=new WeakMap,n5=new WeakMap,Lc=new WeakMap,mR=new WeakMap,pR=new WeakMap,MQ=new WeakMap,LQ=new WeakMap,UB=new WeakMap,qB=new WeakMap,lT=new WeakMap,PQ=new WeakMap,c4e=new WeakMap,d4e=new WeakMap,dg=new WeakSet,aW=function(){const t=me(this,Lc).subarray(4,6),n=me(this,Lc).subarray(16,18),[r,a,i,l]=me(this,__);return[(me(this,mR)+(t[0]-n[0])/2-r)/i,(me(this,pR)+(t[1]-n[1])/2-a)/l,(me(this,mR)+(n[0]-t[0])/2-r)/i,(me(this,pR)+(n[1]-t[1])/2-a)/l]},L9t=function(){const[t,n,r,a]=me(this,__),[i,l,o,c]=Kt(this,dg,aW).call(this);return`M${(me(this,Lc)[2]-t)/r} ${(me(this,Lc)[3]-n)/a} L${(me(this,Lc)[4]-t)/r} ${(me(this,Lc)[5]-n)/a} L${i} ${l} L${o} ${c} L${(me(this,Lc)[16]-t)/r} ${(me(this,Lc)[17]-n)/a} L${(me(this,Lc)[14]-t)/r} ${(me(this,Lc)[15]-n)/a} Z`},P9t=function(t){const n=me(this,q2);t.push(`L${n[4]} ${n[5]} Z`)},I9t=function(t){const[n,r,a,i]=me(this,__),l=me(this,Lc).subarray(4,6),o=me(this,Lc).subarray(16,18),[c,d,u,h]=Kt(this,dg,aW).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}`)},R9t=function(t){const n=me(this,Lc),[r,a,i,l]=me(this,__),[o,c,d,u]=Kt(this,dg,aW).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,me(this,__),me(this,UB),me(this,BB),me(this,$B))},D9t=function(t,n){const r=me(this,q2);return t.set([NaN,NaN,NaN,NaN,r[4],r[5]],n),n+=6},O9t=function(t,n){const r=me(this,Lc).subarray(4,6),a=me(this,Lc).subarray(16,18),[i,l,o,c]=me(this,__),[d,u,h,m]=Kt(this,dg,aW).call(this);return t.set([NaN,NaN,NaN,NaN,(r[0]-i)/o,(r[1]-l)/c,NaN,NaN,NaN,NaN,d,u,NaN,NaN,NaN,NaN,h,m,NaN,NaN,NaN,NaN,(a[0]-i)/o,(a[1]-l)/c],n),n+=24},rs(_4,PQ,8),rs(_4,c4e,2),rs(_4,d4e,me(_4,PQ)+me(_4,c4e));let kSe=_4;var VB,fR,V4,IQ,w_,RQ,$f,ub,iW,oW,z9t;class F9t extends M9t{constructor(n,r,a,i,l,o){super();rs(this,ub);rs(this,VB);rs(this,fR,null);rs(this,V4);rs(this,IQ);rs(this,w_);rs(this,RQ);rs(this,$f);Ot(this,$f,n),Ot(this,w_,r),Ot(this,VB,a),Ot(this,RQ,i),Ot(this,V4,l),Ot(this,IQ,o),Kt(this,ub,z9t).call(this,o);const{x:c,y:d,width:u,height:h}=me(this,fR);for(let m=0,p=n.length;mn[0]-r[0]||n[1]-r[1]||n[2]-r[2]);const t=[];for(const n of me(this,cT))n[3]?(t.push(...Kt(this,u1,Yze).call(this,n)),Kt(this,u1,$9t).call(this,n)):(Kt(this,u1,U9t).call(this,n),t.push(...Kt(this,u1,Yze).call(this,n)));return Kt(this,u1,B9t).call(this,t)}}DQ=new WeakMap,cT=new WeakMap,V2=new WeakMap,u1=new WeakSet,B9t=function(t){const n=[],r=new Set;for(const l of t){const[o,c,d]=l;n.push([o,c,l],[o,d,l])}n.sort((l,o)=>l[1]-o[1]||l[0]-o[0]);for(let l=0,o=n.length;l0;){const l=r.values().next().value;let[o,c,d,u,h]=l;r.delete(l);let m=o,p=c;for(i=[o,d],a.push(i);;){let x;if(r.has(u))x=u;else if(r.has(h))x=h;else break;r.delete(x),[o,c,d,u,h]=x,m!==o&&(i.push(m,p,o,p===c?c:d),m=o),p=p===c?d:c}i.push(m,p)}return new WNn(a,me(this,DQ))},m2e=function(t){const n=me(this,V2);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]=me(this,V2)[a];if(i!==t)break;if(i===t&&l===n){me(this,V2).splice(a,1);return}}},Yze=function(t){const[n,r,a]=t,i=[[n,r,a]],l=Kt(this,u1,m2e).call(this,a);for(let o=0;o=c){if(p>d)i[u][1]=d;else{if(h===1)return[];i.splice(u,1),u--,h--}continue}i[u][2]=c,p>d&&i.push([n,d,p])}}}return i};var OQ,HB;class WNn extends M9t{constructor(n,r){super();rs(this,OQ);rs(this,HB);Ot(this,HB,n),Ot(this,OQ,r)}toSVGPath(){const n=[];for(const r of me(this,HB)){let[a,i]=r;n.push(`M${a} ${i}`);for(let l=2;l-1?(Ot(this,X1,!0),Kt(this,Zl,p2e).call(this,n),Kt(this,Zl,zI).call(this)):me(this,H4)&&(Ot(this,YB,n.anchorNode),Ot(this,UQ,n.anchorOffset),Ot(this,qQ,n.focusNode),Ot(this,VQ,n.focusOffset),Kt(this,Zl,eBe).call(this),Kt(this,Zl,zI).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const n=au.prototype;return md(this,"_keyboardManager",new fee([[["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:me(this,X1)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:me(this,ej),methodOfCreation:me(this,HQ)}}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;qu.initialize(n,r),au._defaultColor||(au._defaultColor=((a=r.highlightColors)==null?void 0:a.values().next().value)||"#fff066")}static updateDefaultParams(n,r){switch(n){case Ll.HIGHLIGHT_DEFAULT_COLOR:au._defaultColor=r;break;case Ll.HIGHLIGHT_THICKNESS:au._defaultThickness=r;break}}translateInPage(n,r){}get toolbarPosition(){return me(this,XB)}updateParams(n,r){switch(n){case Ll.HIGHLIGHT_COLOR:Kt(this,Zl,V9t).call(this,r);break;case Ll.HIGHLIGHT_THICKNESS:Kt(this,Zl,H9t).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[Ll.HIGHLIGHT_DEFAULT_COLOR,au._defaultColor],[Ll.HIGHLIGHT_THICKNESS,au._defaultThickness]]}get propertiesToUpdate(){return[[Ll.HIGHLIGHT_COLOR,this.color||au._defaultColor],[Ll.HIGHLIGHT_THICKNESS,me(this,ej)||au._defaultThickness],[Ll.HIGHLIGHT_FREE,me(this,X1)]]}async addEditToolbar(){const n=await super.addEditToolbar();return n?(this._uiManager.highlightColors&&(Ot(this,ZB,new SSe({editor:this})),n.addColorPicker(me(this,ZB))),n):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(Kt(this,Zl,lW).call(this))}getBaseTranslation(){return[0,0]}getRect(n,r){return super.getRect(n,r,Kt(this,Zl,lW).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){Kt(this,Zl,tBe).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(Kt(this,Zl,zI).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(n){var a;let r=!1;this.parent&&!n?Kt(this,Zl,tBe).call(this):n&&(Kt(this,Zl,zI).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;me(this,X1)?(n=(n-this.rotation+360)%360,a=Kt(i=au,fj,V7).call(i,me(this,W2).box,n)):a=Kt(l=au,fj,V7).call(l,this,n),r.rotate(me(this,zy),n),r.rotate(me(this,Zx),n),r.updateBox(me(this,zy),a),r.updateBox(me(this,Zx),Kt(o=au,fj,V7).call(o,me(this,Jw).box,n))}render(){if(this.div)return this.div;const n=super.render();me(this,QB)&&(n.setAttribute("aria-label",me(this,QB)),n.setAttribute("role","mark")),me(this,X1)?n.classList.add("free"):this.div.addEventListener("keydown",Kt(this,Zl,W9t).bind(this),{signal:this._uiManager._signal});const r=Ot(this,yR,document.createElement("div"));n.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=me(this,gR);const[a,i]=this.parentDimensions;return this.setDims(this.width*a,this.height*i),jSe(this,me(this,yR),["pointerover","pointerleave"]),this.enableEditing(),n}pointerover(){this.isSelected||this.parent.drawLayer.addClass(me(this,Zx),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(me(this,Zx),"hovered")}_moveCaret(n){switch(this.parent.unselect(this),n){case 0:case 2:Kt(this,Zl,f2e).call(this,!0);break;case 1:case 3:Kt(this,Zl,f2e).call(this,!1);break}}select(){var n,r;super.select(),me(this,Zx)&&((n=this.parent)==null||n.drawLayer.removeClass(me(this,Zx),"hovered"),(r=this.parent)==null||r.drawLayer.addClass(me(this,Zx),"selected"))}unselect(){var n;super.unselect(),me(this,Zx)&&((n=this.parent)==null||n.drawLayer.removeClass(me(this,Zx),"selected"),me(this,X1)||Kt(this,Zl,f2e).call(this,!1))}get _mustFixPosition(){return!me(this,X1)}show(n=this._isVisible){super.show(n),this.parent&&(this.parent.drawLayer.show(me(this,zy),n),this.parent.drawLayer.show(me(this,Zx),n))}static startHighlighting(n,r,{target:a,x:i,y:l}){const{x:o,y:c,width:d,height:u}=a.getBoundingClientRect(),h=new AbortController,m=n.combinedSignal(h),p=y=>{y.preventDefault(),y.stopPropagation()},x=y=>{h.abort(),Kt(this,fj,X9t).call(this,n,y)};window.addEventListener("blur",x,{signal:m}),window.addEventListener("pointerup",x,{signal:m}),window.addEventListener("pointerdown",p,{capture:!0,passive:!1,signal:m}),window.addEventListener("contextmenu",qj,{signal:m}),a.addEventListener("pointermove",Kt(this,fj,Z9t).bind(this,n),{signal:m}),this._freeHighlight=new Zze({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,g,b,v;let i=null;if(n instanceof j9t){const{data:{quadPoints:k,rect:C,rotation:T,id:M,color:P,opacity:L,popupRef:I},parent:{page:{pageNumber:O}}}=n;i=n={annotationType:rc.HIGHLIGHT,color:Array.from(P),opacity:L,quadPoints:k,boxes:null,pageIndex:O-1,rect:C.slice(0),rotation:T,id:M,deleted:!1,popupRef:I}}else if(n instanceof YKe){const{data:{inkLists:k,rect:C,rotation:T,id:M,color:P,borderStyle:{rawWidth:L},popupRef:I},parent:{page:{pageNumber:O}}}=n;i=n={annotationType:rc.HIGHLIGHT,color:Array.from(P),thickness:L,inkLists:k,boxes:null,pageIndex:O-1,rect:C.slice(0),rotation:T,id:M,deleted:!1,popupRef:I}}const{color:l,quadPoints:o,inkLists:c,opacity:d}=n,u=await super.deserialize(n,r,a);u.color=vo.makeHexColor(...l),Ot(u,G4,d||1),c&&Ot(u,ej,n.thickness),u.annotationElementId=n.id||null,u._initialData=i;const[h,m]=u.pageDimensions,[p,x]=u.pageTranslation;if(o){const k=Ot(u,H4,[]);for(let C=0;C=0)Ot(this,zy,r),Ot(this,gR,a),this.parent.drawLayer.finalizeLine(r,n),Ot(this,Zx,this.parent.drawLayer.drawOutline(me(this,Jw)));else if(this.parent){const p=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(me(this,zy),n),this.parent.drawLayer.updateBox(me(this,zy),Kt(h=au,fj,V7).call(h,me(this,W2).box,(p-this.rotation+360)%360)),this.parent.drawLayer.updateLine(me(this,Zx),me(this,Jw)),this.parent.drawLayer.updateBox(me(this,Zx),Kt(m=au,fj,V7).call(m,me(this,Jw).box,p))}const{x:l,y:o,width:c,height:d}=n.box;switch(this.rotation){case 0:this.x=l,this.y=o,this.width=c,this.height=d;break;case 90:{const[p,x]=this.parentDimensions;this.x=o,this.y=1-l,this.width=c*x/p,this.height=d*p/x;break}case 180:this.x=1-l,this.y=1-o,this.width=c,this.height=d;break;case 270:{const[p,x]=this.parentDimensions;this.x=1-o,this.y=l,this.width=c*x/p,this.height=d*p/x;break}}const{lastPoint:u}=me(this,Jw).box;Ot(this,XB,[(u[0]-l)/c,(u[1]-o)/d])},V9t=function(n){const r=(l,o)=>{var c,d,u;this.color=l,(c=this.parent)==null||c.drawLayer.changeColor(me(this,zy),l),(d=me(this,ZB))==null||d.updateColor(l),Ot(this,G4,o),(u=this.parent)==null||u.drawLayer.changeOpacity(me(this,zy),o)},a=this.color,i=me(this,G4);this.addCommands({cmd:r.bind(this,n,au._defaultOpacity),undo:r.bind(this,a,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Ll.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(n)},!0)},H9t=function(n){const r=me(this,ej),a=i=>{Ot(this,ej,i),Kt(this,Zl,G9t).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:Ll.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:n},!0)},G9t=function(n){if(!me(this,X1))return;Kt(this,Zl,p2e).call(this,{highlightOutlines:me(this,W2).getNewOutline(n/2)}),this.fixAndSetPosition();const[r,a]=this.parentDimensions;this.setDims(this.width*r,this.height*a)},tBe=function(){me(this,zy)===null||!this.parent||(this.parent.drawLayer.remove(me(this,zy)),Ot(this,zy,null),this.parent.drawLayer.remove(me(this,Zx)),Ot(this,Zx,null))},zI=function(n=this.parent){me(this,zy)===null&&({id:Ig(this,zy)._,clipPathId:Ig(this,gR)._}=n.drawLayer.draw(me(this,W2),this.color,me(this,G4)),Ot(this,Zx,n.drawLayer.drawOutline(me(this,Jw))),me(this,yR)&&(me(this,yR).style.clipPath=me(this,gR)))},fj=new WeakSet,V7=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}},W9t=function(n){au._keyboardManager.exec(this,n)},f2e=function(n){if(!me(this,YB))return;const r=window.getSelection();n?r.setPosition(me(this,YB),me(this,UQ)):r.setPosition(me(this,qQ),me(this,VQ))},lW=function(){return me(this,X1)?this.rotation:0},K9t=function(){if(me(this,X1))return null;const[n,r]=this.pageDimensions,[a,i]=this.pageTranslation,l=me(this,H4),o=new Float32Array(l.length*8);let c=0;for(const{x:d,y:u,width:h,height:m}of l){const p=d*n+a,x=(1-u-m)*r+i;o[c]=o[c+4]=p,o[c+1]=o[c+3]=x,o[c+2]=o[c+6]=p+h*n,o[c+5]=o[c+7]=x+m*r,c+=8}return o},Y9t=function(n){return me(this,W2).serialize(n,Kt(this,Zl,lW).call(this))},Z9t=function(n,r){this._freeHighlight.add(r)&&n.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},X9t=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=""},Q9t=function(n){const{color:r}=this._initialData;return n.color.some((a,i)=>a!==r[i])},rs(au,fj),Ar(au,"_defaultColor",null),Ar(au,"_defaultOpacity",1),Ar(au,"_defaultThickness",12),Ar(au,"_type","highlight"),Ar(au,"_editorType",rc.HIGHLIGHT),Ar(au,"_freeHighlightId",-1),Ar(au,"_freeHighlight",null),Ar(au,"_freeHighlightClipId","");let CSe=au;var vR,bR,r5,W4,tj,_R,wR,jR,K4,JB,NR,kR,uT,ci,J9t,ezt,tzt,szt,nBe,nzt,rBe,rzt,azt,izt,ozt,lzt,BI,aBe,iBe,oBe,x2e,g2e,H7,lBe,y2e,Y3,czt,cBe,dzt,uzt,dBe,v2e,cW;const vp=class vp extends qu{constructor(n){super({...n,name:"inkEditor"});rs(this,ci);rs(this,vR,0);rs(this,bR,0);rs(this,r5,null);rs(this,W4,new Path2D);rs(this,tj,!1);rs(this,_R,null);rs(this,wR,!1);rs(this,jR,!1);rs(this,K4,null);rs(this,JB,null);rs(this,NR,0);rs(this,kR,0);rs(this,uT,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){qu.initialize(n,r)}static updateDefaultParams(n,r){switch(n){case Ll.INK_THICKNESS:vp._defaultThickness=r;break;case Ll.INK_COLOR:vp._defaultColor=r;break;case Ll.INK_OPACITY:vp._defaultOpacity=r/100;break}}updateParams(n,r){switch(n){case Ll.INK_THICKNESS:Kt(this,ci,J9t).call(this,r);break;case Ll.INK_COLOR:Kt(this,ci,ezt).call(this,r);break;case Ll.INK_OPACITY:Kt(this,ci,tzt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[Ll.INK_THICKNESS,vp._defaultThickness],[Ll.INK_COLOR,vp._defaultColor||qu._defaultLineColor],[Ll.INK_OPACITY,Math.round(vp._defaultOpacity*100)]]}get propertiesToUpdate(){return[[Ll.INK_THICKNESS,this.thickness||vp._defaultThickness],[Ll.INK_COLOR,this.color||vp._defaultColor||qu._defaultLineColor],[Ll.INK_OPACITY,Math.round(100*(this.opacity??vp._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(Kt(this,ci,x2e).call(this),Kt(this,ci,g2e).call(this)),this.isAttachedToDOM||(this.parent.add(this),Kt(this,ci,H7).call(this)),Kt(this,ci,cW).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,me(this,r5)&&(clearTimeout(me(this,r5)),Ot(this,r5,null)),(n=me(this,K4))==null||n.disconnect(),Ot(this,K4,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(){me(this,tj)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,Kt(this,ci,aBe).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),Kt(this,ci,iBe).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){me(this,tj)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),Ot(this,tj,!0),this.div.classList.add("disabled"),Kt(this,ci,cW).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()||me(this,tj)||(this.setInForeground(),n.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),Kt(this,ci,nzt).call(this,n.offsetX,n.offsetY))}canvasPointermove(n){n.preventDefault(),Kt(this,ci,rBe).call(this,n.offsetX,n.offsetY)}canvasPointerup(n){n.preventDefault(),Kt(this,ci,oBe).call(this,n)}canvasPointerleave(n){Kt(this,ci,oBe).call(this,n)}get isResizable(){return!this.isEmpty()&&me(this,tj)}render(){if(this.div)return this.div;let n,r;this.width&&(n=this.x,r=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[a,i,l,o]=Kt(this,ci,szt).call(this);if(this.setAt(a,i,0,0),this.setDims(l,o),Kt(this,ci,x2e).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),Ot(this,jR,!0),Kt(this,ci,H7).call(this),this.setDims(this.width*c,this.height*d),Kt(this,ci,BI).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return Kt(this,ci,g2e).call(this),this.div}setDimensions(n,r){const a=Math.round(n),i=Math.round(r);if(me(this,NR)===a&&me(this,kR)===i)return;Ot(this,NR,a),Ot(this,kR,i),this.canvas.style.visibility="hidden";const[l,o]=this.parentDimensions;this.width=n/l,this.height=r/o,this.fixAndSetPosition(),me(this,tj)&&Kt(this,ci,lBe).call(this,n,r),Kt(this,ci,H7).call(this),Kt(this,ci,BI).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(n,r,a){var g,b,v;if(n instanceof YKe)return null;const i=await super.deserialize(n,r,a);i.thickness=n.thickness,i.color=vo.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;Ot(i,tj,!0),Ot(i,NR,Math.round(c)),Ot(i,kR,Math.round(d));const{paths:m,rect:p,rotation:x}=n;for(let{bezier:k}of m){k=Kt(g=vp,Y3,dzt).call(g,k,p,x);const C=[];i.paths.push(C);let T=u*(k[0]-h),M=u*(k[1]-h);for(let L=2,I=k.length;L{this.thickness=i,Kt(this,ci,cW).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:Ll.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},ezt=function(n){const r=i=>{this.color=i,Kt(this,ci,BI).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:Ll.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},tzt=function(n){const r=i=>{this.opacity=i,Kt(this,ci,BI).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:Ll.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},szt=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]}},nBe=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}${x2n(a)}`},nzt=function(n,r){this.canvas.addEventListener("contextmenu",qj,{signal:this._uiManager._signal}),Kt(this,ci,iBe).call(this),Ot(this,_R,new AbortController);const a=this._uiManager.combinedSignal(me(this,_R));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,me(this,jR)||(Ot(this,jR,!0),Kt(this,ci,H7).call(this),this.thickness||(this.thickness=vp._defaultThickness),this.color||(this.color=vp._defaultColor||qu._defaultLineColor),this.opacity??(this.opacity=vp._defaultOpacity)),this.currentPath.push([n,r]),Ot(this,wR,!1),Kt(this,ci,nBe).call(this),Ot(this,uT,()=>{Kt(this,ci,izt).call(this),me(this,uT)&&window.requestAnimationFrame(me(this,uT))}),window.requestAnimationFrame(me(this,uT))},rBe=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=me(this,W4);if(l.push([n,r]),Ot(this,wR,!0),l.length<=2){o.moveTo(...l[0]),o.lineTo(n,r);return}l.length===3&&(Ot(this,W4,o=new Path2D),o.moveTo(...l[0])),Kt(this,ci,ozt).call(this,o,...l.at(-3),...l.at(-2),n,r)},rzt=function(){if(this.currentPath.length===0)return;const n=this.currentPath.at(-1);me(this,W4).lineTo(...n)},azt=function(n,r){Ot(this,uT,null),n=Math.min(Math.max(n,0),this.canvas.width),r=Math.min(Math.max(r,0),this.canvas.height),Kt(this,ci,rBe).call(this,n,r),Kt(this,ci,rzt).call(this);let a;if(this.currentPath.length!==1)a=Kt(this,ci,lzt).call(this);else{const d=[n,r];a=[[d,d.slice(),d.slice(),d]]}const i=me(this,W4),l=this.currentPath;this.currentPath=[],Ot(this,W4,new Path2D);const o=()=>{this.allRawPaths.push(l),this.paths.push(a),this.bezierPath2D.push(i),this._uiManager.rebuild(this)},c=()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(Kt(this,ci,x2e).call(this),Kt(this,ci,g2e).call(this)),Kt(this,ci,cW).call(this))};this.addCommands({cmd:o,undo:c,mustExec:!0})},izt=function(){if(!me(this,wR))return;Ot(this,wR,!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(me(this,W4)),l.restore()},ozt=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)},lzt=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{Ot(this,r5,null),this.canvas.removeEventListener("contextmenu",qj)},10)),Kt(this,ci,azt).call(this,n.offsetX,n.offsetY),this.addToAnnotationStorage(),this.setInBackground()},x2e=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")},g2e=function(){Ot(this,K4,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&this.setDimensions(r.width,r.height)})),me(this,K4).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=me(this,K4))==null||n.disconnect(),Ot(this,K4,null)},{once:!0})},H7=function(){if(!me(this,jR))return;const[n,r]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*n),this.canvas.height=Math.ceil(this.height*r),Kt(this,ci,y2e).call(this)},lBe=function(n,r){const a=Kt(this,ci,v2e).call(this),i=(n-a)/me(this,bR),l=(r-a)/me(this,vR);this.scaleFactor=Math.min(i,l)},y2e=function(){const n=Kt(this,ci,v2e).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+n,this.translationY*this.scaleFactor+n)},Y3=new WeakSet,czt=function(n){const r=new Path2D;for(let a=0,i=n.length;a`image/${r}`))}static get supportedTypesStr(){return md(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(n){return this.supportedTypes.includes(n)}static paste(n,r){r.pasteEditor(rc.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;me(this,z0)&&(Ot(this,_p,null),this._uiManager.imageManager.deleteId(me(this,z0)),(n=me(this,a5))==null||n.remove(),Ot(this,a5,null),(r=me(this,Z4))==null||r.disconnect(),Ot(this,Z4,null),me(this,i5)&&(clearTimeout(me(this,i5)),Ot(this,i5,null))),super.remove()}rebuild(){if(!this.parent){me(this,z0)&&Kt(this,ed,b2e).call(this);return}super.rebuild(),this.div!==null&&(me(this,z0)&&me(this,a5)===null&&Kt(this,ed,b2e).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(me(this,hT)||me(this,_p)||me(this,Y4)||me(this,mT)||me(this,z0))}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(),me(this,_p)?Kt(this,ed,hBe).call(this):Kt(this,ed,b2e).call(this),this.width&&!this.annotationElementId){const[a,i]=this.parentDimensions;this.setAt(n*a,r*i,this.width*a,this.height*i)}return this.div}copyCanvas(n,r,a=!1){var p;n||(n=224);const{width:i,height:l}=me(this,_p),o=new lze;let c=me(this,_p),d=i,u=l,h=null;if(r){if(i>r||l>r){const L=Math.min(r/i,r/l);d=Math.floor(i*L),u=Math.floor(l*L)}h=document.createElement("canvas");const x=h.width=Math.ceil(d*o.sx),y=h.height=Math.ceil(u*o.sy);me(this,j_)||(c=Kt(this,ed,_2e).call(this,x,y));const g=h.getContext("2d");g.filter=this._uiManager.hcmFilter;let b="white",v="#cfcfd8";this._uiManager.hcmFilter!=="none"?v="black":(p=window.matchMedia)!=null&&p.call(window,"(prefers-color-scheme: dark)").matches&&(b="#8f8f9d",v="#42414d");const k=15,C=k*o.sx,T=k*o.sy,M=new OffscreenCanvas(C*2,T*2),P=M.getContext("2d");P.fillStyle=b,P.fillRect(0,0,C*2,T*2),P.fillStyle=v,P.fillRect(0,0,C,T),P.fillRect(C,T,C,T),g.fillStyle=g.createPattern(M,"repeat"),g.fillRect(0,0,x,y),g.drawImage(c,0,0,c.width,c.height,0,0,x,y)}let m=null;if(a){let x,y;if(o.symmetric&&c.widthn||l>n){const v=Math.min(n/i,n/l);x=Math.floor(i*v),y=Math.floor(l*v),me(this,j_)||(c=Kt(this,ed,_2e).call(this,x,y))}const b=new OffscreenCanvas(x,y).getContext("2d",{willReadFrequently:!0});b.drawImage(c,0,0,c.width,c.height,0,0,x,y),m={width:x,height:y,data:b.getImageData(0,0,x,y).data}}return{canvas:h,width:d,height:u,imageData:m}}getImageForAltText(){return me(this,a5)}static async deserialize(n,r,a){var y;let i=null;if(n instanceof N9t){const{data:{rect:g,rotation:b,id:v,structParent:k,popupRef:C},container:T,parent:{page:{pageNumber:M}}}=n,P=T.querySelector("canvas"),L=a.imageManager.getFromCanvas(T.id,P);P.remove();const I=((y=await r._structTree.getAriaAttributes(`${FKe}${v}`))==null?void 0:y.get("aria-label"))||"";i=n={annotationType:rc.STAMP,bitmapId:L.id,bitmap:L.bitmap,pageIndex:M-1,rect:g.slice(0),rotation:b,id:v,deleted:!1,accessibilityData:{decorative:!1,altText:I},isSvg:!1,structParent:k,popupRef:C}}const l=await super.deserialize(n,r,a),{rect:o,bitmap:c,bitmapUrl:d,bitmapId:u,isSvg:h,accessibilityData:m}=n;u&&a.imageManager.isValidId(u)?(Ot(l,z0,u),c&&Ot(l,_p,c)):Ot(l,Y4,d),Ot(l,j_,h);const[p,x]=l.pageDimensions;return l.width=(o[2]-o[0])/p,l.height=(o[3]-o[1])/x,l.annotationElementId=n.id||null,m&&(l.altTextData=m),l._initialData=i,Ot(l,t$,!!i),l}serialize(n=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const a={annotationType:rc.STAMP,bitmapId:me(this,z0),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:me(this,j_),structTreeParentId:this._structTreeParentId};if(n)return a.bitmapUrl=Kt(this,ed,w2e).call(this,!0),a.accessibilityData=this.serializeAltText(!0),a;const{decorative:i,altText:l}=this.serializeAltText(!1);if(!i&&l&&(a.accessibilityData={type:"Figure",alt:l}),this.annotationElementId){const c=Kt(this,ed,pzt).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=me(this,j_)?(a.rect[2]-a.rect[0])*(a.rect[3]-a.rect[1]):null;if(!r.stamps.has(me(this,z0)))r.stamps.set(me(this,z0),{area:o,serialized:a}),a.bitmap=Kt(this,ed,w2e).call(this,!1);else if(me(this,j_)){const c=r.stamps.get(me(this,z0));o>c.area&&(c.area=o,c.serialized.bitmap.close(),c.serialized.bitmap=Kt(this,ed,w2e).call(this,!1))}return a}renderAnnotationElement(n){return n.updateEdited({rect:this.getRect(0,0)}),null}};_p=new WeakMap,z0=new WeakMap,hT=new WeakMap,Y4=new WeakMap,mT=new WeakMap,e$=new WeakMap,a5=new WeakMap,Z4=new WeakMap,i5=new WeakMap,j_=new WeakMap,t$=new WeakMap,ed=new WeakSet,dW=function(n,r=!1){if(!n){this.remove();return}Ot(this,_p,n.bitmap),r||(Ot(this,z0,n.id),Ot(this,j_,n.isSvg)),n.file&&Ot(this,e$,n.file.name),Kt(this,ed,hBe).call(this)},uW=function(){if(Ot(this,hT,null),this._uiManager.enableWaiting(!1),!!me(this,a5)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&me(this,_p)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&me(this,_p)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},b2e=function(){if(me(this,z0)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(me(this,z0)).then(a=>Kt(this,ed,dW).call(this,a,!0)).finally(()=>Kt(this,ed,uW).call(this));return}if(me(this,Y4)){const a=me(this,Y4);Ot(this,Y4,null),this._uiManager.enableWaiting(!0),Ot(this,hT,this._uiManager.imageManager.getFromUrl(a).then(i=>Kt(this,ed,dW).call(this,i)).finally(()=>Kt(this,ed,uW).call(this)));return}if(me(this,mT)){const a=me(this,mT);Ot(this,mT,null),this._uiManager.enableWaiting(!0),Ot(this,hT,this._uiManager.imageManager.getFromFile(a).then(i=>Kt(this,ed,dW).call(this,i)).finally(()=>Kt(this,ed,uW).call(this)));return}const n=document.createElement("input");n.type="file",n.accept=_Y.supportedTypesStr;const r=this._uiManager._signal;Ot(this,hT,new Promise(a=>{n.addEventListener("change",async()=>{if(!n.files||n.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(n.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),Kt(this,ed,dW).call(this,i)}a()},{signal:r}),n.addEventListener("cancel",()=>{this.remove(),a()},{signal:r})}).finally(()=>Kt(this,ed,uW).call(this))),n.click()},hBe=function(){const{div:n}=this;let{width:r,height:a}=me(this,_p);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=Ot(this,a5,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(n.hidden=!1),Kt(this,ed,mBe).call(this,r,a),Kt(this,ed,mzt).call(this),me(this,t$)||(this.parent.addUndoableEditor(this),Ot(this,t$,!0)),this._reportTelemetry({action:"inserted_image"}),me(this,e$)&&u.setAttribute("aria-label",me(this,e$))},hzt=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,me(this,i5)!==null&&clearTimeout(me(this,i5)),Ot(this,i5,setTimeout(()=>{Ot(this,i5,null),Kt(this,ed,mBe).call(this,n,r)},200))},_2e=function(n,r){const{width:a,height:i}=me(this,_p);let l=a,o=i,c=me(this,_p);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},mBe=function(n,r){const a=new lze,i=Math.ceil(n*a.sx),l=Math.ceil(r*a.sy),o=me(this,a5);if(!o||o.width===i&&o.height===l)return;o.width=i,o.height=l;const c=me(this,j_)?me(this,_p):Kt(this,ed,_2e).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)},w2e=function(n){if(n){if(me(this,j_)){const i=this._uiManager.imageManager.getSvgUrl(me(this,z0));if(i)return i}const r=document.createElement("canvas");return{width:r.width,height:r.height}=me(this,_p),r.getContext("2d").drawImage(me(this,_p),0,0),r.toDataURL()}if(me(this,j_)){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(me(this,_p),0,0,me(this,_p).width,me(this,_p).height,0,0,i,l),o.transferToImageBitmap()}return structuredClone(me(this,_p))},mzt=function(){this._uiManager._signal&&(Ot(this,Z4,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&Kt(this,ed,hzt).call(this,r.width,r.height)})),me(this,Z4).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=me(this,Z4))==null||n.disconnect(),Ot(this,Z4,null)},{once:!0}))},pzt=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}},Ar(_Y,"_type","stamp"),Ar(_Y,"_editorType",rc.STAMP);let uBe=_Y;var SR,s$,o5,pT,X4,N_,fT,n$,r$,By,Q4,Fo,xT,cy,fzt,fBe,xBe,gBe,j2e;const E2=class E2{constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:a,accessibilityManager:i,annotationLayer:l,drawLayer:o,textLayer:c,viewport:d,l10n:u}){rs(this,cy);rs(this,SR);rs(this,s$,!1);rs(this,o5,null);rs(this,pT,null);rs(this,X4,null);rs(this,N_,new Map);rs(this,fT,!1);rs(this,n$,!1);rs(this,r$,!1);rs(this,By,null);rs(this,Q4,null);rs(this,Fo);const h=[...me(E2,xT).values()];if(!E2._initialized){E2._initialized=!0;for(const m of h)m.initialize(u,t)}t.registerEditorTypes(h),Ot(this,Fo,t),this.pageIndex=n,this.div=r,Ot(this,SR,i),Ot(this,o5,l),this.viewport=d,Ot(this,By,c),this.drawLayer=o,this._structTree=a,me(this,Fo).addLayer(this)}get isEmpty(){return me(this,N_).size===0}get isInvisible(){return this.isEmpty&&me(this,Fo).getMode()===rc.NONE}updateToolbar(t){me(this,Fo).updateToolbar(t)}updateMode(t=me(this,Fo).getMode()){switch(Kt(this,cy,j2e).call(this),t){case rc.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case rc.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case rc.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 me(E2,xT).values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(t){var n;return t===((n=me(this,By))==null?void 0:n.div)}addInkEditorIfNeeded(t){if(me(this,Fo).getMode()!==rc.INK)return;if(!t){for(const r of me(this,N_).values())if(r.isEmpty()){r.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){me(this,Fo).setEditingState(t)}addCommands(t){me(this,Fo).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=me(this,o5))==null||n.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const r of me(this,N_).values())r.enableEditing(),r.show(!0),r.annotationElementId&&(me(this,Fo).removeChangedExistingAnnotation(r),t.add(r.annotationElementId));if(!me(this,o5))return;const n=me(this,o5).getEditableAnnotations();for(const r of n){if(r.hide(),me(this,Fo).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;Ot(this,r$,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,n=new Map;for(const i of me(this,N_).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(me(this,o5)){const i=me(this,o5).getEditableAnnotations();for(const l of i){const{id:o}=l.data;if(me(this,Fo).isDeletedAnnotationElement(o))continue;let c=n.get(o);if(c){c.resetAnnotationElement(l),c.show(!1),l.show();continue}c=t.get(o),c&&(me(this,Fo).addChangedExistingAnnotation(c),c.renderAnnotationElement(l)&&c.show(!1)),l.show()}}Kt(this,cy,j2e).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const i of me(E2,xT).values())r.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),Ot(this,r$,!1)}getEditableAnnotation(t){var n;return((n=me(this,o5))==null?void 0:n.getEditableAnnotation(t))||null}setActiveEditor(t){me(this,Fo).getActive()!==t&&me(this,Fo).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=me(this,By))!=null&&t.div&&!me(this,Q4)){Ot(this,Q4,new AbortController);const n=me(this,Fo).combinedSignal(me(this,Q4));me(this,By).div.addEventListener("pointerdown",Kt(this,cy,fzt).bind(this),{signal:n}),me(this,By).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=me(this,By))!=null&&t.div&&me(this,Q4)&&(me(this,Q4).abort(),Ot(this,Q4,null),me(this,By).div.classList.remove("highlighting"))}enableClick(){if(me(this,pT))return;Ot(this,pT,new AbortController);const t=me(this,Fo).combinedSignal(me(this,pT));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){var t;(t=me(this,pT))==null||t.abort(),Ot(this,pT,null)}attach(t){me(this,N_).set(t.id,t);const{annotationElementId:n}=t;n&&me(this,Fo).isDeletedAnnotationElement(n)&&me(this,Fo).removeDeletedAnnotationElement(t)}detach(t){var n;me(this,N_).delete(t.id),(n=me(this,SR))==null||n.removePointerInTextLayer(t.contentDiv),!me(this,r$)&&t.annotationElementId&&me(this,Fo).addDeletedAnnotationElement(t)}remove(t){this.detach(t),me(this,Fo).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,me(this,n$)||this.addInkEditorIfNeeded(!1)}changeParent(t){var n;t.parent!==this&&(t.parent&&t.annotationElementId&&(me(this,Fo).addDeletedAnnotationElement(t.annotationElementId),qu.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),me(this,Fo).addEditor(t),this.attach(t),!t.isAttachedToDOM){const n=t.render();this.div.append(n),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),me(this,Fo).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var r;if(!t.isAttachedToDOM)return;const{activeElement:n}=document;t.div.contains(n)&&!me(this,X4)&&(t._focusEventsAllowed=!1,Ot(this,X4,setTimeout(()=>{Ot(this,X4,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:me(this,Fo)._signal}),n.focus())},0))),t._structTreeParentId=(r=me(this,SR))==null?void 0:r.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||(t.parent=this),t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const n=()=>t._uiManager.rebuild(t),r=()=>{t.remove()};this.addCommands({cmd:n,undo:r,mustExec:!1})}getNextId(){return me(this,Fo).getId()}combinedSignal(t){return me(this,Fo).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=me(this,cy,fBe))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,n){me(this,Fo).updateToolbar(t),me(this,Fo).updateMode(t);const{offsetX:r,offsetY:a}=Kt(this,cy,gBe).call(this),i=this.getNextId(),l=Kt(this,cy,xBe).call(this,{parent:this,id:i,x:r,y:a,uiManager:me(this,Fo),isCentered:!0,...n});l&&this.add(l)}async deserialize(t){var n;return await((n=me(E2,xT).get(t.annotationType??t.annotationEditorType))==null?void 0:n.deserialize(t,this,me(this,Fo)))||null}createAndAddNewEditor(t,n,r={}){const a=this.getNextId(),i=Kt(this,cy,xBe).call(this,{parent:this,id:a,x:t.offsetX,y:t.offsetY,uiManager:me(this,Fo),isCentered:n,...r});return i&&this.add(i),i}addNewEditor(){this.createAndAddNewEditor(Kt(this,cy,gBe).call(this),!0)}setSelected(t){me(this,Fo).setSelected(t)}toggleSelected(t){me(this,Fo).toggleSelected(t)}unselect(t){me(this,Fo).unselect(t)}pointerup(t){const{isMac:n}=c1.platform;if(!(t.button!==0||t.ctrlKey&&n)&&t.target===this.div&&me(this,fT)){if(Ot(this,fT,!1),!me(this,s$)){Ot(this,s$,!0);return}if(me(this,Fo).getMode()===rc.STAMP){me(this,Fo).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(me(this,Fo).getMode()===rc.HIGHLIGHT&&this.enableTextSelection(),me(this,fT)){Ot(this,fT,!1);return}const{isMac:n}=c1.platform;if(t.button!==0||t.ctrlKey&&n||t.target!==this.div)return;Ot(this,fT,!0);const r=me(this,Fo).getActive();Ot(this,s$,!r||r.isEmpty())}findNewParent(t,n,r){const a=me(this,Fo).findParent(n,r);return a===null||a===this?!1:(a.changeParent(t),!0)}destroy(){var t,n;((t=me(this,Fo).getActive())==null?void 0:t.parent)===this&&(me(this,Fo).commitOrRemove(),me(this,Fo).setActiveEditor(null)),me(this,X4)&&(clearTimeout(me(this,X4)),Ot(this,X4,null));for(const r of me(this,N_).values())(n=me(this,SR))==null||n.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,me(this,N_).clear(),me(this,Fo).removeLayer(this)}render({viewport:t}){this.viewport=t,nO(this.div,t);for(const n of me(this,Fo).getEditors(this.pageIndex))this.add(n),n.rebuild();this.updateMode()}update({viewport:t}){me(this,Fo).commitOrRemove(),Kt(this,cy,j2e).call(this);const n=this.viewport.rotation,r=t.rotation;if(this.viewport=t,nO(this.div,{rotation:r}),n!==r)for(const a of me(this,N_).values())a.rotate(r);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:n}=this.viewport.rawDims;return[t,n]}get scale(){return me(this,Fo).viewParameters.realScale}};SR=new WeakMap,s$=new WeakMap,o5=new WeakMap,pT=new WeakMap,X4=new WeakMap,N_=new WeakMap,fT=new WeakMap,n$=new WeakMap,r$=new WeakMap,By=new WeakMap,Q4=new WeakMap,Fo=new WeakMap,xT=new WeakMap,cy=new WeakSet,fzt=function(t){me(this,Fo).unselectAll();const{target:n}=t;if(n===me(this,By).div||(n.getAttribute("role")==="img"||n.classList.contains("endOfContent"))&&me(this,By).div.contains(n)){const{isMac:r}=c1.platform;if(t.button!==0||t.ctrlKey&&r)return;me(this,Fo).showAllEditors("highlight",!0,!0),me(this,By).div.classList.add("free"),this.toggleDrawing(),CSe.startHighlighting(this,me(this,Fo).direction==="ltr",{target:me(this,By).div,x:t.x,y:t.y}),me(this,By).div.addEventListener("pointerup",()=>{me(this,By).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:me(this,Fo)._signal}),t.preventDefault()}},fBe=function(){return me(E2,xT).get(me(this,Fo).getMode())},xBe=function(t){const n=me(this,cy,fBe);return n?new n.prototype.constructor(t):null},gBe=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}},j2e=function(){Ot(this,n$,!0);for(const t of me(this,N_).values())t.isEmpty()&&t.remove();Ot(this,n$,!1)},Ar(E2,"_initialized",!1),rs(E2,xT,new Map([Wze,sBe,uBe,CSe].map(t=>[t._editorType,t])));let pBe=E2;var l5,GQ,fx,J4,WQ,vBe,cO,bBe,xzt;const D0=class D0{constructor({pageIndex:t}){rs(this,cO);rs(this,l5,null);rs(this,GQ,0);rs(this,fx,new Map);rs(this,J4,new Map);this.pageIndex=t}setParent(t){if(!me(this,l5)){Ot(this,l5,t);return}if(me(this,l5)!==t){if(me(this,fx).size>0)for(const n of me(this,fx).values())n.remove(),t.append(n);Ot(this,l5,t)}}static get _svgFactory(){return md(this,"_svgFactory",new KKe)}draw(t,n,r,a=!1){const i=Ig(this,GQ)._++,l=Kt(this,cO,bBe).call(this,t.box);l.classList.add(...t.classNamesForDrawing);const o=D0._svgFactory.createElement("defs");l.append(o);const c=D0._svgFactory.createElement("path");o.append(c);const d=`path_p${this.pageIndex}_${i}`;c.setAttribute("id",d),c.setAttribute("d",t.toSVGPath()),a&&me(this,J4).set(i,c);const u=Kt(this,cO,xzt).call(this,o,d),h=D0._svgFactory.createElement("use");return l.append(h),l.setAttribute("fill",n),l.setAttribute("fill-opacity",r),h.setAttribute("href",`#${d}`),me(this,fx).set(i,l),{id:i,clipPathId:`url(#${u})`}}drawOutline(t){const n=Ig(this,GQ)._++,r=Kt(this,cO,bBe).call(this,t.box);r.classList.add(...t.classNamesForOutlining);const a=D0._svgFactory.createElement("defs");r.append(a);const i=D0._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=D0._svgFactory.createElement("mask");a.append(u),o=`mask_p${this.pageIndex}_${n}`,u.setAttribute("id",o),u.setAttribute("maskUnits","objectBoundingBox");const h=D0._svgFactory.createElement("rect");u.append(h),h.setAttribute("width","1"),h.setAttribute("height","1"),h.setAttribute("fill","white");const m=D0._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=D0._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"),me(this,fx).set(n,r),n}finalizeLine(t,n){const r=me(this,J4).get(t);me(this,J4).delete(t),this.updateBox(t,n.box),r.setAttribute("d",n.toSVGPath())}updateLine(t,n){me(this,fx).get(t).firstChild.firstChild.setAttribute("d",n.toSVGPath())}updatePath(t,n){me(this,J4).get(t).setAttribute("d",n.toSVGPath())}updateBox(t,n){var r;Kt(r=D0,WQ,vBe).call(r,me(this,fx).get(t),n)}show(t,n){me(this,fx).get(t).classList.toggle("hidden",!n)}rotate(t,n){me(this,fx).get(t).setAttribute("data-main-rotation",n)}changeColor(t,n){me(this,fx).get(t).setAttribute("fill",n)}changeOpacity(t,n){me(this,fx).get(t).setAttribute("fill-opacity",n)}addClass(t,n){me(this,fx).get(t).classList.add(n)}removeClass(t,n){me(this,fx).get(t).classList.remove(n)}getSVGRoot(t){return me(this,fx).get(t)}remove(t){me(this,J4).delete(t),me(this,l5)!==null&&(me(this,fx).get(t).remove(),me(this,fx).delete(t))}destroy(){Ot(this,l5,null);for(const t of me(this,fx).values())t.remove();me(this,fx).clear(),me(this,J4).clear()}};l5=new WeakMap,GQ=new WeakMap,fx=new WeakMap,J4=new WeakMap,WQ=new WeakSet,vBe=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}%`},cO=new WeakSet,bBe=function(t){var r;const n=D0._svgFactory.create(1,1,!0);return me(this,l5).append(n),n.setAttribute("aria-hidden",!0),Kt(r=D0,WQ,vBe).call(r,n,t),n},xzt=function(t,n){const r=D0._svgFactory.createElement("clipPath");t.append(r);const a=`clip_${n}`;r.setAttribute("id",a),r.setAttribute("clipPathUnits","objectBoundingBox");const i=D0._svgFactory.createElement("use");return r.append(i),i.setAttribute("href",`#${n}`),i.classList.add("clip"),a},rs(D0,WQ);let yBe=D0;Ol.AbortException;Ol.AnnotationEditorLayer;Ol.AnnotationEditorParamsType;Ol.AnnotationEditorType;Ol.AnnotationEditorUIManager;Ol.AnnotationLayer;Ol.AnnotationMode;Ol.ColorPicker;Ol.DOMSVGFactory;Ol.DrawLayer;Ol.FeatureTest;var YNn=Ol.GlobalWorkerOptions;Ol.ImageKind;Ol.InvalidPDFException;Ol.MissingPDFException;Ol.OPS;Ol.OutputScale;Ol.PDFDataRangeTransport;Ol.PDFDateString;Ol.PDFWorker;Ol.PasswordResponses;Ol.PermissionFlag;Ol.PixelsPerInch;Ol.RenderingCancelledException;Ol.TextLayer;Ol.UnexpectedResponseException;Ol.Util;Ol.VerbosityLevel;Ol.XfaLayer;Ol.build;Ol.createValidAbsoluteUrl;Ol.fetchData;var ZNn=Ol.getDocument;Ol.getFilenameFromUrl;Ol.getPdfFilenameFromUrl;Ol.getXfaPageViewport;Ol.isDataScheme;Ol.isPdfFile;Ol.noContextMenu;Ol.normalizeUnicode;Ol.setLayerDimensions;Ol.shadow;Ol.version;const XNn="/assets/pdf.worker.min-GB3t0DcA.mjs";YNn.workerSrc=XNn;const QNn=({blob:s,scale:t=1.5})=>{const n=j.useRef(null),[r,a]=j.useState(!1),[i,l]=j.useState(null);return j.useEffect(()=>{let o=!1;const c=n.current;return!s||!c?void 0:((async()=>{a(!0),l(null);try{const u=await s.arrayBuffer(),h=await ZNn({data:u}).promise;if(o)return;c.innerHTML="";for(let m=1;m<=h.numPages;m+=1){const p=await h.getPage(m);if(o)return;const x=p.getViewport({scale:t}),y=document.createElement("canvas");y.width=Math.floor(x.width),y.height=Math.floor(x.height),y.className="mx-auto w-full max-w-[900px] rounded-md border border-border bg-white shadow-sm";const g=y.getContext("2d");g&&(c.appendChild(y),await p.render({canvasContext:g,viewport:x}).promise)}}catch(u){o||l((u==null?void 0:u.message)||"Could not render the preview")}finally{o||a(!1)}})(),()=>{o=!0})},[s,t]),e.jsxs("div",{className:"relative h-full overflow-y-auto bg-muted/40 p-4",children:[r&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/70",children:e.jsx(Wt,{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 gee({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}=Ns(),d=j.useRef(null),[u,h]=j.useState(!1),m=async p=>{if(!(!p||!c)){if(!p.type.startsWith("image/")){re.error("Please choose an image file");return}if(p.size>20*1024*1024){re.error("That photo is larger than 20 MB");return}h(!0);try{const x=await Gjn(c.id,p,r);n(x),re.success("Photo uploaded")}catch(x){re.error((x==null?void 0:x.message)||"Upload failed")}finally{h(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:Et("space-y-2",o),children:[e.jsx(se,{className:"text-xs",children:s}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Et("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(ac,{className:"h-5 w-5"})})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{ref:d,type:"file",accept:"image/*",className:"hidden",onChange:p=>{var x;return m((x=p.target.files)==null?void 0:x[0])}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:u,onClick:()=>{var p;return(p=d.current)==null?void 0:p.click()},children:[u?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(a1,{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(dr,{className:"h-4 w-4"})," Remove"]})]})]}),e.jsx(ye,{value:t||"",onChange:p=>n(p.target.value||null),placeholder:i}),a&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a})]})}function JNn({value:s,onChange:t}){return e.jsxs(be,{children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ut,{className:"text-base",children:"Co-listing agent"})]}),e.jsx(Mn,{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(Re,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Name"}),e.jsx(ye,{value:s.name,onChange:n=>t({name:n.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:s.title||"",onChange:n=>t({title:n.target.value}),placeholder:"Co-listing agent"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:s.phone||"",onChange:n=>t({phone:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{value:s.email||"",onChange:n=>t({email:n.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(ye,{value:s.brokerageName||"",onChange:n=>t({brokerageName:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"License #"}),e.jsx(ye,{value:s.licenseNumber||"",onChange:n=>t({licenseNumber:n.target.value})})]})]}),e.jsx(gee,{label:"Headshot",value:s.headshotUrl,onChange:n=>t({headshotUrl:n||""}),prefix:"co-agent",round:!0}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Shared bio (optional)"}),e.jsx(Ds,{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 ekn({value:s,onChange:t}){return e.jsxs(be,{children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsx(Ut,{className:"text-base",children:"Presentation theme"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Themes restyle every page — paper, headline type, and palette. Signature follows your own brand colors."})]}),e.jsx(Re,{className:"grid gap-2 sm:grid-cols-2",children:nze.map(n=>{const r=n.id===s;return e.jsxs("button",{type:"button",onClick:()=>t(n.id),className:Et("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(da,{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 tkn={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}]},skn=["cover","welcome","agent","overview","closing"];function nkn({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(be,{children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsx(Ut,{className:"text-base",children:"Edit page wording"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Rewrite the headlines on the built-in pages. The preview updates as you type."})]}),e.jsx(Re,{children:e.jsx(vO,{type:"multiple",className:"w-full",children:skn.filter(i=>i==="cover"||!n.has(i)).map(i=>{const l=$Ot(s,i);return e.jsxs(l6,{value:i,children:[e.jsx(c6,{className:"text-sm",children:t1n[i]}),e.jsxs(d6,{className:"space-y-3 pt-1",children:[tkn[i].map(o=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:o.label}),o.long?e.jsx(Ds,{rows:2,value:l[o.key]||"",placeholder:D9e[i][o.key],onChange:c=>r(i,o.key,c.target.value)}):e.jsx(ye,{value:l[o.key]||"",placeholder:D9e[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(bm,{className:"h-3.5 w-3.5"})," Reset to default wording"]})]})]},i)})})})]})}function rkn({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,bKe(o,n.length)]),i=o=>t(n.filter(c=>c.id!==o).map((c,d)=>({...c,order:d}))),l=(o,c)=>{const d=n.findIndex(m=>m.id===o),u=d+c;if(d<0||u<0||u>=n.length)return;const h=[...n];[h[d],h[u]]=[h[u],h[d]],t(h.map((m,p)=>({...m,order:p})))};return e.jsxs(be,{children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q_,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ut,{className:"text-base",children:"Your own pages"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add About Us, testimonials, track record, or a statement page. Each one is styled to match the rest of the presentation and can be toggled on or off."})]}),e.jsxs(Re,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:lIe.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(Js,{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(Xl,{}),e.jsx(vO,{type:"multiple",className:"w-full",children:n.map((o,c)=>{var d,u,h;return e.jsxs(l6,{value:o.id,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{checked:o.enabled,onCheckedChange:m=>r(o.id,{enabled:m})}),e.jsx(c6,{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=lIe.find(m=>m.layout===o.layout))==null?void 0:u.name),e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:(h=lIe.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(Gm,{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(tx,{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(Rn,{className:"h-3.5 w-3.5"})})]}),e.jsxs(d6,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Placement"}),e.jsxs(vs,{value:o.placement,onValueChange:m=>r(o.id,{placement:m}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"after-agent",children:'After "About your agent"'}),e.jsx(Je,{value:"end",children:"Before the closing page"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Style"}),e.jsxs("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3",children:[e.jsx(Mn,{checked:o.dark,onCheckedChange:m=>r(o.id,{dark:m})}),e.jsx("span",{className:"text-sm",children:"Dark background"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Eyebrow"}),e.jsx(ye,{value:o.kicker,onChange:m=>r(o.id,{kicker:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Headline"}),e.jsx(ye,{value:o.headline,onChange:m=>r(o.id,{headline:m.target.value})})]}),o.layout!=="statement"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Subhead"}),e.jsx(ye,{value:o.subhead,onChange:m=>r(o.id,{subhead:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Body copy"}),e.jsx(Ds,{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(gee,{label:"Photo (optional)",value:o.imageUrl,onChange:m=>r(o.id,{imageUrl:m}),prefix:"custom-page",urlPlaceholder:"…or paste an image URL",hint:"Defaults to the property photo when left empty."}),o.layout==="story"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Photo side"}),e.jsxs(vs,{value:o.imageSide,onValueChange:m=>r(o.id,{imageSide:m}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"right",children:"Right"}),e.jsx(Je,{value:"left",children:"Left"})]})]})]}),(o.layout==="story"||o.layout==="checklist")&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"List items"}),o.bullets.map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{value:m,onChange:x=>{const y=[...o.bullets];y[p]=x.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((x,y)=>y!==p)}),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",disabled:o.bullets.length>=7,onClick:()=>r(o.id,{bullets:[...o.bullets,""]}),children:[e.jsx(Js,{className:"h-3.5 w-3.5"})," Add item"]})]}),o.layout==="testimonials"&&e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-3",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Testimonials (up to 4)"}),o.testimonials.map((m,p)=>e.jsxs("div",{className:"space-y-2 rounded-md border bg-background p-3",children:[e.jsx(Ds,{rows:3,value:m.quote,placeholder:"Client quote",onChange:x=>{const y=[...o.testimonials];y[p]={...m,quote:x.target.value},r(o.id,{testimonials:y})}}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ye,{value:m.name,placeholder:"Name",onChange:x=>{const y=[...o.testimonials];y[p]={...m,name:x.target.value},r(o.id,{testimonials:y})}}),e.jsx(ye,{value:m.detail,placeholder:"Neighborhood or year",onChange:x=>{const y=[...o.testimonials];y[p]={...m,detail:x.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((x,y)=>y!==p)}),children:[e.jsx(Rn,{className:"h-3.5 w-3.5"})," Remove"]})]},p)),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",disabled:o.testimonials.length>=4,onClick:()=>r(o.id,{testimonials:[...o.testimonials,{quote:"",name:"",detail:""}]}),children:[e.jsx(Js,{className:"h-3.5 w-3.5"})," Add testimonial"]})]}),o.layout==="stats"&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Stats (up to 4)"}),o.stats.map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{className:"w-28",value:m.value,placeholder:"27",onChange:x=>{const y=[...o.stats];y[p]={...m,value:x.target.value},r(o.id,{stats:y})}}),e.jsx(ye,{value:m.label,placeholder:"Homes sold",onChange:x=>{const y=[...o.stats];y[p]={...m,label:x.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((x,y)=>y!==p)}),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",disabled:o.stats.length>=4,onClick:()=>r(o.id,{stats:[...o.stats,{value:"",label:""}]}),children:[e.jsx(Js,{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 akn({open:s,onOpenChange:t,defaultName:n,saving:r,onSave:a}){const[i,l]=j.useState(""),[o,c]=j.useState("");return j.useEffect(()=>{s&&(l((n==null?void 0:n.trim())||"My listing presentation"),c(""))},[s,n]),e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Save as a reusable template"}),e.jsx(kr,{children:"Saves your branding, co-listing agent, theme, page wording, custom pages, and marketing plan. The property address and photo are not saved — you add those each time."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Template name"}),e.jsx(ye,{value:i,onChange:d=>l(d.target.value),autoFocus:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Notes (optional)"}),e.jsx(Ds,{rows:2,value:o,onChange:d=>c(d.target.value),placeholder:"Luxury version with co-listing agent and testimonials"})]})]}),e.jsxs(Nr,{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(Wt,{className:"h-4 w-4 animate-spin"})," Save template"]})]})]})})}const Yxt=["welcome","agent","overview","closing"],ikn=()=>{const{id:s}=$i(),t=Hn(),{user:n}=Ns(),{data:r}=BOt(),{data:a,isLoading:i,refetch:l}=Xvn(s),{update:o}=zOt(),{save:c}=FOt(),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,x]=j.useState(z9e(null)),[y,g]=j.useState(UOt),[b,v]=j.useState([]),[k,C]=j.useState(O9e),[T,M]=j.useState(F9e),[P,L]=j.useState(null),[I,O]=j.useState(null),[$,q]=j.useState(!1),[W,G]=j.useState(!1),[K,ee]=j.useState(null),[J,le]=j.useState(!1),[ue,oe]=j.useState(!1),[ie,de]=j.useState(!1),[we,je]=j.useState(!1),[xe,fe]=j.useState(!0),[Se,Ee]=j.useState(!1),Le=j.useRef(null);j.useEffect(()=>{if(!a||d)return;u({title:a.title||"",addressLine1:a.property_address_line1||"",city:a.city||"",state:a.state||"",postalCode:a.postal_code||"",listPrice:a.list_price!=null?String(a.list_price):"",beds:a.beds!=null?String(a.beds):"",baths:a.baths!=null?String(a.baths):"",sqft:a.sqft!=null?String(a.sqft):""});const Ye=a.agent_snapshot;m({...r,...Ye||{}}),x(z9e(a.services)),g(qOt(a.co_agent)),v(HOt(a.custom_pages)),C(a.page_settings&&Object.keys(a.page_settings).length?a.page_settings:O9e),M(a.photo_focal||F9e),L(a.property_photo_path)},[a,r,d]),j.useEffect(()=>{let Ye=!1;return P?_Se(P).then(nt=>{Ye||O(nt)}):O(null),()=>{Ye=!0}},[P]);const De=j.useMemo(()=>!a||!d?null:{...a,title:d.title,property_address_line1:d.addressLine1,city:d.city,state:d.state,postal_code:d.postalCode,list_price:d.listPrice?Number(d.listPrice):null,beds:d.beds?Number(d.beds):null,baths:d.baths?Number(d.baths):null,sqft:d.sqft?Number(d.sqft):null,agent_snapshot:h||{},co_agent:y,custom_pages:b,services:p,page_settings:k,photo_focal:T,property_photo_path:P},[a,d,h,y,b,p,k,T,P]),Be=Ye=>u(nt=>nt&&{...nt,...Ye}),Ne=Ye=>m(nt=>nt&&{...nt,...Ye}),Ge=Ye=>(k.hidden||[]).includes(Ye),_e=(Ye,nt)=>C(rt=>{const Fe=new Set(rt.hidden||[]);return nt?Fe.delete(Ye):Fe.add(Ye),{...rt,hidden:Array.from(Fe)}}),Oe=p.filter(Ye=>Ye.enabled),Ae=1+Yxt.filter(Ye=>!Ge(Ye)&&Ye!=="overview").length+(Ge("overview")?0:1)+Oe.filter(Ye=>Ye.key!=="communication").length+b.filter(Ye=>Ye.enabled).length,Xe=async(Ye=!1)=>{if(De){je(!0);try{await o.mutateAsync({id:De.id,title:De.title||"Untitled Presentation",property_address_line1:De.property_address_line1,city:De.city,state:De.state,postal_code:De.postal_code,list_price:De.list_price,beds:De.beds,baths:De.baths,sqft:De.sqft,agent_snapshot:De.agent_snapshot,co_agent:De.co_agent,custom_pages:De.custom_pages,services:De.services,page_settings:De.page_settings,photo_focal:De.photo_focal,property_photo_path:De.property_photo_path}),Ye||re.success("Presentation saved")}finally{je(!1)}}},Ue=async Ye=>{if(!(!n||!s)){if(!Ye.type.startsWith("image/")){re.error("Please choose a JPG or PNG photo");return}if(Ye.size>25*1024*1024){re.error("That photo is larger than 25 MB");return}q(!0);try{const nt=await Hjn(n.id,s,Ye);L(nt);const rt=await _Se(nt);O(rt?`${rt}${rt.includes("?")?"&":"?"}v=${Date.now()}`:null),await o.mutateAsync({id:s,property_photo_path:nt}),re.success("Photo uploaded")}catch(nt){re.error((nt==null?void 0:nt.message)||"Upload failed")}finally{q(!1)}}},Ze=async()=>{if(De){le(!0);try{const Ye=await l7t(wSe(De,r,I),De.template_id,P);ee(Ye)}catch(Ye){re.error((Ye==null?void 0:Ye.message)||"Could not build the preview")}finally{le(!1)}}};j.useEffect(()=>{if(!xe||!De)return;const Ye=setTimeout(()=>{Ze()},900);return()=>clearTimeout(Ye)},[xe,De]);const Qe=async()=>{if(!(!De||!n)){if(!De.property_photo_path){re.error("Add the primary exterior photo before generating the PDF");return}oe(!0);try{await Xe(!0);const Ye=await c7t(wSe(De,r,I),De.template_id,"print",P);await d7t(n.id,De.id,Ye),await l(),re.success("Presentation downloaded")}catch(Ye){re.error((Ye==null?void 0:Ye.message)||"Could not build the PDF")}finally{oe(!1)}}};return i||!d||!a?e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(gn,{className:"h-10 w-64"}),e.jsx(gn,{className:"h-[60vh] w-full rounded-xl"})]})}):e.jsxs(Vs,{children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t("/apps/listing-presentation-studio"),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(ye,{value:d.title,onChange:Ye=>Be({title:Ye.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:[Oe.length," services selected · ",Ae," pages"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>Xe(),disabled:we,className:"gap-2",children:[we?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4"})," Save"]}),e.jsxs(B,{variant:"outline",onClick:()=>Ee(!0),className:"gap-2",children:[e.jsx($T,{className:"h-4 w-4"})," Save as template"]}),e.jsxs(B,{variant:"outline",onClick:Ze,disabled:J,className:"gap-2",children:[J?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(ma,{className:"h-4 w-4"})," Preview"]}),e.jsxs(B,{variant:"outline",onClick:async()=>{await Xe(!0),de(!0)},className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"})," Email"]}),e.jsxs(B,{onClick:Qe,disabled:ue,className:"gap-2",children:[ue?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(ii,{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(fa,{defaultValue:"property",className:"space-y-4",children:[e.jsxs(xa,{className:"grid w-full grid-cols-4",children:[e.jsx(ss,{value:"property",children:"Property"}),e.jsx(ss,{value:"branding",children:"Branding"}),e.jsx(ss,{value:"plan",children:"Plan"}),e.jsx(ss,{value:"pages",children:"Pages"})]}),e.jsxs(ns,{value:"property",className:"space-y-4",children:[e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"Property address"})}),e.jsxs(Re,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Street address"}),e.jsx(ye,{value:d.addressLine1,onChange:Ye=>Be({addressLine1:Ye.target.value}),placeholder:"1408 Elmwood Drive"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"col-span-2 space-y-1.5",children:[e.jsx(se,{children:"City"}),e.jsx(ye,{value:d.city,onChange:Ye=>Be({city:Ye.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"State"}),e.jsx(ye,{value:d.state,onChange:Ye=>Be({state:Ye.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"ZIP"}),e.jsx(ye,{value:d.postalCode,onChange:Ye=>Be({postalCode:Ye.target.value})})]}),e.jsx(Xl,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"List price (optional)"}),e.jsx(ye,{inputMode:"numeric",value:d.listPrice,onChange:Ye=>Be({listPrice:Ye.target.value.replace(/[^0-9.]/g,"")}),placeholder:"649000"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Square feet"}),e.jsx(ye,{inputMode:"numeric",value:d.sqft,onChange:Ye=>Be({sqft:Ye.target.value.replace(/[^0-9]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Beds"}),e.jsx(ye,{inputMode:"numeric",value:d.beds,onChange:Ye=>Be({beds:Ye.target.value.replace(/[^0-9.]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Baths"}),e.jsx(ye,{inputMode:"numeric",value:d.baths,onChange:Ye=>Be({baths:Ye.target.value.replace(/[^0-9.]/g,"")})})]})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base",children:["Primary exterior photo ",e.jsx("span",{className:"text-destructive",children:"*"})]})}),e.jsxs(Re,{className:"space-y-3",children:[e.jsx("div",{role:"button",tabIndex:0,onClick:()=>{var Ye;return(Ye=Le.current)==null?void 0:Ye.click()},onKeyDown:Ye=>{var nt;return Ye.key==="Enter"&&((nt=Le.current)==null?void 0:nt.click())},onDragOver:Ye=>{Ye.preventDefault(),G(!0)},onDragLeave:()=>G(!1),onDrop:Ye=>{var rt;Ye.preventDefault(),G(!1);const nt=(rt=Ye.dataTransfer.files)==null?void 0:rt[0];nt&&Ue(nt)},className:Et("relative flex h-48 w-full cursor-pointer items-center justify-center overflow-hidden rounded-lg border border-dashed bg-muted/40 transition-colors hover:bg-muted",W&&"border-primary bg-primary/10"),children:I?e.jsx("img",{src:I,alt:"Property exterior",className:"h-full w-full object-cover",style:{objectPosition:`${T.x*100}% ${T.y*100}%`}}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[$?e.jsx(Wt,{className:"h-6 w-6 animate-spin"}):e.jsx(a1,{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:Le,type:"file",accept:"image/*",className:"hidden",onChange:Ye=>{var rt;const nt=(rt=Ye.target.files)==null?void 0:rt[0];nt&&Ue(nt),Ye.target.value=""}}),I&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[e.jsx(YW,{className:"h-3.5 w-3.5"})," Reposition crop"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Horizontal"}),e.jsx(Qf,{value:[T.x*100],min:0,max:100,step:1,onValueChange:([Ye])=>M(nt=>({...nt,x:Ye/100}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Vertical"}),e.jsx(Qf,{value:[T.y*100],min:0,max:100,step:1,onValueChange:([Ye])=>M(nt=>({...nt,y:Ye/100}))})]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>{var Ye;return(Ye=Le.current)==null?void 0:Ye.click()},disabled:$,children:[e.jsx(Ki,{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(ns,{value:"branding",className:"space-y-4",children:[e.jsx(ekn,{value:k.theme||ojn,onChange:Ye=>C(nt=>({...nt,theme:Ye}))}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ut,{className:"text-base",children:"Your details"}),e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:"Loaded from your LevelUp profile"})]})}),e.jsx(Re,{className:"space-y-3",children:h&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edits here apply to this presentation only — your LevelUp profile stays unchanged."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Name"}),e.jsx(ye,{value:h.name,onChange:Ye=>Ne({name:Ye.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Tagline"}),e.jsx(ye,{value:h.tagline||"",onChange:Ye=>Ne({tagline:Ye.target.value}),placeholder:"Helping families move with confidence"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:h.phone||"",onChange:Ye=>Ne({phone:Ye.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{value:h.email||"",onChange:Ye=>Ne({email:Ye.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Website"}),e.jsx(ye,{value:h.website||"",onChange:Ye=>Ne({website:Ye.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(ye,{value:h.brokerageName||"",onChange:Ye=>Ne({brokerageName:Ye.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"License #"}),e.jsx(ye,{value:h.licenseNumber||"",onChange:Ye=>Ne({licenseNumber:Ye.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"License state"}),e.jsx(ye,{value:h.licenseState||"",onChange:Ye=>Ne({licenseState:Ye.target.value})})]})]}),e.jsx(Xl,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Primary color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brandColor,onChange:Ye=>Ne({brandColor:Ye.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(ye,{value:h.brandColor,onChange:Ye=>Ne({brandColor:Ye.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accentColor,onChange:Ye=>Ne({accentColor:Ye.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(ye,{value:h.accentColor,onChange:Ye=>Ne({accentColor:Ye.target.value})})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Headshot URL"}),e.jsx(ye,{value:h.headshotUrl||"",onChange:Ye=>Ne({headshotUrl:Ye.target.value}),placeholder:"Pulled from your profile photo"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Brokerage logo URL"}),e.jsx(ye,{value:h.brokerageLogoUrl||"",onChange:Ye=>Ne({brokerageLogoUrl:Ye.target.value})})]}),r&&e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>m({...r}),children:[e.jsx(Ki,{className:"h-4 w-4"})," Reset to my LevelUp profile"]})]})})]}),e.jsx(JNn,{value:y,onChange:Ye=>g(nt=>({...nt,...Ye}))})]}),e.jsx(ns,{value:"plan",className:"space-y-4",children:e.jsxs(be,{children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsx(Ut,{className:"text-base",children:"Marketing plan"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only the services you turn on appear in the PDF. Uncheck any line item you do not offer."})]}),e.jsx(Re,{children:e.jsx(vO,{type:"multiple",className:"w-full",children:p.slice().sort((Ye,nt)=>Ye.order-nt.order).map(Ye=>{var nt;return e.jsxs(l6,{value:Ye.key,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Mn,{checked:Ye.enabled,onCheckedChange:rt=>x(Fe=>Fe.map(dt=>dt.key===Ye.key?{...dt,enabled:rt}:dt))}),e.jsx(c6,{className:"flex-1 text-left text-sm",children:Ye.title})]}),e.jsxs(d6,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Headline"}),e.jsx(ye,{value:Ye.title,onChange:rt=>x(Fe=>Fe.map(dt=>dt.key===Ye.key?{...dt,title:rt.target.value}:dt))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{rows:4,value:Ye.body,onChange:rt=>x(Fe=>Fe.map(dt=>dt.key===Ye.key?{...dt,body:rt.target.value}:dt))})]}),!!((nt=Ye.options)!=null&&nt.length)&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Included in this page"}),Ye.options.map(rt=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(wi,{className:"mt-0.5",checked:rt.enabled,onCheckedChange:Fe=>x(dt=>dt.map(Dt=>{var pt;return Dt.key===Ye.key?{...Dt,options:(pt=Dt.options)==null?void 0:pt.map(zt=>zt.key===rt.key?{...zt,enabled:!!Fe}:zt)}:Dt}))}),e.jsx("span",{className:"leading-snug",children:rt.label})]},rt.key))]})]})]},Ye.key)})})})]})}),e.jsxs(ns,{value:"pages",className:"space-y-4",children:[e.jsxs(be,{children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsx(Ut,{className:"text-base",children:"Page visibility"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The cover and every enabled service page always print. These supporting pages are optional."})]}),e.jsxs(Re,{className:"space-y-3",children:[Yxt.map(Ye=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx("span",{className:"text-sm",children:n1n[Ye]}),e.jsx(Mn,{checked:!Ge(Ye),onCheckedChange:nt=>_e(Ye,nt)})]},Ye)),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"}),b.filter(Ye=>Ye.enabled&&Ye.placement!=="end").sort((Ye,nt)=>Ye.order-nt.order).map(Ye=>e.jsx("li",{children:Ye.headline||"Custom page"},Ye.id)),!Ge("overview")&&e.jsx("li",{children:"Marketing plan overview"}),Oe.filter(Ye=>Ye.key!=="communication").map(Ye=>e.jsx("li",{children:Ye.title},Ye.key)),b.filter(Ye=>Ye.enabled&&Ye.placement==="end").sort((Ye,nt)=>Ye.order-nt.order).map(Ye=>e.jsx("li",{children:Ye.headline||"Custom page"},Ye.id)),!Ge("closing")&&e.jsx("li",{children:"Communication & closing commitment"})]})]})]})]}),e.jsx(nkn,{pages:k,onChange:C}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsx(Ut,{className:"text-base",children:"What they're saying"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add a testimonial page and drop in up to six client quotes. It styles itself to your theme."})]}),e.jsx(Re,{children:e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>v(Ye=>[...Ye,{...bKe("testimonials",Ye.length),placement:"end"}]),children:`Add a "What they're saying" page`})})]}),e.jsx(rkn,{pages:b,onChange:v})]})]}),e.jsxs(be,{className:"min-h-[70vh] overflow-hidden",children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ut,{className:"text-base",children:"Live preview"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Mn,{checked:xe,onCheckedChange:fe}),"Auto-update"]})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:Ze,disabled:J,className:"gap-2",children:[J?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ki,{className:"h-4 w-4"}),"Refresh"]})]}),e.jsx(Re,{className:"h-[calc(70vh-60px)] p-0",children:K?e.jsx(QNn,{blob:K}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 bg-muted/30 text-center",children:[e.jsx(ma,{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:Ze,disabled:J,className:"gap-2",children:[J?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(ma,{className:"h-4 w-4"}),"Generate preview"]})]})})]})]})]}),e.jsx(akn,{open:Se,onOpenChange:Ee,defaultName:d.title,saving:c.isPending,onSave:async(Ye,nt)=>{await c.mutateAsync({name:Ye,description:nt||null,template_id:a.template_id,agent_snapshot:h||{},co_agent:y,custom_pages:b,services:p,page_settings:k})}}),e.jsx(h7t,{open:ie,onOpenChange:de,row:De,brand:r,photoUrl:I})]})};function okn(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 gzt="popby_geocode_cache_v1";function lkn(){try{return JSON.parse(localStorage.getItem(gzt)||"{}")}catch{return{}}}function ckn(s){try{localStorage.setItem(gzt,JSON.stringify(s))}catch{}}function dkn({contacts:s,onLogPopby:t}){const[n,r]=j.useState(null),[a,i]=j.useState("idle"),[l,o]=j.useState(5),[c,d]=j.useState(""),[u,h]=j.useState(new Map),[m,p]=j.useState(!1);j.useEffect(()=>{(async()=>{const{data:v}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();v!=null&&v.value&&d(v.value)})()},[]);const x=j.useMemo(()=>s.filter(v=>v.isDue&&(v.address||v.city&&v.state||v.zip)),[s]),y=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(v=>{r({lat:v.coords.latitude,lng:v.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};j.useEffect(()=>{if(!c||!n||x.length===0)return;let v=!1;const k=lkn(),C=new Map;x.forEach(M=>{const P=[M.address,M.city,M.state,M.zip].filter(Boolean).join("|").toLowerCase();k[P]&&C.set(M.id,k[P])}),h(new Map(C));const T=x.filter(M=>!([M.address,M.city,M.state,M.zip].filter(Boolean).join("|").toLowerCase()in k));if(T.length!==0)return p(!0),(async()=>{const M=[...T],P=async()=>{var L,I;for(;M.length&&!v;){const O=M.shift(),$=[O.address,O.city,O.state,O.zip].filter(Boolean),q=$.join("|").toLowerCase(),W=$.join(", ");try{const K=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(W)}.json?limit=1&access_token=${c}`)).json();if((I=(L=K==null?void 0:K.features)==null?void 0:L[0])!=null&&I.center){const[ee,J]=K.features[0].center;k[q]={lat:J,lng:ee},C.set(O.id,{lat:J,lng:ee})}else k[q]=null}catch{}}};await Promise.all([P(),P(),P(),P()]),v||(ckn(k),h(new Map(C)),p(!1))})(),()=>{v=!0}},[c,n,x]);const g=j.useMemo(()=>{if(!n)return[];const v=[];return x.forEach(k=>{const C=u.get(k.id);if(!C)return;const T=okn(n.lat,n.lng,C.lat,C.lng);T<=l&&v.push({...k,distanceMiles:T,lat:C.lat,lng:C.lng})}),v.sort((k,C)=>k.distanceMiles-C.distanceMiles)},[n,x,u,l]),b=v=>{const C=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${v.lat},${v.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${v.lat},${v.lng}`;window.open(C,"_blank","noopener")};return e.jsxs(be,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-lg",children:[e.jsx(V9,{className:"h-5 w-5 text-primary"}),"Nearby Now"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Due contacts within driving distance — perfect for errand-day pop-bys."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(vs,{value:String(l),onValueChange:v=>o(Number(v)),children:[e.jsx(gs,{className:"w-[110px] h-9",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"2",children:"2 miles"}),e.jsx(Je,{value:"5",children:"5 miles"}),e.jsx(Je,{value:"10",children:"10 miles"}),e.jsx(Je,{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(Ki,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(V9,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Re,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(oi,{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(po,{className:"h-6 w-6"}),"Location access was blocked. Enable it in your browser to use Nearby Now."]}),a==="unavailable"&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Geolocation isn't available on this device."}),a==="ok"&&!c&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Mapping isn't configured yet — ask an admin to add the Mapbox token."}),a==="ok"&&c&&x.length===0&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"No due contacts have addresses yet. Add street addresses to your sphere to power this."}),a==="ok"&&c&&x.length>0&&m&&g.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(gn,{className:"h-14 w-full"}),e.jsx(gn,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!m&&g.length===0&&x.length>0&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:["No due contacts within ",l," miles. Try widening the radius."]}),g.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(qe,{variant:"secondary",className:"font-medium",children:[g.length," nearby"]}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ki,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:g.map(v=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg bg-card border hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-medium truncate",children:[v.first_name," ",v.last_name]}),e.jsx(qe,{variant:"outline",className:"text-xs",children:v.distanceMiles<1?`${(v.distanceMiles*5280).toFixed(0)} ft`:`${v.distanceMiles.toFixed(1)} mi`}),v.daysOverdue>0&&e.jsxs(qe,{variant:"destructive",className:"text-xs",children:[v.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[v.address,v.city,v.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[v.phone&&e.jsx(B,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${v.phone}`,children:e.jsx(pa,{className:"h-4 w-4"})})}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>b(v),className:"h-9 w-9",title:"Directions",children:e.jsx(ZW,{className:"h-4 w-4"})}),e.jsxs(B,{size:"sm",onClick:()=>t(v),children:[e.jsx(zo,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},v.id))})]})]})]})}const ukn="0dde5abb-0005-4c8c-a471-30d0cbc9e280",hkn=[{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 mkn(){const s=Hn(),t=hRt(),{data:n}=qxn(),{data:r}=lw(),{data:a}=_We(),{data:i}=PAe(90),{data:l}=av(),o=Kxn(),c=Gxn(),d=Hxn(),u=Wxn(),{data:h=[],isLoading:m}=mt({queryKey:["popby-templates"],queryFn:async()=>{const{data:K,error:ee}=await U.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",ukn).order("publish_date",{ascending:!1});if(ee)throw ee;const{data:J}=await U.from("template_likes").select("template_id"),{data:le}=await U.from("template_comments").select("template_id"),ue=new Map;J==null||J.forEach(ie=>{ue.set(ie.template_id,(ue.get(ie.template_id)||0)+1)});const oe=new Map;return le==null||le.forEach(ie=>{oe.set(ie.template_id,(oe.get(ie.template_id)||0)+1)}),(K||[]).map(ie=>({...ie,likesCount:ue.get(ie.id)||0,commentsCount:oe.get(ie.id)||0}))}}),p=K=>{const ee=l==null?void 0:l.find(J=>J.id===K);return ee?`${ee.first_name} ${ee.last_name||""}`.trim():"Unknown"},x=K=>{if(!K)return null;const ee=n==null?void 0:n.find(J=>J.id===K);return(ee==null?void 0:ee.name)||null},[y,g]=j.useState(null),[b,v]=j.useState(!1),[k,C]=j.useState(!1),[T,M]=j.useState(!1),[P,L]=j.useState({popby_item_id:"",notes:""}),[I,O]=j.useState({name:"",description:""}),$=async()=>{y&&(await c.mutateAsync({contact_id:y.id,popby_item_id:P.popby_item_id||void 0,notes:P.notes||void 0}),v(!1),g(null),L({popby_item_id:"",notes:""}))},q=async()=>{I.name.trim()&&(await d.mutateAsync({name:I.name.trim(),description:I.description.trim()||void 0}),M(!1),O({name:"",description:""}))},W=async(K,ee)=>{await u.mutateAsync({relationship_type_id:K,frequency_days:parseInt(ee)})},G=K=>{var J;const ee=a==null?void 0:a.find(le=>le.relationship_type_id===K);return((J=ee==null?void 0:ee.frequency_days)==null?void 0:J.toString())||"90"};return e.jsx(Vs,{title:"Popbys",description:"Drop off gifts to stay top of mind",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Popbys"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(be,{children:e.jsxs(Re,{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(be,{children:e.jsxs(Re,{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(be,{children:e.jsxs(Re,{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(oi,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(B,{variant:"outline",onClick:()=>C(!0),children:[e.jsx(ic,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(B,{variant:"outline",onClick:()=>M(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(fa,{defaultValue:"due",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"due",children:"Due for Popby"}),e.jsx(ss,{value:"activity",children:"Recent Activity"}),e.jsx(ss,{value:"library",children:"Popby Library"}),e.jsx(ss,{value:"templates",children:"Popby Templates"})]}),e.jsxs(ns,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(dkn,{contacts:t||[],onLogPopby:K=>{g(K),v(!0)}}),!t||t.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(zo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No contacts due for a popby right now!"}),e.jsx("p",{className:"text-sm mt-1",children:"Great job staying connected."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(K=>e.jsx(be,{className:"hover:shadow-md transition-shadow",children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:[K.first_name," ",K.last_name]}),K.daysOverdue>0&&e.jsxs(qe,{variant:"destructive",className:"text-xs",children:[K.daysOverdue,"+ days overdue"]}),K.daysSinceLastPopby===null&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"Never visited"})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-1 text-sm text-muted-foreground",children:[K.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(oi,{className:"h-3 w-3"}),K.city||K.address]}),K.tags&&K.tags.length>0&&e.jsx("span",{children:K.tags.map(ee=>{var J;return(J=ee.relationship_type)==null?void 0:J.name}).join(", ")})]}),K.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Bs(new Date(K.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[K.phone&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${K.phone}`,children:e.jsx(pa,{className:"h-4 w-4"})})}),e.jsxs(B,{size:"sm",onClick:()=>{g(K),v(!0)},children:[e.jsx(To,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},K.id))})]}),e.jsx(ns,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Vr,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Re,{className:"space-y-3",children:i.map(K=>e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0 last:pb-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/10 flex items-center justify-center",children:e.jsx(zo,{className:"h-5 w-5 text-orange-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:p(K.contact_id)}),x(K.popby_item_id)&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:x(K.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Bs(new Date(K.completed_at),"MMM d, yyyy h:mm a")}),K.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:K.notes})]})]},K.id))})]})}),e.jsx(ns,{value:"library",className:"space-y-4 mt-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[n==null?void 0:n.map(K=>e.jsx(be,{children:e.jsx(Re,{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(zo,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:K.name}),K.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:K.description}),!K.owner_user_id&&e.jsx(qe,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},K.id)),e.jsx(be,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>M(!0),children:e.jsx(Re,{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(Js,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(ns,{value:"templates",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[h.length," template",h.length!==1?"s":""," found"]}),m&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(4)].map((K,ee)=>e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsx(gn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(gn,{className:"h-5 w-3/4 mb-2"}),e.jsx(gn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(gn,{className:"h-5 w-16"}),e.jsx(gn,{className:"h-5 w-20"})]})]})},ee))}),!m&&h.length===0&&e.jsx(be,{children:e.jsxs(Re,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Eu,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby templates available yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Check back soon for new templates."})]})}),!m&&h.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:h.map(K=>e.jsxs(be,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${K.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:K.preview_image_url?e.jsx("img",{src:K.preview_image_url,alt:K.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})}),e.jsxs(Re,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:K.name}),K.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:zY(K.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(qe,{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(mg,{className:"h-3.5 w-3.5"}),K.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yd,{className:"h-3.5 w-3.5"}),K.commentsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:ee=>{ee.stopPropagation(),s(`/templates/${K.id}`)},children:[e.jsx(Tr,{className:"h-4 w-4"}),"View Template"]})]})]},K.id))})]})]}),e.jsx(Fs,{open:b,onOpenChange:v,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsxs(zs,{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(se,{children:"Popby Item (optional)"}),e.jsxs(vs,{value:P.popby_item_id,onValueChange:K=>L(ee=>({...ee,popby_item_id:K})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a popby item..."})}),e.jsx(ys,{children:n==null?void 0:n.map(K=>e.jsx(Je,{value:K.id,children:K.name},K.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes (optional)"}),e.jsx(Ds,{placeholder:"Any notes about this popby...",value:P.notes,onChange:K=>L(ee=>({...ee,notes:K.target.value}))})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(B,{onClick:$,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(Fs,{open:k,onOpenChange:C,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{children:"Popby Frequency Settings"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set default popby frequency for each relationship type. You can override these per-contact."}),r==null?void 0:r.map(K=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(se,{className:"font-medium",children:K.name}),e.jsxs(vs,{value:G(K.id),onValueChange:ee=>W(K.id,ee),children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:hkn.map(ee=>e.jsx(Je,{value:ee.value,children:ee.label},ee.value))})]})]},K.id))]}),e.jsx(Nr,{children:e.jsx(B,{onClick:()=>C(!1),children:"Done"})})]})}),e.jsx(Fs,{open:T,onOpenChange:M,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Name *"}),e.jsx(ye,{placeholder:"e.g., Homemade cookies",value:I.name,onChange:K=>O(ee=>({...ee,name:K.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{placeholder:"Optional description...",value:I.description,onChange:K=>O(ee=>({...ee,description:K.target.value}))})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>M(!1),children:"Cancel"}),e.jsx(B,{onClick:q,disabled:!I.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const pkn=iS({property_address:Cl().min(1,"Property address is required"),city:Cl().optional(),state:Cl().optional(),zip:Cl().optional(),transaction_type:_qe(["buyer","seller"]),close_date:Cl().min(1,"Close date is required"),sale_price:SK().min(0,"Sale price must be positive"),commission_amount:SK().optional(),lead_source_id:Cl().optional(),client_type_id:Cl().optional(),contact_id:Cl().optional(),notes:Cl().optional(),is_win:cgs()});function yzt({open:s,onOpenChange:t,transaction:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(""),h=V3e(),m=t5s(),{data:p}=gO(),{data:x}=lw(),{data:y}=av(),g=q3e(),b=kVe(),{data:v}=H3e(),k=(v==null?void 0:v.show_commission)??!0,C=D3e({resolver:O3e(pkn),defaultValues:{property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1}});j.useEffect(()=>{n?C.reset({property_address:n.property_address,city:n.city||"",state:n.state||"",zip:n.zip||"",transaction_type:n.transaction_type,close_date:n.close_date,sale_price:Number(n.sale_price),commission_amount:n.commission_amount?Number(n.commission_amount):void 0,lead_source_id:n.lead_source_id||void 0,client_type_id:n.client_type_id||void 0,contact_id:n.contact_id||void 0,notes:n.notes||"",is_win:n.is_win}):C.reset({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1})},[n,C]);const T=async I=>{const O={property_address:I.property_address,transaction_type:I.transaction_type,close_date:I.close_date,sale_price:I.sale_price,is_win:I.is_win,commission_amount:I.commission_amount||null,lead_source_id:I.lead_source_id||null,client_type_id:I.client_type_id||null,contact_id:I.contact_id||null,city:I.city||null,state:I.state||null,zip:I.zip||null,notes:I.notes||null};n?await m.mutateAsync({id:n.id,...O}):await h.mutateAsync(O),t(!1)},M=async()=>{if(!i.trim())return;const[I,...O]=i.trim().split(" "),$=O.join(" ")||null,q=await g.mutateAsync({first_name:I,last_name:$,tagIds:[]});q&&(C.setValue("contact_id",q.id),l(""),c(!1),a(!1))},P=async()=>{if(!d.trim())return;const I=await b.mutateAsync(d.trim());I&&(C.setValue("lead_source_id",I.id),u(""))},L=y==null?void 0:y.find(I=>I.id===C.watch("contact_id"));return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh]",children:[e.jsx($s,{children:e.jsx(zs,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(lo,{className:"max-h-[70vh] pr-4",children:e.jsx(F3e,{...C,children:e.jsxs("form",{onSubmit:C.handleSubmit(T),className:"space-y-4",children:[e.jsx(Np,{control:C.control,name:"property_address",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Property Address *"}),e.jsx(Um,{children:e.jsx(ye,{placeholder:"123 Main St",...I})}),e.jsx(Kv,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(Np,{control:C.control,name:"city",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"City"}),e.jsx(Um,{children:e.jsx(ye,{placeholder:"City",...I})})]})}),e.jsx(Np,{control:C.control,name:"state",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"State"}),e.jsx(Um,{children:e.jsx(ye,{placeholder:"TX",...I})})]})}),e.jsx(Np,{control:C.control,name:"zip",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Zip"}),e.jsx(Um,{children:e.jsx(ye,{placeholder:"75001",...I})})]})})]}),e.jsx(Np,{control:C.control,name:"transaction_type",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Transaction Type *"}),e.jsxs(vs,{onValueChange:I.onChange,value:I.value,children:[e.jsx(Um,{children:e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select type"})})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"buyer",children:"Buyer"}),e.jsx(Je,{value:"seller",children:"Seller"})]})]}),e.jsx(Kv,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Np,{control:C.control,name:"close_date",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Close Date *"}),e.jsx(Um,{children:e.jsx(ye,{type:"date",...I})}),e.jsx(Kv,{})]})}),e.jsx(Np,{control:C.control,name:"sale_price",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Sale Price *"}),e.jsx(Um,{children:e.jsx(ye,{type:"number",placeholder:"0",...I,onChange:O=>I.onChange(Number(O.target.value))})}),e.jsx(Kv,{})]})})]}),k&&e.jsx(Np,{control:C.control,name:"commission_amount",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Commission"}),e.jsx(Um,{children:e.jsx(ye,{type:"number",placeholder:"0",...I,value:I.value??"",onChange:O=>I.onChange(O.target.value?Number(O.target.value):void 0)})})]})}),e.jsx(Np,{control:C.control,name:"lead_source_id",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Lead Source"}),e.jsxs(vs,{onValueChange:I.onChange,value:I.value||"",children:[e.jsx(Um,{children:e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select source"})})}),e.jsx(ys,{children:p==null?void 0:p.map(O=>e.jsx(Je,{value:O.id,children:O.name},O.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Add custom source...",value:d,onChange:I=>u(I.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:P,disabled:!d.trim(),children:e.jsx(Js,{className:"h-4 w-4"})})]}),e.jsx(Np,{control:C.control,name:"client_type_id",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Client Type"}),e.jsxs(vs,{onValueChange:I.onChange,value:I.value||"",children:[e.jsx(Um,{children:e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select client type"})})}),e.jsx(ys,{children:x==null?void 0:x.map(O=>e.jsx(Je,{value:O.id,children:O.name},O.id))})]})]})}),e.jsx(Np,{control:C.control,name:"contact_id",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Client Contact"}),e.jsxs(lc,{open:r,onOpenChange:a,children:[e.jsx(cc,{asChild:!0,children:e.jsx(Um,{children:e.jsxs(B,{variant:"outline",role:"combobox",className:Et("w-full justify-between",!I.value&&"text-muted-foreground"),children:[L?`${L.first_name} ${L.last_name||""}`.trim():"Select contact",e.jsx(fb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(Jl,{className:"w-full p-0",align:"start",children:[e.jsxs(Sb,{children:[e.jsx(Cb,{placeholder:"Search contacts..."}),e.jsxs(Ab,{children:[e.jsx(Tb,{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(Js,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(Eb,{children:y==null?void 0:y.map(O=>e.jsxs(Yy,{value:`${O.first_name} ${O.last_name||""}`,onSelect:()=>{I.onChange(O.id),a(!1)},children:[e.jsx(da,{className:Et("mr-2 h-4 w-4",O.id===I.value?"opacity-100":"opacity-0")}),O.first_name," ",O.last_name||""]},O.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(ye,{placeholder:"Enter contact name...",value:i,onChange:O=>l(O.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:M,disabled:!i.trim()||g.isPending,children:"Add Contact"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(Np,{control:C.control,name:"notes",render:({field:I})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Notes"}),e.jsx(Um,{children:e.jsx(Ds,{placeholder:"Any notes about this transaction...",...I})})]})}),e.jsx(Np,{control:C.control,name:"is_win",render:({field:I})=>e.jsxs(Bm,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx($m,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(Um,{children:e.jsx(Mn,{checked:I.value,onCheckedChange:I.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:h.isPending||m.isPending,children:[n?"Update":"Add"," Transaction"]})]})]})})})]})})}function ZKe({transactions:s,showCommission:t,isLoading:n,agentNameMap:r,readOnly:a}){const[i,l]=j.useState(null),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState("all"),[p,x]=j.useState("all"),[y,g]=j.useState("all"),[b,v]=j.useState(!1),k=s5s(),C=V3e(),{data:T}=gO();lw();const M=Tq(),P=O=>{const{id:$,created_at:q,updated_at:W,lead_source:G,client_type:K,contact:ee,...J}=O;C.mutate(J)},L=()=>{o&&(k.mutate(o),c(null))},I=s.filter(O=>{var ee,J,le,ue;const $=d===""||O.property_address.toLowerCase().includes(d.toLowerCase())||((J=(ee=O.contact)==null?void 0:ee.first_name)==null?void 0:J.toLowerCase().includes(d.toLowerCase()))||((ue=(le=O.contact)==null?void 0:le.last_name)==null?void 0:ue.toLowerCase().includes(d.toLowerCase())),q=h==="all"||O.transaction_type===h,W=p==="all"||O.lead_source_id===p,G=y==="all"||O.client_type_id===y,K=!b||O.is_win;return $&&q&&W&&G&&K});return n?e.jsx(be,{children:e.jsx(Re,{className:"p-6 space-y-4",children:[1,2,3].map(O=>e.jsx(gn,{className:"h-16 w-full"},O))})}):e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs(Ut,{children:["Transactions (",I.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search...",value:d,onChange:O=>u(O.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{className:"w-[100px]",children:e.jsx(bs,{placeholder:"Type"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Types"}),e.jsx(Je,{value:"buyer",children:"Buyer"}),e.jsx(Je,{value:"seller",children:"Seller"})]})]}),e.jsxs(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{className:"w-[130px]",children:e.jsx(bs,{placeholder:"Lead Source"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Sources"}),T==null?void 0:T.map(O=>e.jsx(Je,{value:O.id,children:O.name},O.id))]})]}),e.jsxs(B,{variant:b?"default":"outline",size:"sm",onClick:()=>v(!b),children:[e.jsx(cu,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Re,{children:I.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):M?e.jsx("div",{className:"space-y-3",children:I.map(O=>e.jsxs(be,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium truncate",children:O.property_address}),O.is_win&&e.jsx(cu,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[O.city,O.state?`, ${O.state}`:""]})]}),e.jsx(qe,{variant:O.transaction_type==="buyer"?"default":"secondary",children:O.transaction_type})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Close Date: "}),Vtt(O.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),Su(O.sale_price)]}),t&&O.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),Su(O.commission_amount)]}),O.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),O.lead_source.name]}),O.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),O.contact.first_name," ",O.contact.last_name]}),r&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),r[O.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>l(O),children:e.jsx(kp,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>P(O),children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(O.id),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})]},O.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[r&&e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Close Date"}),e.jsx(Tt,{children:"Sale Price"}),t&&e.jsx(Tt,{children:"Commission"}),e.jsx(Tt,{children:"Lead Source"}),e.jsx(Tt,{children:"Client"}),!a&&e.jsx(Tt,{className:"w-[50px]"})]})}),e.jsx(za,{children:I.map(O=>{var $;return e.jsxs(un,{children:[r&&e.jsx(xt,{className:"font-medium text-sm",children:r[O.owner_user_id]||"Unknown"}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[O.is_win&&e.jsx(cu,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:O.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[O.city,O.state?`, ${O.state}`:""]})]})]})}),e.jsx(xt,{children:e.jsx(qe,{variant:O.transaction_type==="buyer"?"default":"secondary",children:O.transaction_type})}),e.jsx(xt,{children:Vtt(O.close_date)}),e.jsx(xt,{children:Su(O.sale_price)}),t&&e.jsx(xt,{children:O.commission_amount?Su(O.commission_amount):"-"}),e.jsx(xt,{children:(($=O.lead_source)==null?void 0:$.name)||"-"}),e.jsx(xt,{children:O.contact?`${O.contact.first_name} ${O.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(xt,{children:e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(W0,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[e.jsxs(wa,{onClick:()=>l(O),children:[e.jsx(kp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(wa,{onClick:()=>P(O),children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(wa,{onClick:()=>c(O.id),className:"text-destructive",children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},O.id)})})]})})})]}),e.jsx(yzt,{open:!!i,onOpenChange:O=>!O&&l(null),transaction:i||void 0}),e.jsx(Nl,{open:!!o,onOpenChange:O=>!O&&c(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete Transaction?"}),e.jsx(xl,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:L,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function vzt({goals:s,stats:t,year:n,showCommission:r}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===n?a:12,l=12-i,o=(m,p)=>{if(!p||p===0)return null;const x=Math.min(m/p*100,100),y=Math.max(p-m,0),g=l>0?y/l:0,b=i/12*100,v=x>=b?"ahead":x>=b*.8?"on-track":"behind";return{percent:x,remaining:y,pace:g,status:v}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),u=r?o(t.totalCommission,s.gci_goal):null,h=m=>{switch(m){case"ahead":return e.jsxs(qe,{className:"bg-green-500 text-white",children:[e.jsx(kl,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(qe,{variant:"secondary",children:[e.jsx(gN,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(qe,{variant:"destructive",children:[e.jsx(vN,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(uu,{className:"h-5 w-5 text-primary"}),e.jsxs(Ut,{children:[n," Goals Progress"]})]})}),e.jsx(Re,{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(qi,{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(qi,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[Su(t.totalVolume,!0)," of ",Su(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 ",Su(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(qi,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[Su(t.totalCommission,!0)," of ",Su(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 ",Su(u.pace,!0),"/month"]})]})]})})]})}const fkn={light:"",dark:".dark"},bzt=j.createContext(null);function _zt(){const s=j.useContext(bzt);if(!s)throw new Error("useChart must be used within a ");return s}const wzt=j.forwardRef(({id:s,className:t,children:n,config:r,...a},i)=>{const l=j.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(bzt.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":o,ref:i,className:Et("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(xkn,{id:o,config:r}),e.jsx(jb,{children:n})]})})});wzt.displayName="Chart";const xkn=({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(fkn).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},jzt=j.forwardRef(({active:s,payload:t,className:n,indicator:r="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:u,nameKey:h,labelKey:m},p)=>{const{config:x}=_zt(),y=j.useMemo(()=>{var T;if(a||!(t!=null&&t.length))return null;const[b]=t,v=`${m||b.dataKey||b.name||"value"}`,k=_Be(x,b,v),C=!m&&typeof l=="string"?((T=x[l])==null?void 0:T.label)||l:k==null?void 0:k.label;return o?e.jsx("div",{className:Et("font-medium",c),children:o(C,t)}):C?e.jsx("div",{className:Et("font-medium",c),children:C}):null},[l,o,t,a,c,x,m]);if(!s||!(t!=null&&t.length))return null;const g=t.length===1&&r!=="dot";return e.jsxs("div",{ref:p,className:Et("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:[g?null:y,e.jsx("div",{className:"grid gap-1.5",children:t.map((b,v)=>{const k=`${h||b.name||b.dataKey||"value"}`,C=_Be(x,b,k),T=u||b.payload.fill||b.color;return e.jsx("div",{className:Et("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",r==="dot"&&"items-center"),children:d&&(b==null?void 0:b.value)!==void 0&&b.name?d(b.value,b.name,b,v,b.payload):e.jsxs(e.Fragment,{children:[C!=null&&C.icon?e.jsx(C.icon,{}):!i&&e.jsx("div",{className:Et("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":g&&r==="dashed"}),style:{"--color-bg":T,"--color-border":T}}),e.jsxs("div",{className:Et("flex flex-1 justify-between leading-none",g?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[g?y:null,e.jsx("span",{className:"text-muted-foreground",children:(C==null?void 0:C.label)||b.name})]}),b.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:b.value.toLocaleString()})]})]})},b.dataKey)})})]})});jzt.displayName="ChartTooltip";const gkn=j.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=_zt();return n!=null&&n.length?e.jsx("div",{ref:i,className:Et("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=_Be(l,o,c);return e.jsxs("div",{className:Et("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});gkn.displayName="ChartLegend";function _Be(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 lre=["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 XKe({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(be,{children:e.jsx(Re,{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(be,{className:"overflow-hidden",children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Re,{className:"overflow-hidden",children:e.jsx(wzt,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(CAe,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(KD,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(p1,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(f1,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(ff,{content:e.jsx(jzt,{})}),e.jsx(Bj,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Re,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(pWe,{children:[e.jsx($N,{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(_q,{fill:lre[i%lre.length]},`cell-${i}`))}),e.jsx(ff,{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:lre[i%lre.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function ykn(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=hqe(t,r,new Date);if(ZDe(a))return Bs(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if(ZDe(r))return Bs(r,"yyyy-MM-dd")}catch{}return null}const vkn=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function bkn({open:s,onOpenChange:t}){const[n,r]=j.useState([]),[a,i]=j.useState(!1),[l,o]=j.useState(0),{data:c}=gO(),{data:d}=lw(),u=V3e(),h=()=>{const b=vkn.join(","),v=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),k=`${b} ${v}`,C=new Blob([k],{type:"text/csv"}),T=URL.createObjectURL(C),M=document.createElement("a");M.href=T,M.download="transaction-import-template.csv",M.click(),URL.revokeObjectURL(T)},m=b=>{const v=b.split(` `).filter(C=>C.trim());if(v.length<2)return[];const k=v[0].split(",").map(C=>C.trim().toLowerCase().replace(/['"]/g,""));return v.slice(1).map((C,T)=>{var J,le,ue,oe;const M=[];let P="",L=!1;for(const ie of C)ie==='"'?L=!L:ie===","&&!L?(M.push(P.trim()),P=""):P+=ie;M.push(P.trim());const I=ie=>{var we;const de=k.indexOf(ie);return de>=0?(we=M[de])==null?void 0:we.replace(/^["']|["']$/g,"").trim():""},O=(J=I("transaction_type"))==null?void 0:J.toLowerCase(),$=(le=I("sale_price"))==null?void 0:le.replace(/[$,]/g,""),q=(ue=I("commission_amount"))==null?void 0:ue.replace(/[$,]/g,""),W=(oe=I("is_win"))==null?void 0:oe.toLowerCase(),G=I("close_date"),K=ykn(G);let ee;return I("property_address")?["buyer","seller"].includes(O)?K?(!$||isNaN(Number($)))&&(ee="Invalid sale price"):ee=`Invalid date format: "${G}" - use MM/DD/YYYY or YYYY-MM-DD`:ee='Transaction type must be "buyer" or "seller"':ee="Missing property address",{property_address:I("property_address"),city:I("city"),state:I("state"),zip:I("zip"),transaction_type:O==="seller"?"seller":"buyer",close_date:K||"",sale_price:Number($)||0,commission_amount:q?Number(q):null,lead_source_name:I("lead_source"),client_type_name:I("client_type"),is_win:["yes","true","1"].includes(W),notes:I("notes"),error:ee}})},p=b=>{var C;const v=(C=b.target.files)==null?void 0:C[0];if(!v)return;const k=new FileReader;k.onload=T=>{var L;const M=(L=T.target)==null?void 0:L.result,P=m(M);r(P)},k.readAsText(v)},x=async()=>{const b=n.filter(C=>!C.error);if(b.length===0){re.error("No valid transactions to import");return}i(!0),o(0);let v=0,k=0;for(let C=0;CL.name.toLowerCase()===T.lead_source_name.toLowerCase()),P=d==null?void 0:d.find(L=>L.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:(M==null?void 0:M.id)||null,client_type_id:(P==null?void 0:P.id)||null,contact_id:null,notes:T.notes||null,is_win:T.is_win}),v++}catch(M){k++,console.error("Failed to import transaction:",M)}o(Math.round((C+1)/b.length*100))}i(!1),v>0&&re.success(`Imported ${v} transaction${v>1?"s":""}`),k>0&&re.error(`Failed to import ${k} transaction${k>1?"s":""}`),r([]),t(!1)},y=n.filter(b=>!b.error).length,g=n.filter(b=>b.error).length;return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Import Transactions"}),e.jsx(kr,{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(ii,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(ye,{id:"csv-file",type:"file",accept:".csv",onChange:p})]}),n.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(qe,{variant:"outline",children:[n.length," rows found"]}),y>0&&e.jsxs(qe,{className:"bg-green-500 text-white",children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),y," valid"]}),g>0&&e.jsxs(qe,{variant:"destructive",children:[e.jsx(po,{className:"h-3 w-3 mr-1"}),g," 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,v)=>e.jsxs("div",{className:`p-2 rounded text-sm ${b.error?"bg-destructive/10":"bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:b.property_address||"(no address)"}),e.jsx(qe,{variant:b.transaction_type==="buyer"?"default":"secondary",children:b.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[b.close_date," • $",b.sale_price.toLocaleString()]}),b.error&&e.jsx(LHe,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(PHe,{className:"text-xs",children:b.error})})]},v)),n.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",n.length-10," more"]})]})}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${l}%`}})}),e.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",l,"%"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:x,disabled:y===0||a,children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),"Import ",y," Transaction",y!==1?"s":""]})]})]})]})})}const _kn=iS({transactions_goal:SK().min(0).optional(),volume_goal:SK().min(0).optional(),gci_goal:SK().min(0).optional()});function wkn({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=n5s(),{data:i}=H3e(),l=(i==null?void 0:i.show_commission)??!0,o=D3e({resolver:O3e(_kn),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});j.useEffect(()=>{r?o.reset({transactions_goal:r.transactions_goal??void 0,volume_goal:r.volume_goal?Number(r.volume_goal):void 0,gci_goal:r.gci_goal?Number(r.gci_goal):void 0}):o.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[r,o,s]);const c=async d=>{await a.mutateAsync({year:n,transactions_goal:d.transactions_goal??null,volume_goal:d.volume_goal??null,gci_goal:l?d.gci_goal??null:null}),t(!1)};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs($s,{children:[e.jsxs(zs,{children:[n," Goals"]}),e.jsx(kr,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(F3e,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(Np,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Transactions Goal"}),e.jsx(Um,{children:e.jsx(ye,{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(kje,{children:"Total number of deals you want to close"}),e.jsx(Kv,{})]})}),e.jsx(Np,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"Volume Goal ($)"}),e.jsx(Um,{children:e.jsx(ye,{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(kje,{children:"Total sales volume you want to achieve"}),e.jsx(Kv,{})]})}),l&&e.jsx(Np,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(Bm,{children:[e.jsx($m,{children:"GCI Goal ($)"}),e.jsx(Um,{children:e.jsx(ye,{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(kje,{children:"Gross commission income target"}),e.jsx(Kv,{})]})}),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 QKe({transactions:s,isLoading:t}){const n=j.useRef(null),r=j.useRef(null),a=j.useRef([]),i=j.useRef(null),{isAdmin:l}=Ns(),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(0),[p,x]=j.useState(!1),y=s.filter(b=>b.latitude!=null&&b.longitude!=null),g=s.filter(b=>b.latitude==null||b.longitude==null);return j.useEffect(()=>{(async()=>{u(!0);try{const{data:v}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();v!=null&&v.value&&c(v.value)}catch(v){console.error("Error fetching mapbox token:",v)}u(!1)})()},[]),j.useEffect(()=>{if(!o||g.length===0||p)return;(async()=>{var k;x(!0);let v=0;for(const C of g){const T=[C.property_address,C.city,C.state,C.zip].filter(Boolean).join(", ");if(T)try{const P=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(T)}.json?access_token=${o}&limit=1`)).json();if((k=P.features)!=null&&k[0]){const[L,I]=P.features[0].center;await U.from("scorecard_transactions").update({latitude:I,longitude:L}).eq("id",C.id),C.latitude=I,C.longitude=L,v++}}catch(M){console.error("Geocode error:",M)}}m(v),x(!1)})()},[o,s]),j.useEffect(()=>{if(!n.current||!o||r.current)return;$c.accessToken=o;const b=s.filter(C=>C.latitude!=null&&C.longitude!=null);let v=[-98.5795,39.8283],k=4;if(b.length>0){const C=b.reduce((M,P)=>M+P.longitude,0)/b.length,T=b.reduce((M,P)=>M+P.latitude,0)/b.length;v=[C,T],k=b.length===1?12:10}return r.current=new $c.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:k,center:v}),r.current.addControl(new $c.NavigationControl,"top-right"),()=>{var C;(C=r.current)==null||C.remove(),r.current=null}},[o]),j.useEffect(()=>{var v;if(!r.current||!o)return;a.current.forEach(k=>k.remove()),a.current=[],(v=i.current)==null||v.remove();const b=s.filter(k=>k.latitude!=null&&k.longitude!=null);if(b.forEach(k=>{var I;const C=k.transaction_type==="buyer",T=C?"#3B82F6":"#10B981",M=document.createElement("div");M.className="cursor-pointer",M.innerHTML=`
${C?'':''}
`;const P=new $c.Popup({offset:25,closeButton:!0}).setHTML(`
${k.property_address}
${k.city?`
${k.city}${k.state?", "+k.state:""} ${k.zip||""}
`:""}
${C?"Buyer":"Seller"} $${Number(k.sale_price).toLocaleString()}
Closed: ${Ic(k.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(I=k.lead_source)!=null&&I.name?" · "+k.lead_source.name:""}
${k.contact?`
Client: ${k.contact.first_name} ${k.contact.last_name||""}
`:""}
`),L=new $c.Marker(M).setLngLat([k.longitude,k.latitude]).setPopup(P).addTo(r.current);a.current.push(L)}),b.length>1){const k=new $c.LngLatBounds;b.forEach(C=>k.extend([C.longitude,C.latitude])),r.current.fitBounds(k,{padding:60,maxZoom:13})}else b.length===1&&r.current.flyTo({center:[b[0].longitude,b[0].latitude],zoom:12})},[s,o,p]),d||t?e.jsx(be,{children:e.jsx(Re,{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(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(oi,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"No Transactions Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add transactions to see them plotted on the map."})]})]})}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#3B82F6"}}),e.jsx("span",{children:"Buyer"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#10B981"}}),e.jsx("span",{children:"Seller"})]}),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[y.length," of ",s.length," mapped",p&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(po,{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 Nzt=()=>{const{data:s}=Hj();return mt({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:n}=await U.from("team_members").select("user_id").eq("team_id",s.teamId);if(n)throw n;const r=t.map(l=>l.user_id),{data:a,error:i}=await U.from("profiles").select("id, name, email, avatar_url").in("id",r);if(i)throw i;return a||[]},enabled:!!(s!=null&&s.teamId)&&(s==null?void 0:s.role)==="team_leader"})},jkn=s=>{const{data:t}=Hj(),{data:n}=Nzt();return mt({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const r=n.map(o=>o.id);let a=U.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",r).order("close_date",{ascending:!1});s&&(a=a.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:i,error:l}=await a;if(l)throw l;return i},enabled:!!n&&n.length>0})};function Nkn(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 kkn(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function Skn({year:s}){var m;const{data:t,isLoading:n}=Nzt(),{data:r,isLoading:a}=jkn(s),i=Hn(),l=n||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:u,teamChartStats:h}=j.useMemo(()=>{if(!t||!r)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const p=t.map(O=>Nkn(O,r));p.sort((O,$)=>$.totalVolume-O.totalVolume);const x={};t.forEach(O=>{x[O.id]=O.name||O.email});const y=r.length,g=r.reduce((O,$)=>O+Number($.sale_price),0),b=r.reduce((O,$)=>O+(Number($.commission_amount)||0),0),v=r.filter(O=>O.transaction_type==="buyer").length,k=r.filter(O=>O.transaction_type==="seller").length,C={};r.forEach(O=>{var q;const $=((q=O.lead_source)==null?void 0:q.name)||"Unknown";C[$]=(C[$]||0)+1});const T=Object.entries(C).sort((O,$)=>$[1]-O[1])[0],M={};r.forEach(O=>{const $=Ic(O.close_date).toLocaleString("default",{month:"short"});M[$]=(M[$]||0)+1});const L=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(O=>({month:O,count:M[O]||0})),I=Object.entries(C).map(([O,$])=>({name:O,count:$})).sort((O,$)=>$.count-O.count);return{aggregate:{totalTxns:y,buyerCount:v,sellerCount:k,totalVolume:g,avgPrice:y>0?g/y:0,totalGCI:b,topSource:T?{name:T[0],count:T[1]}:null,memberCount:t.length},memberStats:p,topPerformer:p[0]||null,agentNameMap:x,teamChartStats:{transactionsByMonth:L,leadSourceBreakdown:I}}},[t,r]);return l?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(p=>e.jsx(gn,{className:"h-24"},p))}),e.jsx(gn,{className:"h-64"})]}):!o||c.length===0?e.jsx(be,{className:"py-12",children:e.jsxs(Re,{className:"text-center space-y-2",children:[e.jsx(Bn,{className:"h-10 w-10 mx-auto text-muted-foreground"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No Team Data"}),e.jsxs("p",{className:"text-muted-foreground",children:["No scorecard transactions found for your team members in ",s,"."]})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Members"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.memberCount})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ia,{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(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Od,{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:Su(o.totalVolume,!0)})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(kl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Su(o.avgPrice,!0)})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Od,{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:Su(o.totalGCI,!0)})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(cu,{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(be,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Re,{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(ll,{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:Su(d.totalVolume,!0)})]})]})}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Member Performance"})}),e.jsx(Re,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Transactions"}),e.jsx(Tt,{className:"text-center",children:"B / S"}),e.jsx(Tt,{className:"text-right",children:"Volume"}),e.jsx(Tt,{className:"text-right",children:"Avg Price"}),e.jsx(Tt,{className:"text-right",children:"GCI"}),e.jsx(Tt,{className:"text-right"})]})}),e.jsx(za,{children:c.map((p,x)=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[x===0&&p.totalTransactions>0&&e.jsx(ll,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:p.member.avatar_url||void 0}),e.jsx(Da,{className:"text-xs",children:kkn(p.member.name,p.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:p.member.name||p.member.email}),p.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:p.member.email})]})]})}),e.jsx(xt,{className:"text-center font-semibold",children:p.totalTransactions}),e.jsxs(xt,{className:"text-center text-sm",children:[p.buyerCount," / ",p.sellerCount]}),e.jsx(xt,{className:"text-right font-medium",children:Su(p.totalVolume,!0)}),e.jsx(xt,{className:"text-right text-sm",children:Su(p.averagePrice,!0)}),e.jsx(xt,{className:"text-right font-medium",children:Su(p.totalGCI,!0)}),e.jsx(xt,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${p.member.id}`),children:e.jsx(ma,{className:"h-4 w-4"})})})]},p.member.id))})]})})})]}),e.jsxs(fa,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"transactions",children:[e.jsx(ug,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(ss,{value:"charts",children:[e.jsx(ol,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(ss,{value:"map",children:[e.jsx(oi,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(ns,{value:"transactions",children:e.jsx(ZKe,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(ns,{value:"charts",children:h&&e.jsx(XKe,{stats:h,year:s})}),e.jsx(ns,{value:"map",children:e.jsx(QKe,{transactions:r||[],isLoading:a})})]})]})}const N2e=new Date().getFullYear(),Zxt=Array.from({length:10},(s,t)=>N2e-t),cre="all";function Ckn(){var q;const[s,t]=j.useState(N2e),n=s===null?cre:String(s),r=W=>t(W===cre?null:Number(W)),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState("my"),{data:x}=Hj(),y=(x==null?void 0:x.role)==="team_leader",{data:g,isLoading:b}=SVe(s??void 0),{yearStats:v,lifetimeStats:k,isLoading:C,showCommission:T}=oAt(s??void 0),{data:M,isLoading:P}=iAt(s??N2e),{data:L}=H3e(),I=r5s(),O=()=>{if(!g||g.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=g.map(ue=>{var oe,ie;return[ue.property_address,ue.city||"",ue.state||"",ue.zip||"",ue.transaction_type,ue.close_date,ue.sale_price,...T?[ue.commission_amount||""]:[],((oe=ue.lead_source)==null?void 0:oe.name)||"",((ie=ue.client_type)==null?void 0:ie.name)||"",ue.contact?`${ue.contact.first_name} ${ue.contact.last_name||""}`.trim():"",ue.is_win?"Yes":"No",ue.notes||""]}),K=[W,...G].map(ue=>ue.map(oe=>`"${String(oe).replace(/"/g,'""')}"`).join(",")).join(` `),ee=new Blob([K],{type:"text/csv"}),J=URL.createObjectURL(ee),le=document.createElement("a");le.href=J,le.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,le.click(),URL.revokeObjectURL(J)},$=!g||g.length===0;return e.jsxs(Vs,{title:"Scorecard",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),y&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx(B,{variant:m==="my"?"default":"ghost",size:"sm",onClick:()=>p("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(B,{variant:m==="team"?"default":"ghost",size:"sm",onClick:()=>p("team"),className:"h-8",children:[e.jsx(Bn,{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(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"w-[140px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:cre,children:"All Years"}),Zxt.map(W=>e.jsx(Je,{value:String(W),children:W},W))]})]})]}),e.jsx(Skn,{year:s??void 0})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),e.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"w-[140px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:cre,children:"All Years"}),Zxt.map(W=>e.jsx(Je,{value:String(W),children:W},W))]})]}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(ic,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsx(Ut,{className:"text-lg",children:"Settings"})}),e.jsx(Re,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(se,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(Mn,{checked:(L==null?void 0:L.show_commission)??!0,onCheckedChange:W=>I.mutate({show_commission:W})})]})})]}),$&&!b?e.jsx(be,{className:"py-12",children:e.jsxs(Re,{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(ol,{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(Js,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Ja,{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(ii,{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(Js,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(uu,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(B,{variant:"outline",onClick:O,disabled:$,children:[e.jsx(ii,{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(ii,{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(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ia,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:v.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[k.totalTransactions," lifetime"]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[v.buyerCount,"/",v.sellerCount]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Od,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Su(v.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Su(k.totalVolume,!0)," lifetime"]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(kl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Su(v.averagePrice,!0)})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(cu,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((q=v.topLeadSource)==null?void 0:q.name)||"-"}),v.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.topLeadSource.count," deals"]})]})}),T&&e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Od,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Su(v.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Su(k.totalCommission,!0)," lifetime"]})]})}),T&&v.totalNetToAgent>0&&v.totalNetToAgent!==v.totalCommission&&e.jsx(be,{children:e.jsxs(Re,{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(Od,{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:Su(v.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Su(k.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&M&&e.jsx(vzt,{goals:M,stats:v,year:s,showCommission:T}),e.jsxs(fa,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"transactions",children:"Transactions"}),e.jsx(ss,{value:"charts",children:"Charts"}),e.jsxs(ss,{value:"map",children:[e.jsx(oi,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(ns,{value:"transactions",children:e.jsx(ZKe,{transactions:g||[],showCommission:T,isLoading:b})}),e.jsx(ns,{value:"charts",children:e.jsx(XKe,{stats:v,year:s??void 0})}),e.jsx(ns,{value:"map",children:e.jsx(QKe,{transactions:g||[],isLoading:b})})]})]})]})]}),e.jsx(yzt,{open:a,onOpenChange:i}),e.jsx(bkn,{open:l,onOpenChange:o}),e.jsx(wkn,{open:c,onOpenChange:d,year:s??N2e,existingGoals:M})]})}function kzt({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a}){const{user:i}=Ns(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(!1);j.useEffect(()=>{(async()=>{if(!(!s||!i)){d(!0);try{const{data:g,error:b}=await U.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",n).eq("sharing_agent_id",i.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(b)throw b;if(g&&g.share_token)o(g);else if(g&&!g.share_token){const{data:v,error:k}=await U.from("listing_shares").update({share_type:"referral_link"}).eq("id",g.id).select("id, share_token, click_count, lead_count").single();if(k)throw k;o(v)}else{const{data:v,error:k}=await U.from("listing_shares").insert({listing_id:n,sharing_agent_id:i.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(k)throw k;o(v)}}catch(g){console.error("Error creating share link:",g),re.error("Failed to generate share link")}finally{d(!1)}}})()},[s,i,n]);const m=l!=null&&l.share_token?`https://listings.relevelup.com/${r||n}?ref=${l.share_token}`:"",p=async()=>{try{await navigator.clipboard.writeText(m),h(!0),re.success("Link copied to clipboard!"),setTimeout(()=>h(!1),2e3)}catch{re.error("Failed to copy link")}},x=y=>{const g=encodeURIComponent(m),b=encodeURIComponent(`Check out this listing: ${a}`);switch(y){case"email":window.open(`mailto:?subject=${b}&body=${g}`);break;case"text":window.open(`sms:?body=${b}%20${g}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${g}`,"_blank");break}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(kr,{children:"Share this listing with your network. When someone submits a lead through your link, they'll become your contact!"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-lg p-3",children:e.jsxs("p",{className:"text-sm text-amber-800 dark:text-amber-200",children:[e.jsx("strong",{children:"How it works:"})," The listing still shows the original agent's info, but any leads from your unique link go directly to you!"]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:c?"Generating...":m,readOnly:!0,className:"font-mono text-sm"}),e.jsx(B,{onClick:p,disabled:c||!m,variant:u?"default":"outline",children:u?e.jsx(da,{className:"h-4 w-4"}):e.jsx(ja,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>x("email"),disabled:c,children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>x("text"),disabled:c,children:[e.jsx(ro,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>x("facebook"),disabled:c,children:[e.jsx(sx,{className:"h-4 w-4 mr-2"}),"Facebook"]})]})]}),l&&(l.click_count>0||l.lead_count>0)&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(se,{className:"mb-2 block",children:"Your Share Performance"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-muted rounded-lg p-3 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-muted-foreground mb-1",children:[e.jsx(ma,{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(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:l.lead_count})]})]})]})]})]})})}const Akn={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"},Tkn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},Ekn={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function Mkn({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,showActions:i}){var g,b;const{user:l}=Ns(),{data:o}=eAt(s.id),c=JCt(),[d,u]=j.useState(!1),h=v=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(v),m=((g=s.photos)==null?void 0:g.find(v=>v.is_primary))||((b=s.photos)==null?void 0:b[0]),p=(l==null?void 0:l.id)===s.agent_id,x=async v=>{v.stopPropagation();try{const k=await c.mutateAsync(s.id);re.success(k.saved?"Listing saved!":"Listing removed from saved")}catch{re.error("Failed to save listing")}},y=v=>{if(v.stopPropagation(),l)u(!0);else{const k=`https://listings.relevelup.com/${s.slug||s.id}`;navigator.clipboard.writeText(k),re.success("Link copied to clipboard!")}};return e.jsxs(be,{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(H_,{className:"h-12 w-12"})}),e.jsx(qe,{className:`absolute top-2 left-2 ${Akn[s.status]} text-white border-0`,children:Tkn[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:x,children:e.jsx(mo,{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:p?"Copy link":"Share & earn leads",children:p?e.jsx(zd,{className:"h-4 w-4"}):e.jsx(yn,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(kzt,{open:d,onOpenChange:u,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`}),e.jsxs(Re,{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(qe,{variant:"outline",className:"text-xs",children:[e.jsx(Bn,{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(oi,{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(U_,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(t0,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(H_,{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(qe,{variant:"secondary",className:"text-xs",children:Ekn[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(ma,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zd,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mo,{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:v=>{v.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:v=>{v.stopPropagation(),n()},children:[e.jsx(kp,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx(B,{variant:"destructive",size:"sm",onClick:v=>{v.stopPropagation(),r()},children:e.jsx(Rn,{className:"h-4 w-4"})})]})]})]})}const JKe="lu_listing_selection_v1",ASe=24,TSe=new Set;function Szt(){try{return JSON.parse(sessionStorage.getItem(JKe)||"{}")}catch{return{}}}function qIe(s){try{sessionStorage.setItem(JKe,JSON.stringify(s))}catch{}TSe.forEach(t=>t())}let m4=Szt();function Lkn(){m4=Szt(),TSe.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===JKe&&Lkn()});const vA={getSnapshot:()=>m4,subscribe(s){return TSe.add(s),()=>TSe.delete(s)},toggle(s){const t={...m4};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=ASe)return!1;t[s.mlsNumber]=s}return m4=t,qIe(t),!0},remove(s){const t={...m4};delete t[s],m4=t,qIe(t)},clear(){m4={},qIe({})},has(s){return!!m4[s]},all(){return Object.values(m4)}};function Czt(){const s=j.useSyncExternalStore(vA.subscribe,vA.getSnapshot,vA.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:vA.toggle,remove:vA.remove,clear:vA.clear}}const Pkn=new Set(["office_exclusive","coming_soon","pre_market"]);function Ikn(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=Pkn.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 dre(s){const{has:t}=Czt(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(Mkn,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),vA.toggle(Ikn(s.listing))||re.error(`You can select up to ${ASe} 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(da,{className:"h-4 w-4"}):e.jsx(on,{className:"h-4 w-4"})})]})}function Rkn({open:s,onOpenChange:t,listings:n}){const{user:r}=Ns(),{leadSite:a}=h0(),[i,l]=j.useState("grid"),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(new Set),[y,g]=j.useState(!1),[b,v]=j.useState(!1),{data:k}=AAe(),[C,T]=j.useState(!1);j.useEffect(()=>{!s||!(r!=null&&r.id)||U.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle().then(({data:K})=>v(!!(K!=null&&K.gmail_email)))},[s,r==null?void 0:r.id]),j.useEffect(()=>{if(s){if(!o){const K=Array.from(new Set(n.map(J=>J.city).filter(Boolean))),ee=K.length===1?` in ${K[0]}`:"";c(n.length===1?`New listing for you${ee}`:`${n.length} hand-picked listings${ee}`)}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:M=[],isLoading:P}=mt({queryKey:["send-listings-contacts",r==null?void 0:r.id],queryFn:async()=>{const{data:K}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, city").eq("owner_user_id",r.id).not("email","is",null).neq("email","").order("first_name");return K||[]},enabled:!!(r!=null&&r.id)&&s}),{data:L}=mt({queryKey:["send-listings-suggestions",n.map(K=>K.mlsNumber).join(",")],queryFn:async()=>{const{data:K,error:ee}=await U.functions.invoke("listing-email-suggestions",{body:{listings:n.map(J=>({mlsNumber:J.mlsNumber,city:J.city,state:J.state,price:J.price,bedrooms:J.bedrooms,bathrooms:J.bathrooms}))}});if(ee)throw ee;return K},enabled:s&&n.length>0}),I=(L==null?void 0:L.suggestions)||[],O=j.useMemo(()=>{const K=h.trim().toLowerCase();return K?M.filter(ee=>`${ee.first_name??""} ${ee.last_name??""} ${ee.email} ${ee.city??""}`.toLowerCase().includes(K)):M},[M,h]),$=K=>{x(ee=>{const J=new Set(ee);return J.has(K)?J.delete(K):J.add(K),J})},q=()=>{x(K=>{const ee=new Set(K);return I.forEach(J=>ee.add(J.contact_id)),ee})},W=n.length>0&&n.every(K=>K.mlsNumber.startsWith("lx-")),G=async()=>{if(!W&&!(a!=null&&a.id)){re.error("You need an active lead site to send listings.");return}if(!o.trim())return re.error("Subject is required");if(p.size===0)return re.error("Pick at least one recipient");if(!b&&k&&!k.hasVerifiedSes){T(!0);return}const K=M.filter(ee=>p.has(ee.id)).map(ee=>({contact_id:ee.id,email:ee.email,first_name:ee.first_name,last_name:ee.last_name}));g(!0);try{const{data:ee,error:J}=await U.functions.invoke("listing-email-send",{body:{lead_site_id:(a==null?void 0:a.id)||null,layout:i,subject:o.trim(),intro_message:d.trim()||null,listings:n.map(le=>({mlsNumber:le.mlsNumber,address:le.address,city:le.city,state:le.state,zip:le.zip,price:le.price,bedrooms:le.bedrooms,bathrooms:le.bathrooms,sqft:le.sqft,status:le.status,photos:(le.photos||[]).slice(0,1),description:le.description||"",external_url:le.externalUrl||null,is_private:le.is_private===!0})),recipients:K}});if(J)throw J;if(!(ee!=null&&ee.success))throw new Error((ee==null?void 0:ee.error)||"Send failed");re.success(`Sent ${ee.sent}/${K.length} via ${b?"Gmail":"Amazon SES"}${ee.failed?` · ${ee.failed} failed`:""}`),vA.clear(),x(new Set),t(!1)}catch(ee){re.error((ee==null?void 0:ee.message)||"Failed to send")}finally{g(!1)}};return e.jsxs(Fs,{open:s,onOpenChange:t,children:[e.jsxs(Os,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs($s,{className:"px-6 pt-6 pb-2",children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(kr,{children:W?"Send your Listing Exchange properties. Recipients land on listings.relevelup.com and clicks track back to the contact.":"Drive traffic to your site. Recipients land on your lead site and clicks show up on Mission Control."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-0 flex-1 overflow-hidden",children:[e.jsxs("div",{className:"overflow-y-auto px-6 pb-4 space-y-4 border-r",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Selected listings"}),e.jsx("div",{className:"mt-2 flex gap-2 overflow-x-auto pb-1",children:n.map(K=>{var ee;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:((ee=K.photos)==null?void 0:ee[0])&&e.jsx("img",{src:K.photos[0],alt:"",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"p-1.5",children:[e.jsxs("div",{className:"text-[11px] font-semibold truncate",children:["$",(K.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[K.city,", ",K.state]})]})]},K.mlsNumber)})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Layout"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[e.jsxs("button",{type:"button",onClick:()=>l("grid"),className:`rounded-lg border p-3 text-left transition ${i==="grid"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(r0,{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(ac,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Hero + list"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"First listing gets spotlight"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"subject",children:"Subject"}),e.jsx(ye,{id:"subject",value:o,onChange:K=>c(K.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"intro",children:"Personal message"}),e.jsx(Ds,{id:"intro",value:d,onChange:K=>u(K.target.value),placeholder:"Optional intro shown above the listings…",className:"mt-1 min-h-[120px]"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Use ",e.jsx("code",{className:"px-1 rounded bg-muted",children:"{{first_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 text-xs text-muted-foreground",children:["Sending via"," ",e.jsx("span",{className:"font-medium text-foreground",children:b?"your connected Gmail":"Amazon SES"}),". Every click tracks back to the contact and triggers a buyer signal."]})]}),e.jsxs("div",{className:"flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"px-6 pt-4 pb-2 space-y-3",children:[I.length>0&&e.jsxs(be,{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(yn,{className:"h-4 w-4 text-amber-600"}),e.jsxs("div",{className:"text-sm font-medium",children:[I.length," smart ",I.length===1?"match":"matches"]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:q,children:"Add all"})]}),e.jsx(lo,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:I.slice(0,12).map(K=>{const ee=p.has(K.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(wi,{checked:ee,onCheckedChange:()=>$(K.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[K.first_name," ",K.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",K.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:K.reason})]})]},K.contact_id)})})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",O.length,")"]}),p.size>0&&e.jsxs(qe,{variant:"secondary",children:[p.size," selected"]})]}),e.jsx(ye,{placeholder:"Search contacts…",value:h,onChange:K=>m(K.target.value)})]}),e.jsx("div",{className:"flex-1 overflow-hidden px-6 pb-2",children:e.jsx("div",{className:"border rounded-md h-full",children:e.jsx(lo,{className:"h-full",children:P?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):O.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:O.map(K=>{const ee=p.has(K.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx(wi,{checked:ee,onCheckedChange:()=>$(K.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[K.first_name," ",K.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[K.email,K.city&&e.jsxs(e.Fragment,{children:[" · ",K.city]})]})]})]},K.id)})})})})}),e.jsxs("div",{className:"px-6 py-2 text-xs text-muted-foreground border-t flex items-center justify-between",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:p.size})," recipients"]}),p.size>0&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>x(new Set),children:[e.jsx(dr,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(Nr,{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||p.size===0,children:y?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Send to ",p.size," ",p.size===1?"contact":"contacts"]})})]})]}),e.jsx(TAe,{open:C,onOpenChange:T,hasPending:!!(k!=null&&k.hasPendingSes),pendingEmails:k==null?void 0:k.pendingEmails})]})}function Dkn(){const{selected:s,count:t,remove:n,clear:r}=Czt(),[a,i]=j.useState(!1);return t===0?null:e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 z-50 w-[min(96vw,820px)]",children:e.jsxs("div",{className:"rounded-2xl border bg-background/95 backdrop-blur shadow-2xl p-3 flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-primary/10 text-primary flex items-center justify-center font-semibold",children:t}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium leading-tight",children:[t," listing",t===1?"":"s"," selected"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t>=ASe?"Max reached":`Pick up to ${ASe}`})]})]}),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(dr,{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(Rn,{className:"h-4 w-4"})," Clear"]}),e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(Dr,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(Rkn,{open:a,onOpenChange:i,listings:s})]})}const Okn=[{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"}],Fkn=[{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 zkn({filters:s,onFiltersChange:t,onClose:n}){const r=()=>{t({sortBy:"newest"})};return e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(Ut,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:r,children:"Clear All"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(dr,{className:"h-4 w-4"})})]})]}),e.jsxs(Re,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:s.status||"all",onValueChange:a=>t({...s,status:a==="all"?void 0:a}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"All statuses"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Statuses"}),Okn.map(a=>e.jsx(Je,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Type"}),e.jsxs(vs,{value:s.propertyType||"all",onValueChange:a=>t({...s,propertyType:a==="all"?void 0:a}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"All types"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Types"}),Fkn.map(a=>e.jsx(Je,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Min Price"}),e.jsx(ye,{type:"number",placeholder:"No minimum",value:s.minPrice||"",onChange:a=>t({...s,minPrice:a.target.value?Number(a.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Max Price"}),e.jsx(ye,{type:"number",placeholder:"No maximum",value:s.maxPrice||"",onChange:a=>t({...s,maxPrice:a.target.value?Number(a.target.value):void 0})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(Mn,{checked:s.openToReferrals||!1,onCheckedChange:a=>t({...s,openToReferrals:a||void 0})})]})]})]})}function Bkn({leaderboard:s}){const t=r=>{switch(r){case 0:return e.jsx(ll,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(_3,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(cu,{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(qe,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ll,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Re,{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(zd,{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(ia,{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(_3,{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(ll,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Community Leaderboard"})}),e.jsx(Re,{children:e.jsxs(fa,{defaultValue:"sharers",children:[e.jsxs(xa,{className:"w-full",children:[e.jsxs(ss,{value:"sharers",className:"flex-1",children:[e.jsx(zd,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(ss,{value:"listers",className:"flex-1",children:[e.jsx(ia,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(ns,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(ns,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const Xxt={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},Qxt={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 $kn(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function Ukn({listings:s,isLoading:t}){const n=Hn(),r=j.useRef(null),a=j.useRef(null),i=j.useRef([]),{isAdmin:l}=Ns(),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(!1),p=s.filter(y=>y.latitude!=null&&y.longitude!=null),x=s.filter(y=>(y.latitude==null||y.longitude==null)&&(y.property_address||y.city));return j.useEffect(()=>{(async()=>{u(!0);try{const{data:g}=await U.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();g!=null&&g.value&&c(g.value)}catch(g){console.error("Error fetching mapbox token:",g)}u(!1)})()},[]),j.useEffect(()=>{if(!o||x.length===0||h)return;(async()=>{var g;m(!0);for(const b of x){const v=[b.property_address,b.city,b.state].filter(Boolean).join(", ");if(v)try{const C=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(v)}.json?access_token=${o}&limit=1`)).json();if((g=C.features)!=null&&g[0]){const[T,M]=C.features[0].center;await U.from("listings").update({latitude:M,longitude:T}).eq("id",b.id),b.latitude=M,b.longitude=T}}catch(k){console.error("Geocode error:",k)}}m(!1)})()},[o,s]),j.useEffect(()=>{if(!r.current||!o||a.current)return;$c.accessToken=o;const y=s.filter(v=>v.latitude!=null&&v.longitude!=null);let g=[-98.5795,39.8283],b=4;if(y.length>0){const v=y.reduce((C,T)=>C+T.longitude,0)/y.length,k=y.reduce((C,T)=>C+T.latitude,0)/y.length;g=[v,k],b=y.length===1?12:10}return a.current=new $c.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:b,center:g}),a.current.addControl(new $c.NavigationControl,"top-right"),()=>{var v;(v=a.current)==null||v.remove(),a.current=null}},[o]),j.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(g=>g.remove()),i.current=[];const y=s.filter(g=>g.latitude!=null&&g.longitude!=null);if(y.forEach(g=>{var M,P,L;const b=Xxt[g.status]||"#10B981",v=((M=g.photos)==null?void 0:M.find(I=>I.is_primary))||((P=g.photos)==null?void 0:P[0]),k=document.createElement("div");k.className="cursor-pointer",k.innerHTML=`
`;const C=new $c.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${v!=null&&v.photo_url?``:""}
${$kn(g.price)}
${g.property_address||""}
${g.city}, ${g.state}
${Qxt[g.status]||g.status} ${g.bedrooms?`${g.bedrooms} bed`:""} ${g.bathrooms?`${g.bathrooms} bath`:""}
${(L=g.agent)!=null&&L.name?`
Listed by ${g.agent.name}
`:""}
Click to view details →
`),T=new $c.Marker(k).setLngLat([g.longitude,g.latitude]).setPopup(C).addTo(a.current);i.current.push(T)}),y.length>1){const g=new $c.LngLatBounds;y.forEach(b=>g.extend([b.longitude,b.latitude])),a.current.fitBounds(g,{padding:60,maxZoom:13})}else y.length===1&&a.current.flyTo({center:[y[0].longitude,y[0].latitude],zoom:12})},[s,o,h]),j.useEffect(()=>(window.__navigateToListing__=y=>{n(`/mission-control/listings/${y}`)},()=>{delete window.__navigateToListing__}),[n]),d||t?e.jsx(be,{children:e.jsx(Re,{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(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(oi,{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(Xxt).map(([y,g])=>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:g}}),e.jsx("span",{className:"text-xs",children:Qxt[y]})]},y)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[p.length," of ",s.length," mapped",h&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(po,{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 wBe="homereel_mv_prefill",jBe="homereel_mv_badge_default";function Azt(s){try{sessionStorage.setItem(wBe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(jBe,JSON.stringify(s.badge))}catch{}}function o$n(){try{const s=sessionStorage.getItem(wBe);return s?(sessionStorage.removeItem(wBe),JSON.parse(s)):null}catch{return null}}function l$n(){try{const s=sessionStorage.getItem(jBe);return s?(sessionStorage.removeItem(jBe),JSON.parse(s)):null}catch{return null}}function Tzt(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 qkn(){var I,O,$,q,W,G,K,ee;const s=Hn(),{brokerageId:t}=Ns(),{data:n,isLoading:r}=YCt(),[a,i]=j.useState("feed"),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState({sortBy:"newest"}),{data:m,isLoading:p}=ZCt({...u,city:c||u.city}),{data:x,isLoading:y}=Bks(),{data:g,isLoading:b}=XCt(),{data:v,isLoading:k}=Vks(),{data:C,isLoading:T}=Wks(),{data:M}=Gks(),P=QCt(),L=async J=>{if(await Bi("Are you sure you want to delete this listing? This action cannot be undone."))try{await P.mutateAsync(J),re.success("Listing deleted successfully")}catch{re.error("Failed to delete listing")}};return r?e.jsx(Vs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):n?e.jsxs(Vs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Js,{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(be,{children:e.jsxs(Re,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(ia,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("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(be,{children:e.jsxs(Re,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(mo,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(x==null?void 0:x.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(LR,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(g==null?void 0:g.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(Bn,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((I=v==null?void 0:v.sent)==null?void 0:I.length)||0)+(((O=v==null?void 0:v.received)==null?void 0:O.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(fa,{value:a,onValueChange:i,children:[e.jsxs(xa,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(ss,{value:"feed",children:"Community Feed"}),t&&e.jsx(ss,{value:"brokerage",children:"Brokerage"}),e.jsx(ss,{value:"my-listings",children:"My Listings"}),e.jsx(ss,{value:"saved",children:"Saved"}),e.jsx(ss,{value:"referrals",children:"Referrals"}),e.jsx(ss,{value:"map",children:"Map"}),e.jsx(ss,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(ns,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by city or neighborhood...",value:c,onChange:J=>d(J.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:u.sortBy,onValueChange:J=>h({...u,sortBy:J}),children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"Sort by"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"newest",children:"Newest First"}),e.jsx(Je,{value:"updated",children:"Recently Updated"}),e.jsx(Je,{value:"price_asc",children:"Price: Low to High"}),e.jsx(Je,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(Nj,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(zkn,{filters:u,onFiltersChange:h,onClose:()=>o(!1)}),p?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((J,le)=>e.jsxs(be,{children:[e.jsx(gn,{className:"h-48 w-full"}),e.jsxs(Re,{className:"p-4 space-y-2",children:[e.jsx(gn,{className:"h-5 w-3/4"}),e.jsx(gn,{className:"h-4 w-1/2"}),e.jsx(gn,{className:"h-4 w-1/4"})]})]},le))}):(m==null?void 0:m.length)===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center",children:[e.jsx(ia,{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(Js,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:m==null?void 0:m.map(J=>e.jsx(dre,{listing:J,onClick:()=>s(`/mission-control/listings/${J.id}`)},J.id))})]}),e.jsx(ns,{value:"my-listings",className:"space-y-4",children:b?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((J,le)=>e.jsxs(be,{children:[e.jsx(gn,{className:"h-48 w-full"}),e.jsxs(Re,{className:"p-4 space-y-2",children:[e.jsx(gn,{className:"h-5 w-3/4"}),e.jsx(gn,{className:"h-4 w-1/2"})]})]},le))}):(g==null?void 0:g.length)===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center",children:[e.jsx(LR,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Share your listings with the LevelUp community!"}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Js,{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:g==null?void 0:g.map(J=>e.jsx(dre,{listing:J,showActions:!0,onClick:()=>s(`/mission-control/listings/${J.id}`),onEdit:()=>s(`/mission-control/listings/${J.id}/edit`),onDelete:()=>L(J.id),onCreateMusicVideo:()=>{const le=(J.photos??[]).slice().sort((ue,oe)=>(oe.is_primary?1:0)-(ue.is_primary?1:0)||(ue.sort_order??0)-(oe.sort_order??0)).map(ue=>ue.photo_url).filter(Boolean);if(le.length===0){re.error("Add photos to this listing first.");return}Azt({photos:le,details:{address:J.property_address||`${J.city??""} ${J.state??""}`.trim(),beds:J.bedrooms?String(J.bedrooms):"",baths:J.bathrooms?String(J.bathrooms):"",sqft:J.square_footage?String(J.square_footage):"",price:J.price?String(J.price):"",highlights:J.description||""},sourceLabel:"My Listings",badge:Tzt(J.status,J.price)}),s("/admin/beta/homereel?tab=music-video")}},J.id))})}),e.jsx(ns,{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((J,le)=>e.jsxs(be,{children:[e.jsx(gn,{className:"h-48 w-full"}),e.jsxs(Re,{className:"p-4 space-y-2",children:[e.jsx(gn,{className:"h-5 w-3/4"}),e.jsx(gn,{className:"h-4 w-1/2"})]})]},le))}):(x==null?void 0:x.length)===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center",children:[e.jsx(mo,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),e.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:x==null?void 0:x.map(J=>e.jsx(dre,{listing:J.listing,onClick:()=>s(`/mission-control/listings/${J.listing.id}`)},J.id))})}),e.jsx(ns,{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(zd,{className:"h-4 w-4"}),"Referrals Sent (",(($=v==null?void 0:v.sent)==null?void 0:$.length)||0,")"]}),((q=v==null?void 0:v.sent)==null?void 0:q.length)===0?e.jsx(be,{children:e.jsx(Re,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(W=v==null?void 0:v.sent)==null?void 0:W.map(J=>{var le,ue;return e.jsx(be,{children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:J.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((le=J.listing)==null?void 0:le.property_address)||((ue=J.listing)==null?void 0:ue.city)})]}),e.jsx(qe,{variant:J.status==="closed"?"default":"secondary",children:J.status.replace("_"," ")})]})})},J.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),"Referrals Received (",((G=v==null?void 0:v.received)==null?void 0:G.length)||0,")"]}),((K=v==null?void 0:v.received)==null?void 0:K.length)===0?e.jsx(be,{children:e.jsx(Re,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(ee=v==null?void 0:v.received)==null?void 0:ee.map(J=>{var le;return e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:J.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(le=J.sender)==null?void 0:le.name]})]}),e.jsx(qe,{variant:J.status==="closed"?"default":"secondary",children:J.status.replace("_"," ")})]}),e.jsx(B,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${J.listing_id}`),children:"View Listing"})]})},J.id)})})]})]})}),t&&e.jsx(ns,{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((J,le)=>e.jsxs(be,{children:[e.jsx(gn,{className:"h-48 w-full"}),e.jsxs(Re,{className:"p-4 space-y-2",children:[e.jsx(gn,{className:"h-5 w-3/4"}),e.jsx(gn,{className:"h-4 w-1/2"})]})]},le))}):(C==null?void 0:C.length)===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center",children:[e.jsx(LR,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No brokerage listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No agents in your brokerage have added listings yet."}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add a Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:C==null?void 0:C.map(J=>e.jsx(dre,{listing:J,onClick:()=>s(`/mission-control/listings/${J.id}`)},J.id))})}),e.jsx(ns,{value:"map",children:e.jsx(Ukn,{listings:m||[],isLoading:p})}),e.jsx(ns,{value:"leaderboard",children:e.jsx(Bkn,{leaderboard:M})})]})]}),e.jsx(Dkn,{})]}):e.jsx(Vs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center",children:[e.jsx(ia,{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 Ezt(s){return mt({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:n}=await U.from("listing_documents").select("*").eq("listing_id",s).order("sort_order",{ascending:!0}).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Vkn(){const{user:s}=Ns(),t=as();return vt({mutationFn:async({listingId:n,file:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s.id}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await U.storage.from("listing-documents").upload(i,r,{contentType:r.type||void 0});if(l)throw l;const{data:o,error:c}=await U.from("listing_documents").insert({listing_id:n,owner_user_id:s.id,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["listing-documents",r.listingId]})}})}function Hkn(){const s=as();return vt({mutationFn:async({id:t,storage_path:n,listingId:r})=>{await U.storage.from("listing-documents").remove([n]);const{error:a}=await U.from("listing_documents").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function Gkn(){const s=as();return vt({mutationFn:async({id:t,visible:n,listingId:r})=>{const{error:a}=await U.from("listing_documents").update({visible_on_exchange:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}async function Mzt(s){const{data:t,error:n}=await U.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const Wkn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function Kkn({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=Ezt(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 Mzt(i);window.open(l,"_blank")}catch{re.error("Failed to open document")}};return e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[e.jsx($r,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(Re,{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($r,{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:Wkn(i.file_size)})]}),e.jsx(ii,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}var Ykn=Object.defineProperty,ESe=Object.getOwnPropertySymbols,Lzt=Object.prototype.hasOwnProperty,Pzt=Object.prototype.propertyIsEnumerable,Jxt=(s,t,n)=>t in s?Ykn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,NBe=(s,t)=>{for(var n in t||(t={}))Lzt.call(t,n)&&Jxt(s,n,t[n]);if(ESe)for(var n of ESe(t))Pzt.call(t,n)&&Jxt(s,n,t[n]);return s},kBe=(s,t)=>{var n={};for(var r in s)Lzt.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&ESe)for(var r of ESe(s))t.indexOf(r)<0&&Pzt.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var iO;(s=>{const t=class Bc{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cBc.MAX_VERSION)throw new RangeError("Version value out of range");if(h<-1||h>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let m=[];for(let x=0;x7)throw new RangeError("Invalid value");let x,y;for(x=u;;x++){const k=Bc.getNumDataCodewords(x,d)*8,C=l.getTotalBits(c,x);if(C<=k){y=C;break}if(x>=h)throw new RangeError("Data too long")}for(const k of[Bc.Ecc.MEDIUM,Bc.Ecc.QUARTILE,Bc.Ecc.HIGH])p&&y<=Bc.getNumDataCodewords(x,k)*8&&(d=k);let g=[];for(const k of c){n(k.mode.modeBits,4,g),n(k.numChars,k.mode.numCharCountBits(x),g);for(const C of k.getData())g.push(C)}a(g.length==y);const b=Bc.getNumDataCodewords(x,d)*8;a(g.length<=b),n(0,Math.min(4,b-g.length),g),n(0,(8-g.length%8)%8,g),a(g.length%8==0);for(let k=236;g.lengthv[C>>>3]|=k<<7-(C&7)),new Bc(x,d,v,m)}getModule(c,d){return 0<=c&&c>>9)*1335;const h=(d<<10|u)^21522;a(h>>>15==0);for(let m=0;m<=5;m++)this.setFunctionModule(8,m,r(h,m));this.setFunctionModule(8,7,r(h,6)),this.setFunctionModule(8,8,r(h,7)),this.setFunctionModule(7,8,r(h,8));for(let m=9;m<15;m++)this.setFunctionModule(14-m,8,r(h,m));for(let m=0;m<8;m++)this.setFunctionModule(this.size-1-m,8,r(h,m));for(let m=8;m<15;m++)this.setFunctionModule(8,this.size-15+m,r(h,m));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let c=this.version;for(let u=0;u<12;u++)c=c<<1^(c>>>11)*7973;const d=this.version<<12|c;a(d>>>18==0);for(let u=0;u<18;u++){const h=r(d,u),m=this.size-11+u%3,p=Math.floor(u/3);this.setFunctionModule(m,p,h),this.setFunctionModule(p,m,h)}}drawFinderPattern(c,d){for(let u=-4;u<=4;u++)for(let h=-4;h<=4;h++){const m=Math.max(Math.abs(h),Math.abs(u)),p=c+h,x=d+u;0<=p&&p{(k!=y-m||T>=x)&&v.push(C[k])});return a(v.length==p),v}drawCodewords(c){if(c.length!=Math.floor(Bc.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let d=0;for(let u=this.size-1;u>=1;u-=2){u==6&&(u=5);for(let h=0;h>>3],7-(d&7)),d++)}}a(d==c.length*8)}applyMask(c){if(c<0||c>7)throw new RangeError("Mask value out of range");for(let d=0;d5&&c++):(this.finderPenaltyAddHistory(x,y),p||(c+=this.finderPenaltyCountPatterns(y)*Bc.PENALTY_N3),p=this.modules[m][g],x=1);c+=this.finderPenaltyTerminateAndCount(p,x,y)*Bc.PENALTY_N3}for(let m=0;m5&&c++):(this.finderPenaltyAddHistory(x,y),p||(c+=this.finderPenaltyCountPatterns(y)*Bc.PENALTY_N3),p=this.modules[g][m],x=1);c+=this.finderPenaltyTerminateAndCount(p,x,y)*Bc.PENALTY_N3}for(let m=0;mp+(x?1:0),d);const u=this.size*this.size,h=Math.ceil(Math.abs(d*20-u*10)/u)-1;return a(0<=h&&h<=9),c+=h*Bc.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.lengthBc.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(Bc.getNumRawDataModules(c)/8)-Bc.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*Bc.NUM_ERROR_CORRECTION_BLOCKS[d.ordinal][c]}static reedSolomonComputeDivisor(c){if(c<1||c>255)throw new RangeError("Degree out of range");let d=[];for(let h=0;h0);for(const h of c){const m=h^u.shift();u.push(0),d.forEach((p,x)=>u[x]^=Bc.reedSolomonMultiply(p,m))}return u}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let u=0;for(let h=7;h>=0;h--)u=u<<1^(u>>>7)*285,u^=(d>>>h&1)*c;return a(u>>>8==0),u}finderPenaltyCountPatterns(c){const d=c[1];a(d<=this.size*3);const u=d>0&&c[2]==d&&c[3]==d*3&&c[4]==d&&c[5]==d;return(u&&c[0]>=d*4&&c[6]>=d?1:0)+(u&&c[6]>=d*4&&c[0]>=d?1:0)}finderPenaltyTerminateAndCount(c,d,u){return c&&(this.finderPenaltyAddHistory(d,u),d=0),d+=this.size,this.finderPenaltyAddHistory(d,u),this.finderPenaltyCountPatterns(u)}finderPenaltyAddHistory(c,d){d[0]==0&&(c+=this.size),d.pop(),d.unshift(c)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],s.QrCode=t;function n(o,c,d){if(c<0||c>31||o>>>c)throw new RangeError("Value out of range");for(let u=c-1;u>=0;u--)d.push(o>>>u&1)}function r(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class af{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 af(af.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!af.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={}))})(iO||(iO={}));(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={}))})(iO||(iO={}));var w9=iO;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var Zkn={L:w9.QrCode.Ecc.LOW,M:w9.QrCode.Ecc.MEDIUM,Q:w9.QrCode.Ecc.QUARTILE,H:w9.QrCode.Ecc.HIGH},Izt=128,Rzt="L",Dzt="#FFFFFF",Ozt="#000000",Fzt=!1,zzt=1,Xkn=4,Qkn=0,Jkn=.1;function Bzt(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 $zt(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 e5n(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*Jkn),l=a/t,o=(r.width||i)*l,c=(r.height||i)*l,d=r.x==null?s.length/2-o/2:r.x*l,u=r.y==null?s.length/2-c/2:r.y*l,h=r.opacity==null?1:r.opacity;let m=null;if(r.excavate){let x=Math.floor(d),y=Math.floor(u),g=Math.ceil(o+d-x),b=Math.ceil(c+u-y);m={x,y,w:g,h:b}}const p=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:m,opacity:h,crossOrigin:p}}function t5n(s,t){return t!=null?Math.max(Math.floor(t),0):s?Xkn:Qkn}function Uzt({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Lt.useMemo(()=>{const x=(Array.isArray(s)?s:[s]).reduce((y,g)=>(y.push(...w9.QrSegment.makeSegments(g)),y),[]);return w9.QrCode.encodeSegments(x,Zkn[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:m}=Lt.useMemo(()=>{let p=c.getModules();const x=t5n(r,a),y=p.length+x*2,g=e5n(p,l,x,i);return{cells:p,margin:x,numCells:y,calculatedImageSettings:g}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:m}}var s5n=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),n5n=Lt.forwardRef(function(t,n){const r=t,{value:a,size:i=Izt,level:l=Rzt,bgColor:o=Dzt,fgColor:c=Ozt,includeMargin:d=Fzt,minVersion:u=zzt,boostLevel:h,marginSize:m,imageSettings:p}=r,y=kBe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:g}=y,b=kBe(y,["style"]),v=p==null?void 0:p.src,k=Lt.useRef(null),C=Lt.useRef(null),T=Lt.useCallback(G=>{k.current=G,typeof n=="function"?n(G):n&&(n.current=G)},[n]),[M,P]=Lt.useState(!1),{margin:L,cells:I,numCells:O,calculatedImageSettings:$}=Uzt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:m,imageSettings:p,size:i});Lt.useEffect(()=>{if(k.current!=null){const G=k.current,K=G.getContext("2d");if(!K)return;let ee=I;const J=C.current,le=$!=null&&J!==null&&J.complete&&J.naturalHeight!==0&&J.naturalWidth!==0;le&&$.excavation!=null&&(ee=$zt(I,$.excavation));const ue=window.devicePixelRatio||1;G.height=G.width=i*ue;const oe=i/O*ue;K.scale(oe,oe),K.fillStyle=o,K.fillRect(0,0,O,O),K.fillStyle=c,s5n?K.fill(new Path2D(Bzt(ee,L))):I.forEach(function(ie,de){ie.forEach(function(we,je){we&&K.fillRect(je+L,de+L,1,1)})}),$&&(K.globalAlpha=$.opacity),le&&K.drawImage(J,$.x+L,$.y+L,$.w,$.h)}}),Lt.useEffect(()=>{P(!1)},[v]);const q=NBe({height:i,width:i},g);let W=null;return v!=null&&(W=Lt.createElement("img",{src:v,key:v,style:{display:"none"},onLoad:()=>{P(!0)},ref:C,crossOrigin:$==null?void 0:$.crossOrigin})),Lt.createElement(Lt.Fragment,null,Lt.createElement("canvas",NBe({style:q,height:i,width:i,ref:T,role:"img"},b)),W)});n5n.displayName="QRCodeCanvas";var PN=Lt.forwardRef(function(t,n){const r=t,{value:a,size:i=Izt,level:l=Rzt,bgColor:o=Dzt,fgColor:c=Ozt,includeMargin:d=Fzt,minVersion:u=zzt,boostLevel:h,title:m,marginSize:p,imageSettings:x}=r,y=kBe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:g,cells:b,numCells:v,calculatedImageSettings:k}=Uzt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:p,imageSettings:x,size:i});let C=b,T=null;x!=null&&k!=null&&(k.excavation!=null&&(C=$zt(b,k.excavation)),T=Lt.createElement("image",{href:x.src,height:k.h,width:k.w,x:k.x+g,y:k.y+g,preserveAspectRatio:"none",opacity:k.opacity,crossOrigin:k.crossOrigin}));const M=Bzt(C,g);return Lt.createElement("svg",NBe({height:i,width:i,viewBox:`0 0 ${v} ${v}`,ref:n,role:"img"},y),!!m&&Lt.createElement("title",null,m),Lt.createElement("path",{fill:o,d:`M0,0 h${v}v${v}H0z`,shapeRendering:"crispEdges"}),Lt.createElement("path",{fill:c,d:M,shapeRendering:"crispEdges"}),T)});PN.displayName="QRCodeSVG";function r5n({open:s,onOpenChange:t,url:n,title:r,fileBase:a}){const i=j.useRef(null),o=`${(h=>h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing")(a||r||"listing")}-qr`,c=()=>{var m;const h=(m=i.current)==null?void 0:m.querySelector("svg");return h?new XMLSerializer().serializeToString(h):null},d=()=>{const h=c();if(!h)return;const m=new Blob([h],{type:"image/svg+xml;charset=utf-8"}),p=document.createElement("a");p.href=URL.createObjectURL(m),p.download=`${o}.svg`,p.click(),URL.revokeObjectURL(p.href)},u=(h=1024)=>{const m=c();if(!m)return;const p=new Image,x=new Blob([m],{type:"image/svg+xml;charset=utf-8"}),y=URL.createObjectURL(x);p.onload=()=>{const g=document.createElement("canvas");g.width=h,g.height=h;const b=g.getContext("2d");b&&(b.fillStyle="#ffffff",b.fillRect(0,0,h,h),b.drawImage(p,0,0,h,h),URL.revokeObjectURL(y),g.toBlob(v=>{if(!v)return;const k=document.createElement("a");k.href=URL.createObjectURL(v),k.download=`${o}.png`,k.click(),URL.revokeObjectURL(k.href)},"image/png"))},p.src=y};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Listing QR Code"}),e.jsx(kr,{children:"Scans straight to the public listing page — great for flyers, signs, and open houses."})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{ref:i,className:"rounded-xl bg-white p-4 shadow-sm border",children:e.jsx(PN,{value:n,size:220,level:"H",includeMargin:!0})}),e.jsx("p",{className:"text-xs text-muted-foreground break-all text-center",children:n})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>u(),className:"gap-2",children:[e.jsx(ii,{className:"h-4 w-4"}),"PNG"]}),e.jsxs(B,{variant:"outline",onClick:d,className:"gap-2",children:[e.jsx(ii,{className:"h-4 w-4"}),"SVG"]}),e.jsxs(B,{variant:"outline",onClick:async()=>{await navigator.clipboard.writeText(n),re.success("Link copied")},className:"gap-2",children:[e.jsx(ja,{className:"h-4 w-4"}),"Copy link"]})]})]})})}const a5n=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)}`},egt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),fM="#D4AF37",tgt="#0F172A",sgt=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}),ngt=(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)},hW=(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()}…`},i5n=(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},l5n=s=>s instanceof DOMException||s instanceof Error?s.name:null;function qzt({listingId:s,open:t,onOpenChange:n}){var T,M;const{data:r}=NVe(s||""),[a,i]=j.useState(null),[l,o]=j.useState(!1),[c,d]=j.useState(null),[u,h]=j.useState(null),m=((r==null?void 0:r.photos)||[]).slice().sort((P,L)=>P.is_primary&&!L.is_primary?-1:!P.is_primary&&L.is_primary?1:(P.sort_order??0)-(L.sort_order??0));j.useEffect(()=>{var L;if(!t)return;const P=((L=m[0])==null?void 0:L.photo_url)||null;h(I=>I||P)},[t,r==null?void 0:r.id,m.length]),j.useEffect(()=>{let P=!1;if(!(!t||!(r!=null&&r.agent_id)))return(async()=>{var $,q,W,G;const{data:L}=await U.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",r.agent_id).maybeSingle();if(P)return;const I=L,O=(($=I==null?void 0:I.brokerage)==null?void 0:$.name)||((W=(q=r.agent)==null?void 0:q.brokerage)==null?void 0:W.name)||null;i({name:(I==null?void 0:I.name)||((G=r.agent)==null?void 0:G.name)||"Agent",phone:(I==null?void 0:I.phone)||(I==null?void 0:I.phone_e164)||null,avatar_url:(I==null?void 0:I.avatar_url)||null,brokerage:O})})(),()=>{P=!0}},[t,r==null?void 0:r.agent_id]),j.useEffect(()=>{if(!t){d(null),h(null);return}if(!r||!a)return;const P=setTimeout(()=>{p()},350);return()=>clearTimeout(P)},[t,r==null?void 0:r.id,a==null?void 0:a.name,u]);const p=async()=>{if(!(!r||!a)){o(!0);try{const P=document.createElement("canvas");P.width=1080,P.height=1080;const L=P.getContext("2d");if(!L)throw new Error("Canvas unavailable");if(L.fillStyle=tgt,L.fillRect(0,0,1080,1080),v){const G=await sgt(v);ngt(L,G,0,0,1080,1080)}const I=L.createLinearGradient(0,0,0,1080);I.addColorStop(0,"rgba(15,23,42,0.58)"),I.addColorStop(.34,"rgba(15,23,42,0.16)"),I.addColorStop(.62,"rgba(15,23,42,0.48)"),I.addColorStop(1,"rgba(15,23,42,0.98)"),L.fillStyle=I,L.fillRect(0,0,1080,1080),L.fillStyle=fM,L.fillRect(56,62,72,2),L.font="600 22px Arial, sans-serif",o5n(L,"JUST LISTED",146,72,8),L.save(),L.shadowColor="rgba(0,0,0,0.55)",L.shadowBlur=24,L.shadowOffsetY=4,L.fillStyle="#F8FAFC",L.font="600 64px Georgia, serif",L.textBaseline="top";const O=i5n(L,r.property_address||`${r.city||""}, ${r.state||""}`.trim(),952,2);let $=O.length>1?590:654;O.forEach(G=>{L.fillText(G,64,$),$+=70}),L.restore();const q=[r.city,r.state].filter(Boolean).join(", ")+(r.neighborhood?` · ${r.neighborhood}`:"");L.fillStyle="rgba(248,250,252,0.9)",L.font="600 26px Arial, sans-serif",L.fillText(hW(L,q.toUpperCase(),952),64,$+8),L.fillStyle=fM,L.font="700 56px Arial, sans-serif",L.fillText(egt(r.price),64,$+58),C.length>0&&(L.fillStyle="rgba(248,250,252,0.86)",L.font="600 22px Arial, sans-serif",L.fillText(hW(L,C.join(" · "),430),360,$+78));const W=L.createLinearGradient(0,880,0,1080);if(W.addColorStop(0,"rgba(15,23,42,0.96)"),W.addColorStop(1,"#0B1322"),L.fillStyle=W,L.fillRect(0,880,1080,200),L.fillStyle=fM,L.fillRect(0,880,1080,2),L.save(),L.beginPath(),L.arc(124,980,60,0,Math.PI*2),L.closePath(),L.fillStyle="#1E293B",L.fill(),L.lineWidth=6,L.strokeStyle=fM,L.stroke(),L.clip(),a.avatar_url)try{const G=await sgt(a.avatar_url);ngt(L,G,64,920,120,120)}catch{L.fillStyle=fM,L.font="700 48px Arial, sans-serif",L.textAlign="center",L.textBaseline="middle",L.fillText(a.name.charAt(0).toUpperCase(),124,982)}else L.fillStyle=fM,L.font="700 48px Arial, sans-serif",L.textAlign="center",L.textBaseline="middle",L.fillText(a.name.charAt(0).toUpperCase(),124,982);L.restore(),L.textAlign="left",L.textBaseline="alphabetic",L.fillStyle="#F8FAFC",L.font="600 38px Georgia, serif",L.fillText(hW(L,a.name,k?430:820),212,970),a.brokerage&&(L.fillStyle=fM,L.font="600 20px Arial, sans-serif",L.fillText(hW(L,a.brokerage.toUpperCase(),k?430:820),212,1008)),k&&(L.textAlign="right",L.fillStyle="rgba(212,175,55,0.86)",L.font="600 16px Arial, sans-serif",L.fillText("CALL · TEXT",1016,958),L.fillStyle="#F8FAFC",L.font="600 38px Arial, sans-serif",L.fillText(k,1016,1008)),d(P.toDataURL("image/png"))}catch(P){console.error("Generate graphic error",P),re.error("Could not generate graphic")}finally{o(!1)}}},x=async P=>(await fetch(P)).blob(),y=async()=>{if(!c)return;const P=document.createElement("a");P.href=c,P.download=`just-listed-${(r==null?void 0:r.slug)||(r==null?void 0:r.id)||"graphic"}.png`,P.click(),re.success("Downloaded!")},g=async()=>{if(c)try{const P=await x(c);await navigator.clipboard.write([new ClipboardItem({"image/png":P})]),re.success("Copied to clipboard")}catch{re.error("Copy not supported in this browser")}},b=async()=>{if(c)try{const P=await x(c),L=new File([P],"just-listed.png",{type:"image/png"});navigator.canShare&&navigator.canShare({files:[L]})?await navigator.share({files:[L],title:"Just Listed"}):y()}catch(P){l5n(P)!=="AbortError"&&re.error("Share failed")}},v=u||((T=m[0])==null?void 0:T.photo_url)||null,k=a5n(a==null?void 0:a.phone),C=[r!=null&&r.bedrooms?`${r.bedrooms} BD`:null,r!=null&&r.bathrooms?`${r.bathrooms} BA`:null,r!=null&&r.square_footage?`${r.square_footage.toLocaleString()} SF`:null].filter(Boolean);return e.jsx(Fs,{open:t,onOpenChange:n,children:e.jsx(Os,{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($s,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs(zs,{className:"flex items-center gap-2 pr-8",children:[e.jsx(yn,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Your Just Listed Graphic"})]}),e.jsx(kr,{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:tgt},children:[v&&e.jsx("img",{src:v,alt:"Selected property",className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-slate-950/65 via-slate-950/25 to-slate-950"}),e.jsxs("div",{className:"absolute left-4 right-4 top-4 flex items-center gap-2",children:[e.jsx("span",{className:"h-px w-6 bg-amber-400"}),e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-[0.28em] text-amber-300",children:"Just Listed"})]}),e.jsxs("div",{className:"absolute left-4 right-4 bottom-[64px] text-white",children:[e.jsx("div",{className:"line-clamp-2 font-serif text-[18px] font-semibold leading-[1.05] drop-shadow-lg",children:(r==null?void 0:r.property_address)||`${(r==null?void 0:r.city)||""}, ${(r==null?void 0:r.state)||""}`}),e.jsxs("div",{className:"mt-1 truncate text-[9px] font-semibold uppercase tracking-[0.18em] text-white/85",children:[[r==null?void 0:r.city,r==null?void 0:r.state].filter(Boolean).join(", "),r!=null&&r.neighborhood?` · ${r.neighborhood}`:""]}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[e.jsx("span",{className:"text-[16px] font-bold text-amber-300",children:r?egt(r.price):""}),C.length>0&&e.jsx("span",{className:"truncate text-[8px] font-semibold uppercase tracking-[0.14em] text-white/80",children:C.join(" · ")})]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 flex h-[52px] items-center border-t border-amber-400 bg-slate-950/95 px-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-amber-400 bg-slate-800 text-xs font-bold text-amber-300",children:a!=null&&a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:"",className:"h-full w-full object-cover"}):(M=a==null?void 0:a.name)==null?void 0:M.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(Wt,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Crafting your graphic…"})]})]}),m.length>1&&e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose photo"}),e.jsx("div",{className:"flex gap-2 pb-2",style:{overflowX:"auto",overflowY:"hidden",WebkitOverflowScrolling:"touch"},children:m.map(P=>{const L=u===P.photo_url;return e.jsx("button",{type:"button",onClick:()=>h(P.photo_url),className:`relative shrink-0 h-14 w-14 rounded-md overflow-hidden border-2 transition ${L?"border-amber-500 ring-2 ring-amber-500/30":"border-transparent hover:border-muted-foreground/40"}`,children:e.jsx("img",{src:P.photo_url,alt:"",className:"w-full h-full object-cover"})},P.id)})})]})]}),e.jsxs("div",{className:"px-5 pb-5 pt-2 shrink-0 border-t bg-background flex flex-wrap justify-end gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>void p(),disabled:l||!r||!a,children:"Regenerate"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:g,disabled:!c,className:"gap-1.5",children:[e.jsx(ja,{className:"h-3.5 w-3.5"})," Copy"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:b,disabled:!c,className:"gap-1.5",children:[e.jsx(zd,{className:"h-3.5 w-3.5"})," Share"]}),e.jsxs(B,{size:"sm",onClick:y,disabled:!c,className:"gap-1.5",children:[e.jsx(ii,{className:"h-3.5 w-3.5"})," Download"]})]})]})})})}function c5n(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const d5n={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function u5n({open:s,onOpenChange:t,listing:n}){const{user:r}=Ns(),{data:a=[],isLoading:i}=av(),{data:l=[]}=lw(),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(new Set),[p,x]=j.useState(!1),[y,g]=j.useState(null);j.useEffect(()=>{s||(c(""),u("all"),m(new Set),x(!1))},[s]),j.useEffect(()=>{!s||!r||(async()=>{const{data:L}=await U.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();g((L==null?void 0:L.gmail_email)||null)})()},[s,r]);const b=j.useMemo(()=>a.filter(L=>L.email),[a]),v=j.useMemo(()=>{let L=b;if(d!=="all"&&(L=L.filter(I=>{var O;return(O=I.tags)==null?void 0:O.some($=>$.relationship_type_id===d)})),o.trim()){const I=o.toLowerCase();L=L.filter(O=>`${O.first_name||""} ${O.last_name||""}`.toLowerCase().includes(I)||(O.email||"").toLowerCase().includes(I))}return L},[b,o,d]),k=()=>{h.size===v.length?m(new Set):m(new Set(v.map(L=>L.id)))},C=L=>{const I=new Set(h);I.has(L)?I.delete(L):I.add(L),m(I)},T=j.useMemo(()=>b.filter(L=>h.has(L.id)).map(L=>({id:L.id,first_name:L.first_name||"there",last_name:L.last_name,email:L.email})),[b,h]),{defaultSubject:M,defaultBody:P}=j.useMemo(()=>{var ie,de,we,je;const L=n.property_address||`${n.city}, ${n.state}`,I=c5n(n.price),O=d5n[n.property_type]||"home",$=n.bedrooms?`${n.bedrooms} bed`:"",q=n.bathrooms?`${n.bathrooms} bath`:"",W=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",G=[$,q,W].filter(Boolean).join(" • "),K=`https://listings.relevelup.com/${n.slug||n.id}`,ee=((de=(ie=n.photos)==null?void 0:ie.find(xe=>xe.is_primary))==null?void 0:de.photo_url)||((je=(we=n.photos)==null?void 0:we[0])==null?void 0:je.photo_url)||"",le={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[n.status]||"New Listing",ue=`${le}: ${L} — ${I}`,oe=`

Hi {{first_name}},

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

${ee?` ${L} `:""}
${le}

${I}

${L}

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

${G?`

${G} • ${O}

`:""} 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:oe}},[n]);return p?e.jsx(cw,{open:p,onOpenChange:L=>{x(L),L||t(!1)},bulkContacts:T,defaultSubject:M,defaultBody:P,gmailEmail:y}):e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(kr,{children:"Pick which contacts should hear about this property. We'll personalize each email with their name."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search contacts...",value:o,onChange:L=>c(L.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:d,onValueChange:u,children:[e.jsx(gs,{className:"sm:w-[180px]",children:e.jsx(bs,{placeholder:"Filter by tag"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All contacts"}),l.map(L=>e.jsx(Je,{value:L.id,children:L.name},L.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(wi,{checked:v.length>0&&h.size===v.length,className:"pointer-events-none"}),e.jsx("span",{children:h.size===v.length&&v.length>0?"Deselect all":`Select all (${v.length})`})]}),e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Bn,{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(Wt,{className:"h-5 w-5 animate-spin mr-2"}),"Loading your contacts..."]}):v.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:b.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:v.map(L=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(wi,{checked:h.has(L.id),onCheckedChange:()=>C(L.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[L.first_name," ",L.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:L.email})]}),L.tags&&L.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:L.tags.slice(0,2).map(I=>{var O;return e.jsx(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(O=I.relationship_type)==null?void 0:O.name},I.id)})})]},L.id))})}),e.jsx(Xl,{}),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:()=>x(!0),disabled:h.size===0,className:"gap-2",children:[e.jsx(on,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}function mj(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 yee(){const s=ei();return mt({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Vzt(){const s=ei(),t=as();return vt({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:n}=await U.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function gTe(){const s=ei();return mt({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at) `).eq("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Hzt(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("deal_pipeline").insert({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||null,contact_id:n.contact_id||null,listing_id:n.listing_id||null,property_address:n.property_address||null,city:n.city||null,state:n.state||null,zip_code:n.zip_code||null,expected_price:n.expected_price||null,expected_commission:n.expected_commission||null,commission_percentage:n.commission_percentage||3,target_close_date:n.target_close_date||null,contract_date:n.contract_date||null,listing_date:n.listing_date||null,priority:n.priority||"medium",probability:n.probability||50,notes:n.notes||null,owner_user_id:s}).select().single();if(a)throw a;return await U.from("deal_activities").insert([{deal_id:r.id,activity_type:"system",title:"Deal created",description:`Deal "${n.deal_name}" was created`}]),r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function Gzt(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("deal_pipeline").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function h5n(){const s=as();return vt({mutationFn:async({dealId:t,stageId:n,stageName:r})=>{const{data:a,error:i}=await U.from("deal_pipeline").update({stage_id:n}).eq("id",t).select().single();if(i)throw i;return await U.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${r}`,metadata:{new_stage_id:n,new_stage_name:r}}),a},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function m5n(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("deal_pipeline").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function p5n(s){return mt({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function f5n(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("deal_activities").insert([{deal_id:t.deal_id,activity_type:t.activity_type,title:t.title,description:t.description||null}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-activities",n.deal_id]})}})}function x5n(s){return mt({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function g5n(){const s=as();return vt({mutationFn:async({id:t,is_completed:n,deal_id:r})=>{const{data:a,error:i}=await U.from("deal_checklist_items").update({is_completed:n,completed_at:n?new Date().toISOString():null}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function y5n(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("deal_checklist_items").insert([{deal_id:t.deal_id,title:t.title,description:t.description||null,due_date:t.due_date||null,sort_order:t.sort_order||0}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function v5n(){const s=ei();return mt({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",s);if(n)throw n;const r=(t==null?void 0:t.filter(o=>{var c,d,u;return!((c=o.deal_pipeline_stages)!=null&&c.is_won_stage)&&!((d=o.deal_pipeline_stages)!=null&&d.is_lost_stage)&&((u=o.deal_pipeline_stages)==null?void 0:u.name)!=="Cancelled"}))||[],a=(t==null?void 0:t.filter(o=>{var c;return(c=o.deal_pipeline_stages)==null?void 0:c.is_won_stage}))||[],i=new Date().getFullYear(),l=a.filter(o=>{const c=o.actual_close_date;return c?new Date(c).getFullYear()===i:!0});return{totalDeals:(t==null?void 0:t.length)||0,activeDeals:r.length,wonDeals:a.length,pipelineValue:r.reduce((o,c)=>o+(c.expected_price||0),0),expectedCommission:r.reduce((o,c)=>o+(c.expected_commission||0),0),expectedNetToAgent:r.reduce((o,c)=>o+(mj(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+(mj(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0),0),ytdWonNet:l.reduce((o,c)=>o+(mj(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(mj(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(mj(c)||0)*d},0)}},enabled:!!s})}function b5n(s){const t=ei();return mt({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:n,error:r}=await U.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("listing_id",s).maybeSingle();if(r)throw r;return n},enabled:!!t&&!!s})}function _5n(){const s=as();return vt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await U.from("deal_pipeline").update({listing_id:n}).eq("id",t).select().single();if(a)throw a;return await U.from("deal_activities").insert({deal_id:t,activity_type:"system",title:"Linked to Listing Exchange",description:"This deal is now synced with Listing Exchange",metadata:{listing_id:n}}),r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",n.listingId]})}})}function w5n(){const s=as();return vt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await U.from("deal_pipeline").update({listing_id:null}).eq("id",t).select().single();if(a)throw a;return{data:r,listingId:n}},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",t.listingId]})}})}function j5n({listing:s}){const t=Hn(),[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l,isLoading:o}=b5n(s.id),{data:c,isLoading:d}=yee(),{data:u,isLoading:h}=gTe(),m=Vzt(),p=_5n(),x=w5n(),y=Hzt(),g=(u==null?void 0:u.filter(T=>!T.listing_id))||[],b=T=>{if(!(c!=null&&c.length))return null;switch(T){case"coming_soon":case"active":case"price_improvement":return c.find(M=>M.name==="Active");case"under_contract":return c.find(M=>M.name==="Under Contract");case"sold":return c.find(M=>M.is_won_stage);default:return c.find(M=>M.name==="Active")}},v=async()=>{i(!0);try{c!=null&&c.length||await m.mutateAsync();const T=b(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}),re.success("Deal created and linked to listing!")}catch(T){console.error("Failed to create deal:",T),re.error("Failed to create deal")}finally{i(!1)}},k=async()=>{if(!n){re.error("Please select a deal");return}try{await p.mutateAsync({dealId:n,listingId:s.id}),re.success("Listing linked to deal!"),r("")}catch{re.error("Failed to link listing")}},C=async()=>{if(l)try{await x.mutateAsync({dealId:l.id,listingId:s.id}),re.success("Listing unlinked from deal")}catch{re.error("Failed to unlink listing")}};return o||d?e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(v3,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Re,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Wt,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(be,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(Rc,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Re,{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(qe,{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(Xa,{className:"h-3 w-3 ml-1"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:C,disabled:x.isPending,children:x.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(ZR,{className:"h-4 w-4"})})]})]})]}):e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(v3,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Re,{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:v,disabled:a||y.isPending,className:"w-full",size:"sm",children:[a||y.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),g.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"flex-1 text-sm",children:e.jsx(bs,{placeholder:"Link to existing deal..."})}),e.jsx(ys,{children:g.map(T=>e.jsx(Je,{value:T.id,children:T.deal_name},T.id))})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:k,disabled:!n||p.isPending,children:p.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Rc,{className:"h-4 w-4"})})]})]})]})]})}const N5n={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"},k5n={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},rgt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function S5n(){var ue,oe,ie,de,we,je,xe,fe,Se;const{listingId:s}=$i(),t=Hn(),{user:n}=Ns(),{data:r,isLoading:a}=NVe(s||""),{data:i}=eAt(s||""),{data:l}=Uks(s||""),o=JCt(),c=$ks(),d=qks(),u=QCt(),h=Hks(),[m,p]=j.useState(!1),[x,y]=j.useState(!1),[g,b]=j.useState(!1),[v,k]=j.useState(!1),[C,T]=j.useState(!1),[M,P]=j.useState(!1),[L,I]=j.useState(null),[O,$]=j.useState({buyerName:"",buyerType:"",notes:""}),q=(n==null?void 0:n.id)===(r==null?void 0:r.agent_id),W=Ee=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ee),G=async Ee=>{const Le=`https://listings.relevelup.com/${(r==null?void 0:r.slug)||(r==null?void 0:r.id)}`,De=`Check out this listing: ${(r==null?void 0:r.property_address)||(r==null?void 0:r.city)}`;d.mutate({listingId:r.id,shareType:Ee});try{switch(Ee){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Le)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Le),re.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${De} ${Le}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(De)}&body=${encodeURIComponent(`Check out this listing: ${Le}`)}`);break}}catch(Be){console.error("Share error:",Be),re.error("Failed to share")}},K=async()=>{try{await u.mutateAsync(r.id),re.success("Listing deleted"),t("/mission-control/listings")}catch{re.error("Failed to delete listing")}},ee=async()=>{if(!O.buyerName.trim()){re.error("Please enter buyer name");return}try{await h.mutateAsync({listingId:r.id,listingAgentId:r.agent_id,buyerName:O.buyerName,buyerType:O.buyerType||void 0,notes:O.notes||void 0}),re.success("Referral sent successfully!"),y(!1),$({buyerName:"",buyerType:"",notes:""})}catch{re.error("Failed to send referral")}},J=Ee=>{var Oe,Ae;const Le=(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`,De=W((r==null?void 0:r.price)||0),Be=r!=null&&r.bedrooms?`${r.bedrooms}BD`:"",Ne=r!=null&&r.bathrooms?`${r.bathrooms}BA`:"",Ge=r!=null&&r.square_footage?`${r.square_footage.toLocaleString()}SF`:"",_e=[Be,Ne,Ge].filter(Boolean).join(" | ");switch(Ee){case"just_listed":return`🏡 JUST LISTED! ${Le} ${De} ${_e} ${(r==null?void 0:r.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Oe=r==null?void 0:r.city)==null?void 0:Oe.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Le} Now ${De}! ${_e} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${rgt[(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! ${_e} DM me for details! 📩 #ComingSoon #RealEstate #${(Ae=r==null?void 0:r.city)==null?void 0:Ae.replace(/\s/g,"")}`;default:return""}};if(a)return e.jsx(Vs,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(gn,{className:"h-10 w-32"}),e.jsx(gn,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(gn,{className:"h-48"}),e.jsx(gn,{className:"h-48"}),e.jsx(gn,{className:"h-48"})]})]})});if(!r)return e.jsx(Vs,{title:"Listing Not Found",description:"",children:e.jsx(be,{children:e.jsxs(Re,{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 le=((ue=r.photos)==null?void 0:ue.find(Ee=>Ee.is_primary))||((oe=r.photos)==null?void 0:oe[0]);return e.jsxs(Vs,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Back to Listings"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsx("div",{className:"aspect-[16/10] rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>le&&I(le.photo_url),children:le?e.jsx("img",{src:le.photo_url,alt:"Primary",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No photos"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:(ie=r.photos)==null?void 0:ie.slice(1,5).map((Ee,Le)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>I(Ee.photo_url),children:e.jsx("img",{src:Ee.photo_url,alt:`Photo ${Le+2}`,className:"w-full h-full object-cover"})},Ee.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsx(be,{children:e.jsxs(Re,{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(qe,{className:`${N5n[r.status]} text-white border-0`,children:k5n[r.status]}),r.is_featured&&e.jsxs(qe,{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(qe,{variant:"outline",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:W(r.price)}),r.property_address&&e.jsx("p",{className:"text-xl font-medium",children:r.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(oi,{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(mo,{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(L5,{className:"h-4 w-4"}):e.jsx(Nx,{className:"h-4 w-4"})}),!q&&e.jsxs(B,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>b(!0),children:[e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(zd,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(xd,{children:[e.jsxs(wa,{onClick:()=>G("copy"),children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(wa,{onClick:()=>G("facebook"),children:[e.jsx(sx,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(wa,{onClick:()=>G("text"),children:[e.jsx(ro,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(wa,{onClick:()=>G("email"),children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),q&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>{const Ee=(r.photos??[]).slice().sort((Le,De)=>(De.is_primary?1:0)-(Le.is_primary?1:0)||(Le.sort_order??0)-(De.sort_order??0)).map(Le=>Le.photo_url).filter(Boolean);if(Ee.length===0){re.error("Add photos to this listing first.");return}Azt({photos:Ee,details:{address:r.property_address||`${r.city??""} ${r.state??""}`.trim(),beds:r.bedrooms?String(r.bedrooms):"",baths:r.bathrooms?String(r.bathrooms):"",sqft:r.square_footage?String(r.square_footage):"",price:r.price?String(r.price):"",highlights:r.description||""},sourceLabel:"Listing Exchange",badge:Tzt(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(yn,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs(B,{variant:"outline",onClick:()=>P(!0),className:"gap-2",children:[e.jsx(hg,{className:"h-4 w-4"}),"QR Code"]}),e.jsxs(B,{variant:"outline",onClick:()=>k(!0),className:"gap-2",children:[e.jsx(on,{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(yn,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/listings/${r.id}/edit`),children:[e.jsx(kp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>p(!0),children:e.jsx(Rn,{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(U_,{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(t0,{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(H_,{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(ra,{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(qe,{variant:"secondary",children:[e.jsx(Ni,{className:"h-3 w-3 mr-1"}),rgt[r.property_type]]}),r.lot_size&&e.jsxs(qe,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx(qe,{variant:"secondary",children:"HOA"})]}),r.description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Description"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})]}),r.agent_notes&&r.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.agent_notes})]}),r.co_agent_name&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Co-Listing Agent"}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border p-3",children:[r.co_agent_photo_url?e.jsx("img",{src:r.co_agent_photo_url,alt:r.co_agent_name,className:"h-12 w-12 rounded-full object-cover"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center text-sm font-medium",children:r.co_agent_name.charAt(0)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:r.co_agent_name}),r.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:r.co_agent_brokerage}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:[r.co_agent_email,r.co_agent_phone].filter(Boolean).join(" · ")})]})]})]}),r.mls_link&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(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(ma,{className:"h-4 w-4"}),r.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(zd,{className:"h-4 w-4"}),r.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mo,{className:"h-4 w-4"}),r.save_count," saves"]})]})]})}),r.allow_sharing&&e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Share Content"})}),e.jsx(Re,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Ee=>e.jsxs("div",{className:"p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("p",{className:"font-medium text-sm capitalize",children:[Ee.replace("_"," ")," Caption"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(J(Ee)),re.success("Caption copied!")},children:e.jsx(ja,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:J(Ee)})]},Ee))})]}),e.jsx(Kkn,{listingId:r.id,ownerOnly:q})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Re,{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:((we=(de=r.agent)==null?void 0:de.name)==null?void 0:we.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((je=r.agent)==null?void 0:je.name)||"Unknown"}),((fe=(xe=r.agent)==null?void 0:xe.brokerage)==null?void 0:fe.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),!q&&e.jsx("div",{className:"space-y-2",children:((Se=r.agent)==null?void 0:Se.email)&&e.jsx(B,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${r.agent.email}`,children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),q&&e.jsx(j5n,{listing:r}),!q&&r.open_to_referrals&&e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Re,{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(Fs,{open:!!L,onOpenChange:()=>I(null),children:e.jsx(Os,{className:"max-w-4xl",children:e.jsx("img",{src:L||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(Fs,{open:m,onOpenChange:p,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Delete Listing"}),e.jsx(kr,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:K,disabled:u.isPending,children:u.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(Fs,{open:x,onOpenChange:y,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Send Buyer Referral"}),e.jsx(kr,{children:"Submit buyer information to the listing agent"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Buyer Name *"}),e.jsx(ye,{value:O.buyerName,onChange:Ee=>$({...O,buyerName:Ee.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Buyer Type"}),e.jsxs(vs,{value:O.buyerType,onValueChange:Ee=>$({...O,buyerType:Ee}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select type"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"first_time",children:"First-Time Buyer"}),e.jsx(Je,{value:"investor",children:"Investor"}),e.jsx(Je,{value:"relocating",children:"Relocating"}),e.jsx(Je,{value:"upgrade",children:"Upgrading"}),e.jsx(Je,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes"}),e.jsx(Ds,{value:O.notes,onChange:Ee=>$({...O,notes:Ee.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(B,{onClick:ee,disabled:h.isPending,children:h.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(r5n,{open:M,onOpenChange:P,url:`https://listings.relevelup.com/${r.slug||r.id}`,title:r.property_address||`${r.city}, ${r.state}`,fileBase:r.slug||r.property_address||r.city}),e.jsx(kzt,{open:g,onOpenChange:b,listingId:(r==null?void 0:r.id)||"",listingSlug:(r==null?void 0:r.slug)||null,listingTitle:(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`}),r&&e.jsx(u5n,{open:v,onOpenChange:k,listing:r}),e.jsx(qzt,{listingId:(r==null?void 0:r.id)||null,open:C,onOpenChange:T})]})}function C5n({onImport:s}){const[t,n]=j.useState(""),[r,a]=j.useState([]),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),h=j.useRef(),m=j.useRef(null);j.useEffect(()=>{const v=k=>{m.current&&!m.current.contains(k.target)&&c(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]);const p=async v=>{if(v.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:k,error:C}=await U.functions.invoke("mls-listing-search",{body:{query:v}});if(C)throw C;a((k==null?void 0:k.listings)||[]),c(!0)}catch(k){console.error("MLS search error:",k),a([])}finally{l(!1)}},x=v=>{n(v),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(v),400)},y=v=>{u(v.mlsNumber),s(v),c(!1),n(`${v.address}, ${v.city}`),re.success(`Imported: ${v.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},g=v=>v?`$${v.toLocaleString()}`:"",b=v=>{const k=(v||"").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":v||"Other"};return e.jsxs(be,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(ii,{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(Re,{children:e.jsxs("div",{ref:m,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:t,onChange:v=>x(v.target.value),onFocus:()=>r.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(Wt,{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(dr,{className:"h-4 w-4"})})]}),o&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border rounded-lg shadow-lg max-h-[400px] overflow-y-auto",children:r.length===0&&!i?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No properties found. Try a different address."}):r.map(v=>e.jsxs("button",{type:"button",onClick:()=>y(v),disabled:d===v.mlsNumber,className:"w-full text-left p-3 hover:bg-accent/50 transition-colors border-b last:border-0 flex items-start gap-3",children:[v.photos[0]?e.jsx("img",{src:v.photos[0],alt:"",className:"w-16 h-12 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-16 h-12 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(oi,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.city,", ",v.state," ",v.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:g(v.price)}),v.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(U_,{className:"h-3 w-3"})," ",v.bedrooms]}),v.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(t0,{className:"h-3 w-3"})," ",v.bathrooms]}),v.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(j3,{className:"h-3 w-3"})," ",v.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(qe,{variant:"outline",className:"text-[10px]",children:b(v.propertyType)}),v.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[v.photos.length," photos"]})]})]},v.mlsNumber))})]})})]})}function A5n({photo:s,onRemove:t,onSetPrimary:n}){const{attributes:r,listeners:a,setNodeRef:i,transform:l,transition:o,isDragging:c}=RCe({id:s.id}),d={transform:RE.Transform.toString(l),transition:o};return e.jsxs("div",{ref:i,style:d,className:Et("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(Fp,{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(dr,{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 T5n({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){const l=SCe(I$(uq,{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(b=>b.id===u.id),p=o.findIndex(b=>b.id===h.id),x=[...o],[y]=x.splice(m,1);x.splice(p,0,y);const g=x.map((b,v)=>({...b,sort_order:v}));a(g)};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(LCe,{sensors:l,collisionDetection:CCe,onDragEnd:c,children:e.jsx(ICe,{items:o.map(d=>d.id),strategy:qJ,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(d=>e.jsx(A5n,{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(Wt,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{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 E5n({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=Hn(),{user:a}=Ns(),[i,l]=j.useState(!1),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,x]=j.useState({});j.useEffect(()=>{s&&a?y():m(null)},[s,a]);const y=async()=>{if(!s)return;const{data:I,error:O}=await U.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("id",s).eq("is_deleted",!1).single();!O&&I&&(m(I),g(I))},g=async I=>{try{const{data:O,error:$}=await U.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:I.bunny_video_id,isAgentVideo:!0}});!$&&(O!=null&&O.thumbnailUrl)&&x(q=>({...q,[I.id]:{thumbnailUrl:O.thumbnailUrl}}))}catch(O){console.warn("Failed to get signed URL",O)}},b=async()=>{if(a){u(!0);try{const{data:I,error:O}=await U.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(O)throw O;c(I||[]),I!=null&&I.length&&v(I)}catch(I){console.error("Error fetching videos:",I),re.error("Failed to load videos")}finally{u(!1)}}},v=async I=>{var O;try{const $=I.map(ee=>ee.bunny_video_id),{data:q,error:W}=await U.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:$,isAgentVideo:!0}});if(W)throw W;const G=(q==null?void 0:q.assets)||{},K={};for(const ee of I)(O=G[ee.bunny_video_id])!=null&&O.thumbnailUrl&&(K[ee.id]={thumbnailUrl:G[ee.bunny_video_id].thumbnailUrl});x(ee=>({...ee,...K}))}catch($){console.warn("Failed to bulk-fetch signed URLs",$)}},k=()=>{l(!0),b()},C=I=>{t(I.id),m(I),l(!1),re.success("Video selected")},T=()=>{t(null),m(null)},M=()=>{const I=n?`/mission-control/listings/${n}/edit`:"/mission-control/listings/new";r(`/mission-control/video?returnUrl=${encodeURIComponent(I)}`)},P=I=>{if(!I)return"0:00";const O=Math.floor(I/60),$=I%60;return`${O}:${$.toString().padStart(2,"0")}`},L=I=>{var O;return((O=p[I.id])==null?void 0:O.thumbnailUrl)||I.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[h?e.jsx(be,{className:"overflow-hidden",children:e.jsx(Re,{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:[L(h)?e.jsx("img",{src:L(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(Zr,{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(fd,{className:"h-6 w-6 text-white fill-white"})}),h.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:P(h.duration_seconds)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.title||"Untitled Video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Property Video Tour"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:k,children:"Change"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:T,className:"text-destructive hover:text-destructive",children:e.jsx(dr,{className:"h-4 w-4"})})]})]})})}):e.jsx(be,{className:"border-dashed",children:e.jsx(Re,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Zr,{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(i1,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(B,{type:"button",variant:"outline",onClick:M,className:"gap-2",children:[e.jsx(s0,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(i1,{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(Wt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Zr,{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:M,className:"gap-2",children:[e.jsx(s0,{className:"h-4 w-4"}),"Record Your First Video"]})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 p-1",children:o.map(I=>e.jsxs("button",{type:"button",onClick:()=>C(I),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===I.id?"border-primary ring-2 ring-primary/20":"border-transparent hover:border-muted-foreground/30"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[L(I)?e.jsx("img",{src:L(I),alt:I.title||"Video",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Zr,{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(fd,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),I.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:P(I.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:I.title||"Untitled Video"})})]},I.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:M,className:"gap-2",children:[e.jsx(s0,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const M5n=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function L5n({listingId:s}){const t=j.useRef(null),{data:n=[],isLoading:r}=Ezt(s),a=Vkn(),i=Hkn(),l=Gkn(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){re.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(h){re.error(`Failed to upload ${u.name}: ${h.message}`)}}t.current&&(t.current.value=""),re.success("Documents uploaded")}},c=async d=>{try{const u=await Mzt(d);window.open(u,"_blank")}catch{re.error("Failed to open document")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:t,type:"file",multiple:!0,accept:".pdf,application/pdf",className:"hidden",onChange:d=>o(d.target.files)}),e.jsxs(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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ja,{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(be,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx($r,{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:M5n(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(ma,{className:"h-3 w-3"}):e.jsx(n0,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(Mn,{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(ii,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:async()=>{await Bi(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(dr,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const P5n=[{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"}],I5n=[{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 R5n({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=RCe({id:s}),u={transform:RE.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(Fp,{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(dr,{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 D5n({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=SCe(I$(uq,{activationConstraint:{distance:5}})),o=s.map((d,u)=>`pending-${u}`),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const m=o.indexOf(u.id),p=o.indexOf(h.id),x=[...s],y=[...t],[g]=x.splice(m,1),[b]=y.splice(m,1);x.splice(p,0,g),y.splice(p,0,b),r(x,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(LCe,{sensors:l,collisionDetection:CCe,onDragEnd:c,children:e.jsx(ICe,{items:o,strategy:qJ,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(R5n,{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(Wt,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{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 agt(){const{listingId:s}=$i(),[t]=dc(),n=t.get("brokerage"),r=Hn(),{user:a}=Ns(),{hasLeadSite:i}=h0(),l=!!s&&s!=="new",o=!!n&&!l,[c,d]=j.useState([]),[u,h]=j.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:m,isLoading:p}=NVe(l?s:""),x=Pks(),y=Iks(),g=Rks(),b=Dks(),v=Oks(),k=Fks(),C=zks(),{data:T=[]}=mt({queryKey:["brokerage-agents",n],queryFn:async()=>{if(!n)return[];const{data:fe,error:Se}=await U.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name");if(Se)throw Se;return fe||[]},enabled:o}),[M,P]=j.useState(""),[L,I]=j.useState(!1),[O,$]=j.useState([]),[q,W]=j.useState([]),[G,K]=j.useState(!1),ee=async fe=>{if(fe.size>5*1024*1024){re.error("Image must be under 5MB");return}K(!0);try{const Se=fe.name.split(".").pop()||"jpg",Ee=`${(a==null?void 0:a.id)||"anon"}/co-agents/${Date.now()}.${Se}`,{error:Le}=await U.storage.from("listing-photos").upload(Ee,fe,{upsert:!0});if(Le)throw Le;const{data:De}=U.storage.from("listing-photos").getPublicUrl(Ee);le(Be=>({...Be,co_agent_photo_url:De.publicUrl})),re.success("Headshot uploaded")}catch(Se){re.error((Se==null?void 0:Se.message)||"Failed to upload headshot")}finally{K(!1)}},[J,le]=j.useState({property_address:"",city:"",state:"",neighborhood:"",price:"",property_type:"single_family",status:"active",bedrooms:"",bathrooms:"",square_footage:"",lot_size:"",year_built:"",has_hoa:!1,description:"",agent_notes:"",agent_notes_public:!1,mls_link:"",video_link:"",video_id:null,co_agent_name:"",co_agent_email:"",co_agent_phone:"",co_agent_brokerage:"",co_agent_photo_url:"",allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,share_with_brokerage:!1,is_public:!0});j.useEffect(()=>{var fe,Se,Ee,Le,De;m&&l&&le({property_address:m.property_address||"",city:m.city||"",state:m.state||"",neighborhood:m.neighborhood||"",price:((fe=m.price)==null?void 0:fe.toString())||"",property_type:m.property_type,status:m.status,bedrooms:((Se=m.bedrooms)==null?void 0:Se.toString())||"",bathrooms:((Ee=m.bathrooms)==null?void 0:Ee.toString())||"",square_footage:((Le=m.square_footage)==null?void 0:Le.toString())||"",lot_size:m.lot_size||"",year_built:((De=m.year_built)==null?void 0:De.toString())||"",has_hoa:m.has_hoa,description:m.description||"",agent_notes:m.agent_notes||"",agent_notes_public:m.agent_notes_public,mls_link:m.mls_link||"",video_link:m.video_link||"",video_id:m.video_id||null,co_agent_name:m.co_agent_name||"",co_agent_email:m.co_agent_email||"",co_agent_phone:m.co_agent_phone||"",co_agent_brokerage:m.co_agent_brokerage||"",co_agent_photo_url:m.co_agent_photo_url||"",allow_sharing:m.allow_sharing,open_to_referrals:m.open_to_referrals,open_to_social_promotion:m.open_to_social_promotion,share_with_brokerage:m.share_with_brokerage??!1,is_public:m.is_public})},[m,l]);const ue=fe=>{var De,Be;const Se={"single family":"single_family",detached:"single_family",residential:"single_family",condo:"condo",condominium:"condo",apartment:"condo",townhouse:"townhouse",townhome:"townhouse",land:"land",lot:"land","lots and land":"land","multi-family":"multi_family","multi family":"multi_family",duplex:"multi_family",commercial:"commercial"},Ee=(fe.propertyType||"").toLowerCase(),Le=((De=Object.entries(Se).find(([Ne])=>Ee.includes(Ne)))==null?void 0:De[1])||"other";le(Ne=>({...Ne,property_address:fe.address||Ne.property_address,city:fe.city||Ne.city,state:fe.state||Ne.state,price:fe.price?String(fe.price):Ne.price,property_type:Le,bedrooms:fe.bedrooms?String(fe.bedrooms):Ne.bedrooms,bathrooms:fe.bathrooms?String(fe.bathrooms):Ne.bathrooms,square_footage:fe.sqft?String(fe.sqft):Ne.square_footage,lot_size:fe.lotSize?String(fe.lotSize):Ne.lot_size,year_built:fe.yearBuilt?String(fe.yearBuilt):Ne.year_built,description:fe.description||Ne.description})),((Be=fe.photos)==null?void 0:Be.length)>0&&(d(fe.photos),q.forEach(Ne=>URL.revokeObjectURL(Ne)),$([]),W([]))},oe=fe=>{if(!fe)return;const Se=Array.from(fe);$(Le=>[...Le,...Se]);const Ee=Se.map(Le=>URL.createObjectURL(Le));W(Le=>[...Le,...Ee])},ie=fe=>{URL.revokeObjectURL(q[fe]),$(Se=>Se.filter((Ee,Le)=>Le!==fe)),W(Se=>Se.filter((Ee,Le)=>Le!==fe))},de=async fe=>{var Se;if(!(!fe||!m)){I(!0);try{for(const Ee of Array.from(fe)){const Le=Ee.name.split(".").pop(),De=`${a==null?void 0:a.id}/${m.id}/${Date.now()}.${Le}`,{error:Be}=await U.storage.from("listing-photos").upload(De,Ee);if(Be)throw Be;const{data:{publicUrl:Ne}}=U.storage.from("listing-photos").getPublicUrl(De);await b.mutateAsync({listingId:m.id,photoUrl:Ne,isPrimary:!((Se=m.photos)!=null&&Se.length)})}re.success("Photos uploaded!")}catch(Ee){console.error("Upload error:",Ee),re.error("Failed to upload photos")}finally{I(!1)}}},we=async fe=>{for(let Se=0;Se{if(m)try{await v.mutateAsync({photoId:fe,listingId:m.id}),re.success("Photo removed")}catch{re.error("Failed to remove photo")}},xe=async fe=>{if(fe.preventDefault(),!J.city.trim()||!J.state.trim()||!J.price){re.error("Please fill in required fields (City, State, Price)");return}if(o&&!M){re.error("Please select an agent to assign this listing to");return}try{const Se={property_address:J.property_address||null,city:J.city,state:J.state,neighborhood:J.neighborhood||null,price:Number(J.price),property_type:J.property_type,status:J.status,bedrooms:J.bedrooms?Number(J.bedrooms):null,bathrooms:J.bathrooms?Number(J.bathrooms):null,square_footage:J.square_footage?Number(J.square_footage):null,lot_size:J.lot_size||null,year_built:J.year_built?Number(J.year_built):null,has_hoa:J.has_hoa,description:J.description||null,agent_notes:J.agent_notes||null,agent_notes_public:J.agent_notes_public,mls_link:J.mls_link||null,video_link:J.video_link||null,video_id:J.video_id||null,co_agent_name:J.co_agent_name||null,co_agent_email:J.co_agent_email||null,co_agent_phone:J.co_agent_phone||null,co_agent_brokerage:J.co_agent_brokerage||null,co_agent_photo_url:J.co_agent_photo_url||null,allow_sharing:J.allow_sharing,open_to_referrals:J.open_to_referrals,open_to_social_promotion:J.open_to_social_promotion,share_with_brokerage:J.share_with_brokerage,is_public:J.is_public};if(l)await g.mutateAsync({id:s,...Se}),re.success("Listing updated!"),r(`/mission-control/listings/${s}`);else{I(!0);let Ee;if(o&&M?Ee=await y.mutateAsync({agentId:M,...Se}):Ee=await x.mutateAsync(Se),O.length>0)try{await we(Ee.id),q.forEach(De=>URL.revokeObjectURL(De)),$([]),W([])}catch(De){console.error("Photo upload error:",De),re.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let De=0;Der(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(_a,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Assign to Agent *"})}),e.jsxs(Re,{children:[e.jsxs(vs,{value:M,onValueChange:P,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select an agent..."})}),e.jsx(ys,{children:T.map(fe=>e.jsx(Je,{value:fe.id,children:fe.name||fe.email},fe.id))})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"This listing will appear on the selected agent's Listing Exchange."})]})]}),!l&&i&&!o&&e.jsx(C5n,{onImport:ue}),c.length>0&&e.jsxs(be,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Ft,{className:"pb-3",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(ii,{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(Re,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((fe,Se)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:fe,alt:"",className:"w-full h-full object-cover"})},Se)),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(dr,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Property Details"})}),e.jsx(Re,{className:"space-y-4",children:e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"sm:col-span-2 space-y-2",children:[e.jsx(se,{children:"Property Address"}),e.jsx(ye,{value:J.property_address,onChange:fe=>le({...J,property_address:fe.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"City *"}),e.jsx(ye,{value:J.city,onChange:fe=>le({...J,city:fe.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"State *"}),e.jsx(ye,{value:J.state,onChange:fe=>le({...J,state:fe.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Neighborhood"}),e.jsx(ye,{value:J.neighborhood,onChange:fe=>le({...J,neighborhood:fe.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Price *"}),e.jsx(ye,{type:"number",value:J.price,onChange:fe=>le({...J,price:fe.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Type"}),e.jsxs(vs,{value:J.property_type,onValueChange:fe=>le({...J,property_type:fe}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:I5n.map(fe=>e.jsx(Je,{value:fe.value,children:fe.label},fe.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:J.status,onValueChange:fe=>le({...J,status:fe}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:P5n.map(fe=>e.jsx(Je,{value:fe.value,children:fe.label},fe.value))})]})]})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Property Specs (Optional)"})}),e.jsx(Re,{children:e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Bedrooms"}),e.jsx(ye,{type:"number",value:J.bedrooms,onChange:fe=>le({...J,bedrooms:fe.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Bathrooms"}),e.jsx(ye,{type:"number",step:"0.5",value:J.bathrooms,onChange:fe=>le({...J,bathrooms:fe.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Sq Ft"}),e.jsx(ye,{type:"number",value:J.square_footage,onChange:fe=>le({...J,square_footage:fe.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Lot Size"}),e.jsx(ye,{value:J.lot_size,onChange:fe=>le({...J,lot_size:fe.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Year Built"}),e.jsx(ye,{type:"number",value:J.year_built,onChange:fe=>le({...J,year_built:fe.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(Mn,{checked:J.has_hoa,onCheckedChange:fe=>le({...J,has_hoa:fe})}),e.jsx(se,{children:"Has HOA"})]})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Description & Links"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{value:J.description,onChange:fe=>le({...J,description:fe.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Agent Notes"}),e.jsx(Ds,{value:J.agent_notes,onChange:fe=>le({...J,agent_notes:fe.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{checked:J.agent_notes_public,onCheckedChange:fe=>le({...J,agent_notes_public:fe})}),e.jsx(se,{className:"text-sm text-muted-foreground",children:"Make notes visible to other agents"})]})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"MLS Link"}),e.jsx(ye,{value:J.mls_link,onChange:fe=>le({...J,mls_link:fe.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Video Link"}),e.jsx(ye,{value:J.video_link,onChange:fe=>le({...J,video_link:fe.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Co-Listing Agent (optional)"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Credit a second agent on this listing. Their info appears on the listing page alongside yours."}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Name"}),e.jsx(ye,{value:J.co_agent_name,onChange:fe=>le({...J,co_agent_name:fe.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(ye,{value:J.co_agent_brokerage,onChange:fe=>le({...J,co_agent_brokerage:fe.target.value}),placeholder:"Brokerage name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{type:"email",value:J.co_agent_email,onChange:fe=>le({...J,co_agent_email:fe.target.value}),placeholder:"agent@email.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:J.co_agent_phone,onChange:fe=>le({...J,co_agent_phone:fe.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-4",children:[J.co_agent_photo_url?e.jsx("img",{src:J.co_agent_photo_url,alt:"Co-listing agent headshot",className:"h-20 w-20 rounded-full object-cover border"}):e.jsx("div",{className:"h-20 w-20 rounded-full border border-dashed flex items-center justify-center text-muted-foreground",children:e.jsx(Ja,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"co-agent-headshot",type:"file",accept:"image/*",className:"hidden",onChange:fe=>{var Ee;const Se=(Ee=fe.target.files)==null?void 0:Ee[0];fe.target.value="",Se&&ee(Se)}}),e.jsx(B,{type:"button",variant:"outline",disabled:G,onClick:()=>{var fe;return(fe=document.getElementById("co-agent-headshot"))==null?void 0:fe.click()},children:G?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"})," Uploading…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"})," ",J.co_agent_photo_url?"Replace photo":"Upload photo"]})}),J.co_agent_photo_url&&e.jsxs(B,{type:"button",variant:"ghost",onClick:()=>le(fe=>({...fe,co_agent_photo_url:""})),children:[e.jsx(dr,{className:"h-4 w-4 mr-1"})," Remove"]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"JPG or PNG, up to 5MB."})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Re,{children:e.jsx(E5n,{selectedVideoId:J.video_id,onVideoSelect:fe=>le({...J,video_id:fe}),listingId:l?s:void 0})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Photos"})}),e.jsx(Re,{children:l&&(m!=null&&m.photos)?e.jsx(T5n,{photos:m.photos,uploading:L,onUpload:fe=>de(fe),onRemove:fe=>je(fe),onReorder:fe=>{k.mutate({photos:fe.map(Se=>({id:Se.id,sort_order:Se.sort_order,is_primary:Se.is_primary}))})},onSetPrimary:fe=>{m&&C.mutate({photoId:fe,listingId:m.id})}}):e.jsx(D5n,{photoUrls:q,onRemove:ie,onReorder:(fe,Se)=>{W(fe),$(Se)},pendingPhotos:O,uploading:L,onUpload:oe})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ii,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Re,{children:l&&s?e.jsx(L5n,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Sharing & Collaboration"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(Mn,{checked:J.allow_sharing,onCheckedChange:fe=>le({...J,allow_sharing:fe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(Mn,{checked:J.open_to_referrals,onCheckedChange:fe=>le({...J,open_to_referrals:fe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(Mn,{checked:J.open_to_social_promotion,onCheckedChange:fe=>le({...J,open_to_social_promotion:fe})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(Mn,{checked:J.share_with_brokerage,onCheckedChange:fe=>le({...J,share_with_brokerage:fe})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(Mn,{checked:J.is_public,onCheckedChange:fe=>le({...J,is_public:fe})})]})]})]}),e.jsx(B,{type:"submit",className:"w-full",size:"lg",disabled:x.isPending||g.isPending,children:x.isPending||g.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(qzt,{listingId:u.listingId,open:u.open,onOpenChange:fe=>{if(!fe){const{nextPath:Se}=u;h({open:!1,listingId:null,nextPath:Se}),r(Se)}}})]})}const SBe=[{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"}],Wzt=[{type:"extra_video",label:"Extra Video / Reel",icon:Zr,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:EW,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:ac,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:yN,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:Vr,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:vc,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],O5n=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],VIe={sections:Object.fromEntries(SBe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},F5n=()=>Math.random().toString(36).slice(2,10);function z5n(){const{listingId:s}=$i(),t=Hn(),{user:n}=Ns(),r=as(),[a,i]=j.useState("desktop"),[l,o]=j.useState(VIe),[c,d]=j.useState(!1),[u,h]=j.useState(0),{data:m,isLoading:p}=mt({queryKey:["listing-customize",s],queryFn:async()=>{const{data:O,error:$}=await U.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if($)throw $;return O},enabled:!!s});j.useEffect(()=>{var O,$;m!=null&&m.page_config&&o({...VIe,...m.page_config||{},sections:{...VIe.sections,...((O=m.page_config)==null?void 0:O.sections)||{}},addons:(($=m.page_config)==null?void 0:$.addons)||[]})},[m==null?void 0:m.id]);const x=!!n&&!!m&&n.id===m.agent_id,y=j.useMemo(()=>m?`/public/listing/${m.slug||m.id}?preview=1&t=${u}`:"",[m,u]),g=j.useMemo(()=>m?`https://listings.relevelup.com/${m.slug||m.id}`:"",[m]),b=vt({mutationFn:async()=>{const{error:O}=await U.from("listings").update({page_config:l}).eq("id",s);if(O)throw O},onSuccess:()=>{re.success("Saved. Your public page is live."),d(!1),r.invalidateQueries({queryKey:["listing-customize",s]}),r.invalidateQueries({queryKey:["public-listing"]}),h(O=>O+1)},onError:O=>re.error(`Save failed: ${O.message||"Try again"}`)}),v=O=>{o($=>({...$,...O})),d(!0)},k=(O,$)=>v({sections:{...l.sections||{},[O]:$}}),C=O=>v({addons:[...l.addons||[],{id:F5n(),type:O,data:{}}]}),T=(O,$)=>v({addons:(l.addons||[]).map(q=>q.id===O?{...q,data:{...q.data,...$}}:q)}),M=O=>v({addons:(l.addons||[]).filter($=>$.id!==O)}),P=(O,$)=>{const q=[...l.addons||[]],W=q.findIndex(K=>K.id===O);if(W<0)return;const G=W+$;G<0||G>=q.length||([q[W],q[G]]=[q[G],q[W]],v({addons:q}))};if(p)return e.jsx(Vs,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!m)return e.jsx(Vs,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!x)return e.jsx(Vs,{title:"",description:"",children:e.jsxs("div",{className:"p-8",children:[e.jsx("p",{children:"You can only customize your own listing pages."}),e.jsx(B,{className:"mt-3",onClick:()=>t(`/mission-control/listings/${m.id}`),children:"Back"})]})});const L=(l.addons||[]).length,I=Object.values(l.sections||{}).filter(Boolean).length;return e.jsxs(Vs,{title:"",description:"",children:[e.jsxs("div",{className:"sticky top-0 z-30 -mx-4 sm:-mx-6 px-4 sm:px-6 py-3 bg-background/85 backdrop-blur border-b flex items-center gap-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t(`/mission-control/listings/${m.id}`),children:[e.jsx(_a,{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(Cj,{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(Jy,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(O=>O+1),children:[e.jsx(Ki,{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:g,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:()=>b.mutate(),disabled:!c||b.isPending,children:b.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Jo,{className:"h-3.5 w-3.5 mr-1.5"})," Save & Publish"]})})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[minmax(360px,440px)_1fr] gap-6 mt-4",children:[e.jsx(lo,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(eG,{icon:e.jsx(yn,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(O=>e.jsx("button",{onClick:()=>v({hero_style:O}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===O?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:O},O))})]})}),e.jsx(eG,{icon:e.jsx(Ac,{className:"h-4 w-4"}),title:"Accent color",desc:"Highlights on the public page",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("button",{onClick:()=>v({accent_color:null}),className:`h-9 px-3 rounded-full text-xs border ${l.accent_color?"border-border hover:bg-muted":"border-primary bg-primary/5 text-primary"}`,children:"Default"}),O5n.map(O=>e.jsx("button",{onClick:()=>v({accent_color:O}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===O?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:O},"aria-label":O},O))]})}),e.jsx(eG,{icon:e.jsx(um,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Ds,{value:l.custom_note||"",onChange:O=>v({custom_note:O.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(eG,{icon:e.jsx(N4,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${I} of ${SBe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:SBe.map(O=>{var q;const $=((q=l.sections)==null?void 0:q[O.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:O.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:O.hint})]}),e.jsx(Mn,{checked:$,onCheckedChange:W=>k(O.key,W)})]},O.key)})})}),e.jsxs(eG,{icon:e.jsx(Js,{className:"h-4 w-4"}),title:"Add-on modules",desc:"Drop in extras to make this page unique",rightLabel:L?`${L} added`:void 0,children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Wzt.map(O=>e.jsxs("button",{onClick:()=>C(O.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${O.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(O.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:O.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:O.desc})]},O.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((O,$)=>e.jsx(B5n,{addon:O,onChange:q=>T(O.id,q),onRemove:()=>M(O.id),onMoveUp:$>0?()=>P(O.id,-1):void 0,onMoveDown:$P(O.id,1):void 0},O.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx(B,{className:"w-full",onClick:()=>b.mutate(),disabled:!c||b.isPending,children:b.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Jo,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(be,{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(ma,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx(qe,{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(da,{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(Cj,{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(Jy,{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 eG({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 B5n({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=Wzt.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(Fp,{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(Fp,{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(Rn,{className:"h-3.5 w-3.5"})})]})]}),s.type==="extra_video"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Video URL"}),e.jsx(ye,{placeholder:"https://youtu.be/…",value:s.data.url||"",onChange:o=>t({url:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Title (optional)"}),e.jsx(ye,{placeholder:"e.g. Sunset drone flyover",value:s.data.title||"",onChange:o=>t({title:o.target.value})})]}),s.type==="tour_3d"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"3D tour embed URL"}),e.jsx(ye,{placeholder:"https://my.matterport.com/show/?m=…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]}),s.type==="floor_plans"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Floor plan image URLs (one per line)"}),e.jsx(Ds,{rows:3,placeholder:`https://…/floor1.jpg https://…/floor2.jpg`,value:(s.data.urls||[]).join(` `),onChange:o=>t({urls:o.target.value.split(` `).map(c=>c.trim()).filter(Boolean)})})]}),s.type==="testimonial"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Quote"}),e.jsx(Ds,{rows:3,placeholder:`"Best home-buying experience we've ever had."`,value:s.data.quote||"",onChange:o=>t({quote:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Attribution"}),e.jsx(ye,{placeholder:"Sarah & Mike, past clients",value:s.data.author||"",onChange:o=>t({author:o.target.value})})]}),s.type==="countdown"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Headline"}),e.jsx(ye,{placeholder:"Offers due",value:s.data.headline||"",onChange:o=>t({headline:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Deadline (date & time)"}),e.jsx(ye,{type:"datetime-local",value:s.data.deadline||"",onChange:o=>t({deadline:o.target.value})})]}),s.type==="custom_cta"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Button label"}),e.jsx(ye,{placeholder:"Download brochure",value:s.data.label||"",onChange:o=>t({label:o.target.value})}),e.jsx(se,{className:"text-xs",children:"Link URL"}),e.jsx(ye,{placeholder:"https://…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]})]})}const Kzt="teleprompter_settings",HIe={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function $5n(){try{const s=localStorage.getItem(Kzt);return s?{...HIe,...JSON.parse(s)}:HIe}catch{return HIe}}function U5n(s){try{localStorage.setItem(Kzt,JSON.stringify(s))}catch{}}function eYe({text:s,isVisible:t,onToggleVisibility:n,isRecording:r=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=j.useRef(null),c=j.useRef(null),d=j.useRef(0),u=j.useRef(0),[h,m]=j.useState($5n),{scrollSpeed:p,fontSize:x,lineHeight:y,opacity:g,position:b,isMirrored:v}=h,k=j.useCallback((q,W)=>{m(G=>{const K={...G,[q]:W};return U5n(K),K})},[]),[C,T]=j.useState(!1),[M,P]=j.useState(null),L=j.useCallback(q=>{if(!o.current)return;d.current===0&&(d.current=q);const W=q-d.current;d.current=q,u.current+=p*W/1e3;const G=Math.floor(u.current);G>0&&(o.current.scrollTop+=G,u.current-=G);const{scrollTop:K,scrollHeight:ee,clientHeight:J}=o.current;if(K+J>=ee){T(!1);return}c.current=requestAnimationFrame(L)},[p]);j.useEffect(()=>(C?(d.current=0,u.current=0,c.current=requestAnimationFrame(L)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[C,L]),j.useEffect(()=>{if(r&&t)if(o.current&&(o.current.scrollTop=0),a){P(3);let q=3;const W=setInterval(()=>{q-=1,q<=0?(clearInterval(W),P(null),i==null||i(),T(!0)):P(q)},1e3);return()=>clearInterval(W)}else setTimeout(()=>T(!0),100);else r||(T(!1),P(null))},[r,t,a,i]);const I=j.useCallback(()=>{o.current&&(o.current.scrollTop=0),T(!1)},[]),O=j.useCallback(()=>{T(q=>!q)},[]);if(!t)return e.jsx("div",{className:Et("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(ma,{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:Et("absolute inset-0 pointer-events-none",l),children:[M!==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:M},M),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:Et("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",$[b],M!==null&&"opacity-30"),style:{opacity:M!==null?.3:g},children:e.jsxs("div",{ref:o,className:Et("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",v&&"scale-x-[-1]"),style:{maskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)",WebkitMaskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)"},children:[e.jsx("div",{className:"h-full",style:{minHeight:"100%"}}),e.jsx("p",{className:"text-white text-center font-medium drop-shadow-lg",style:{fontSize:`${x}px`,lineHeight: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(lc,{children:[e.jsx(cc,{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(ic,{className:"h-4 w-4"})})}),e.jsx(Jl,{className:"w-72",side:"left",align:"start",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium",children:"Teleprompter Settings"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p})]}),e.jsx(Qf,{value:[p],onValueChange:([q])=>k("scrollSpeed",q),min:1,max:100,step:1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[x,"px"]})]}),e.jsx(Qf,{value:[x],onValueChange:([q])=>k("fontSize",q),min:16,max:48,step:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:y.toFixed(1)})]}),e.jsx(Qf,{value:[y*10],onValueChange:([q])=>k("lineHeight",q/10),min:12,max:24,step:1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(g*100),"%"]})]}),e.jsx(Qf,{value:[g*100],onValueChange:([q])=>k("opacity",q/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:b==="top"?"default":"outline",size:"sm",onClick:()=>k("position","top"),children:e.jsx(Qy,{className:"h-4 w-4"})}),e.jsx(B,{variant:b==="center"?"default":"outline",size:"sm",onClick:()=>k("position","center"),children:e.jsx(gN,{className:"h-4 w-4"})}),e.jsx(B,{variant:b==="bottom"?"default":"outline",size:"sm",onClick:()=>k("position","bottom"),children:e.jsx(Po,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs",children:"Mirror Mode"}),e.jsx(Mn,{checked:v,onCheckedChange:q=>k("isMirrored",q)})]})]})})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:O,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:C?e.jsx(ay,{className:"h-4 w-4"}):e.jsx(fd,{className:"h-4 w-4"})}),e.jsx(B,{variant:"secondary",size:"icon",onClick:I,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(bm,{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(n0,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function q5n({onSelectScript:s,onCreateNew:t,selectedScriptId:n,className:r}){const{toast:a}=pi(),[i,l]=j.useState(""),[o,c]=j.useState(null),[d,u]=j.useState("levelup"),{data:h,isLoading:m}=wgn(),{data:p,isLoading:x}=jgn(),{data:y,isLoading:g}=Ngn(),b=kgn(),v=j.useMemo(()=>p?p.filter(P=>{const L=!i||P.title.toLowerCase().includes(i.toLowerCase())||P.script_text.toLowerCase().includes(i.toLowerCase())||P.tags.some(O=>O.toLowerCase().includes(i.toLowerCase())),I=!o||P.category_id===o;return L&&I}):[],[p,i,o]),k=j.useMemo(()=>y?y.filter(P=>!i||P.title.toLowerCase().includes(i.toLowerCase())||P.script_text.toLowerCase().includes(i.toLowerCase())):[],[y,i]),C=P=>{s({title:P.title,text:P.script_text})},T=async P=>{try{await b.mutateAsync(P),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},M=m||x||g;return e.jsxs("div",{className:Et("flex flex-col h-full",r),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search scripts...",value:i,onChange:P=>l(P.target.value),className:"pl-9"})]})}),e.jsxs(fa,{value:d,onValueChange:P=>u(P),className:"flex-1 flex flex-col",children:[e.jsxs(xa,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(ss,{value:"levelup",children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(ss,{value:"my-scripts",children:[e.jsx(s1,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(ns,{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(qe,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),h==null?void 0:h.map(P=>e.jsx(qe,{variant:o===P.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(P.id),children:P.name},P.id))]}),e.jsx(lo,{className:"flex-1 max-h-[50vh]",children:M?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx($r,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No scripts found"})]}):e.jsx("div",{className:"space-y-2",children:v.map(P=>e.jsxs(be,{className:Et("cursor-pointer hover:bg-accent/50 transition-colors",n===P.id&&"ring-2 ring-primary"),onClick:()=>C(P),children:[e.jsx(Ft,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Ut,{className:"text-sm font-medium truncate",children:P.title}),P.category&&e.jsx(qe,{variant:"secondary",className:"mt-1 text-xs",children:P.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:L=>{L.stopPropagation(),T(P)},children:e.jsx(s1,{className:"h-4 w-4"})}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Re,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:P.script_text})})]},P.id))})})]}),e.jsxs(ns,{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(Js,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(lo,{className:"flex-1 max-h-[50vh]",children:g?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Wt,{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(s1,{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(P=>e.jsxs(be,{className:Et("cursor-pointer hover:bg-accent/50 transition-colors",n===P.id&&"ring-2 ring-primary"),onClick:()=>C(P),children:[e.jsx(Ft,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Ut,{className:"text-sm font-medium truncate",children:P.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:P.is_custom?e.jsx(qe,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(qe,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Re,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:P.script_text})})]},P.id))})})]})]})]})}function V5n({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=j.useState(()=>{const o=jz(s);return new Set([o.category])}),l=o=>{i(c=>{const d=new Set(c);return d.has(o)?d.delete(o):d.add(o),d})};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Share Page Template"}),r&&e.jsx(Wt,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:ONs.map(o=>{const c=FNs(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(i0,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(o0,{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(Po,{className:Et("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(l0,{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:Et("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(da,{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: "',jz(s).headerText(n),'"']})]})}function Yzt({open:s,onOpenChange:t,video:n,contactName:r,onTemplateUpdated:a}){const[i,l]=j.useState(n.page_template||"default"),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(n.page_template||"default"),[p,x]=j.useState([]),[y,g]=j.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[b,v]=j.useState(!1),[k,C]=j.useState(!1),T=n.share_token?`https://video.relevelup.com/${n.share_token}`:"";j.useEffect(()=>{s&&p.length===0&&M()},[s]);const M=async()=>{C(!0);try{const{data:K,error:ee}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(ee)throw ee;const J=(K||[]).map(le=>({id:le.id,name:[le.first_name,le.last_name].filter(Boolean).join(" ")||"Unnamed",email:le.email||null}));x(J)}catch(K){console.error("Failed to fetch contacts:",K)}finally{C(!1)}},P=async K=>{g(K),v(!1),c(!0);try{const{error:ee}=await U.from("agent_videos").update({contact_id:(K==null?void 0:K.id)||null,recipient_name:(K==null?void 0:K.name)||null}).eq("id",n.id);if(ee)throw ee;re.success(K?`Assigned to ${K.name}`:"Contact removed"),a==null||a()}catch(ee){console.error("Failed to update contact:",ee),re.error("Failed to update contact")}finally{c(!1)}},L=async K=>{l(K),c(!0);try{const{error:ee}=await U.from("agent_videos").update({page_template:K}).eq("id",n.id);if(ee)throw ee;m(K),re.success("Template saved!"),a==null||a()}catch(ee){console.error("Failed to save template:",ee),re.error("Failed to save template"),l(h)}finally{c(!1)}},I=(y==null?void 0:y.name)||null,O=()=>{const K=n.title||"Video Message",ee=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},$=async()=>{if(!n.thumbnail_url){re.error("Video thumbnail not available yet");return}const K=O(),ee=`Watch: ${n.title||"Video Message"} ${T}`;try{const J=new Blob([K],{type:"text/html"}),le=new Blob([ee],{type:"text/plain"}),ue=new ClipboardItem({"text/html":J,"text/plain":le});await navigator.clipboard.write([ue]),re.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(ee+` `+K),re.success("Copied! Paste into your email.")}},q=async()=>{await navigator.clipboard.writeText(T),u(!0),re.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},W=()=>{const ee=jz(i).headerText(I),J=i==="default"?`Check out this video: ${T}`:`${ee} Check out this special video: ${T}`;window.open(`sms:?body=${encodeURIComponent(J)}`,"_self")},G=()=>{const K=jz(i),ee=K.headerText(I),J=i==="default"?n.title||"Video Message":ee,le=`${K.subText} Watch the video: ${T}`,ue=y!=null&&y.email?encodeURIComponent(y.email):"";window.open(`mailto:${ue}?subject=${encodeURIComponent(J)}&body=${encodeURIComponent(le)}`,"_self")};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(vc,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(kr,{children:"Choose a themed page template and share your video"})]}),e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(lc,{open:b,onOpenChange:v,children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":b,className:"flex-1 justify-between",disabled:o,children:[y?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Eo,{className:"h-4 w-4 text-muted-foreground"}),y.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(fb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Jl,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Sb,{children:[e.jsx(Cb,{placeholder:"Search contacts..."}),e.jsxs(Ab,{children:[e.jsx(Tb,{children:k?"Loading...":"No contacts found."}),e.jsx(Eb,{children:p.map(K=>e.jsxs(Yy,{value:K.name,onSelect:()=>P(K),children:[e.jsx(da,{className:Et("mr-2 h-4 w-4",(y==null?void 0:y.id)===K.id?"opacity-100":"opacity-0")}),K.name]},K.id))})]})]})})]}),y&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>P(null),disabled:o,className:"shrink-0",children:e.jsx(dr,{className:"h-4 w-4"})})]}),y&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',jz(i).headerText(y.name),'"']})]}),e.jsx(V5n,{selectedTemplate:i,onSelect:L,contactName:I,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:T,readOnly:!0,className:"font-mono text-sm"}),e.jsx(B,{onClick:q,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(ja,{className:"h-4 w-4"}),"Copy"]})})]})]}),n.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Share for Email"}),e.jsxs(B,{variant:"outline",className:"w-full gap-2",onClick:$,children:[e.jsx(ac,{className:"h-4 w-4"}),"Copy with Thumbnail (for Gmail)"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste into Gmail to embed a clickable video thumbnail"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"flex-1 gap-2",onClick:W,children:[e.jsx(ro,{className:"h-4 w-4"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1 gap-2",onClick:G,children:[e.jsx(on,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(Nr,{children:e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function H5n(){var Ue;const s=Hn(),[t]=dc(),{toast:n}=pi(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=bRt(),{data:u}=av(),h=hS(),m=Egn(),[p,x]=j.useState("record"),[y,g]=j.useState(""),[b,v]=j.useState(!1),[k,C]=j.useState(!1),[T,M]=j.useState(!1),[P,L]=j.useState(null),[I,O]=j.useState(0),[$,q]=j.useState(0),[W,G]=j.useState(null),[K,ee]=j.useState(null),[J,le]=j.useState(r||""),[ue,oe]=j.useState(""),[ie,de]=j.useState(""),[we,je]=j.useState(null),[xe,fe]=j.useState(null),[Se,Ee]=j.useState(null),[Le,De]=j.useState(!1),Be=j.useCallback(async(Ze,Qe)=>{L(Ze),x("uploading");try{const{videoId:Ye,uploadUrl:nt}=await w6(ue||"Quick Video Touch");G(Ye);const{apiKey:rt}=await j6(Ye),Fe=new XMLHttpRequest;Fe.upload.onprogress=zt=>{zt.lengthComputable&&O(zt.loaded/zt.total*100)},await new Promise((zt,Gt)=>{Fe.onload=()=>{Fe.status>=200&&Fe.status<300?zt():Gt(new Error(`Upload failed: ${Fe.status}`))},Fe.onerror=()=>Gt(new Error("Upload failed")),Fe.open("PUT",nt),Fe.setRequestHeader("AccessKey",rt),Fe.send(Ze)}),x("processing");let dt=0;const Dt=Date.now(),pt=90*1e3;for(;dt<4;){if(await new Promise(Gt=>setTimeout(Gt,3e3)),Date.now()-Dt>pt){const Gt=Ze.size/1048576,qs=`https://iframe.mediadelivery.net/play/${Ye}/${Ye}`;await h.mutateAsync({bunny_video_id:Ye,playback_url:qs,file_size_mb:Gt,title:ue||"Quick Video Touch",notes:ie||void 0,contact_id:J&&J!=="none"?J:void 0,status:"processing",touch_type:"video_touch"}),n({title:"Video saved — still processing",description:'Your video has been saved and will appear in your library with a "processing" badge. It will be ready to share once encoding completes (usually within a few minutes).',duration:8e3}),s("/mission-control/video-library");return}const zt=await $j(Ye);if(dt=zt.status,q(zt.encodeProgress||0),dt===4)ee({playbackUrl:zt.directPlayUrl,thumbnailUrl:zt.thumbnailUrl,previewUrl:zt.previewUrl||null,duration:zt.length||Qe,fileSizeMb:(zt.storageSize||Ze.size)/(1024*1024)});else if(dt===5||dt===6)throw new Error("Video processing failed")}x("details")}catch(Ye){console.error("Upload error:",Ye),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),x("record")}},[ue,n]),Ne=async()=>{if(!(!W||!K))try{const Ze=J&&J!=="none"?J:null,Qe=await h.mutateAsync({bunny_video_id:W,contact_id:Ze,playback_url:K.playbackUrl,thumbnail_url:K.thumbnailUrl,preview_url:K.previewUrl,duration_seconds:K.duration,file_size_mb:K.fileSizeMb,title:ue||"Quick Video Touch",notes:ie,task_id:a||null,status:"ready"});je(Qe.id),fe(Qe.share_token||null),Ze&&await m.mutateAsync({contactId:Ze,videoId:Qe.id,notes:ie}),n({title:"Video saved successfully!"}),x("share")}catch(Ze){console.error("Save video error:",Ze),n({title:"Failed to save video",description:(Ze==null?void 0:Ze.message)||"Please try again.",variant:"destructive"})}},Ge=(Ze,Qe)=>{navigator.clipboard.writeText(Qe),Ee(Ze),setTimeout(()=>Ee(null),2e3),n({title:"Copied to clipboard!"})},_e=()=>xe?`https://video.relevelup.com/${xe}`:(K==null?void 0:K.playbackUrl)||"",Oe=()=>{const Ze=u==null?void 0:u.find(Fe=>Fe.id===J),Qe=Ze?`${Ze.first_name}`:"",Ye=(Ze==null?void 0:Ze.phone)||"",nt=(Ze==null?void 0:Ze.email)||"",rt=_e();return{text:`Hey${Qe?` ${Qe}`:""}! I recorded a quick video for you: ${rt}`,link:rt,contactPhone:Ye,contactEmail:nt}},Ae=()=>{const{text:Ze,contactPhone:Qe}=Oe(),Ye=Qe?`sms:${Qe}?body=${encodeURIComponent(Ze)}`:`sms:?body=${encodeURIComponent(Ze)}`;window.open(Ye,"_self")},Xe=()=>{const{link:Ze,contactEmail:Qe}=Oe(),Ye="Check out this video",nt=`I recorded a quick video for you: ${Ze}`,rt=Qe?`mailto:${Qe}?subject=${encodeURIComponent(Ye)}&body=${encodeURIComponent(nt)}`:`mailto:?subject=${encodeURIComponent(Ye)}&body=${encodeURIComponent(nt)}`;window.open(rt,"_self")};return i?e.jsx(Vs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(_a,{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($r,{className:"h-4 w-4"}),"Video Library"]}),c&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm text-warning",children:["Storage: ",o.toFixed(0),"% used"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.toFixed(0)," MB remaining"]})]})]})]}),p==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(k6,{maxDurationSeconds:600,onRecordingComplete:Be,onRecordingStateChange:M,className:"w-full",teleprompterContent:b&&y&&e.jsx(eYe,{text:y,isVisible:b,onToggleVisibility:()=>v(!1),isRecording:T,startCountdown:!1})}),!b&&y&&e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>v(!0),children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(be,{className:"lg:col-span-1",children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsx(Ds,{placeholder:"Type or paste your script here...",value:y,onChange:Ze=>g(Ze.target.value),rows:6}),e.jsxs(v1,{open:k,onOpenChange:C,children:[e.jsx(yJ,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full",children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(rv,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(Lb,{className:"p-4 border-b",children:e.jsx(Pb,{children:"Select a Script"})}),e.jsx(q5n,{onSelectScript:Ze=>{g(Ze.text),C(!1),v(!0)},className:"h-[calc(100vh-80px)]"})]})]}),y&&e.jsx(B,{className:"w-full",onClick:()=>v(!0),children:"Use Script"})]})]})]}),p==="uploading"&&e.jsx(be,{className:"max-w-md mx-auto",children:e.jsxs(Re,{className:"pt-6 text-center",children:[e.jsx(Ja,{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(qi,{value:I,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[I.toFixed(0),"%"]})]})}),p==="processing"&&e.jsx(be,{className:"max-w-md mx-auto",children:e.jsxs(Re,{className:"pt-6 text-center space-y-4",children:[e.jsx(Wt,{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(qi,{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.`})]})}),p==="details"&&e.jsxs(be,{className:"max-w-lg mx-auto",children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Video Details"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:ue,onChange:Ze=>oe(Ze.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Attach to Contact (Optional)"}),e.jsxs(vs,{value:J,onValueChange:le,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"No contact - use anywhere"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(vc,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),u==null?void 0:u.map(Ze=>e.jsx(Je,{value:Ze.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Eo,{className:"h-4 w-4"}),Ze.first_name," ",Ze.last_name]})},Ze.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ds,{value:ie,onChange:Ze=>de(Ze.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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),p==="share"&&e.jsxs(be,{className:"max-w-lg mx-auto",children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Re,{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(ro,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:Xe,children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>Ge("link",Oe().link),children:[e.jsx(vc,{className:"h-4 w-4 mr-2"}),"Copy Video Link",Se==="link"&&e.jsx(da,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>De(!0),children:[e.jsx(Ac,{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:()=>{x("record"),L(null),G(null),ee(null)},children:"Record Another"})]})]})]}),we&&xe&&e.jsx(Yzt,{open:Le,onOpenChange:De,video:{id:we,share_token:xe,title:ue||null,contact_id:J||null,thumbnail_url:(K==null?void 0:K.thumbnailUrl)||null},contactName:((Ue=u==null?void 0:u.find(Ze=>Ze.id===J))==null?void 0:Ue.first_name)||null})]})}):e.jsx(Vs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(hd,{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 G5n({open:s,onOpenChange:t,video:n,gmailEmail:r,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=j.useState([]),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[x,y]=j.useState(""),[g,b]=j.useState(""),[v,k]=j.useState(""),[C,T]=j.useState(!1),M=pRt(),P=n.share_token?`https://video.relevelup.com/share/video/${n.share_token}`:"",L=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:a||n.thumbnail_url||"",I=n.title||"Video Message";j.useEffect(()=>{s&&l.length===0&&O()},[s]),j.useEffect(()=>{if(s&&(b(`I recorded a video for you — ${I}`),k("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),y(""),n.contact_id)){const ee=l.find(J=>J.id===n.contact_id);ee&&(d(ee),y(ee.email||""))}},[s,n.contact_id,l]);const O=async()=>{p(!0);try{const{data:ee,error:J}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(J)throw J;o(ee||[])}catch{console.error("Failed to fetch contacts")}finally{p(!1)}},$=ee=>{d(ee),h(!1),y(ee.email||""),k(`Hey ${ee.first_name}! I recorded a quick video just for you. Click below to watch it:`),b(`I recorded a video for you — ${I}`)},q=()=>{d(null),y(""),k("Hey! I recorded a quick video just for you. Click below to watch it:")},W=ee=>`${ee.first_name} ${ee.last_name||""}`.trim(),G=ee=>{const J=v.split(/\n\n+/).map(oe=>`

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

`).join(""),le=ee?xRt(ee):P,ue=ee?``:"";return`
${J}

▶ Watch Video

${ue}
`},K=async()=>{var ee;if(!x){re.error("Please enter a recipient email");return}if(!P){re.error("Video does not have a share link");return}T(!0);try{let J;try{const de=c?W(c):x.split("@")[0];J=(await M.mutateAsync({video_id:n.id,recipient_email:x,recipient_name:de,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(de){console.warn("Failed to create tracking record, sending without tracking:",de)}const le=G(J),{data:ue,error:oe}=await U.functions.invoke("gmail-send",{body:{to:x,subject:g,body:le,contactId:(c==null?void 0:c.id)||null}});let ie=null;if(oe&&((ee=oe.context)!=null&&ee.json))try{ie=await oe.context.json()}catch{}if((ie==null?void 0:ie.error)==="insufficient_scope"||(ue==null?void 0:ue.error)==="insufficient_scope"){re.error((ie==null?void 0:ie.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(oe)throw new Error((ie==null?void 0:ie.message)||oe.message);if(!(ue!=null&&ue.success))throw new Error((ue==null?void 0:ue.error)||"Failed to send");re.success("Video email sent!"),t(!1),i==null||i()}catch(J){console.error("Gmail send error:",J),re.error("Failed to send: "+(J instanceof Error?J.message:"Unknown error"))}finally{T(!1)}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-red-500"}),"Send Video via Gmail"]}),r&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:r})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(lc,{open:u,onOpenChange:h,children:[e.jsx(cc,{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(Eo,{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(fb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Jl,{className:"w-[350px] p-0",align:"start",children:e.jsxs(Sb,{children:[e.jsx(Cb,{placeholder:"Search contacts..."}),e.jsxs(Ab,{children:[e.jsx(Tb,{children:m?"Loading...":"No contacts found."}),e.jsx(Eb,{children:l.filter(ee=>ee.email).map(ee=>e.jsxs(Yy,{value:`${ee.first_name} ${ee.last_name||""} ${ee.email||""}`,onSelect:()=>$(ee),children:[e.jsx(da,{className:Et("mr-2 h-4 w-4",(c==null?void 0:c.id)===ee.id?"opacity-100":"opacity-0")}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:W(ee)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ee.email})]})]},ee.id))})]})]})})]}),c&&e.jsx(B,{variant:"ghost",size:"icon",onClick:q,className:"shrink-0",children:e.jsx(dr,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(ye,{id:"video-to",value:x,onChange:ee=>y(ee.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(Xl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"video-subject",children:"Subject"}),e.jsx(ye,{id:"video-subject",value:g,onChange:ee=>b(ee.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Ds,{id:"video-message",value:v,onChange:ee=>k(ee.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Video Preview (embedded in email)"}),e.jsxs("div",{className:"relative rounded-lg overflow-hidden bg-black",style:{maxWidth:320},children:[L?e.jsx("img",{src:L,alt:I,className:"w-full aspect-video object-cover"}):e.jsx("div",{className:"w-full aspect-video flex items-center justify-center bg-muted",children:e.jsx(fd,{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(fd,{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:C,children:"Cancel"}),e.jsxs(B,{onClick:K,disabled:C||!x||!g,className:"gap-2",children:[C?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"}),C?"Sending...":"Send Video Email"]})]})]})]})})}const W5n=()=>{const{user:s}=Ns();return mt({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.rpc("get_team_videos",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})};function K5n({recipient:s}){return s.watched_at?e.jsxs(qe,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(fd,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(qe,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(ag,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(qe,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(ma,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(qe,{variant:"outline",className:"text-[10px]",children:[e.jsx(Dr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function Y5n({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=agn(n);return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(ol,{className:"h-5 w-5"}),"Send Analytics: ",r]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(gn,{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(Tt,{children:"Recipient"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Sent"}),e.jsx(Tt,{children:"Last Activity"})]})}),e.jsx(za,{children:a.map(l=>e.jsxs(un,{children:[e.jsx(xt,{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(xt,{children:e.jsx(K5n,{recipient:l})}),e.jsx(xt,{className:"text-xs text-muted-foreground",children:Bs(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(xt,{className:"text-xs text-muted-foreground",children:l.last_activity_at?oc(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function Z5n(){const{data:s,isLoading:t}=ign(),{data:n=[],isLoading:r}=ogn(),[a,i]=j.useState(null),l=t||r,o=n.reduce((c,d)=>{const u=d.agent_videos,h=(u==null?void 0:u.id)||d.video_id;return c[h]||(c[h]={videoId:h,title:(u==null?void 0:u.title)||"Untitled",thumbnailUrl:u==null?void 0:u.thumbnail_url,recipients:[]}),c[h].recipients.push(d),c},{});return l?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((c,d)=>e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(gn,{className:"h-4 w-20"})}),e.jsx(Re,{children:e.jsx(gn,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(Dr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Re,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(ma,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(ag,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Re,{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(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(fr,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Re,{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(Zr,{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(Dr,{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(ma,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(ag,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(kl,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(Y5n,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function X5n({previewSrc:s,thumbnailSrc:t,alt:n,isHovered:r}){const[a,i]=j.useState(!1),[l,o]=j.useState(!1),c=r&&s&&!a,d=t&&!l;return!d&&!c?e.jsx("div",{className:"w-full h-full flex items-center justify-center absolute inset-0 bg-muted",children:e.jsx(Zr,{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 Q5n({video:s,previewSrc:t,thumbnailSrc:n,onOpen:r,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:u,onSendViaGmail:h,isGmailConnected:m,getContactName:p,getShareUrl:x,copyToClipboard:y,formatDuration:g}){const[b,v]=j.useState(!1);return e.jsxs(be,{className:"overflow-hidden group cursor-pointer",onClick:r,onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx(X5n,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:b}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(fd,{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:g(s.duration_seconds)}),s.status!=="ready"&&e.jsx(qe,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Re,{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(Eo,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),e.jsx("span",{children:Bs(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(ma,{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(on,{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(Eo,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),e.jsx("span",{children:Bs(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(ma,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:k=>k.stopPropagation(),children:e.jsx(W0,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",className:"bg-popover",children:[e.jsxs(wa,{onClick:k=>{k.stopPropagation(),r()},children:[e.jsx(ma,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(uy,{}),e.jsxs(wa,{onClick:k=>{k.stopPropagation(),u()},children:[e.jsx(Ac,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(wa,{onClick:k=>{k.stopPropagation(),y(x(s),"Share link")},children:[e.jsx(vc,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(wa,{onClick:k=>{k.stopPropagation(),o()},children:[e.jsx(qT,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(wa,{onClick:k=>{k.stopPropagation(),c()},children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(wa,{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(wa,{onClick:k=>{k.stopPropagation(),h==null||h()},children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(wa,{onClick:k=>{k.stopPropagation(),i()},children:[e.jsx(Za,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(uy,{}),s.contact_id&&e.jsxs(wa,{onClick:k=>{k.stopPropagation(),l()},children:[e.jsx(Eo,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(wa,{onClick:k=>{k.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function J5n(){var qs,As;const s=Hn(),{data:t,isLoading:n,refetch:r}=Sgn(),{data:a}=RAe(),{data:i}=av(),l=Tgn(),o=Agn(),{isGmailConnected:c,gmailEmail:d}=Tf(),{data:u}=Hj(),{data:h=[],isLoading:m}=W5n(),[p,x]=j.useState("my"),[y,g]=j.useState(""),[b,v]=j.useState(null),[k,C]=j.useState(!1),[T,M]=j.useState(!1),[P,L]=j.useState(!1),[I,O]=j.useState(!1),[$,q]=j.useState(!1),[W,G]=j.useState(""),[K,ee]=j.useState(!1),[J,le]=j.useState(!1),[ue,oe]=j.useState(!1),[ie,de]=j.useState(!1),[we,je]=j.useState(""),[xe,fe]=j.useState({}),Se=Bt=>{if(!Bt)return"Unassigned";const At=i==null?void 0:i.find(Is=>Is.id===Bt);return At?`${At.first_name} ${At.last_name||""}`.trim():"Unknown"},Ee=Bt=>{if(!Bt)return"0:00";const At=Math.floor(Bt/60),Is=Bt%60;return`${At}:${Is.toString().padStart(2,"0")}`},[Le,De]=j.useState("all"),Be=t==null?void 0:t.filter(Bt=>{const At=Bt.category||"general";if(Le==="general"&&At!=="general"||Le==="open_house"&&At!=="open_house")return!1;if(!y)return!0;const Is=Se(Bt.contact_id).toLowerCase(),jt=(Bt.title||"").toLowerCase(),Qs=(Bt.notes||"").toLowerCase();return Is.includes(y.toLowerCase())||jt.includes(y.toLowerCase())||Qs.includes(y.toLowerCase())}),Ne=(t==null?void 0:t.filter(Bt=>(Bt.category||"general")==="open_house").length)||0,Ge=(t==null?void 0:t.filter(Bt=>(Bt.category||"general")==="general").length)||0,_e=(t||[]).filter(Bt=>Bt.status==="processing"&&Bt.bunny_video_id).map(Bt=>Bt.id).join(",");j.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const At=t.filter(jt=>jt.status==="processing"&&jt.bunny_video_id);if(!At.length)return;let Is=!1;for(const jt of At)try{const{data:Qs,error:cn}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:jt.bunny_video_id,isAgentVideo:!0}});if(cn||!Qs)continue;Qs.status===4&&(await U.from("agent_videos").update({status:"ready",playback_url:Qs.directPlayUrl,thumbnail_url:Qs.thumbnailUrl,preview_url:Qs.previewUrl,duration_seconds:Qs.length||jt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",jt.id),Is=!0)}catch(Qs){console.warn("Reconcile check failed for video",jt.id,Qs)}Is&&r()})()},[_e,r]),j.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const At=t.filter(qt=>(qt==null?void 0:qt.bunny_video_id)&&!xe[qt.id]);if(!At.length)return;const Is=At.map(qt=>qt.bunny_video_id),{data:jt,error:Qs}=await U.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:Is,isAgentVideo:!0}});if(Qs)throw Qs;const cn=(jt==null?void 0:jt.assets)||{};fe(qt=>{const Gs={...qt};for(const Ls of At)cn[Ls.bunny_video_id]&&(Gs[Ls.id]={previewUrl:cn[Ls.bunny_video_id].previewUrl,thumbnailUrl:cn[Ls.bunny_video_id].thumbnailUrl});return Gs})})().catch(At=>console.warn("Failed to load signed Bunny asset URLs",At))},[t,xe]);const Oe=(a==null?void 0:a.total_storage_mb)||0,Ae=(a==null?void 0:a.max_storage_mb)||1024,Xe=Oe/Ae*100,Ue=Xe>=80,Ze=Xe>=100,Qe=async(Bt,At)=>{await navigator.clipboard.writeText(Bt),re.success(`${At} copied to clipboard`)},Ye=Bt=>Bt.share_token?`https://video.relevelup.com/${Bt.share_token}`:Bt.playback_url||"",nt=Bt=>{const At=Ye(Bt),Is=i==null?void 0:i.find(Ls=>Ls.id===Bt.contact_id),jt=Se(Bt.contact_id),Qs=jt!=="Unassigned"?jt.split(" ")[0]:"",cn=(Is==null?void 0:Is.phone)||"",qt=`Hey${Qs?` ${Qs}`:""}! I recorded a quick video message for you. Check it out: ${At}`,Gs=cn?`sms:${cn}?body=${encodeURIComponent(qt)}`:`sms:?body=${encodeURIComponent(qt)}`;window.open(Gs,"_self")},rt=Bt=>{const At=i==null?void 0:i.find(Gs=>Gs.id===Bt.contact_id),Is=(At==null?void 0:At.email)||"",jt=Ye(Bt),Qs="Check out this video",cn=`I recorded a quick video for you: ${jt}`,qt=Is?`mailto:${Is}?subject=${encodeURIComponent(Qs)}&body=${encodeURIComponent(cn)}`:`mailto:?subject=${encodeURIComponent(Qs)}&body=${encodeURIComponent(cn)}`;window.open(qt,"_self")},Fe=Bt=>{var Qs;const At=Ye(Bt),Is=Bt.title||"Video Message",jt=Bt.share_token?`https://video.relevelup.com/thumb/${Bt.share_token}`:((Qs=xe[Bt.id])==null?void 0:Qs.thumbnailUrl)||Bt.thumbnail_url||"";return``},dt=async Bt=>{if(!Bt.thumbnail_url&&!Bt.share_token){re.error("Video thumbnail not available yet");return}const At=Fe(Bt),Is=Ye(Bt),jt=`Watch: ${Bt.title||"Video Message"} ${Is}`;try{const Qs=new Blob([At],{type:"text/html"}),cn=new Blob([jt],{type:"text/plain"}),qt=new ClipboardItem({"text/html":Qs,"text/plain":cn});await navigator.clipboard.write([qt]),re.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(jt+` `+At),re.success("Copied! Paste into your email.")}},Dt=async Bt=>{try{re.loading("Preparing download...",{id:"download"});const{data:At,error:Is}=await U.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:Bt.bunny_video_id,isAgentVideo:!0}});if(Is||!(At!=null&&At.downloadUrl))throw new Error((Is==null?void 0:Is.message)||"Failed to get download URL");const Qs=`${((Bt.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,cn=await fetch(At.downloadUrl);if(!cn.ok)throw new Error("Failed to fetch video file");const qt=await cn.blob(),Gs=URL.createObjectURL(qt),Ls=document.createElement("a");Ls.href=Gs,Ls.download=Qs,Ls.rel="noreferrer",document.body.appendChild(Ls),Ls.click(),Ls.remove(),URL.revokeObjectURL(Gs),re.success("Download started",{id:"download"})}catch(At){console.error("Download error:",At),re.error("Could not force download (your browser may block it).",{id:"download"})}},pt=async Bt=>{v(Bt),ee(!0),G(""),q(!0);try{const{data:At,error:Is}=await U.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:Bt.bunny_video_id,title:Bt.title,isAgentVideo:!0,shareToken:Bt.share_token}});if(Is||!(At!=null&&At.html))throw new Error("Failed to generate CRM embed code");G(At.html)}catch(At){console.error("CRM embed error:",At),re.error("Failed to generate CRM embed code"),q(!1)}finally{ee(!1)}},zt=Bt=>{v(Bt),C(!0)},Gt=async()=>{if(b)try{await l.mutateAsync({id:b.id,bunnyVideoId:b.bunny_video_id,hardDelete:!0}),M(!1),v(null),re.success("Video deleted successfully")}catch{re.error("Failed to delete video")}};return e.jsx(Vs,{title:"Video Library",description:"Manage your video touches",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5 ml-2",children:[e.jsx("button",{onClick:()=>x("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${p==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&((qs=u.team)==null?void 0:qs.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>x("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${p==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>x("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${p==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(ol,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),p==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>L(!0),children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(B,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),p==="team"?e.jsx(eSn,{videos:h,isLoading:m,searchTerm:y,setSearchTerm:g}):p==="analytics"?e.jsx(Z5n,{}):e.jsxs(e.Fragment,{children:[e.jsx(be,{className:Ue?"border-amber-500":Ze?"border-destructive":"",children:e.jsxs(Re,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(UW,{className:`h-5 w-5 ${Ze?"text-destructive":Ue?"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:[Oe.toFixed(1)," MB / ",Ae>=1024?`${(Ae/1024).toFixed(0)} GB`:`${Ae} MB`]})]}),e.jsx(qi,{value:Math.min(Xe,100),className:`h-2 ${Ze?"[&>div]:bg-destructive":Ue?"[&>div]:bg-amber-500":""}`})]}),Ue&&!Ze&&e.jsxs(qe,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(po,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Ze&&e.jsxs(qe,{variant:"destructive",children:[e.jsx(po,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),Ze&&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(Bt=>e.jsxs("button",{onClick:()=>De(Bt.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Le===Bt.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[Bt.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:Bt.count})]},Bt.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search videos by contact, title, or notes...",value:y,onChange:Bt=>g(Bt.target.value),className:"pl-10"})]}),n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):(Be==null?void 0:Be.length)===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center",children:[e.jsx(Zr,{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(Js,{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(Bt=>{var At,Is;return e.jsx(Q5n,{video:Bt,previewSrc:(At=xe[Bt.id])==null?void 0:At.previewUrl,thumbnailSrc:(Is=xe[Bt.id])==null?void 0:Is.thumbnailUrl,onOpen:()=>zt(Bt),onDelete:()=>{v(Bt),M(!0)},onRename:()=>{v(Bt),je(Bt.title||""),de(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${Bt.contact_id}`),onGetEmbedCode:()=>{v(Bt),O(!0)},onCopyEmailHtml:()=>dt(Bt),onEmbedToCrm:()=>pt(Bt),onShareWithTemplate:()=>{v(Bt),le(!0)},onSendViaGmail:()=>{v(Bt),oe(!0)},isGmailConnected:c,getContactName:Se,getShareUrl:Ye,copyToClipboard:Qe,formatDuration:Ee},Bt.id)})}),e.jsx(Fs,{open:k,onOpenChange:C,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs($s,{children:[e.jsx(zs,{children:(b==null?void 0:b.title)||"Video Preview"}),e.jsx(kr,{children:(b==null?void 0:b.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Eo,{className:"h-3 w-3"}),Se(b.contact_id)]})})]}),b&&e.jsxs("div",{className:"space-y-4",children:[b.status==="processing"?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6 bg-muted/50 rounded-lg border border-dashed border-border text-center space-y-4",children:[e.jsx("div",{className:"relative",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Wt,{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:()=>{C(!1),r()},children:[e.jsx(Ki,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:b.playback_url?(()=>{let Bt=b.playback_url;return Bt.includes("iframe.mediadelivery.net/play/")&&(Bt=Bt.replace("/play/","/embed/"),Bt+=(Bt.includes("?")?"&":"?")+"autoplay=false&responsive=true"),Bt.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:Bt,title:b.title||"Video preview",className:"absolute top-0 left-0 w-full h-full rounded-lg",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0}):e.jsx("video",{src:b.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:b.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>re.error("Video preview failed to load")},b.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(Zr,{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:()=>nt(b),children:[e.jsx(ro,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(B,{variant:"outline",onClick:()=>rt(b),children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>Qe(Ye(b),"Share link"),children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(B,{variant:"outline",onClick:()=>dt(b),children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(B,{variant:"outline",onClick:()=>Dt(b),children:[e.jsx(ii,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>{C(!1),pt(b)},children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(B,{variant:"outline",onClick:()=>{C(!1),le(!0)},children:[e.jsx(Ac,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(b==null?void 0:b.share_token)&&e.jsxs(B,{variant:"outline",onClick:()=>{C(!1),oe(!0)},children:[e.jsx(Dr,{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:()=>{C(!1),M(!0)},children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(Fs,{open:T,onOpenChange:M,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Delete Video"}),e.jsx(kr,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>M(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Gt,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(_Rt,{open:P,onOpenChange:L}),e.jsx(Fs,{open:I,onOpenChange:O,children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Embed Video"}),e.jsx(kr,{children:"Copy this code to embed the video on your website."})]}),b&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Embed Code"}),e.jsx(Ds,{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 Bt=``;Qe(Bt,"Embed code")},children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Copy Embed Code"]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this code into your website's HTML where you want the video to appear. The video will automatically resize to fit its container."})]})]})}),b&&e.jsx(Yzt,{open:J,onOpenChange:le,video:b,contactName:Se(b.contact_id)}),b&&e.jsx(G5n,{open:ue,onOpenChange:oe,video:b,gmailEmail:d,signedThumbnailUrl:(As=xe[b.id])==null?void 0:As.thumbnailUrl}),e.jsx(Fs,{open:ie,onOpenChange:de,children:e.jsxs(Os,{className:"max-w-sm",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Rename Video"}),e.jsx(kr,{children:"Enter a new title for this video."})]}),e.jsx(ye,{value:we,onChange:Bt=>je(Bt.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:Bt=>{Bt.key==="Enter"&&we.trim()&&o.mutate({id:b.id,title:we.trim()},{onSuccess:()=>{re.success("Video renamed"),de(!1)}})}}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>de(!1),children:"Cancel"}),e.jsx(B,{disabled:!we.trim()||o.isPending,onClick:()=>{o.mutate({id:b.id,title:we.trim()},{onSuccess:()=>{re.success("Video renamed"),de(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(Fs,{open:$,onOpenChange:q,children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Tr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(kr,{children:"Copy this HTML code and paste it into your CRM's email editor. It uses a simple image + link format that works in all CRM email programs."})]}),K?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Wt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):W?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"CRM Email HTML"}),e.jsx(Ds,{readOnly:!0,rows:12,value:W,className:"font-mono text-xs"})]}),e.jsxs(B,{className:"w-full",onClick:()=>{Qe(W,"CRM embed code")},children:[e.jsx(ja,{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 eSn({videos:s,isLoading:t,searchTerm:n,setSearchTerm:r}){const a=j.useMemo(()=>{if(!n)return s;const o=n.toLowerCase();return s.filter(c=>(c.title||"").toLowerCase().includes(o)||(c.owner_name||"").toLowerCase().includes(o)||(c.recipient_name||"").toLowerCase().includes(o))},[s,n]),i=j.useMemo(()=>{const o=new Map;return a.forEach(c=>{const d=o.get(c.owner_user_id);d?d.videos.push(c):o.set(c.owner_user_id,{name:c.owner_name,avatar:c.owner_avatar_url,videos:[c]})}),Array.from(o.entries())},[a]),l=o=>{if(!o)return"0:00";const c=Math.floor(o/60),d=o%60;return`${c}:${d.toString().padStart(2,"0")}`};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{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(be,{children:e.jsxs(Re,{className:"py-12 text-center",children:[e.jsx(Bn,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No team videos"}),e.jsx("p",{className:"text-muted-foreground",children:s.length===0?"Your teammates haven't recorded any videos yet.":"No videos match your search."})]})}):e.jsx("div",{className:"space-y-6",children:i.map(([o,c])=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ra,{className:"h-7 w-7",children:[e.jsx(Fi,{src:c.avatar||""}),e.jsx(Da,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(qe,{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(be,{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(Zr,{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(Re,{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(Eo,{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(ma,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),Bs(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const tSn=()=>{const{user:s}=Ns();return mt({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.rpc("get_team_deals",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},igt=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function sSn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=tSn(),[a,i]=j.useState(""),[l,o]=j.useState("all"),c=j.useMemo(()=>{if(!n)return new Map;const x=new Map;let y=0;return n.forEach(g=>{x.has(g.owner_user_id)||(x.set(g.owner_user_id,{name:g.owner_name||"Unknown",avatar:g.owner_avatar_url,color:igt[y%igt.length]}),y++)}),x},[n]),d=j.useMemo(()=>Array.from(c.entries()).map(([x,y])=>({id:x,...y})),[c]),u=j.useMemo(()=>{if(!n)return[];let x=n;if(l!=="all"&&(x=x.filter(y=>y.owner_user_id===l)),a.trim()){const y=a.toLowerCase();x=x.filter(g=>{var b,v,k,C;return g.deal_name.toLowerCase().includes(y)||((b=g.contact_name)==null?void 0:b.toLowerCase().includes(y))||((v=g.property_address)==null?void 0:v.toLowerCase().includes(y))||((k=g.city)==null?void 0:k.toLowerCase().includes(y))||((C=g.owner_name)==null?void 0:C.toLowerCase().includes(y))})}return x},[n,a,l]),h=j.useMemo(()=>{const x=new Map;return u.forEach(y=>{const g=y.stage_name||"Unknown";x.has(g)||x.set(g,{name:g,color:y.stage_color,icon:y.stage_icon,deals:[],totalValue:0});const b=x.get(g);b.deals.push(y),b.totalValue+=y.sale_price||0}),Array.from(x.values())},[u]),m=x=>x>=1e6?`$${(x/1e6).toFixed(1)}M`:x>=1e3?`$${(x/1e3).toFixed(0)}K`:`$${x.toFixed(0)}`,p=x=>x?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(x):null;return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"Team Pipeline"]})}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"relative flex-1 max-w-xs",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search deals...",value:a,onChange:x=>i(x.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"All Members"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Members"}),d.map(x=>e.jsx(Je,{value:x.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full inline-block",style:{backgroundColor:x.color}}),x.name]})},x.id))]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-3 ml-auto text-xs text-muted-foreground",children:[d.slice(0,6).map(x=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:x.color}}),x.name.split(" ")[0]]},x.id)),d.length>6&&e.jsxs("span",{children:["+",d.length-6," more"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden mt-2",children:r?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(x=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(gn,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(gn,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(gn,{className:"h-24 w-full rounded-lg"})]},x))}):h.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Bn,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No team deals found"}),e.jsx("p",{className:"text-sm",children:"Team members' deals will appear here."})]})}):e.jsx("div",{className:"flex gap-3 h-full overflow-x-auto pb-2",children:h.map(x=>{const y=x.icon&&T4e[x.icon]||Sx;return e.jsxs("div",{className:"flex flex-col h-full min-w-[260px] max-w-[300px] flex-1 bg-muted/30 rounded-xl border border-border/50",children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:x.color||"hsl(var(--border))",borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-md flex items-center justify-center",style:{backgroundColor:x.color?`${x.color}20`:void 0},children:e.jsx(y,{className:"h-3.5 w-3.5",style:{color:x.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:x.name})]}),e.jsx(qe,{variant:"secondary",className:"text-xs px-2",children:x.deals.length})]}),x.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:m(x.totalValue)})]}),e.jsx(lo,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:x.deals.map(g=>{const b=c.get(g.owner_user_id);return e.jsx(nSn,{deal:g,ownerColor:(b==null?void 0:b.color)||"#888",ownerName:(b==null?void 0:b.name)||"Unknown",ownerAvatar:(b==null?void 0:b.avatar)||null,formatPrice:p},g.id)})})})]},x.name)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2 border-t shrink-0",children:[u.length," deal",u.length!==1?"s":""," across ",h.length," stage",h.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function nSn({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(Ra,{className:"h-4 w-4",children:[e.jsx(Fi,{src:r||""}),e.jsx(Da,{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(qe,{variant:"outline",className:Et("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(ia,{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(Od,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function rSn({members:s,enabledMembers:t,onToggleMember:n,isOpen:r,onToggleOpen:a}){const i=t.size;return e.jsxs("div",{className:Et("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(Bn,{className:"h-4 w-4 shrink-0 text-primary"}),r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs font-semibold flex-1 text-left",children:"Team"}),i>0&&e.jsx("span",{className:"text-[10px] bg-primary text-primary-foreground rounded-full px-1.5 py-0.5",children:i}),e.jsx(Cc,{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:Et("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(Ra,{className:"h-7 w-7",children:[e.jsx(Fi,{src:l.avatar_url||""}),e.jsx(Da,{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:Et("text-xs truncate flex-1",o?"font-medium text-foreground":"text-muted-foreground"),children:l.name}),e.jsx(Mn,{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(Ra,{className:Et("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(Fi,{src:l.avatar_url||""}),e.jsx(Da,{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 ogt=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function aSn(){const s=ei(),{data:t}=Hj(),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 U.from("team_members").select("user_id, role").eq("team_id",r).neq("user_id",s);if(l)throw l;if(!i||i.length===0)return[];const o=i.map(u=>u.user_id),{data:c,error:d}=await U.from("profiles").select("id, name, avatar_url").in("id",o);if(d)throw d;return(c||[]).map((u,h)=>({id:u.id,name:u.name||"Unknown",avatar_url:u.avatar_url,color:ogt[h%ogt.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function iSn(s){return mt({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:n}=await U.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at), deal_pipeline_stages(name) `).in("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return(t||[]).map(r=>{var a;return{...r,_stage_name:((a=r.deal_pipeline_stages)==null?void 0:a.name)||null}})},enabled:s.length>0})}function oSn(){const s=ei();return mt({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:n}=await U.from("deal_tags").select("id, deal_id, tag").eq("owner_user_id",s);if(n)throw n;const r=t||[],a={},i=new Set;r.forEach(o=>{a[o.deal_id]||(a[o.deal_id]=[]),a[o.deal_id].push(o.tag),i.add(o.tag)});const l=Array.from(i).sort((o,c)=>o.localeCompare(c));return{tags:r,byDeal:a,unique:l}},enabled:!!s})}function Zzt({stages:s,currentStageId:t,onStageSelect:n,disabled:r}){const[a,i]=j.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&n(c.id,c.name),i(!1)};return e.jsxs(kd,{open:a,onOpenChange:i,children:[e.jsx(Sd,{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(xd,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&T4e[c.icon]||Sx,u=c.id===t;return e.jsxs(wa,{onClick:()=>o(c),className:Et("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(da,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const lSn={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"}},cSn={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 Xzt({deal:s,onClick:t,isDragging:n,stages:r,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,ownerInfo:o=null}){var v,k;const c=Tq(),d=lSn[s.deal_type],u=cSn[s.priority],h=j.useMemo(()=>s.target_close_date?Fj(Ic(s.target_close_date),new Date):null,[s.target_close_date]),m=h!==null&&h<0,p=h!==null&&h<=7&&h>=0,x=j.useMemo(()=>{var M;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const C=((M=s.listing)==null?void 0:M.created_at)||s.listing_date;if(!C)return null;const T=s.contract_date?Ic(s.contract_date):new Date;return Fj(T,Ic(C))},[s]),y=l&&!s.scorecard_transaction_id,g=!!s.scorecard_transaction_id,b=C=>C?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(C):null;return e.jsx(be,{className:Et("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(Re,{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(Ra,{className:"h-4 w-4",children:[e.jsx(Fi,{src:o.avatar_url||""}),e.jsx(Da,{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(qe,{variant:"outline",className:Et("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(Ra,{className:"h-5 w-5",children:e.jsxs(Da,{className:"text-[10px] bg-primary/10 text-primary",children:[(v=s.contact.first_name)==null?void 0:v[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(Rc,{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(ll,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),g&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(Rr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),x!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(ym,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Et("font-medium",x>90?"text-red-600":x>60?"text-amber-600":"text-muted-foreground"),children:[x," 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(ia,{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(Od,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:b(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",b(s.expected_commission)," GCI"]}),(()=>{const C=mj(s);return C!==null&&C!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",b(C)," 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:Et("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",u.color),children:[e.jsx("div",{className:Et("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(Zzt,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(C,T)=>a(s.id,C,T)}):s.target_close_date?e.jsxs("div",{className:Et("flex items-center gap-1 text-[10px]",m&&"text-red-600",p&&!m&&"text-amber-600",!m&&!p&&"text-muted-foreground"),children:[m?e.jsx(po,{className:"h-3 w-3"}):e.jsx(ra,{className:"h-3 w-3"}),e.jsx("span",{children:m?`${Math.abs(h)}d overdue`:p?`${h}d left`:Bs(Ic(s.target_close_date),"MMM d")})]}):null]})]})})}function dSn({stage:s,deals:t,onDealClick:n,onAddDeal:r,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,getOwnerInfo:d}){const u=j.useRef(null),h=t.reduce((g,b)=>g+(b.expected_price||0),0),m=t.reduce((g,b)=>g+(b.expected_commission||0),0),p=t.reduce((g,b)=>g+(mj(b)||0),0),x=g=>g>=1e6?`$${(g/1e6).toFixed(1)}M`:g>=1e3?`$${(g/1e3).toFixed(0)}K`:`$${g.toFixed(0)}`,y=s.icon&&T4e[s.icon]||Sx;return e.jsxs("div",{ref:u,className:Et("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:g=>i(g,s.id),onDrop:g=>l(g,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(qe,{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:x(h)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[x(m)," GCI"]}),p>0&&p!==m&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[x(p)," Net"]})]})]})]}),e.jsx(lo,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(g=>e.jsx("div",{draggable:!0,onDragStart:b=>{b.dataTransfer.effectAllowed="move",a(g.id,s.id)},children:e.jsx(Xzt,{deal:g,onClick:()=>n(g),isWonStage:c,ownerInfo:(d==null?void 0:d(g))||null})},g.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(Js,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function uSn({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:uu,color:"text-blue-500",bgColor:"bg-blue-500/10"},{label:"Weighted GCI",value:n((s==null?void 0:s.weightedGCI)||0),icon:az,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:mz,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:n1,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:kl,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(be,{className:"animate-pulse",children:e.jsx(Re,{className:"p-4",children:e.jsx("div",{className:"h-10 bg-muted rounded"})})},a))}):e.jsx(RN,{children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:r.map(a=>{const i=e.jsx(be,{className:"border-border/50 hover:shadow-sm transition-shadow",children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Et("p-2 rounded-lg",a.bgColor),children:e.jsx(a.icon,{className:Et("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(Cu,{children:[e.jsx(Au,{asChild:!0,children:i}),e.jsx(ou,{children:e.jsx("p",{children:a.tooltip})})]},a.label):i})})})}function hSn({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=Ns(),[a,i]=j.useState(s.portal_enabled);if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(qe,{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(i0,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(o0,{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(yn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(qe,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(Po,{className:Et("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(l0,{children:e.jsxs("div",{className:"px-4 pb-4 space-y-5 border-t pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Enable Client Portal"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Create a beautiful portal your client can track their deal from"})]}),e.jsx(Mn,{checked:s.portal_enabled,onCheckedChange:o=>l({portal_enabled:o})})]}),s.portal_enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(ob,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:Et("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(eh,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(du,{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:Et("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(eh,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm font-medium",children:"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(wi,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"require_onboarding",className:"text-sm font-medium cursor-pointer",children:"Require client onboarding before portal access"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Client confirms contact details + preferences before viewing portal. Info is saved to your contacts."})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(wi,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(se,{htmlFor:"allow_spouse",className:"text-sm cursor-pointer",children:"Allow client to add spouse/partner during onboarding"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-sm font-medium",children:"Client Invite Details"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(ye,{value:s.client_name,onChange:o=>l({client_name:o.target.value}),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(ye,{type:"email",value:s.client_email,onChange:o=>l({client_email:o.target.value}),placeholder:"jane@example.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(ye,{type:"tel",value:s.client_phone,onChange:o=>l({client_phone:o.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(vs,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"email",children:"Email"}),e.jsxs(Je,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const mSn=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],pSn=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function fSn({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=yee(),{data:i}=av(),{data:l}=XCt(),o=q3e(),c=Hzt(),d=Gzt(),u=NWe(),[h,m]=j.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[p,x]=j.useState(""),[y,g]=j.useState(!1),[b,v]=j.useState(!1),[k,C]=j.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)))||[],[M,P]=j.useState({deal_name:"",deal_type:"buyer",stage_id:"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:"",team_split_pct:"",referral_fee_pct:"",franchise_fee_pct:"",transaction_fee:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""});j.useEffect(()=>{var W,G,K,ee,J,le,ue,oe;s&&(n?(P({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||"",contact_id:n.contact_id||"",listing_id:n.listing_id||"",property_address:n.property_address||"",city:n.city||"",state:n.state||"",zip_code:n.zip_code||"",expected_price:((W=n.expected_price)==null?void 0:W.toString())||"",commission_percentage:((G=n.commission_percentage)==null?void 0:G.toString())||"3",brokerage_split_pct:((K=n.brokerage_split_pct)==null?void 0:K.toString())||"",team_split_pct:((ee=n.team_split_pct)==null?void 0:ee.toString())||"",referral_fee_pct:((J=n.referral_fee_pct)==null?void 0:J.toString())||"",franchise_fee_pct:((le=n.franchise_fee_pct)==null?void 0:le.toString())||"",transaction_fee:((ue=n.transaction_fee)==null?void 0:ue.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?Ic(n.target_close_date):void 0,contract_date:n.contract_date?Ic(n.contract_date):void 0,listing_date:n.listing_date?Ic(n.listing_date):void 0,priority:n.priority,probability:n.probability.toString(),notes:n.notes||""}),n.contact&&x(`${n.contact.first_name} ${n.contact.last_name}`)):(P({deal_name:"",deal_type:"buyer",stage_id:r||((oe=a==null?void 0:a[0])==null?void 0:oe.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:""}),x(""),m({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,n,r,a]);const L=i==null?void 0:i.filter(W=>{var de,we,je,xe,fe;const G=p.toLowerCase().trim();if(!G)return!0;const K=((de=W.first_name)==null?void 0:de.toLowerCase())||"",ee=((we=W.last_name)==null?void 0:we.toLowerCase())||"",J=((je=W.email)==null?void 0:je.toLowerCase())||"",le=((fe=(xe=W.phone)==null?void 0:xe.toLowerCase)==null?void 0:fe.call(xe))||"",ue=`${K} ${ee}`.trim(),oe=`${ee} ${K}`.trim();if(ue.includes(G)||oe.includes(G)||K.includes(G)||ee.includes(G)||J.includes(G)||le.includes(G))return!0;const ie=G.split(/\s+/).filter(Boolean);return ie.length>1?ie.every(Se=>K.includes(Se)||ee.includes(Se)||J.includes(Se)||le.includes(Se)):!1}).slice(0,8),I=()=>{const W=parseFloat(M.expected_price)||0,G=parseFloat(M.commission_percentage)||0;return W*(G/100)},O=()=>{const W=I();if(!W)return null;const G=parseFloat(M.brokerage_split_pct)||0,K=parseFloat(M.team_split_pct)||0,ee=parseFloat(M.referral_fee_pct)||0,J=parseFloat(M.franchise_fee_pct)||0,le=parseFloat(M.transaction_fee)||0;if(M.commission_calc_method==="referral_first"){let oe=W;ee&&(oe-=W*ee/100);let ie=oe;return G&&(ie-=oe*G/100),K&&(ie-=W*K/100),J&&(ie-=W*J/100),le&&(ie-=le),Math.max(0,ie)}let ue=W;return G&&(ue=ue*((100-G)/100)),K&&(ue=ue*((100-K)/100)),ee&&(ue=ue-W*ee/100),J&&(ue=ue-W*J/100),le&&(ue=ue-le),Math.max(0,ue)},$=async W=>{var G,K,ee;if(W.preventDefault(),!M.deal_name.trim()){re.error("Please enter a deal name");return}try{const J={deal_name:M.deal_name,deal_type:M.deal_type,stage_id:M.stage_id||null,contact_id:M.contact_id||null,listing_id:M.listing_id||null,property_address:M.property_address||null,city:M.city||null,state:M.state||null,zip_code:M.zip_code||null,expected_price:M.expected_price?parseFloat(M.expected_price):null,expected_commission:I()||null,commission_percentage:M.commission_percentage?parseFloat(M.commission_percentage):3,brokerage_split_pct:M.brokerage_split_pct?parseFloat(M.brokerage_split_pct):null,team_split_pct:M.team_split_pct?parseFloat(M.team_split_pct):null,referral_fee_pct:M.referral_fee_pct?parseFloat(M.referral_fee_pct):null,franchise_fee_pct:M.franchise_fee_pct?parseFloat(M.franchise_fee_pct):null,transaction_fee:M.transaction_fee?parseFloat(M.transaction_fee):null,commission_calc_method:M.commission_calc_method,target_close_date:((G=M.target_close_date)==null?void 0:G.toISOString().split("T")[0])||null,contract_date:((K=M.contract_date)==null?void 0:K.toISOString().split("T")[0])||null,listing_date:((ee=M.listing_date)==null?void 0:ee.toISOString().split("T")[0])||null,priority:M.priority,probability:parseInt(M.probability)||50,notes:M.notes||null};if(n)await d.mutateAsync({id:n.id,...J}),re.success("Deal updated successfully");else{const le=await c.mutateAsync(J);if(re.success("Deal created successfully"),h.portal_enabled&&(le!=null&&le.id))try{await u.mutateAsync({deal_id:le.id,visibility:h.visibility,require_onboarding:h.require_onboarding,allow_spouse:h.allow_spouse,client_name:h.client_name||null,client_email:h.client_email||null,client_phone:h.client_phone||null,invite_method:h.invite_method}),re.success("Client portal created!")}catch{re.error("Deal created, but portal setup failed")}}t(!1)}catch{re.error("Failed to save deal")}},q=c.isPending||d.isPending;return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(kr,{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(se,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(ye,{id:"deal_name",value:M.deal_name,onChange:W=>P(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(se,{children:"Deal Type"}),e.jsxs(vs,{value:M.deal_type,onValueChange:W=>P(G=>({...G,deal_type:W})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:mSn.map(W=>e.jsx(Je,{value:W.value,children:W.label},W.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Stage"}),e.jsxs(vs,{value:M.stage_id||"none",onValueChange:W=>P(G=>({...G,stage_id:W==="none"?"":W})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select stage"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No Stage"}),a==null?void 0:a.map(W=>e.jsx(Je,{value:W.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:W.color}}),W.name]})},W.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:p,onChange:W=>{x(W.target.value),g(!0),v(!1),W.target.value||P(G=>({...G,contact_id:""}))},onFocus:()=>g(!0),placeholder:"Search contacts...",className:"pl-9"}),y&&p&&e.jsxs("div",{className:"absolute z-10 w-full mt-1 bg-background border rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[L&&L.length>0?L.map(W=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{P(G=>({...G,contact_id:W.id})),x(`${W.first_name} ${W.last_name}`),g(!1)},children:[e.jsx(Eo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[W.first_name," ",W.last_name]}),W.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:W.email})]},W.id)):e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"No contacts found"}),e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2 border-t text-primary font-medium",onClick:()=>{const W=p.trim().split(/\s+/);C({first_name:W[0]||"",last_name:W.slice(1).join(" ")||"",email:"",phone:""}),v(!0),g(!1)},children:[e.jsx(Sl,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',p.trim(),'"']})]})]})]}),b&&e.jsxs("div",{className:"border rounded-lg p-3 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(Sl,{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:()=>v(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ye,{placeholder:"First name *",value:k.first_name,onChange:W=>C(G=>({...G,first_name:W.target.value})),className:"h-8 text-sm"}),e.jsx(ye,{placeholder:"Last name",value:k.last_name,onChange:W=>C(G=>({...G,last_name:W.target.value})),className:"h-8 text-sm"}),e.jsx(ye,{placeholder:"Email",type:"email",value:k.email,onChange:W=>C(G=>({...G,email:W.target.value})),className:"h-8 text-sm"}),e.jsx(ye,{placeholder:"Phone",type:"tel",value:k.phone,onChange:W=>C(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&&(P(G=>({...G,contact_id:W.id})),x(`${W.first_name} ${W.last_name||""}`.trim()),v(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Sl,{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(se,{className:"flex items-center gap-2",children:[e.jsx(Rc,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(vs,{value:M.listing_id||"none",onValueChange:W=>{const G=W==="none"?"":W,K=T.find(ee=>ee.id===G);P(K?ee=>{var J;return{...ee,listing_id:G,deal_type:"seller",property_address:K.property_address||ee.property_address,city:K.city||ee.city,state:K.state||ee.state,expected_price:((J=K.price)==null?void 0:J.toString())||ee.expected_price}}:ee=>({...ee,listing_id:G}))},children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a listing to sync status..."})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"None"}),T.map(W=>e.jsx(Je,{value:W.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:W.property_address||`${W.city}, ${W.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(W.price/1e3).toFixed(0),"K"]})]})},W.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status changes will sync automatically between the deal and listing."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Property Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(se,{htmlFor:"property_address",children:"Address"}),e.jsx(ye,{id:"property_address",value:M.property_address,onChange:W=>P(G=>({...G,property_address:W.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(ye,{id:"city",value:M.city,onChange:W=>P(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(se,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:M.state,onChange:W=>P(G=>({...G,state:W.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(ye,{id:"zip_code",value:M.zip_code,onChange:W=>P(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(se,{htmlFor:"expected_price",children:"Expected Price"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(ye,{id:"expected_price",type:"number",value:M.expected_price,onChange:W=>P(G=>({...G,expected_price:W.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{id:"commission_percentage",type:"number",step:"0.1",value:M.commission_percentage,onChange:W=>P(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(se,{children:"Expected GCI"}),e.jsx(ye,{value:I()?`$${I().toLocaleString()}`:"-",disabled:!0,className:"bg-muted"})]})]}),e.jsxs("details",{className:"group",children:[e.jsxs("summary",{className:"text-xs font-medium text-muted-foreground cursor-pointer hover:text-foreground flex items-center gap-1 py-1",children:[e.jsx("span",{className:"group-open:rotate-90 transition-transform text-[10px]",children:"▶"}),"Commission Splits (optional)"]}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-muted/50",children:[e.jsx(se,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(vs,{value:M.commission_calc_method,onValueChange:W=>P(G=>({...G,commission_calc_method:W})),children:[e.jsx(gs,{className:"h-7 text-xs",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(Je,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),M.commission_calc_method==="referral_first"&&e.jsx("p",{className:"text-[10px] text-muted-foreground bg-blue-50 dark:bg-blue-950/30 p-2 rounded",children:"💡 Referral fee is deducted from GCI first, then the brokerage split is applied to the remaining amount."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",step:"1",min:"0",max:"100",value:M.brokerage_split_pct,onChange:W=>P(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(se,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",step:"1",min:"0",max:"100",value:M.team_split_pct,onChange:W=>P(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(se,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",step:"1",min:"0",max:"100",value:M.referral_fee_pct,onChange:W=>P(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(se,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",step:"1",min:"0",max:"100",value:M.franchise_fee_pct,onChange:W=>P(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(se,{className:"text-xs",children:"Transaction Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"$"}),e.jsx(ye,{type:"number",step:"1",min:"0",value:M.transaction_fee,onChange:W=>P(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(se,{className:"text-xs",children:"Net to Agent"}),e.jsx(ye,{value:O()?`$${Math.round(O()).toLocaleString()}`:"-",disabled:!0,className:"bg-muted h-8 text-sm font-semibold"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Dates & Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Target Close Date"}),e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!M.target_close_date&&"text-muted-foreground"),children:[e.jsx(ra,{className:"mr-2 h-4 w-4"}),M.target_close_date?Bs(M.target_close_date,"PPP"):"Pick a date"]})}),e.jsx(Jl,{className:"w-auto p-0",align:"start",children:e.jsx(o1,{mode:"single",selected:M.target_close_date,onSelect:W=>P(G=>({...G,target_close_date:W})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Contract Date"}),e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!M.contract_date&&"text-muted-foreground"),children:[e.jsx(ra,{className:"mr-2 h-4 w-4"}),M.contract_date?Bs(M.contract_date,"PPP"):"Pick a date"]})}),e.jsx(Jl,{className:"w-auto p-0",align:"start",children:e.jsx(o1,{mode:"single",selected:M.contract_date,onSelect:W=>P(G=>({...G,contract_date:W})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),(M.deal_type==="seller"||M.deal_type==="dual")&&!M.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(se,{children:"Listing Date (for Days on Market)"}),e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!M.listing_date&&"text-muted-foreground"),children:[e.jsx(ra,{className:"mr-2 h-4 w-4"}),M.listing_date?Bs(M.listing_date,"PPP"):"Pick a date"]})}),e.jsx(Jl,{className:"w-auto p-0",align:"start",children:e.jsx(o1,{mode:"single",selected:M.listing_date,onSelect:W=>P(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(se,{children:"Priority"}),e.jsxs(vs,{value:M.priority,onValueChange:W=>P(G=>({...G,priority:W})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:pSn.map(W=>e.jsx(Je,{value:W.value,children:W.label},W.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",min:"0",max:"100",value:M.probability,onChange:W=>P(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(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Ds,{id:"notes",value:M.notes,onChange:W=>P(G=>({...G,notes:W.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!n&&e.jsx(hSn,{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:q,children:[q&&e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function xSn({dealId:s}){const t=ei(),n=as(),[r,a]=j.useState(""),[i,l]=j.useState(!1),{data:o=[]}=mt({queryKey:["deal-tags",s],queryFn:async()=>{const{data:x,error:y}=await U.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(y)throw y;return x},enabled:!!s}),{data:c=[]}=mt({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:x,error:y}=await U.from("deal_tags").select("tag").eq("owner_user_id",t);if(y)throw y;return[...new Set(x.map(b=>b.tag))].sort()},enabled:!!t}),d=vt({mutationFn:async x=>{if(!t)throw new Error("Not authenticated");const{error:y}=await U.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:x.trim()});if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]}),n.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=vt({mutationFn:async x=>{const{error:y}=await U.from("deal_tags").delete().eq("id",x);if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]})}}),h=()=>{const x=r.trim();x&&(o.some(y=>y.tag.toLowerCase()===x.toLowerCase())||d.mutate(x))},m=o.map(x=>x.tag.toLowerCase()),p=c.filter(x=>x.toLowerCase().includes(r.toLowerCase())&&!m.includes(x.toLowerCase())).slice(0,5);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.map(x=>e.jsxs(qe,{variant:"secondary",className:"gap-1 text-xs",children:[x.tag,e.jsx("button",{type:"button",onClick:()=>u.mutate(x.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(dr,{className:"h-3 w-3"})})]},x.id)),!i&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground px-2 py-0.5 rounded border border-dashed border-border hover:border-primary transition-colors",children:[e.jsx(Js,{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(ye,{value:r,onChange:x=>a(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),h()),x.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:h,disabled:!r.trim()||d.isPending,className:"h-8 px-3 rounded-md bg-primary text-primary-foreground text-xs font-medium disabled:opacity-50 shrink-0",children:"Add"}),e.jsx("button",{type:"button",onClick:()=>{l(!1),a("")},className:"h-8 px-2 rounded-md bg-muted text-muted-foreground text-xs shrink-0",children:"Cancel"})]}),r&&p.length>0&&e.jsx("div",{className:"absolute z-20 w-full mt-1 bg-background border rounded shadow-lg max-h-32 overflow-y-auto",children:p.map(x=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:y=>{y.preventDefault(),d.mutate(x)},children:x},x))})]})]})}function gSn(s){return mt({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function ySn(){const s=ei(),t=as();return vt({mutationFn:async({dealId:n,file:r})=>{if(!s)throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await U.storage.from("deal-files").upload(i,r);if(l)throw l;const{data:o,error:c}=await U.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]})}})}function vSn(){const s=as();return vt({mutationFn:async({fileId:t,storagePath:n,dealId:r})=>{await U.storage.from("deal-files").remove([n]);const{error:a}=await U.from("deal_files").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function bSn(){const s=as();return vt({mutationFn:async({fileId:t,visible:n,dealId:r})=>{const{error:a}=await U.from("deal_files").update({visible_on_portal:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}async function _Sn(s){const{data:t,error:n}=await U.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const lgt={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function Qzt({open:s,onOpenChange:t}){const{data:n,isLoading:r}=N0n(),a=k0n(),i=S0n(),l=C0n(),[o,c]=j.useState(!1),[d,u]=j.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[h,m]=j.useState(""),p=async()=>{if(d.question_text.trim())try{await a.mutateAsync({question_text:d.question_text.trim(),field_type:d.field_type,options:d.field_type==="dropdown"?d.options:[],is_required:d.is_required,sort_order:((n==null?void 0:n.length)||0)+1}),u({question_text:"",field_type:"text",options:[],is_required:!1}),m(""),c(!1),re.success("Question added")}catch{re.error("Failed to add question")}},x=async v=>{try{await l.mutateAsync(v),re.success("Question removed")}catch{re.error("Failed to remove question")}},y=async(v,k)=>{try{await i.mutateAsync({id:v,is_required:k})}catch{re.error("Failed to update question")}},g=()=>{h.trim()&&(u(v=>({...v,options:[...v.options,h.trim()]})),m(""))},b=v=>{u(k=>({...k,options:k.options.filter((C,T)=>T!==v)}))};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Custom Intake Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"These questions appear on all your portal onboarding forms."})]}),e.jsx(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(Wt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),n==null?void 0:n.map(v=>{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(Fp,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:v.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(qe,{variant:"secondary",className:"text-xs",children:lgt[v.field_type]||v.field_type}),v.is_required&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"Required"})]}),v.field_type==="dropdown"&&((k=v.options)==null?void 0:k.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",v.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(Mn,{checked:v.is_required,onCheckedChange:C=>y(v.id,C),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>x(v.id),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]})},v.id)}),!r&&(n==null?void 0:n.length)===0&&!o&&e.jsxs("div",{className:"text-center py-8 border border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No custom questions yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add questions that clients will answer during onboarding."})]}),o&&e.jsxs("div",{className:"border-2 border-primary/20 rounded-lg p-4 space-y-3 bg-primary/5",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Question"}),e.jsx(ye,{value:d.question_text,onChange:v=>u(k=>({...k,question_text:v.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(lgt).map(([v,k])=>e.jsx("button",{type:"button",onClick:()=>u(C=>({...C,field_type:v,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:k},v))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((v,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:v}),e.jsx("button",{onClick:()=>b(k),className:"text-muted-foreground hover:text-destructive",children:e.jsx(dr,{className:"h-3.5 w-3.5"})})]},k)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:h,onChange:v=>m(v.target.value),onKeyDown:v=>v.key==="Enter"&&(v.preventDefault(),g()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx(B,{variant:"outline",size:"sm",onClick:g,disabled:!h.trim(),className:"h-8",children:e.jsx(Js,{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(Mn,{checked:d.is_required,onCheckedChange:v=>u(k=>({...k,is_required:v}))}),e.jsx(se,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs(B,{size:"sm",onClick:p,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(Wt,{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(Js,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function wSn({override:s,onChange:t}){const n=ei(),{data:r}=C3t(),[a,i]=j.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){re.error("Image must be under 5MB");return}i(u);try{const h=await A3t(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){re.error(`Upload failed: ${h.message||h}`)}finally{i(null)}}},c=Object.values(s||{}).some(d=>d!=null&&d!=="");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-primary/5 border border-primary/10",children:[e.jsx(yn,{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(cgt,{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(cgt,{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(dgt,{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(dgt,{label:"Accent Color",value:s.accent_color??null,globalValue:(r==null?void 0:r.accent_color)??null,onChange:d=>l({accent_color:d})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(ye,{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(Rn,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function cgt({label:s,value:t,globalValue:n,uploading:r,onUpload:a,onClear:i,aspect:l}){const o=t||n,c=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{className:"text-sm font-medium",children:s}),c?e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Overridden"}):n?e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Using global"}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Et("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(ac,{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(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ja,{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(Rn,{className:"h-3.5 w-3.5"})})]})]})]})}function dgt({label:s,value:t,globalValue:n,onChange:r}){const a=t||n||"#000000",i=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:s}),i&&e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Overridden"})]}),e.jsxs("div",{className:Et("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(ye,{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(Rn,{className:"h-3 w-3"})})]})]})}function jSn({portalId:s,agentUserId:t}){const n=as(),{data:r,isLoading:a}=mt({queryKey:["portal-vendor-manage",s,t],queryFn:async()=>{const{data:h}=await U.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),m=h==null?void 0:h.brokerage_id,p=U.from("vendors").select("*").eq("is_active",!0),x=m?p.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${m})`):p.eq("owner_type","agent").eq("owner_user_id",t),[{data:y,error:g},{data:b},{data:v}]=await Promise.all([x.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),U.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),U.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(g)throw g;const k=new Map;(b||[]).forEach(T=>k.set(T.vendor_id,T.is_visible));const C=new Map;return(v||[]).forEach(T=>C.set(T.vendor_id,T.is_visible)),{vendors:y||[],selMap:k,overrideMap:C}}}),i=vt({mutationFn:async({vendorId:h,isVisible:m})=>{const{data:p}=await U.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",h).maybeSingle();if(p){const{error:x}=await U.from("portal_vendor_overrides").update({is_visible:m}).eq("id",p.id);if(x)throw x}else{const{error:x}=await U.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:h,is_visible:m});if(x)throw x}},onSuccess:()=>{n.invalidateQueries({queryKey:["portal-vendor-manage",s,t]}),n.invalidateQueries({queryKey:["portal-vendors",s]})},onError:h=>re.error(h.message)});if(a)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Wt,{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(fN,{className:"w-10 h-10 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors in your library yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Add vendors in the Vendors tab of Client Portals, then toggle them here per portal."})]});const d=h=>{const m=c.get(h.id);if(m!==void 0)return m;if(h.is_required)return!0;const p=o.get(h.id);return p===void 0?!0:p!==!1},u=h=>{var m;return((m=JU.find(p=>p.value===h))==null?void 0:m.label)||h};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Choose which vendors from your library appear in ",e.jsx("em",{children:"this specific portal"}),". Changes here only affect this deal — your global vendor library and other portals are unaffected."]}),e.jsx(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(qe,{variant:"outline",className:"text-[10px] shrink-0",children:u(h.category)}),h.owner_type==="brokerage"&&e.jsx(qe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),h.is_required&&e.jsx(qe,{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(Mn,{checked:m,disabled:h.is_required||i.isPending,onCheckedChange:p=>i.mutate({vendorId:h.id,isVisible:p})})]},h.id)})})})]})}function NSn({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=j.useState(""),[o,c]=j.useState(!1),{data:d,isLoading:u}=mt({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:x,error:y}=await U.from("client_portals").select(` id, slug, client_name, client_email, deal_id, archived_at, deal_pipeline (id, deal_name, deal_type, property_address) `).eq("owner_user_id",t).neq("id",s).is("archived_at",null).eq("is_enabled",!0);if(y)throw y;return x},enabled:o||!!r}),h=j.useMemo(()=>!r||!d?null:d.find(x=>x.id===r),[r,d]),m=j.useMemo(()=>!d||!n?[]:d.filter(x=>{var y;return((y=x.client_email)==null?void 0:y.toLowerCase())===n.toLowerCase()&&x.id!==s}),[d,n,s]),p=j.useMemo(()=>{if(!d||!i.trim())return[];const x=i.toLowerCase();return d.filter(y=>{var b,v,k,C;const g=y.deal_pipeline;return((b=y.client_name)==null?void 0:b.toLowerCase().includes(x))||((v=y.client_email)==null?void 0:v.toLowerCase().includes(x))||((k=g==null?void 0:g.deal_name)==null?void 0:k.toLowerCase().includes(x))||((C=g==null?void 0:g.property_address)==null?void 0:C.toLowerCase().includes(x))})},[d,i]);if(r){const x=h==null?void 0:h.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Linked Portal"}),e.jsxs("div",{className:"flex items-center gap-2 bg-primary/5 border border-primary/20 rounded-lg p-3",children:[e.jsx(Rc,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:(h==null?void 0:h.client_name)||(x==null?void 0:x.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(x==null?void 0:x.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(x==null?void 0:x.property_address)||"No address"]})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(ZR,{className:"h-3 w-3 mr-1"}),"Unlink"]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Client will see both transactions in a tabbed view on one portal link."})]})}return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Link Another Transaction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Combine buy + sell into one portal"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(Rc,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&m.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground font-medium",children:"✨ Suggested match (same client email)"}),m.map(x=>{const y=x.deal_pipeline;return e.jsxs("button",{onClick:()=>a(x.id),className:"w-full flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5 hover:bg-amber-100 transition-colors text-left",children:[e.jsx(qe,{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)||x.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:y==null?void 0:y.property_address})]}),e.jsx(Rc,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},x.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{value:i,onChange:x=>l(x.target.value),placeholder:"Search by name, email, or address...",className:"pl-8 h-8 text-xs",autoFocus:!0})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Wt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),p.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:p.map(x=>{const y=x.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(x.id),c(!1),l("")},className:"w-full flex items-center gap-2 border rounded-lg p-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(qe,{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)||x.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:x.client_email})]})]},x.id)})}),i&&p.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function tYe({contactId:s,onVideoReady:t}){const[n,r]=j.useState(!1),[a,i]=j.useState("record"),[l,o]=j.useState(0),[c,d]=j.useState(0),u=hS(),h=()=>{i("record"),o(0),d(0)},m=x=>{!x&&(a==="uploading"||a==="processing")||(r(x),x||h())},p=j.useCallback(async(x,y)=>{i("uploading");try{const g="Card Video",{videoId:b,libraryId:v}=await w6(g),{uploadUrl:k,apiKey:C}=await j6(b),T=new XMLHttpRequest;T.upload.onprogress=q=>{q.lengthComputable&&o(q.loaded/q.total*100)},await new Promise((q,W)=>{T.onload=()=>T.status>=200&&T.status<300?q():W(new Error("Upload failed")),T.onerror=()=>W(new Error("Upload failed")),T.open("PUT",k),T.setRequestHeader("AccessKey",C),T.send(x)}),i("processing");let M=0;const P=Date.now(),L=9e4,I=`https://iframe.mediadelivery.net/embed/${v}/${b}`;for(;M<4;){if(await new Promise(W=>setTimeout(W,3e3)),Date.now()-P>L){const W=x.size/1048576;await u.mutateAsync({bunny_video_id:b,playback_url:`https://iframe.mediadelivery.net/play/${v}/${b}`,file_size_mb:W,title:g,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(I),re.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const q=await $j(b);if(M=q.status,d(q.encodeProgress||0),M===5||M===6)throw new Error("Video processing failed")}const O=await $j(b),$=(O.storageSize||x.size)/(1024*1024);await u.mutateAsync({bunny_video_id:b,contact_id:s||void 0,playback_url:O.directPlayUrl||I,thumbnail_url:O.thumbnailUrl,preview_url:O.previewUrl||null,duration_seconds:O.length||y,file_size_mb:$,title:g,status:"ready",touch_type:"video"}),t(I),re.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(g){console.error("Recording upload error:",g),re.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(Fs,{open:n,onOpenChange:m,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(Os,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(k6,{maxDurationSeconds:600,onRecordingComplete:p,onError:x=>re.error(x)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Wt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(qi,{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(Wt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(qi,{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(To,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const kSn=s=>`portal-settings-draft:${s}`;function sYe({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=Eq(),[i,l]=j.useState(!1),o=j.useMemo(()=>kSn(n.id),[n.id]),[c,d]=j.useState(!1),[u,h]=j.useState(n.next_step_text||""),[m,p]=j.useState(n.next_step_video_url||""),[x,y]=j.useState(n.inspection_date||""),[g,b]=j.useState(n.appraisal_date||""),[v,k]=j.useState(n.welcome_message||""),[C,T]=j.useState(n.review_url||""),[M,P]=j.useState(n.show_post_close_tips),[L,I]=j.useState(n.notify_client),[O,$]=j.useState(n.require_onboarding),[q,W]=j.useState(n.allow_spouse),[G,K]=j.useState(n.visibility),[ee,J]=j.useState(n.stage_mapping||[]),[le,ue]=j.useState(null),[oe,ie]=j.useState(n.linked_portal_id||null),[de,we]=j.useState(n.referral_enabled??!0),[je,xe]=j.useState(n.referral_reward_text||""),[fe,Se]=j.useState(n.referral_cta_headline||""),[Ee,Le]=j.useState(n.homeowner_hub_video_url||""),[De,Be]=j.useState(n.branding_override||{}),Ne=()=>{h(n.next_step_text||""),p(n.next_step_video_url||""),y(n.inspection_date||""),b(n.appraisal_date||""),k(n.welcome_message||""),T(n.review_url||""),P(n.show_post_close_tips),I(n.notify_client),$(n.require_onboarding),W(n.allow_spouse),K(n.visibility),J(n.stage_mapping||[]),ie(n.linked_portal_id||null),we(n.referral_enabled??!0),xe(n.referral_reward_text||""),Se(n.referral_cta_headline||""),Le(n.homeowner_hub_video_url||""),Be(n.branding_override||{})};j.useEffect(()=>{d(!1);const Ze=localStorage.getItem(o);if(Ze)try{const Qe=JSON.parse(Ze);h(Qe.nextStepText||""),p(Qe.nextStepVideo||""),y(Qe.inspectionDate||""),b(Qe.appraisalDate||""),k(Qe.welcomeMessage||""),T(Qe.reviewUrl||""),P(!!Qe.showPostClose),I(!!Qe.notifyClient),$(!!Qe.requireOnboarding),W(!!Qe.allowSpouse),K(Qe.visibility||n.visibility),J(Qe.stageMapping||[]),ie(Qe.linkedPortalId??null),we(Qe.referralEnabled??!0),xe(Qe.referralRewardText||""),Se(Qe.referralCtaHeadline||""),Le(Qe.homeownerHubVideoUrl||""),Be(Qe.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}Ne(),d(!0)},[o,n]),j.useEffect(()=>{if(!c)return;const Ze={nextStepText:u,nextStepVideo:m,inspectionDate:x,appraisalDate:g,welcomeMessage:v,reviewUrl:C,showPostClose:M,notifyClient:L,requireOnboarding:O,allowSpouse:q,visibility:G,stageMapping:ee,linkedPortalId:oe,referralEnabled:de,referralRewardText:je,referralCtaHeadline:fe,homeownerHubVideoUrl:Ee,brandingOverride:De};u!==(n.next_step_text||"")||m!==(n.next_step_video_url||"")||x!==(n.inspection_date||"")||g!==(n.appraisal_date||"")||v!==(n.welcome_message||"")||C!==(n.review_url||"")||M!==n.show_post_close_tips||L!==n.notify_client||O!==n.require_onboarding||q!==n.allow_spouse||G!==n.visibility||JSON.stringify(ee)!==JSON.stringify(n.stage_mapping||[])||oe!==(n.linked_portal_id||null)||de!==(n.referral_enabled??!0)||je!==(n.referral_reward_text||"")||fe!==(n.referral_cta_headline||"")||Ee!==(n.homeowner_hub_video_url||"")||JSON.stringify(De)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(Ze)):localStorage.removeItem(o)},[u,m,x,g,v,C,M,L,O,q,G,ee,oe,de,je,fe,Ee,De,o,c,n]);const Ge=()=>{localStorage.removeItem(o),Ne()},_e=async()=>{try{await a.mutateAsync({id:n.id,next_step_text:u||null,next_step_video_url:m||null,inspection_date:x||null,appraisal_date:g||null,welcome_message:v||null,review_url:C||null,show_post_close_tips:M,notify_client:L,require_onboarding:O,allow_spouse:q,visibility:G,stage_mapping:ee.length>0?ee:null,linked_portal_id:oe,referral_enabled:de,referral_reward_text:je||null,referral_cta_headline:fe||null,homeowner_hub_video_url:Ee||null,branding_override:Object.values(De).some(Qe=>Qe!=null&&Qe!=="")?De:null});const Ze=n.linked_portal_id;oe&&oe!==Ze&&await U.from("client_portals").update({linked_portal_id:n.id}).eq("id",oe),!oe&&Ze&&await U.from("client_portals").update({linked_portal_id:null}).eq("id",Ze),localStorage.removeItem(o),re.success("Portal settings saved"),t(!1)}catch{re.error("Failed to save settings")}},Oe=()=>{J([...ee,{label:""}])},Ae=Ze=>{J(ee.filter((Qe,Ye)=>Ye!==Ze)),le===Ze&&ue(null)},Xe=(Ze,Qe,Ye)=>{const nt=[...ee];nt[Ze]={...nt[Ze],[Qe]:Ye},J(nt)},Ue=()=>{const Qe=L3e(null).map(Ye=>({label:Ye.label,description:Ye.description,stageId:void 0}));J(Qe)};return e.jsxs(e.Fragment,{children:[e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx($s,{children:e.jsx(zs,{children:"Portal Settings"})}),e.jsxs(fa,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(xa,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(ss,{value:"general",children:"General"}),e.jsx(ss,{value:"timeline",children:"Timeline"}),e.jsx(ss,{value:"content",children:"Content"}),e.jsx(ss,{value:"vendors",children:"Vendors"}),e.jsx(ss,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(ns,{value:"general",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Visibility"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Public portals appear without restrictions"})]}),e.jsx("div",{className:"flex gap-1",children:["private","public"].map(Ze=>e.jsx("button",{onClick:()=>K(Ze),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${G===Ze?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:Ze.charAt(0).toUpperCase()+Ze.slice(1)},Ze))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Require Onboarding"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clients must fill out intake form"})]}),e.jsx(Mn,{checked:O,onCheckedChange:$})]}),O&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx(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(se,{className:"text-sm font-medium",children:"Allow Spouse/Partner"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show spouse fields on onboarding"})]}),e.jsx(Mn,{checked:q,onCheckedChange:W})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Post-Close Celebration"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show congrats card when deal closes"})]}),e.jsx(Mn,{checked:M,onCheckedChange:P})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Notify Client on Updates"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Email client when you post portal updates"})]}),e.jsx(Mn,{checked:L,onCheckedChange:I})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(NSn,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:oe,onLink:ie})}),e.jsx("div",{children:e.jsx(ye,{type:"date",value:x,onChange:Ze=>y(Ze.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(ye,{type:"date",value:g,onChange:Ze=>b(Ze.target.value),className:"mt-1"})]})]}),e.jsx(ns,{value:"timeline",className:"space-y-4 mt-0 px-1",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Client-Facing Stages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Customize the client-friendly stage labels shown on the portal timeline"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:Ue,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.'}),ee.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:Ue,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:ee.map((Ze,Qe)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fp,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(ye,{value:Ze.label,onChange:Ye=>Xe(Qe,"label",Ye.target.value),placeholder:`Stage ${Qe+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>ue(le===Qe?null:Qe),children:le===Qe?"Less":"More"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Ae(Qe),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]}),le===Qe&&e.jsxs("div",{className:"ml-6 space-y-2 pl-2 border-l-2 border-primary/15 pb-2",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:Ze.description||"",onChange:Ye=>Xe(Qe,"description",Ye.target.value),placeholder:"e.g. Now it's time to start actively looking at homes",className:"mt-0.5 w-full rounded-md border border-input bg-background px-3 py-2 text-xs min-h-[50px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Video"}),Ze.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:Ze.video_url.length>40?Ze.video_url.slice(0,40)+"...":Ze.video_url}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>Xe(Qe,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(tYe,{onVideoReady:Ye=>Xe(Qe,"video_url",Ye)}),e.jsx(LO,{userId:r,onSelect:Ye=>Xe(Qe,"video_url",Ye),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 Ye=prompt("Paste a YouTube or Loom URL:");Ye&&Xe(Qe,"video_url",Ye)},children:[e.jsx(vc,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},Qe))}),ee.length>0&&e.jsxs(B,{variant:"outline",size:"sm",onClick:Oe,className:"mt-2 text-xs w-full",children:[e.jsx(Js,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(ns,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:v,onChange:Ze=>k(Ze.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[60px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"Welcome! Here's everything you need for your transaction."})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"What's Next"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Tell your client what to expect next"}),e.jsx("textarea",{value:u,onChange:Ze=>h(Ze.target.value),className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[60px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",placeholder:"We're waiting on the inspection report..."})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(ye,{value:m,onChange:Ze=>p(Ze.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Review URL"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown after deal closes"}),e.jsx(ye,{value:C,onChange:Ze=>T(Ze.target.value),className:"mt-1",placeholder:"https://g.page/r/..."})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-base",children:"🎁"}),e.jsx(se,{className:"text-sm font-semibold",children:"Homeowner Hub & Referrals"})]}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-2",children:'Shown automatically when the deal is in a "won" stage.'}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Show Referral Card"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Big CTA asking client to refer friends"})]}),e.jsx(Mn,{checked:de,onCheckedChange:we})]}),de&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Headline"}),e.jsx(ye,{value:fe,onChange:Ze=>Se(Ze.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Reward (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"What the client gets for a successful referral"}),e.jsx(ye,{value:je,onChange:Ze=>xe(Ze.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Personal Welcome Video URL (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:'A "welcome home" video shown above the referral card'}),e.jsx(ye,{value:Ee,onChange:Ze=>Le(Ze.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(ns,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(jSn,{portalId:n.id,agentUserId:r})}),e.jsx(ns,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(wSn,{override:De,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:_e,disabled:a.isPending,children:[a.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(Qzt,{open:i,onOpenChange:l})]})}const SSn=s=>`portal-update-draft:${s}`;function nYe({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=j.useMemo(()=>SSn(n),[n]),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState(!1),[x,y]=j.useState(a??!1),[g,b]=j.useState(!1),v=PRt();j.useEffect(()=>{b(!1);const T=localStorage.getItem(i);if(T)try{const M=JSON.parse(T);o(M.title||""),d(M.content||""),h(M.videoUrl||""),p(!!M.isStageChange),y(typeof M.sendNotification=="boolean"?M.sendNotification:a??!1),b(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),p(!1),y(a??!1),b(!0)},[i,a]),j.useEffect(()=>{if(!g)return;const T={title:l,content:c,videoUrl:u,isStageChange:m,sendNotification:x};l.trim()||c.trim()||u.trim()||m||x!==(a??!1)?localStorage.setItem(i,JSON.stringify(T)):localStorage.removeItem(i)},[l,c,u,m,x,g,i,a]);const k=()=>{localStorage.removeItem(i),o(""),d(""),h(""),p(!1),y(a??!1)},C=async()=>{if(l.trim())try{if(await v.mutateAsync({portal_id:n,title:l.trim(),content:c.trim()||void 0,video_url:u.trim()||void 0,is_stage_change:m}),x&&r)try{const T=q5(r);await U.functions.invoke("send-portal-notification",{body:{portal_id:n,update_title:l.trim(),update_content:c.trim()||null,portal_url:T}}),re.success("Update posted & client notified")}catch(T){console.error("Notification failed:",T),re.success("Update posted (notification failed to send)")}else re.success("Update posted to portal");k(),t(!1)}catch{re.error("Failed to post update")}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Title *"}),e.jsx(ye,{value:l,onChange:T=>o(T.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Message"}),e.jsx("textarea",{value:c,onChange: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(se,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(ye,{value:u,onChange:T=>h(T.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("button",{type:"button",onClick:()=>p(!m),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${m?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-background text-muted-foreground border-input"}`,children:"📊 Stage Change"}),e.jsxs("button",{type:"button",onClick:()=>y(!x),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${x?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[x?e.jsx(Nx,{className:"h-3 w-3"}):e.jsx(L5,{className:"h-3 w-3"}),x?"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:C,disabled:!l.trim()||v.isPending,children:[v.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function rYe({open:s,onOpenChange:t,portal:n,dealName:r}){const a=Eq(),{isGmailConnected:i,gmailEmail:l}=Tf(),[o,c]=j.useState(n.client_name||""),[d,u]=j.useState(n.client_email||""),[h,m]=j.useState(!1),[p,x]=j.useState(!1),y=q5(n.slug),g=o.split(" ")[0]||"there",b=`Your Transaction Portal – ${r}`,v=`Hi ${g}, 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),x(!0),setTimeout(()=>x(!1),2e3),re.success("Portal link copied!")},C=async()=>{if(!d.trim()){re.error("Please enter the client email");return}m(!0);try{await a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:M}=await U.functions.invoke("gmail-send",{body:{to:d,subject:b,body:v.replace(/\n/g,"
")}});if(M){let P="";try{const L=M==null?void 0:M.context;if(L&&typeof L.json=="function"){const I=await L.json();P=(I==null?void 0:I.message)||(I==null?void 0:I.error)||""}}catch{}throw new Error(P||M.message||"Failed to send invite")}re.success(`Invite sent to ${d}`),t(!1)}catch(M){re.error(M.message||"Failed to send invite")}finally{m(!1)}},T=()=>{const M=encodeURIComponent(b),P=encodeURIComponent(v);window.open(`mailto:${d}?subject=${M}&body=${P}`,"_blank"),a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"}).catch(()=>{})};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(ye,{value:o,onChange:M=>c(M.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(ye,{type:"email",value:d,onChange:M=>u(M.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Portal Link"}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 bg-muted/50 rounded-md px-3 py-2",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:y})}),e.jsx(B,{variant:"outline",size:"icon",onClick:k,className:"shrink-0",children:p?e.jsx(da,{className:"h-4 w-4 text-emerald-600"}):e.jsx(ja,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(B,{onClick:C,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(on,{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(ja,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function CSn({deal:s}){const{isAdmin:t,user:n}=Ns(),{data:r,isLoading:a}=w0n(s.id),i=NWe(),l=Eq(),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,x]=j.useState(!1),y=`portal-management-ui:${s.id}`;if(j.useEffect(()=>{const M=sessionStorage.getItem(y);if(M)try{const P=JSON.parse(M);u(!!P.settingsOpen),m(!!P.composerOpen),x(!!P.inviteOpen)}catch{sessionStorage.removeItem(y)}},[y]),j.useEffect(()=>{d||h||p?sessionStorage.setItem(y,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:p})):sessionStorage.removeItem(y)},[d,h,p,y]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Wt,{className:"h-3 w-3 animate-spin ml-auto"})]})});const g=async()=>{var M,P;c(!0);try{await i.mutateAsync({deal_id:s.id,visibility:"private",require_onboarding:!0,client_name:s.contact?`${s.contact.first_name} ${s.contact.last_name}`:void 0,client_email:((M=s.contact)==null?void 0:M.email)||void 0,client_phone:((P=s.contact)==null?void 0:P.phone)||void 0}),re.success("Client portal enabled!")}catch{re.error("Failed to create portal")}finally{c(!1)}},b=async M=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:M}),re.success(M?"Portal enabled":"Portal disabled")}catch{re.error("Failed to update portal")}},v=()=>{if(!r)return;const M=q5(r.slug);navigator.clipboard.writeText(M),re.success("Portal link copied!")},k=()=>{if(!r)return;const M=q5(r.slug);window.open(M,"_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(yn,{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:g,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const C=q5(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(yn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(qe,{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(Mn,{checked:r.is_enabled,onCheckedChange:b})]}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Visibility:"}),e.jsx(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:r.visibility==="private"?"Private":"Public"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Onboarding:"}),e.jsx("span",{className:"text-foreground",children:r.require_onboarding?"Required":"Disabled"})]}),r.client_name&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Client:"}),e.jsx("span",{className:"text-foreground",children:r.client_name})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-md p-2 mb-3",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:C})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:v,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(ja,{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:()=>x(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Dr,{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(v5,{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(ic,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(Yn,{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(zo,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(sYe,{open:d,onOpenChange:u,portal:r,dealOwnerId:T}),e.jsx(nYe,{open:h,onOpenChange:m,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(rYe,{open:p,onOpenChange:x,portal:r,dealName:s.deal_name})]})}const ASn=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function TSn(s){return mt({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:n}=await U.from("deal_contacts").select(` id, deal_id, contact_id, role, created_at, contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("deal_id",s).order("created_at");if(n)throw n;return t||[]},enabled:!!s})}function ESn(){const s=as();return vt({mutationFn:async({dealId:t,contactId:n,role:r})=>{const{data:a,error:i}=await U.from("deal_contacts").insert({deal_id:t,contact_id:n,role:r}).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),re.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?re.error("This contact is already linked to this deal"):re.error("Failed to link contact")}})}function MSn(){const s=as();return vt({mutationFn:async({id:t,dealId:n})=>{const{error:r}=await U.from("deal_contacts").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),re.success("Contact removed from deal")},onError:()=>{re.error("Failed to remove contact")}})}function LSn({dealId:s,primaryContactId:t}){const n=Hn(),{data:r,isLoading:a}=TSn(s),{data:i}=av(),l=ESn(),o=MSn(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState("Client"),x=new Set((r==null?void 0:r.map(k=>k.contact_id))||[]);t&&x.add(t);const y=i==null?void 0:i.filter(k=>{var T,M,P;if(x.has(k.id))return!1;if(!u.trim())return!0;const C=u.toLowerCase();return((T=k.first_name)==null?void 0:T.toLowerCase().includes(C))||((M=k.last_name)==null?void 0:M.toLowerCase().includes(C))||((P=k.email)==null?void 0:P.toLowerCase().includes(C))}).slice(0,8),g=k=>{l.mutate({dealId:s,contactId:k,role:m}),d(!1),h("")},b=k=>{o.mutate({id:k,dealId:s})},v={Client:"bg-primary/10 text-primary","Co-Buyer":"bg-blue-500/10 text-blue-600","Co-Seller":"bg-emerald-500/10 text-emerald-600",Spouse:"bg-pink-500/10 text-pink-600",Lender:"bg-amber-500/10 text-amber-600","Title Company":"bg-purple-500/10 text-purple-600",Inspector:"bg-orange-500/10 text-orange-600",Appraiser:"bg-cyan-500/10 text-cyan-600",Attorney:"bg-slate-500/10 text-slate-600",Contractor:"bg-lime-500/10 text-lime-600",Other:"bg-muted text-muted-foreground"};return!(r!=null&&r.length)&&!c?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(lc,{open:c,onOpenChange:d,children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(Jl,{className:"w-80 p-3",align:"start",children:e.jsx(ugt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,filteredContacts:y,onAdd:g})})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4"}),"Linked Contacts",r&&r.length>0&&e.jsx(qe,{variant:"secondary",className:"text-[10px] px-1.5",children:r.length})]}),e.jsxs(lc,{open:c,onOpenChange:d,children:[e.jsx(cc,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(Js,{className:"h-3.5 w-3.5"})})}),e.jsx(Jl,{className:"w-80 p-3",align:"end",children:e.jsx(ugt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,filteredContacts:y,onAdd:g})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(k=>{var C,T,M,P,L,I,O,$;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(Ra,{className:"h-7 w-7",children:e.jsxs(Da,{className:"text-[10px] bg-primary/10 text-primary",children:[(T=(C=k.contact)==null?void 0:C.first_name)==null?void 0:T[0],(P=(M=k.contact)==null?void 0:M.last_name)==null?void 0:P[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>n(`/mission-control/contacts/${k.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(L=k.contact)==null?void 0:L.first_name," ",(I=k.contact)==null?void 0:I.last_name]})}),e.jsx(qe,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${v[k.role]||v.Other}`,children:k.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((O=k.contact)==null?void 0:O.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(pa,{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(on,{className:"h-3 w-3"})})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>b(k.id),children:e.jsx(Rn,{className:"h-3 w-3"})})]})]},k.id)})})]})}function ugt({search:s,setSearch:t,selectedRole:n,setSelectedRole:r,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"h-8 text-sm",children:e.jsx(bs,{placeholder:"Role"})}),e.jsx(ys,{children:ASn.map(l=>e.jsx(Je,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{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 mW=[{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"}],PSn=[{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 ISn(){const s=as();return vt({mutationFn:async({dealId:t,dates:n})=>{const r={};Object.entries(n).forEach(([i,l])=>{r[i]=l&&l.trim()!==""?l:null});const{error:a}=await U.from("deal_pipeline").update(r).eq("id",t);if(a)throw a},onSuccess:()=>{s.invalidateQueries({queryKey:["deals"]}),s.invalidateQueries({queryKey:["deal-pipeline"]}),s.invalidateQueries({queryKey:["tc-dashboard"]})}})}function RSn(){const s=as();return vt({mutationFn:async({dealId:t,completed:n})=>{const{error:r}=await U.from("deal_pipeline").update({completed_key_dates:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deals"]}),s.invalidateQueries({queryKey:["deal-pipeline"]}),s.invalidateQueries({queryKey:["tc-dashboard"]})}})}function DSn(){return mt({queryKey:["tc-playbooks"],queryFn:async()=>{const{data:s,error:t}=await U.from("tc_playbooks").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;const{data:n,error:r}=await U.from("tc_playbook_tasks").select("*").order("sort_order");if(r)throw r;return(s||[]).map(a=>({...a,tasks:(n||[]).filter(i=>i.playbook_id===a.id)}))},staleTime:10*6e4})}function OSn(){const s=ei(),t=as();return vt({mutationFn:async({playbookId:n,dealId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a,error:i},{data:l,error:o}]=await Promise.all([U.from("deal_pipeline").select("*").eq("id",r).single(),U.from("tc_playbook_tasks").select("*").eq("playbook_id",n).order("sort_order")]);if(i)throw i;if(o)throw o;if(!l||l.length===0)return 0;const{data:c}=await U.from("deal_tasks").select("title").eq("deal_id",r),d=new Set((c||[]).map(x=>String(x.title).toLowerCase())),u=a,h=(x,y)=>{const g=x==="stage_entry"?null:u[x],b=g?new Date(`${g}T12:00:00`):new Date;return b.setDate(b.getDate()+(y||0)),b.toISOString().split("T")[0]},m=l.filter(x=>!d.has(String(x.title).toLowerCase())).map((x,y)=>({owner_user_id:s,deal_id:r,contact_id:u.contact_id,stage_id:u.stage_id,title:x.title,description:x.description,priority:x.priority,status:"todo",due_date:h(x.due_anchor,x.due_offset_days),sort_order:y}));if(m.length===0)return 0;const{error:p}=await U.from("deal_tasks").insert(m);if(p)throw p;return m.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]}),t.invalidateQueries({queryKey:["tc-dashboard"]})}})}function FSn(){const s=ei(),t=as();return vt({mutationFn:async({playbookId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a},{data:i,error:l}]=await Promise.all([U.from("tc_playbooks").select("deal_type").eq("id",n).single(),U.from("tc_playbook_tasks").select("*").eq("playbook_id",n).order("sort_order")]);if(l)throw l;if(!i||i.length===0)return 0;const{data:o}=await U.from("deal_task_templates").select("title").eq("owner_user_id",s).eq("stage_id",r),c=new Set((o||[]).map(h=>String(h.title).toLowerCase())),d=i.filter(h=>!c.has(String(h.title).toLowerCase())).map((h,m)=>({owner_user_id:s,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_anchor:h.due_anchor,default_due_offset_days:h.due_offset_days,deal_type:(a==null?void 0:a.deal_type)??null,playbook_id:n,sort_order:m}));if(d.length===0)return 0;const{error:u}=await U.from("deal_task_templates").insert(d);if(u)throw u;return d.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function zSn(){const s=ei();return mt({queryKey:["tc-dashboard",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("deal_pipeline").select(` id, deal_name, deal_type, property_address, city, state, expected_price, expected_commission, stage_id, contact_id, contract_date, target_close_date, actual_close_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, earnest_money_due_date, title_docs_due_date, final_walkthrough_date, stage:deal_pipeline_stages(id, name, color, is_won_stage, is_lost_stage), contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("owner_user_id",s);if(n)throw n;const r=(t||[]).filter(l=>{var o,c;return!((o=l.stage)!=null&&o.is_lost_stage)&&!((c=l.stage)!=null&&c.is_won_stage)}),a=r.map(l=>l.id);let i={};if(a.length>0){const{data:l}=await U.from("deal_tasks").select("id, deal_id, title, status, priority, due_date").in("deal_id",a).order("due_date",{ascending:!0,nullsFirst:!1});(l||[]).forEach(o=>{var c;o.deal_id&&(i[c=o.deal_id]||(i[c]=[])).push(o)})}return r.map(l=>({...l,tasks:i[l.id]||[]}))},enabled:!!s})}function aYe(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 zk(s){const t=aYe(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 BSn(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const $Sn={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 USn(s){const t=aYe(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function hgt(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 qSn({deal:s,compact:t=!1}){const n=ISn(),r=RSn(),[a,i]=j.useState(!1),[l,o]=j.useState({}),c=Array.isArray(s==null?void 0:s.completed_key_dates)?s.completed_key_dates:[],[d,u]=j.useState(c),h=c.join(","),m=j.useRef(h);j.useEffect(()=>{m.current!==h&&(m.current=h,u(c))},[h]);const p=d,x=()=>{const I={};mW.forEach(O=>{I[O.key]=(s==null?void 0:s[O.key])??""}),o(I),i(!0)},y=async()=>{try{await n.mutateAsync({dealId:s.id,dates:l}),re.success("Transaction dates updated"),i(!1)}catch(I){re.error((I==null?void 0:I.message)||"Could not save dates")}},g=async(I,O)=>{const $=p;u(I);try{await r.mutateAsync({dealId:s.id,completed:I}),re.success(O)}catch(q){u($),re.error((q==null?void 0:q.message)||"Could not update milestone")}},b=j.useMemo(()=>mW.map(I=>{const O=(s==null?void 0:s[I.key])??null,$=zk(O),q=p.includes(I.key),W=O?q?"done":BSn($):"none";return{...I,value:O,days:$,isDone:q,state:W}}),[s,p.join(",")]),v=b.filter(I=>I.value).length,k=b.filter(I=>I.state==="done").length,C=zk(s==null?void 0:s.target_close_date),T=b.filter(I=>I.value&&!I.isDone&&I.days!==null&&I.days>=0).sort((I,O)=>(I.days??0)-(O.days??0))[0],M=b.filter(I=>I.state==="overdue"),P=()=>{const I=Array.from(new Set([...p,...M.map(O=>O.key)]));g(I,"Past milestones marked complete")},L=(I,O)=>{const $=O?p.filter(q=>q!==I):[...p,I];g($,O?"Marked as not complete":"Milestone completed")};return e.jsx(RN,{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(ym,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold leading-tight",children:"Transaction Timeline"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:C!==null?C>=0?`${C} day${C===1?"":"s"} to closing · ${k}/${v} milestones done`:`Closing was ${Math.abs(C)} day${Math.abs(C)===1?"":"s"} ago`:`${v} of ${mW.length} key dates set`})]})]}),e.jsxs(lc,{open:a,onOpenChange:I=>I?x():i(!1),children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"shrink-0 gap-1.5",children:[e.jsx(Za,{className:"h-3.5 w-3.5"}),t?"":"Edit dates"]})}),e.jsxs(Jl,{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:mW.map(I=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{htmlFor:`kd-${I.key}`,className:"text-xs text-muted-foreground",children:I.label}),e.jsx(ye,{id:`kd-${I.key}`,type:"date",value:l[I.key]??"",onChange:O=>o($=>({...$,[I.key]:O.target.value})),className:"h-9"})]},I.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(Wt,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}),"Save"]})]})]})]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-3 gap-2",children:b.map(I=>{const O=!!I.value;return e.jsxs(Cu,{children:[e.jsx(Au,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:!O||r.isPending,onClick:()=>O&&L(I.key,I.isDone),className:Et("relative text-left rounded-lg border px-2.5 py-2 transition-colors w-full",$Sn[I.state],O&&"hover:brightness-105 cursor-pointer"),children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide opacity-70 truncate pr-4",children:I.short}),e.jsx("p",{className:"text-sm font-semibold leading-tight truncate",children:USn(I.value)??"—"}),I.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:hgt(I.state,I.days)}),O&&e.jsx("span",{className:Et("absolute top-1.5 right-1.5 h-4 w-4 rounded-full border flex items-center justify-center",I.isDone?"bg-emerald-500 border-emerald-500 text-white":"border-current opacity-40"),children:I.isDone&&e.jsx(da,{className:"h-2.5 w-2.5"})})]})}),e.jsx(ou,{side:"top",children:I.value?I.isDone?`${I.label} completed — click to reopen`:`Click to mark ${I.label} complete`:`${I.label} — not set`})]},I.key)})}),(M.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(PR,{className:"h-3 w-3"}),k," completed"]}),M.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(hd,{className:"h-3 w-3"}),M.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," · ",hgt(T.state,T.days)]}),M.length>0&&e.jsxs("button",{type:"button",onClick:P,disabled:r.isPending,className:"ml-auto inline-flex items-center gap-1 rounded-full border px-2.5 py-1 font-medium hover:bg-muted transition-colors",children:[e.jsx(PR,{className:"h-3 w-3"}),"Mark past dates complete"]})]}),M.length>0&&e.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:"Dates in the past show as awaiting confirmation until you check them off — tap a tile to mark it complete."}),v===0&&e.jsx("p",{className:"mt-3 text-xs text-muted-foreground text-center",children:"No key dates yet. Add them to unlock automatic deadline reminders."})]})]})})}const VSn={Home:ia,FileSignature:cA,Handshake:fN,CalendarClock:ym,Sparkles:yn,ClipboardCheck:x3},HSn={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 GSn(s,t){var a;const n=((a=PSn.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 Jzt({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=DSn(),{data:l}=yee(),o=OSn(),c=FSn(),[d,u]=j.useState(null),[h,m]=j.useState({}),p=g=>{if(h[g.id])return h[g.id];const b=l==null?void 0:l.find(v=>{var k,C;return((k=v.name)==null?void 0:k.toLowerCase())===((C=g.target_stage_name)==null?void 0:C.toLowerCase())});return(b==null?void 0:b.id)??""},x=async g=>{if(n){u(g.id);try{const b=await o.mutateAsync({playbookId:g.id,dealId:n});re.success(b>0?`Added ${b} task${b===1?"":"s"} to this deal`:"All tasks already exist on this deal"),b>0&&t(!1)}catch(b){re.error((b==null?void 0:b.message)||"Could not apply playbook")}finally{u(null)}}},y=async g=>{const b=p(g);if(!b){re.error("Pick which stage this playbook should trigger on");return}u(`install-${g.id}`);try{const v=await c.mutateAsync({playbookId:g.id,stageId:b});re.success(v>0?`Automated — ${v} task${v===1?"":"s"} will now be created every time a deal reaches this stage`:"This playbook is already automated for that stage")}catch(v){re.error((v==null?void 0:v.message)||"Could not automate playbook")}finally{u(null)}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0",children:[e.jsx($s,{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(Op,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx(zs,{children:"Transaction Playbooks"}),e.jsx(kr,{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 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"p-6 pt-4",children:i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(vO,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(g=>{const b=VSn[g.icon||"ClipboardCheck"]||x3,v=g.accent_color||"hsl(var(--primary))";return e.jsxs(l6,{value:g.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(c6,{className:"px-4 py-3 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3 text-left flex-1 min-w-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${v}1a`},children:e.jsx(b,{className:"h-5 w-5",style:{color:v}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm",children:g.name}),e.jsxs(qe,{variant:"secondary",className:"text-[10px]",children:[g.tasks.length," steps"]}),g.deal_type&&e.jsx(qe,{variant:"outline",className:"text-[10px] capitalize",children:g.deal_type})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:g.description})]})]})}),e.jsxs(d6,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:g.tasks.map((k,C)=>e.jsxs("div",{className:"flex items-start gap-2.5 rounded-lg border bg-background px-3 py-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-muted-foreground mt-0.5 w-4 shrink-0",children:C+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children: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:GSn(k.due_anchor,k.due_offset_days)})]}),e.jsx("span",{className:Et("text-[10px] px-1.5 py-0.5 rounded-full shrink-0 capitalize",HSn[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:()=>x(g),disabled:d===g.id,children:[d===g.id?e.jsx(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(jf,{className:"h-3.5 w-3.5"}),"Add to this deal"]}),e.jsxs("div",{className:"flex gap-2 flex-1",children:[e.jsxs(vs,{value:p(g),onValueChange:k=>m(C=>({...C,[g.id]:k})),children:[e.jsx(gs,{className:"h-9 text-xs flex-1",children:e.jsx(bs,{placeholder:"Trigger stage"})}),e.jsx(ys,{children:(l||[]).map(k=>e.jsx(Je,{value:k.id,children:k.name},k.id))})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>y(g),disabled:d===`install-${g.id}`,children:[d===`install-${g.id}`?e.jsx(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(nz,{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(Rr,{className:"h-3 w-3"}),"Automating adds these steps to every future deal that reaches that stage."]})]})]},g.id)})})})})]})})}const WSn={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"}},KSn={note:ro,call:pa,email:on,meeting:ra,stage_change:Tr,task_completed:Rr,document:ia,system:Vr};function YSn({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var De,Be;const l=Hn(),{data:o,isLoading:c}=p5n((s==null?void 0:s.id)||""),{data:d,isLoading:u}=x5n((s==null?void 0:s.id)||""),h=f5n(),m=y5n(),p=g5n(),x=m5n(),{data:y,isLoading:g}=gSn((s==null?void 0:s.id)||""),b=ySn(),v=vSn(),k=bSn(),C=j.useRef(null),[T,M]=j.useState(""),[P,L]=j.useState(""),[I,O]=j.useState(!1),[$,q]=j.useState(!1),[W,G]=j.useState(!1);if(!s)return null;const K=WSn[s.deal_type],ee=(()=>{var _e;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const Ne=((_e=s.listing)==null?void 0:_e.created_at)||s.listing_date;if(!Ne)return null;const Ge=s.contract_date?Ic(s.contract_date):new Date;return Fj(Ge,Ic(Ne))})(),J=Ne=>Ne?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ne):"-",le=async()=>{if(T.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:T}),M(""),re.success("Note added")}catch{re.error("Failed to add note")}},ue=async()=>{if(P.trim())try{await m.mutateAsync({deal_id:s.id,title:P,sort_order:((d==null?void 0:d.length)||0)+1}),L(""),re.success("Task added")}catch{re.error("Failed to add task")}},oe=async(Ne,Ge)=>{try{await p.mutateAsync({id:Ne,is_completed:Ge,deal_id:s.id})}catch{re.error("Failed to update task")}},ie=async()=>{try{await x.mutateAsync(s.id),re.success("Deal deleted"),n(!1)}catch{re.error("Failed to delete deal")}},de=(d==null?void 0:d.filter(Ne=>Ne.is_completed).length)||0,we=(d==null?void 0:d.length)||0,je=(y==null?void 0:y.length)||0,xe=Ne=>Ne<1024?`${Ne} B`:Ne<1024*1024?`${(Ne/1024).toFixed(1)} KB`:`${(Ne/(1024*1024)).toFixed(1)} MB`,fe=Ne=>Ne?Ne.startsWith("image/")?ac:Ne.includes("pdf")?$r:z9:z9,Se=async Ne=>{const Ge=Ne.target.files;if(!(!Ge||!s)){G(!0);try{for(const _e of Array.from(Ge)){if(_e.size>20*1024*1024){re.error(`${_e.name} exceeds 20MB limit`);continue}await b.mutateAsync({dealId:s.id,file:_e})}re.success("File(s) uploaded")}catch{re.error("Failed to upload file")}finally{G(!1),C.current&&(C.current.value="")}}},Ee=async(Ne,Ge)=>{if(s)try{await v.mutateAsync({fileId:Ne,storagePath:Ge,dealId:s.id}),re.success("File deleted")}catch{re.error("Failed to delete file")}},Le=async(Ne,Ge)=>{try{const _e=await _Sn(Ne),Oe=document.createElement("a");Oe.href=_e,Oe.download=Ge,Oe.target="_blank",document.body.appendChild(Oe),Oe.click(),document.body.removeChild(Oe)}catch{re.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(v1,{open:t,onOpenChange:n,children:e.jsxs(rv,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(Lb,{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(qe,{variant:"outline",className:Et("text-xs",K.color),children:K.label}),e.jsxs(qe,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(Pb,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(xSn,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(kp,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>q(!0),children:e.jsx(Rn,{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(Ra,{className:"h-10 w-10",children:e.jsxs(Da,{className:"bg-primary/10 text-primary",children:[(De=s.contact.first_name)==null?void 0:De[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(pa,{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(on,{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(LSn,{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(ia,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:s.property_address||"Address TBD"}),e.jsx("p",{className:"text-muted-foreground",children:[s.city,s.state,s.zip_code].filter(Boolean).join(", ")})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Expected Price"}),e.jsx("p",{className:"text-lg font-bold",children:J(s.expected_price)})]}),e.jsxs("div",{className:"bg-emerald-500/10 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Expected GCI"}),e.jsx("p",{className:"text-lg font-bold text-emerald-600",children:J(s.expected_commission)})]}),(s.brokerage_split_pct||s.team_split_pct||s.referral_fee_pct||s.franchise_fee_pct||s.transaction_fee)&&e.jsxs("div",{className:"col-span-2 bg-muted/30 rounded-lg p-3 space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Commission Splits"}),s.brokerage_split_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Brokerage Split"}),e.jsxs("span",{children:[s.brokerage_split_pct,"%",s.expected_commission?` (${J(s.expected_commission*s.brokerage_split_pct/100)})`:""]})]}),s.team_split_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Team Split"}),e.jsxs("span",{children:[s.team_split_pct,"%"]})]}),s.referral_fee_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Referral Fee"}),e.jsxs("span",{children:[s.referral_fee_pct,"%"]})]}),s.franchise_fee_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Franchise Fee"}),e.jsxs("span",{children:[s.franchise_fee_pct,"%"]})]}),s.transaction_fee!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Transaction Fee"}),e.jsx("span",{children:J(s.transaction_fee)})]}),s.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:J(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(ll,{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(Rr,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),ee!==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:Et("text-lg font-bold",ee>90?"text-red-600":ee>60?"text-amber-600":"text-foreground"),children:[ee," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ra,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",Bs(Ic(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Od,{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(qSn,{deal:s}),e.jsx(CSn,{deal:s}),e.jsxs(fa,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(xa,{className:"w-full grid grid-cols-3",children:[e.jsxs(ss,{value:"tasks",className:"gap-1",children:[e.jsx(Rr,{className:"h-4 w-4"}),"Tasks ",we>0&&`(${de}/${we})`]}),e.jsxs(ss,{value:"files",className:"gap-1",children:[e.jsx(ZT,{className:"h-4 w-4"}),"Files ",je>0&&`(${je})`]}),e.jsxs(ss,{value:"activity",className:"gap-1",children:[e.jsx(Vr,{className:"h-4 w-4"}),"Activity"]})]}),e.jsxs(ns,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Add a new task...",value:P,onChange:Ne=>L(Ne.target.value),onKeyDown:Ne=>Ne.key==="Enter"&&ue()}),e.jsx(B,{onClick:ue,disabled:!P.trim(),children:e.jsx(Js,{className:"h-4 w-4"})}),e.jsxs(B,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>O(!0),children:[e.jsx(Op,{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:Et("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(wi,{checked:Ne.is_completed,onCheckedChange:Ge=>oe(Ne.id,!!Ge)}),e.jsx("span",{className:Et("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:Bs(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(ns,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:C,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=C.current)==null?void 0:Ne.click()},disabled:W,children:[W?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ja,{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=fe(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:[xe(Ne.file_size)," · ",Bs(new Date(Ne.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(RN,{children:e.jsxs(Cu,{children:[e.jsx(Au,{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(ma,{className:"h-4 w-4"}):e.jsx(n0,{className:"h-4 w-4"})})}),e.jsx(ou,{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:()=>Le(Ne.storage_path,Ne.file_name),children:e.jsx(ii,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Ee(Ne.id,Ne.storage_path),children:e.jsx(dr,{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(ns,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ds,{placeholder:"Add a note...",value:T,onChange:Ne=>M(Ne.target.value),rows:2}),e.jsxs(B,{onClick:le,disabled:!T.trim(),size:"sm",className:"w-full",children:[e.jsx(Dr,{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=KSn[Ne.activity_type]||Vr;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:oc(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(Jzt,{open:I,onOpenChange:O,dealId:s==null?void 0:s.id,dealName:s==null?void 0:s.deal_name}),e.jsx(Nl,{open:$,onOpenChange:q,children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete Deal?"}),e.jsxs(xl,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:ie,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function ZSn({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=V3e(),i=Gzt(),{data:l}=gO(),{data:o}=lw(),[c,d]=j.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:Bs(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});j.useEffect(()=>{if(n&&s){const m=n.deal_type==="seller"?"seller":"buyer",p=n.expected_price||0,x=n.commission_percentage||3,y=n.expected_commission||p*x/100;d({property_address:n.property_address||n.deal_name||"",city:n.city||"",state:n.state||"",zip:n.zip_code||"",transaction_type:m,close_date:n.actual_close_date||n.target_close_date||Bs(new Date,"yyyy-MM-dd"),sale_price:p,commission_amount:y,lead_source_id:"",client_type_id:"",notes:n.notes||""})}},[n,s]);const u=async m=>{if(m.preventDefault(),!!n)try{const p=await a.mutateAsync({property_address:c.property_address,city:c.city||null,state:c.state||null,zip:c.zip||null,transaction_type:c.transaction_type,close_date:c.close_date,sale_price:c.sale_price,commission_amount:c.commission_amount||null,brokerage_split_pct:n.brokerage_split_pct||null,team_split_pct:n.team_split_pct||null,franchise_fee_pct:n.franchise_fee_pct||null,referral_fee_pct:n.referral_fee_pct||null,transaction_fee:n.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:n.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:n.id,scorecard_transaction_id:p.id,actual_close_date:c.close_date}),re.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(p){console.error("Error syncing to scorecard:",p),re.error("Failed to add to scorecard")}},h=m=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(m);return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{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(ll,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx(zs,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(kr,{className:"text-center",children:"Review and confirm the details before adding this deal to your Scorecard."})]}),e.jsxs("form",{onSubmit:u,className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(ye,{id:"property_address",value:c.property_address,onChange:m=>d(p=>({...p,property_address:m.target.value})),placeholder:"123 Main St",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"city",children:"City"}),e.jsx(ye,{id:"city",value:c.city,onChange:m=>d(p=>({...p,city:m.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:c.state,onChange:m=>d(p=>({...p,state:m.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"zip",children:"Zip"}),e.jsx(ye,{id:"zip",value:c.zip,onChange:m=>d(p=>({...p,zip:m.target.value})),placeholder:"75001"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Transaction Type *"}),e.jsxs(vs,{value:c.transaction_type,onValueChange:m=>d(p=>({...p,transaction_type:m})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"buyer",children:"Buyer"}),e.jsx(Je,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(ye,{id:"close_date",type:"date",value:c.close_date,onChange:m=>d(p=>({...p,close_date:m.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(Od,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(ye,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:m=>d(p=>({...p,sale_price:Number(m.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(QT,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(ye,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:m=>d(p=>({...p,commission_amount:Number(m.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Lead Source"}),e.jsxs(vs,{value:c.lead_source_id,onValueChange:m=>d(p=>({...p,lead_source_id:m})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select source"})}),e.jsx(ys,{children:l==null?void 0:l.map(m=>e.jsx(Je,{value:m.id,children:m.name},m.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Client Type"}),e.jsxs(vs,{value:c.client_type_id,onValueChange:m=>d(p=>({...p,client_type_id:m})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select type"})}),e.jsx(ys,{children:o==null?void 0:o.map(m=>e.jsx(Je,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"notes",children:"Notes"}),e.jsx(Ds,{id:"notes",value:c.notes,onChange:m=>d(p=>({...p,notes:m.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(Nr,{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(Xa,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const XSn={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"}},mgt={urgent:0,high:1,medium:2,low:3};function QSn({deals:s,stages:t,onDealClick:n,onStageChange:r}){const[a,i]=j.useState("target_close_date"),[l,o]=j.useState("asc"),c=p=>{a===p?o(x=>x==="asc"?"desc":"asc"):(i(p),o("asc"))},d=j.useMemo(()=>[...s].sort((p,x)=>{var g,b;let y=0;switch(a){case"deal_name":y=p.deal_name.localeCompare(x.deal_name);break;case"stage":{const v=((g=t.find(C=>C.id===p.stage_id))==null?void 0:g.sort_order)||0,k=((b=t.find(C=>C.id===x.stage_id))==null?void 0:b.sort_order)||0;y=v-k;break}case"expected_price":y=(p.expected_price||0)-(x.expected_price||0);break;case"expected_commission":y=(p.expected_commission||0)-(x.expected_commission||0);break;case"target_close_date":{const v=p.target_close_date?Ic(p.target_close_date).getTime():1/0,k=x.target_close_date?Ic(x.target_close_date).getTime():1/0;y=v-k;break}case"priority":y=mgt[p.priority]-mgt[x.priority];break}return l==="asc"?y:-y}),[s,t,a,l]),u=p=>p?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(p):"—",h=p=>p?t.find(x=>x.id===p):null,m=({field:p,children:x})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(p),children:[x,a===p?l==="asc"?e.jsx(Gm,{className:"ml-2 h-4 w-4"}):e.jsx(tx,{className:"ml-2 h-4 w-4"}):e.jsx(_x,{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(Tt,{className:"w-[250px]",children:e.jsx(m,{field:"deal_name",children:"Deal Name"})}),e.jsx(Tt,{className:"w-[150px]",children:e.jsx(m,{field:"stage",children:"Stage"})}),e.jsx(Tt,{className:"w-[100px]",children:"Type"}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_price",children:"Price"})}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_commission",children:"GCI"})}),e.jsx(Tt,{className:"w-[130px]",children:e.jsx(m,{field:"target_close_date",children:"Close Date"})}),e.jsx(Tt,{className:"w-[100px]",children:e.jsx(m,{field:"priority",children:"Priority"})})]})}),e.jsx(za,{children:d.map(p=>{h(p.stage_id);const x=XSn[p.deal_type],y=p.target_close_date?Fj(Ic(p.target_close_date),new Date):null,g=y!==null&&y<0,b=y!==null&&y<=7&&y>=0;return e.jsxs(un,{className:Et("cursor-pointer hover:bg-muted/50 transition-colors",g&&"bg-red-50/50"),onClick:()=>n(p),children:[e.jsx(xt,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:p.deal_name}),p.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[p.contact.first_name," ",p.contact.last_name]})]})}),e.jsx(xt,{onClick:v=>v.stopPropagation(),children:e.jsx(Zzt,{stages:t,currentStageId:p.stage_id||"",onStageSelect:(v,k)=>r(p.id,v,k)})}),e.jsx(xt,{children:e.jsx(qe,{variant:"outline",className:Et("text-xs",x.color),children:x.label})}),e.jsx(xt,{children:e.jsx("span",{className:"font-medium",children:u(p.expected_price)})}),e.jsx(xt,{children:e.jsx("span",{className:"text-emerald-600",children:u(p.expected_commission)})}),e.jsx(xt,{children:p.target_close_date?e.jsxs("div",{className:Et("flex items-center gap-1 text-sm",g&&"text-red-600",b&&!g&&"text-amber-600"),children:[g&&e.jsx(po,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:Bs(Ic(p.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(xt,{children:e.jsx(qe,{variant:"outline",className:Et("text-xs capitalize",p.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",p.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",p.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",p.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:p.priority})})]},p.id)})})]})})}function JSn(){const s=ei();return mt({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name), stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function e4n(s){const t=ei();return mt({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:n,error:r}=await U.from("deal_tasks").select(` *, stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("deal_id",s).order("sort_order",{ascending:!0});if(r)throw r;return n},enabled:!!t&&!!s})}function t4n(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("deal_tasks").insert({owner_user_id:s,title:n.title,description:n.description||null,deal_id:n.deal_id||null,contact_id:n.contact_id||null,stage_id:n.stage_id||null,priority:n.priority||"medium",status:n.status||"todo",due_date:n.due_date||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function s4n(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("deal_tasks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function n4n(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("deal_tasks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function yTe(){const s=as();return vt({mutationFn:async({id:t,status:n})=>{const{data:r,error:a}=await U.from("deal_tasks").update({status:n,completed_at:n==="done"?new Date().toISOString():null}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function r4n(){const s=as();return vt({mutationFn:async t=>{if(t.length===0)return;const{error:n}=await U.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function a4n(s){const t=ei();return mt({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let n=U.from("deal_task_templates").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});s&&(n=n.eq("stage_id",s));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function i4n(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("deal_task_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title,description:n.description||null,priority:n.priority||"medium",default_due_offset_days:n.default_due_offset_days||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function o4n(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("deal_task_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function l4n(){const s=ei(),t=as();return vt({mutationFn:async({dealId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await U.from("deal_task_templates").select("*").eq("owner_user_id",s).eq("stage_id",r).order("sort_order");if(i)throw i;if(!a||a.length===0)return[];const{data:l}=await U.from("deal_tasks").select("title, stage_id").eq("deal_id",n).eq("stage_id",r),o=new Set((l||[]).map(h=>h.title)),c=a.filter(h=>!o.has(h.title)).map((h,m)=>({owner_user_id:s,deal_id:n,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_date:h.default_due_offset_days?new Date(Date.now()+h.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:m,status:"todo"}));if(c.length===0)return[];const{data:d,error:u}=await U.from("deal_tasks").insert(c).select();if(u)throw u;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const c4n={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function d4n({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=e4n(s?n:void 0),u=r4n(),h=l4n(),[m,p]=j.useState(new Set),[x,y]=j.useState(!1),g=(c||[]).filter(C=>C.status!=="done");j.useEffect(()=>{g.length>0&&p(new Set(g.map(C=>C.id)))},[c]);const b=C=>{p(T=>{const M=new Set(T);return M.has(C)?M.delete(C):M.add(C),M})},v=async()=>{y(!0);try{const C=Array.from(m);C.length>0&&await u.mutateAsync(C),await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(C){console.error("Stage move failed:",C),re.error((C==null?void 0:C.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(C){console.error("Stage move (skip) failed:",C),re.error((C==null?void 0:C.message)||"Failed to move deal. Please try again.")}finally{y(!1)}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[480px]",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Move Deal"}),e.jsxs(kr,{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(qe,{variant:"outline",className:"text-sm",children:a}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(qe,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):g.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:g.length})," incomplete task",g.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:g.map(C=>e.jsxs("label",{className:"flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",children:[e.jsx(wi,{checked:m.has(C.id),onCheckedChange:()=>b(C.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[c4n[C.priority]," ",C.title]}),C.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:C.stage.color+"20",color:C.stage.color},children:C.stage.name})]},C.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{m.size===g.length?p(new Set):p(new Set(g.map(C=>C.id)))},children:m.size===g.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:k,disabled:x,children:"Skip"}),e.jsxs(B,{size:"sm",onClick:v,disabled:x,children:[x&&e.jsx(Wt,{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(Rr,{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:v,disabled:x,children:[x&&e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const u4n=[{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"}],h4n=[{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 eBt({open:s,onOpenChange:t}){const n=ei(),{data:r,isLoading:a}=C3t(),i=F_s(),[l,o]=j.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null,portal_theme:"noir"}),[c,d]=j.useState(null);j.useEffect(()=>{s&&o({logo_url:(r==null?void 0:r.logo_url)??null,cover_photo_url:(r==null?void 0:r.cover_photo_url)??null,brand_color:(r==null?void 0:r.brand_color)??null,accent_color:(r==null?void 0:r.accent_color)??null,tagline:(r==null?void 0:r.tagline)??null,welcome_message:(r==null?void 0:r.welcome_message)??null,portal_theme:(r==null?void 0:r.portal_theme)??"noir"})},[s,r]);const u=p=>o(x=>({...x,...p})),h=async(p,x)=>{if(n){if(p.size>5*1024*1024){re.error("Image must be under 5MB");return}d(x);try{const y=await A3t(n,p,x);u(x==="logo"?{logo_url:y}:{cover_photo_url:y})}catch(y){re.error(`Upload failed: ${y.message||y}`)}finally{d(null)}}},m=async()=>{try{await i.mutateAsync(l),re.success("Portal branding saved"),t(!1)}catch{re.error("Failed to save branding")}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Ac,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(kr,{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(Wt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(m4n,{draft:l}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Portal Theme"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The overall look and feel your clients see when they open their portal."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:h4n.map(p=>{const x=(l.portal_theme??"noir")===p.id;return e.jsxs("button",{type:"button",onClick:()=>u({portal_theme:p.id}),className:Et("rounded-xl border-2 p-3 text-left transition-all",x?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsx("div",{className:"rounded-lg overflow-hidden mb-2",style:{background:p.bg},children:e.jsxs("div",{className:"p-3 space-y-1.5",children:[e.jsx("div",{className:"h-1.5 w-10 rounded-full",style:{background:p.accent}}),e.jsx("div",{className:"h-2.5 w-20 rounded",style:{background:p.ink,opacity:.85}}),e.jsx("div",{className:"h-6 rounded-md",style:{background:p.surface,border:`1px solid ${p.accent}44`}})]})}),e.jsx("div",{className:"text-sm font-medium text-foreground",children:p.name}),e.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:p.description})]},p.id)})})]}),e.jsx(pgt,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:p=>h(p,"logo"),onClear:()=>u({logo_url:null}),aspect:"square"}),e.jsx(pgt,{label:"Cover Photo",hint:"Hero background at the top of the portal. Wide landscape works best.",value:l.cover_photo_url,uploading:c==="cover",onUpload:p=>h(p,"cover"),onClear:()=>u({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Brand Colors"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used for the header background and primary buttons."})]}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:u4n.map(p=>{const x=l.brand_color===p.brand&&l.accent_color===p.accent;return e.jsxs("button",{type:"button",onClick:()=>u({brand_color:p.brand,accent_color:p.accent}),className:Et("group relative rounded-lg border-2 p-2 text-left transition-all",x?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsxs("div",{className:"flex h-6 rounded-md overflow-hidden",children:[e.jsx("div",{className:"flex-1",style:{background:p.brand}}),e.jsx("div",{className:"flex-1",style:{background:p.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:p.name})]},p.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(fgt,{label:"Brand",value:l.brand_color,onChange:p=>u({brand_color:p})}),e.jsx(fgt,{label:"Accent",value:l.accent_color,onChange:p=>u({accent_color:p})})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Tagline"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Short line shown under your name."}),e.jsx(ye,{value:l.tagline||"",onChange:p=>u({tagline:p.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Default Welcome Message"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown on the portal hero. Per-deal welcome messages override this."}),e.jsx("textarea",{value:l.welcome_message||"",onChange:p=>u({welcome_message:p.target.value}),placeholder:"Welcome! Here's everything you need for your transaction.",className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[70px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",maxLength:300})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:m,disabled:i.isPending,children:[i.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function m4n({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 pgt({label:s,hint:t,value:n,uploading:r,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:s}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:t}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Et("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(ac,{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(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ja,{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(Rn,{className:"h-3.5 w-3.5"})})]})]})]})}function fgt({label:s,value:t,onChange:n}){const r=t||"#000000";return e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:s}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 h-9 rounded-md border border-input bg-background px-2",children:[e.jsx("input",{type:"color",value:r,onChange:a=>n(a.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(ye,{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 p4n(){const s=ei();return mt({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("client_portals").select("*").eq("owner_user_id",s);if(n)throw n;return t||[]},enabled:!!s})}function f4n({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=NWe(),d=Eq(),u=ERt(),h=MRt(),[m,p]=j.useState(!1),x=!!(r!=null&&r.archived_at),y=async()=>{p(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),re.success("Portal enabled!")}catch{re.error("Failed to create portal")}finally{p(!1)}},g=async T=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:T}),re.success(T?"Portal enabled":"Portal disabled")}catch{re.error("Failed to update portal")}},b=()=>{r&&(navigator.clipboard.writeText(q5(r.slug)),re.success("Link copied!"))},v=()=>{r&&window.open(q5(r.slug),"_blank")},k=async()=>{if(r)try{await u.mutateAsync(r.id),re.success("Portal archived")}catch{re.error("Failed to archive portal")}},C=async()=>{if(r)try{await h.mutateAsync(r.id),re.success("Portal restored")}catch{re.error("Failed to restore portal")}};return r?x?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(Yn,{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(qe,{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:C,className:"text-xs gap-1",children:[e.jsx(zT,{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(Rn,{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(Yn,{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(qe,{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:b,title:"Copy link",children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:v,title:"Preview",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(r,t),title:"Invite client",children:e.jsx(Dr,{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(v5,{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(ic,{className:"h-3.5 w-3.5"})}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Hy,{className:"h-3.5 w-3.5"})})}),e.jsx(xd,{align:"end",children:e.jsxs(wa,{onClick:k,children:[e.jsx(gm,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(Mn,{checked:r.is_enabled,onCheckedChange:g,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(Wt,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(yn,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function tBt(){const{data:s,isLoading:t}=gTe(),{data:n,isLoading:r}=p4n(),[a,i]=j.useState(""),[l,o]=j.useState("all"),c=LRt(),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,x]=j.useState(null),[y,g]=j.useState(null),[b,v]=j.useState(!1),k=ei(),C=t||r,T=new Map;n==null||n.forEach(q=>T.set(q.deal_id,q));const P=[...(s||[]).filter(q=>{var J,le,ue,oe,ie;const W=T.get(q.id),G=a.toLowerCase(),K=!G||q.deal_name.toLowerCase().includes(G)||((le=(J=q.contact)==null?void 0:J.first_name)==null?void 0:le.toLowerCase().includes(G))||((oe=(ue=q.contact)==null?void 0:ue.last_name)==null?void 0:oe.toLowerCase().includes(G))||((ie=W==null?void 0:W.client_name)==null?void 0:ie.toLowerCase().includes(G));let ee=!0;return l==="active"?ee=!!(W!=null&&W.is_enabled)&&!(W!=null&&W.archived_at):l==="disabled"?ee=!!W&&!W.is_enabled&&!W.archived_at:l==="archived"?ee=!!(W!=null&&W.archived_at):l==="none"?ee=!W:l==="all"&&(ee=!(W!=null&&W.archived_at)||!W),K&&ee})].sort((q,W)=>{const G=T.get(q.id),K=T.get(W.id);if(G!=null&&G.archived_at&&!(K!=null&&K.archived_at))return 1;if(!(G!=null&&G.archived_at)&&(K!=null&&K.archived_at)||G&&!K)return-1;if(!G&&K)return 1;if(G&&K){if(G.is_enabled&&!K.is_enabled)return-1;if(!G.is_enabled&&K.is_enabled)return 1}return 0}),L=(n==null?void 0:n.filter(q=>!q.archived_at).length)||0,I=(n==null?void 0:n.filter(q=>q.is_enabled&&!q.archived_at).length)||0,O=(n==null?void 0:n.filter(q=>q.archived_at).length)||0,$=async()=>{if(y)try{await c.mutateAsync({id:y.id,dealId:y.deal_id}),re.success("Portal permanently deleted"),g(null)}catch{re.error("Failed to delete portal")}};return C?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(Wt,{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(yn,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[L," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[I," active · ",L-I," disabled",O>0&&` · ${O} archived`]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>v(!0),className:"gap-1.5",children:[e.jsx(Ac,{className:"h-3.5 w-3.5"}),"Portal Branding"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search deals or clients...",value:a,onChange:q=>i(q.target.value),className:"pl-9 pr-8"}),a&&e.jsx("button",{onClick:()=>i(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(dr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:["all","active","disabled","archived","none"].map(q=>e.jsx(B,{variant:l===q?"secondary":"ghost",size:"sm",onClick:()=>o(q),className:"text-xs px-3 capitalize",children:q==="none"?"No Portal":q},q))})]}),e.jsx(lo,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[P.map(q=>{const W=T.get(q.id)||null,G=q.contact?`${q.contact.first_name||""} ${q.contact.last_name||""}`.trim():"";return e.jsx(f4n,{dealId:q.id,dealName:q.deal_name,contactName:G,portal:W,onSettingsOpen:u,onComposerOpen:K=>m(K),onInviteOpen:(K,ee)=>x({portal:K,dealName:ee}),onDeleteConfirm:g},q.id)}),P.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-muted rounded-full flex items-center justify-center",children:e.jsx(yn,{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(sYe,{open:!!d,onOpenChange:q=>!q&&u(null),portal:d,dealOwnerId:k||""}),h&&e.jsx(nYe,{open:!!h,onOpenChange:q=>!q&&m(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),p&&e.jsx(rYe,{open:!!p,onOpenChange:q=>!q&&x(null),portal:p.portal,dealName:p.dealName}),e.jsx(eBt,{open:b,onOpenChange:v}),e.jsx(Nl,{open:!!y,onOpenChange:q=>!q&&g(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Permanently delete this portal?"}),e.jsx(xl,{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(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:$,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}class x4n extends j.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("DealPipeline error:",t,n)}render(){return this.state.hasError?e.jsx(Vs,{children:e.jsxs("div",{className:"flex flex-col items-center justify-center h-[60vh] gap-4 text-center px-4",children:[e.jsx("div",{className:"w-16 h-16 bg-destructive/10 rounded-full flex items-center justify-center",children:e.jsx("span",{className:"text-2xl",children:"⚠️"})}),e.jsx("h2",{className:"text-xl font-semibold",children:"Something went wrong"}),e.jsx("p",{className:"text-muted-foreground max-w-md",children:"There was an error in the deal pipeline. Click below to try again."}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),className:"px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:bg-primary/90",children:"Try Again"}),e.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 border border-border rounded-md text-sm font-medium hover:bg-muted",children:"Refresh Page"})]})]})}):this.props.children}}const tG="deal-pipeline-detail-sheet";function g4n(){var Ls;const s=Tq(),{data:t,isLoading:n}=yee(),{data:r,isLoading:a,refetch:i}=gTe(),{data:l,isLoading:o}=v5n(),c=Vzt(),d=h5n(),[u,h]=j.useState("board"),[m,p]=j.useState(!1),[x,y]=j.useState(!1),[g,b]=j.useState(null),[v,k]=j.useState(null),[C,T]=j.useState(null),[M,P]=j.useState(null),[L,I]=j.useState(!1),[O,$]=j.useState(null),[q,W]=j.useState(""),[G,K]=j.useState("all"),[ee,J]=j.useState("all"),[le,ue]=j.useState("all"),{data:oe}=oSn(),[ie,de]=j.useState(!1),[we,je]=j.useState(!1),[xe,fe]=j.useState(new Set),Se=j.useRef(!1),[Ee,Le]=j.useState(null),{data:De}=Hj(),{isTeamLeader:Be,teamMembers:Ne}=aSn(),Ge=j.useMemo(()=>Array.from(xe),[xe]),{data:_e}=iSn(Ge),Oe=j.useMemo(()=>{const sn=new Map;return Ne.forEach(Hs=>sn.set(Hs.id,{name:Hs.name,avatar_url:Hs.avatar_url,color:Hs.color})),sn},[Ne]),Ae=j.useCallback(sn=>sn.owner_user_id&&Oe.get(sn.owner_user_id)||null,[Oe]),Xe=j.useCallback(sn=>{fe(Hs=>{const nn=new Set(Hs);return nn.has(sn)?nn.delete(sn):nn.add(sn),nn})},[]);j.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[Ue,Ze]=dc(),Qe=j.useRef(!1);j.useEffect(()=>{const sn=Ue.get("deal");if(sn&&r&&r.length>0&&!Qe.current){const Hs=r.find(nn=>nn.id===sn);Hs&&(Qe.current=!0,b(Hs),y(!0),Ue.delete("deal"),Ze(Ue,{replace:!0}))}},[r,Ue]);const Ye=j.useMemo(()=>{if(!_e||!t)return[];const sn=new Map(t.map(Hs=>[Hs.name,Hs.id]));return _e.map(Hs=>{const nn=Hs._stage_name&&sn.get(Hs._stage_name)||null;return{...Hs,stage_id:nn||Hs.stage_id}})},[_e,t]),nt=j.useMemo(()=>[...r||[],...Ye],[r,Ye]);j.useEffect(()=>{if(Se.current||nt.length===0)return;Se.current=!0;const sn=sessionStorage.getItem(tG);if(sn)try{const Hs=JSON.parse(sn);if(!Hs.open||!Hs.dealId)return;const nn=nt.find(tn=>tn.id===Hs.dealId);nn&&(b(nn),y(!0))}catch{sessionStorage.removeItem(tG)}},[nt]),j.useEffect(()=>{x&&(g!=null&&g.id)?sessionStorage.setItem(tG,JSON.stringify({dealId:g.id,open:!0})):sessionStorage.removeItem(tG)},[x,g==null?void 0:g.id]);const rt=(oe==null?void 0:oe.byDeal)||{},Fe=(oe==null?void 0:oe.unique)||[],dt=nt.filter(sn=>{var Xs,Ba,Hr,mr,pr,rn;const Hs=q.toLowerCase(),nn=rt[sn.id]||[],tn=!Hs||sn.deal_name.toLowerCase().includes(Hs)||((Ba=(Xs=sn.contact)==null?void 0:Xs.first_name)==null?void 0:Ba.toLowerCase().includes(Hs))||((mr=(Hr=sn.contact)==null?void 0:Hr.last_name)==null?void 0:mr.toLowerCase().includes(Hs))||((pr=sn.property_address)==null?void 0:pr.toLowerCase().includes(Hs))||((rn=sn.city)==null?void 0:rn.toLowerCase().includes(Hs))||nn.some(Jn=>Jn.toLowerCase().includes(Hs)),_n=G==="all"||sn.deal_type===G,Cn=ee==="all"||nn.includes(ee),Un=sn.actual_close_date||sn.target_close_date||sn.contract_date||sn.created_at,Kr=Un?String(Un).slice(0,4):null;return tn&&_n&&Cn&&(le==="all"||Kr===le)}),Dt=j.useMemo(()=>{const sn=new Set;return sn.add(String(new Date().getFullYear())),nt.forEach(Hs=>{const nn=Hs.actual_close_date||Hs.target_close_date||Hs.contract_date||Hs.created_at;nn&&sn.add(String(nn).slice(0,4))}),Array.from(sn).sort((Hs,nn)=>Number(nn)-Number(Hs))},[nt]),pt=j.useMemo(()=>{if(!t)return l||null;const sn=new Set(t.filter(Un=>Un.is_won_stage).map(Un=>Un.id)),Hs=new Set(t.filter(Un=>Un.is_lost_stage).map(Un=>Un.id)),nn=nt.filter(Un=>Un.stage_id&&!sn.has(Un.stage_id)&&!Hs.has(Un.stage_id)),tn=nt.filter(Un=>Un.stage_id&&sn.has(Un.stage_id)),_n=new Date().getFullYear(),Cn=tn.filter(Un=>Un.actual_close_date?new Date(Un.actual_close_date).getFullYear()===_n:!0);return{totalDeals:nt.length,activeDeals:nn.length,wonDeals:tn.length,pipelineValue:nn.reduce((Un,Kr)=>Un+(Kr.expected_price||0),0),expectedCommission:nn.reduce((Un,Kr)=>Un+(Kr.expected_commission||0),0),expectedNetToAgent:nn.reduce((Un,Kr)=>Un+(mj(Kr)||0),0),wonValue:tn.reduce((Un,Kr)=>Un+(Kr.expected_price||0),0),weightedGCI:nn.reduce((Un,Kr)=>Un+(Kr.expected_commission||0)*((Kr.probability??50)/100),0),weightedNet:nn.reduce((Un,Kr)=>Un+(mj(Kr)||0)*((Kr.probability??50)/100),0),ytdWonDeals:Cn.length,ytdWonGCI:Cn.reduce((Un,Kr)=>Un+(Kr.expected_commission||0),0),ytdWonNet:Cn.reduce((Un,Kr)=>Un+(mj(Kr)||0),0),projectedAnnualNet:Cn.reduce((Un,Kr)=>Un+(mj(Kr)||0),0)+nn.reduce((Un,Kr)=>Un+(mj(Kr)||0)*((Kr.probability??50)/100),0)}},[nt,t,l]),zt=sn=>{b(sn),y(!0)},Gt=sn=>{k(sn||null),b(null),p(!0)},qs=sn=>{b(sn),y(!1),p(!0)},As=sn=>{y(sn),sn||sessionStorage.removeItem(tG)},Bt=(sn,Hs)=>{T(sn)},At=(sn,Hs)=>{sn.preventDefault(),sn.dataTransfer.dropEffect="move",P(Hs)},Is=async(sn,Hs)=>{if(sn.preventDefault(),P(null),!C)return;const nn=r==null?void 0:r.find(Cn=>Cn.id===C),tn=t==null?void 0:t.find(Cn=>Cn.id===Hs),_n=t==null?void 0:t.find(Cn=>Cn.id===(nn==null?void 0:nn.stage_id));if(!nn||!tn||nn.stage_id===Hs){T(null);return}Le({dealId:C,dealName:nn.deal_name,fromStageName:(_n==null?void 0:_n.name)||"Unknown",toStageName:tn.name,toStageId:Hs,isWonStage:tn.is_won_stage,deal:nn}),T(null)},jt=async()=>{if(!Ee)return;const{dealId:sn,toStageId:Hs,toStageName:nn,isWonStage:tn,deal:_n}=Ee;if(await d.mutateAsync({dealId:sn,stageId:Hs,stageName:nn}),re.success(`Moved to ${nn}`),tn&&!_n.scorecard_transaction_id){const Cn={..._n,stage_id:Hs};$(Cn),I(!0)}},Qs=j.useCallback(async(sn,Hs,nn)=>{const tn=r==null?void 0:r.find(Un=>Un.id===sn),_n=t==null?void 0:t.find(Un=>Un.id===Hs),Cn=t==null?void 0:t.find(Un=>Un.id===(tn==null?void 0:tn.stage_id));!tn||!_n||tn.stage_id===Hs||Le({dealId:sn,dealName:tn.deal_name,fromStageName:(Cn==null?void 0:Cn.name)||"Unknown",toStageName:nn,toStageId:Hs,isWonStage:_n.is_won_stage,deal:tn})},[r,t]),cn=sn=>dt.filter(Hs=>Hs.stage_id===sn),qt=n||a,Gs=s?"list":u;return e.jsxs(Vs,{children:[e.jsxs("div",{className:"flex flex-col h-[calc(100vh-4rem)]",children:[e.jsxs("div",{className:"shrink-0 p-4 md:p-6 pb-0 space-y-4",children:[e.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(Ki,{className:"h-4 w-4"})}),!s&&e.jsx(RN,{children:e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsxs(Cu,{children:[e.jsx(Au,{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(r0,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Board"})]})}),e.jsx(ou,{children:"Kanban board view"})]}),e.jsxs(Cu,{children:[e.jsx(Au,{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(ug,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"List"})]})}),e.jsx(ou,{children:"Grouped list view"})]}),e.jsxs(Cu,{children:[e.jsx(Au,{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(oz,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Table"})]})}),e.jsx(ou,{children:"Sortable table view"})]}),e.jsxs(Cu,{children:[e.jsx(Au,{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(yn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Portals"})]})}),e.jsx(ou,{children:"Client portal management"})]})]})}),De&&!Be&&e.jsxs(B,{variant:"outline",onClick:()=>de(!0),children:[e.jsx(Bn,{className:"h-4 w-4 mr-2"}),"Team"]}),e.jsxs(B,{onClick:()=>Gt(),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Deal"]})]})]}),Gs!=="portals"&&e.jsx(uSn,{stats:pt,isLoading:o}),Gs!=="portals"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search deals, contacts, addresses, tags...",value:q,onChange:sn=>W(sn.target.value),className:"pl-9 pr-8"}),q&&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(dr,{className:"h-4 w-4"})})]}),e.jsxs(vs,{value:G,onValueChange:K,children:[e.jsx(gs,{className:"w-[140px]",children:e.jsx(bs,{placeholder:"All Types"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Types"}),e.jsx(Je,{value:"buyer",children:"Buyer"}),e.jsx(Je,{value:"seller",children:"Seller"}),e.jsx(Je,{value:"dual",children:"Dual"}),e.jsx(Je,{value:"referral",children:"Referral"}),e.jsx(Je,{value:"lease",children:"Lease"})]})]}),e.jsxs(vs,{value:le,onValueChange:ue,children:[e.jsx(gs,{className:"w-[120px]",children:e.jsx(bs,{placeholder:"Year"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Years"}),Dt.map(sn=>e.jsx(Je,{value:sn,children:sn},sn))]})]}),e.jsxs(vs,{value:ee,onValueChange:J,children:[e.jsxs(gs,{className:"w-[160px]",children:[e.jsx(wf,{className:"h-3.5 w-3.5 mr-1.5 text-muted-foreground"}),e.jsx(bs,{placeholder:"All Tags"})]}),e.jsxs(ys,{className:"max-h-[300px]",children:[e.jsx(Je,{value:"all",children:"All Tags"}),Fe.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),Fe.map(sn=>e.jsx(Je,{value:sn,children:sn},sn))]})]}),ee!=="all"&&e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(wf,{className:"h-3 w-3"}),ee,e.jsx("button",{onClick:()=>J("all"),className:"ml-1 hover:text-foreground","aria-label":"Clear tag filter",children:e.jsx(dr,{className:"h-3 w-3"})})]}),(q||G!=="all"||ee!=="all"||le!=="all")&&e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[dt.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(rSn,{members:Ne,enabledMembers:xe,onToggleMember:Xe,isOpen:we,onToggleOpen:()=>je(sn=>!sn)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:qt?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(sn=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(gn,{className:"h-full rounded-xl"})},sn))}):Gs==="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(sn=>e.jsx(dSn,{stage:sn,deals:cn(sn.id),onDealClick:zt,onAddDeal:Gt,onDragStart:Bt,onDragOver:At,onDrop:Is,isDragOver:M===sn.id,isWonStage:sn.is_won_stage,getOwnerInfo:Ae},sn.id))}),e.jsx(KU,{orientation:"horizontal"})]}):Gs==="table"?e.jsx(lo,{className:"h-full",children:e.jsx(QSn,{deals:dt,stages:t||[],onDealClick:zt,onStageChange:Qs})}):Gs==="portals"?e.jsx(tBt,{}):e.jsx(lo,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(sn=>{const Hs=cn(sn.id);return Hs.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:sn.color}}),e.jsx("h3",{className:"font-semibold",children:sn.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",Hs.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:Hs.map(nn=>e.jsx(Xzt,{deal:nn,onClick:()=>zt(nn),stages:t,onStageChange:Qs,showStagePicker:!0,isWonStage:sn.is_won_stage,ownerInfo:Ae(nn)},nn.id))})]},sn.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(r0,{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:()=>Gt(),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((r==null?void 0:r.length)||0)>0&&dt.length===0&&e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-muted rounded-full flex items-center justify-center",children:e.jsx(Fr,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No matching deals"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Try adjusting your search or filters"}),e.jsx(B,{variant:"outline",onClick:()=>{W(""),K("all"),J("all"),ue("all")},children:"Clear Filters"})]})]})})})]})]}),e.jsx(fSn,{open:m,onOpenChange:p,deal:g,defaultStageId:v}),e.jsx(YSn,{deal:g,open:x,onOpenChange:As,onEdit:qs,isWonStage:g?(Ls=t==null?void 0:t.find(sn=>sn.id===g.stage_id))==null?void 0:Ls.is_won_stage:!1,onAddToScorecard:sn=>{$(sn),I(!0),y(!1)}}),e.jsx(ZSn,{open:L,onOpenChange:I,deal:O,onComplete:()=>{i(),$(null)}}),Ee&&e.jsx(d4n,{open:!!Ee,onOpenChange:sn=>{sn||Le(null)},dealId:Ee.dealId,dealName:Ee.dealName,fromStageName:Ee.fromStageName,toStageName:Ee.toStageName,toStageId:Ee.toStageId,onConfirm:jt}),e.jsx(sSn,{open:ie,onOpenChange:de})]})}function y4n(){return e.jsx(x4n,{children:e.jsx(g4n,{})})}function sBt({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var W;const i=t4n(),l=s4n(),{data:o}=gTe(),c=ei(),{data:d}=mt({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:G,error:K}=await U.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(K)throw K;return G},enabled:!!c&&s}),[u,h]=j.useState(""),[m,p]=j.useState(""),[x,y]=j.useState("none"),[g,b]=j.useState("none"),[v,k]=j.useState("medium"),[C,T]=j.useState("todo"),[M,P]=j.useState(),[L,I]=j.useState(!1),[O,$]=j.useState(!1);j.useEffect(()=>{n?(h(n.title),p(n.description||""),y(n.deal_id||"none"),b(n.contact_id||"none"),k(n.priority),T(n.status),P(n.due_date?Ep(n.due_date):void 0)):(h(""),p(""),y(r||"none"),b("none"),k("medium"),T("todo"),P(void 0))},[n,s,r]);const q=async()=>{if(!u.trim()){re.error("Task title is required");return}try{const G={title:u.trim(),description:m.trim()||null,deal_id:x==="none"?null:x,contact_id:g==="none"?null:g,stage_id:a||null,priority:v,status:C,due_date:M?Bs(M,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...G}),re.success("Task updated")):(await i.mutateAsync(G),re.success("Task created")),t(!1)}catch{re.error("Failed to save task")}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[480px]",children:[e.jsx($s,{children:e.jsx(zs,{children:n?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(ye,{value:u,onChange:G=>h(G.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{value:m,onChange:G=>p(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(se,{children:"Priority"}),e.jsxs(vs,{value:v,onValueChange:G=>k(G),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"low",children:"🟢 Low"}),e.jsx(Je,{value:"medium",children:"🟡 Medium"}),e.jsx(Je,{value:"high",children:"🟠 High"}),e.jsx(Je,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:C,onValueChange:G=>T(G),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"todo",children:"To Do"}),e.jsx(Je,{value:"in_progress",children:"In Progress"}),e.jsx(Je,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due Date"}),e.jsxs(lc,{children:[e.jsx(cc,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Et("w-full justify-start text-left font-normal",!M&&"text-muted-foreground"),children:[e.jsx(ra,{className:"mr-2 h-4 w-4"}),M?Bs(M,"PPP"):"Pick a date"]})}),e.jsx(Jl,{className:"w-auto p-0",align:"start",children:e.jsx(o1,{mode:"single",selected:M,onSelect:P,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Link to Deal"}),e.jsxs(lc,{open:L,onOpenChange:I,children:[e.jsx(cc,{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(Ni,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),x!=="none"?((W=o==null?void 0:o.find(G=>G.id===x))==null?void 0:W.deal_name)||"Select deal":"No Deal"]}),e.jsx(fb,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Jl,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Sb,{children:[e.jsx(Cb,{placeholder:"Search deals..."}),e.jsxs(Ab,{children:[e.jsx(Tb,{children:"No deals found."}),e.jsxs(Eb,{children:[e.jsxs(Yy,{value:"no-deal",onSelect:()=>{y("none"),I(!1)},children:[e.jsx(da,{className:Et("mr-2 h-4 w-4",x==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(G=>e.jsxs(Yy,{value:G.deal_name,onSelect:()=>{y(G.id),I(!1)},children:[e.jsx(da,{className:Et("mr-2 h-4 w-4",x===G.id?"opacity-100":"opacity-0")}),G.deal_name]},G.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Link to Contact"}),e.jsxs(lc,{open:O,onOpenChange:$,children:[e.jsx(cc,{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(Eo,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),g!=="none"?(()=>{const G=d==null?void 0:d.find(K=>K.id===g);return G?`${G.first_name} ${G.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(fb,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Jl,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Sb,{children:[e.jsx(Cb,{placeholder:"Search contacts..."}),e.jsxs(Ab,{children:[e.jsx(Tb,{children:"No contacts found."}),e.jsxs(Eb,{children:[e.jsxs(Yy,{value:"no-contact",onSelect:()=>{b("none"),$(!1)},children:[e.jsx(da,{className:Et("mr-2 h-4 w-4",g==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(G=>e.jsxs(Yy,{value:`${G.first_name} ${G.last_name}`,onSelect:()=>{b(G.id),$(!1)},children:[e.jsx(da,{className:Et("mr-2 h-4 w-4",g===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:q,disabled:i.isPending||l.isPending,children:n?"Save Changes":"Create Task"})]})]})]})})}const v4n={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 b4n({tasks:s}){const t=yTe(),n=n4n(),r=Hn(),[a,i]=j.useState(null),l=async u=>{const h=u.status==="done"?"todo":"done";try{await t.mutateAsync({id:u.id,status:h})}catch{re.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),re.success("Task deleted")}catch{re.error("Failed to delete task")}};if(s.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx(Rr,{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(xgt,{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(Ni,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:h.dealName}),e.jsxs(qe,{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(xgt,{task:m,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:p=>r(`/mission-control/pipeline?deal=${p}`)},m.id))]},u)),a&&e.jsx(sBt,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function xgt({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&F5(Ep(s.due_date))&&!Jg(Ep(s.due_date)),o=!i&&s.due_date&&Jg(Ep(s.due_date)),c=v4n[s.priority];return e.jsxs("div",{className:Et("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(Rr,{className:"h-5 w-5 text-emerald-500"}):e.jsx(Sx,{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:Et("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(Eo,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(qe,{variant:"outline",className:Et("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:Et("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(Vr,{className:"h-3 w-3"}),Bs(Ep(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(kp,{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(Rn,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const _4n=[{status:"todo",label:"To Do",icon:Sx,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:vh,color:"border-t-blue-500"},{status:"done",label:"Done",icon:Rr,color:"border-t-emerald-500"}],w4n={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function j4n({tasks:s}){const t=yTe(),n=j.useMemo(()=>{const i={todo:[],in_progress:[],done:[]};return s.forEach(l=>i[l.status].push(l)),i},[s]),r=(i,l)=>{i.dataTransfer.setData("taskId",l)},a=async(i,l)=>{i.preventDefault();const o=i.dataTransfer.getData("taskId");if(!o)return;const c=s.find(d=>d.id===o);if(!(!c||c.status===l))try{await t.mutateAsync({id:o,status:l})}catch{re.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:_4n.map(i=>e.jsxs("div",{className:Et("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(qe,{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(N4n,{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 N4n({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&F5(Ep(s.due_date))&&!Jg(Ep(s.due_date)),a=!n&&s.due_date&&Jg(Ep(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:Et("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:w4n[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Et("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(Ni,{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(Eo,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Et("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(Vr,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",Bs(Ep(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 ggt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function k4n({tasks:s}){const[t,n]=j.useState(new Date),r=yTe(),a=Vu(t),i=Uv(t),l=xg(a),o=v$(i),c=XDe({start:l,end:o}),d=j.useMemo(()=>{const m=new Map;return s.forEach(p=>{if(!p.due_date)return;const x=p.due_date,y=m.get(x)||[];y.push(p),m.set(x,y)}),m},[s]),u=j.useMemo(()=>s.filter(m=>!m.due_date),[s]),h=async m=>{const p=m.status==="done"?"todo":"done";try{await r.mutateAsync({id:m.id,status:p})}catch{re.error("Failed to update task")}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>n(e8(t,1)),children:e.jsx(Cc,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:Bs(t,"MMMM yyyy")}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>n(Ax(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 p=Bs(m,"yyyy-MM-dd"),x=d.get(p)||[],y=GU(m,t),g=Jg(m);return e.jsxs("div",{className:Et("border-r border-b min-h-[100px] p-1",!y&&"bg-muted/30",g&&"bg-primary/5"),children:[e.jsx("div",{className:Et("text-xs font-medium mb-1 text-right px-1",!y&&"text-muted-foreground/40",g&&"text-primary font-bold"),children:Bs(m,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[x.slice(0,3).map(b=>e.jsxs("button",{onClick:()=>h(b),className:Et("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",b.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[b.status==="done"?e.jsx(Rr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Sx,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[ggt[b.priority]," ",b.title]})]},b.id)),x.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",x.length-3," more"]})]})]},p)})}),u.length>0&&e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",u.length,")"]}),e.jsx("div",{className:"space-y-1",children:u.map(m=>e.jsxs("button",{onClick:()=>h(m),className:Et("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(Rr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Sx,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[ggt[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 S4n={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function C4n({open:s,onOpenChange:t,stages:n}){var b;const[r,a]=j.useState(((b=n[0])==null?void 0:b.id)||""),{data:i,isLoading:l}=a4n(r||void 0),o=i4n(),c=o4n(),[d,u]=j.useState(""),[h,m]=j.useState("medium"),[p,x]=j.useState(""),y=async()=>{if(!(!d.trim()||!r))try{await o.mutateAsync({stage_id:r,title:d.trim(),priority:h,default_due_offset_days:p?parseInt(p):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),x(""),re.success("Template added")}catch{re.error("Failed to add template")}},g=async v=>{try{await c.mutateAsync(v),re.success("Template deleted")}catch{re.error("Failed to delete template")}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[560px]",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(OW,{className:"h-5 w-5"}),"Task Templates by Stage"]})}),e.jsx("p",{className:"text-sm text-muted-foreground -mt-2",children:"Create default tasks that auto-populate when a deal enters a stage."}),e.jsxs("div",{children:[e.jsx(se,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:n.filter(v=>!v.is_won_stage&&!v.is_lost_stage).map(v=>e.jsx("button",{onClick:()=>a(v.id),className:Et("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",r===v.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:v.name},v.id))})]}),e.jsx(lo,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((v,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:S4n[v.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:v.title}),v.default_due_offset_days&&e.jsxs(qe,{variant:"outline",className:"text-[10px]",children:["+",v.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>g(v.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(Rn,{className:"h-3.5 w-3.5 text-destructive"})})]},v.id)),(i==null?void 0:i.length)===0&&r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),r&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Task title...",value:d,onChange:v=>u(v.target.value),className:"flex-1",onKeyDown:v=>v.key==="Enter"&&y()}),e.jsxs(vs,{value:h,onValueChange:v=>m(v),children:[e.jsx(gs,{className:"w-[100px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"low",children:"🟢 Low"}),e.jsx(Je,{value:"medium",children:"🟡 Med"}),e.jsx(Je,{value:"high",children:"🟠 High"}),e.jsx(Je,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(ye,{type:"number",placeholder:"e.g., 7",value:p,onChange:v=>x(v.target.value)})]}),e.jsxs(B,{onClick:y,disabled:!d.trim()||o.isPending,children:[e.jsx(Js,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function A4n(){const{data:s,isLoading:t}=JSn(),{data:n}=yee(),[r,a]=j.useState("list"),[i,l]=j.useState(""),[o,c]=j.useState("active"),[d,u]=j.useState("all"),[h,m]=j.useState("all"),[p,x]=j.useState(!1),[y,g]=j.useState(!1),b=j.useMemo(()=>{if(!s)return[];const C=new Map;return s.forEach(T=>{T.deal&&C.set(T.deal.id,T.deal.deal_name)}),Array.from(C,([T,M])=>({id:T,name:M}))},[s]),v=j.useMemo(()=>s?s.filter(C=>{var O,$,q,W;const T=i.toLowerCase(),M=!T||C.title.toLowerCase().includes(T)||(($=(O=C.deal)==null?void 0:O.deal_name)==null?void 0:$.toLowerCase().includes(T))||`${((q=C.contact)==null?void 0:q.first_name)||""} ${((W=C.contact)==null?void 0:W.last_name)||""}`.toLowerCase().includes(T),P=o==="all"||o==="active"&&C.status!=="done"||o==="todo"&&C.status==="todo"||o==="in_progress"&&C.status==="in_progress"||o==="done"&&C.status==="done"||o==="overdue"&&C.status!=="done"&&C.due_date&&F5(Ep(C.due_date))&&!Jg(Ep(C.due_date)),L=d==="all"||C.priority===d,I=h==="all"||h==="no_deal"&&!C.deal_id||C.deal_id===h;return M&&P&&L&&I}):[],[s,i,o,d,h]),k=j.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const C=s.filter(T=>T.status!=="done");return{total:C.length,overdue:C.filter(T=>T.due_date&&F5(Ep(T.due_date))&&!Jg(Ep(T.due_date))).length,dueToday:C.filter(T=>T.due_date&&Jg(Ep(T.due_date))).length,dueThisWeek:C.filter(T=>T.due_date&&Fhs(Ep(T.due_date))).length,completed:s.filter(T=>T.status==="done").length}},[s]);return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>g(!0),children:[e.jsx(Nj,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(B,{size:"sm",onClick:()=>x(!0),children:[e.jsx(Js,{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(ug,{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(hd,{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(Vr,{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(Vc,{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(Rr,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search tasks...",value:i,onChange:C=>l(C.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:d,onValueChange:u,children:[e.jsx(gs,{className:"w-[130px]",children:e.jsx(bs,{placeholder:"Priority"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Priorities"}),e.jsx(Je,{value:"urgent",children:"🔴 Urgent"}),e.jsx(Je,{value:"high",children:"🟠 High"}),e.jsx(Je,{value:"medium",children:"🟡 Medium"}),e.jsx(Je,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{className:"w-[160px]",children:e.jsx(bs,{placeholder:"Deal"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Deals"}),e.jsx(Je,{value:"no_deal",children:"No Deal"}),b.map(C=>e.jsx(Je,{value:C.id,children:C.name},C.id))]})]}),e.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[e.jsx("button",{onClick:()=>a("list"),className:`p-1.5 rounded-md transition-colors ${r==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(ug,{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(v3,{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(Vc,{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(b4n,{tasks:v}),r==="kanban"&&e.jsx(j4n,{tasks:v}),r==="calendar"&&e.jsx(k4n,{tasks:v})]}),e.jsx(sBt,{open:p,onOpenChange:x}),e.jsx(C4n,{open:y,onOpenChange:g,stages:n||[]})]})})}function T4n(s){const t=aYe(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function E4n({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 ure({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:Et("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 M4n(){const s=Hn(),{data:t,isLoading:n}=zSn(),r=yTe(),[a,i]=j.useState(""),[l,o]=j.useState(!1),[c,d]=j.useState("all"),u=j.useMemo(()=>{let v=t||[];c==="contract"&&(v=v.filter(C=>!!C.contract_date));const k=a.trim().toLowerCase();return k&&(v=v.filter(C=>{var T,M,P,L;return((T=C.deal_name)==null?void 0:T.toLowerCase().includes(k))||((M=C.property_address)==null?void 0:M.toLowerCase().includes(k))||`${((P=C.contact)==null?void 0:P.first_name)??""} ${((L=C.contact)==null?void 0:L.last_name)??""}`.toLowerCase().includes(k)})),v},[t,a,c]),h=j.useMemo(()=>{const v=[];return(u||[]).forEach(k=>{mW.forEach(C=>{const T=k[C.key],M=zk(T);T&&M!==null&&M<=30&&v.push({id:`${k.id}-${C.key}`,kind:"date",label:C.label,dealId:k.id,dealName:k.deal_name,date:T,days:M})}),k.tasks.filter(C=>C.status!=="done"&&C.due_date).forEach(C=>{const T=zk(C.due_date);T!==null&&T<=30&&v.push({id:C.id,kind:"task",label:C.title,dealId:k.id,dealName:k.deal_name,date:C.due_date,days:T,priority:C.priority})})}),v.sort((k,C)=>k.days-C.days)},[u]),m=j.useMemo(()=>({overdue:h.filter(v=>v.days<0),today:h.filter(v=>v.days===0),week:h.filter(v=>v.days>0&&v.days<=7),later:h.filter(v=>v.days>7)}),[h]),p=j.useMemo(()=>{const v=t||[],k=v.filter(M=>{const P=zk(M.target_close_date);return P!==null&&P>=0&&P<=7}).length,C=v.reduce((M,P)=>M+P.tasks.filter(L=>{const I=zk(L.due_date);return L.status!=="done"&&I!==null&&I<0}).length,0),T=v.reduce((M,P)=>M+(Number(P.expected_price)||0),0);return{active:v.length,closingSoon:k,overdueTasks:C,volume:T}},[t]),x=v=>v.tasks.length===0?0:v.tasks.filter(k=>k.status==="done").length/v.tasks.length*100,y=v=>s(`/mission-control/pipeline?deal=${v}`),g=async v=>{try{await r.mutateAsync({id:v,status:"done"}),re.success("Task completed")}catch{re.error("Could not update task")}},b=({title:v,items:k,tone:C})=>{if(k.length===0)return null;const T=C==="danger"?"bg-destructive":C==="warn"?"bg-amber-500":"bg-primary";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx("span",{className:Et("h-1.5 w-1.5 rounded-full",T)}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:v}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",k.length,")"]})]}),k.slice(0,12).map(M=>e.jsxs("div",{className:Et("group flex items-center gap-3 rounded-lg border px-3 py-2 transition-colors hover:bg-muted/50",C==="danger"&&"border-destructive/30 bg-destructive/5"),children:[M.kind==="task"?e.jsx(wi,{className:"shrink-0",onCheckedChange:()=>g(M.id),"aria-label":`Complete ${M.label}`}):e.jsx(ym,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>y(M.dealId),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"text-sm font-medium leading-tight truncate",children:M.label}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[M.dealName," · ",T4n(M.date)]})]}),e.jsx("span",{className:Et("text-[11px] font-semibold shrink-0 tabular-nums",M.days<0?"text-destructive":M.days<=3?"text-amber-600":"text-muted-foreground"),children:M.days<0?`${Math.abs(M.days)}d late`:M.days===0?"Today":`${M.days}d`})]},M.id))]})};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"p-4 sm:p-6 space-y-6 max-w-[1400px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Transaction Coordinator"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every deadline, every checklist, one screen. Nothing slips."})]}),e.jsxs(B,{onClick:()=>o(!0),className:"gap-2 shrink-0",children:[e.jsx(Op,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(ure,{icon:r1,label:"Active transactions",value:p.active}),e.jsx(ure,{icon:Fd,label:"Closing within 7 days",value:p.closingSoon,tone:"warn"}),e.jsx(ure,{icon:hd,label:"Overdue tasks",value:p.overdueTasks,tone:p.overdueTasks>0?"danger":"good"}),e.jsx(ure,{icon:kl,label:"Pipeline volume",value:p.volume>=1e6?`$${(p.volume/1e6).toFixed(1)}M`:`$${Math.round(p.volume/1e3)}K`,tone:"good"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search transactions, addresses, or clients...",value:a,onChange:v=>i(v.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-1 rounded-lg border p-1 bg-card",children:[e.jsx(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(Wt,{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(ym,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"text-sm font-semibold",children:"Deadline Radar"}),e.jsx(qe,{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(Rr,{className:"h-8 w-8 text-emerald-500 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing due in the next 30 days."})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(b,{title:"Overdue",items:m.overdue,tone:"danger"}),e.jsx(b,{title:"Today",items:m.today,tone:"warn"}),e.jsx(b,{title:"This week",items:m.week,tone:"warn"}),e.jsx(b,{title:"Coming up",items:m.later,tone:"default"})]})]})}),e.jsx("div",{className:"lg:col-span-3 space-y-3",children:u.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed p-12 text-center",children:[e.jsx(ia,{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(v=>{const k=x(v),C=zk(v.target_close_date),T=v.tasks.filter(L=>L.status!=="done"),M=T.filter(L=>{const I=zk(L.due_date);return I!==null&&I<0}),P=T.filter(L=>L.due_date).sort((L,I)=>(zk(L.due_date)??0)-(zk(I.due_date)??0))[0];return e.jsx("button",{type:"button",onClick:()=>y(v.id),className:"w-full text-left rounded-xl border bg-card p-4 hover:border-primary/40 hover:shadow-sm transition-all group",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(E4n,{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:v.deal_name}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[v.property_address||"Address TBD",v.contact&&` · ${v.contact.first_name} ${v.contact.last_name}`]})]}),e.jsx(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:[v.stage&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:`${v.stage.color}1f`,color:v.stage.color},children:v.stage.name}),e.jsx(qe,{variant:"outline",className:"text-[10px] capitalize",children:v.deal_type}),C!==null&&e.jsx(qe,{variant:"secondary",className:Et("text-[10px]",C<0&&"bg-destructive/10 text-destructive",C>=0&&C<=7&&"bg-amber-500/10 text-amber-700 dark:text-amber-400"),children:C<0?`Closing ${Math.abs(C)}d overdue`:`Closes in ${C}d`}),M.length>0&&e.jsxs(qe,{className:"text-[10px] bg-destructive/10 text-destructive hover:bg-destructive/10",children:[M.length," overdue"]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(qi,{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:[v.tasks.filter(L=>L.status==="done").length," of"," ",v.tasks.length," steps complete"]}),P&&e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate max-w-[55%]",children:["Next: ",P.title]})]})]}),v.tasks.length===0&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2 italic",children:"No checklist yet — open the deal and apply a playbook."})]})]})},v.id)})})]})]}),e.jsx(Jzt,{open:l,onOpenChange:o})]})}function nBt(){const s=ei();return mt({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("portal_referrals").select("*, client_portals!inner(slug, client_name, deal_id)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function L4n(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("portal_referrals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function P4n(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("portal_referrals").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const I4n=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),GIe=[{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"}],R4n={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function rBt(){const{data:s=[],isLoading:t}=nBt(),n=L4n(),r=P4n(),[a,i]=j.useState("all"),[l,o]=j.useState({}),c=j.useMemo(()=>a==="all"?s:s.filter(p=>p.status===a),[s,a]),d=j.useMemo(()=>({total:s.length,new:s.filter(p=>p.status==="new").length,converted:s.filter(p=>p.status==="converted").length}),[s]),u=(p,x)=>{n.mutate({id:p.id,status:x}),re.success("Status updated")},h=p=>{const x=l[p.id];n.mutate({id:p.id,agent_notes:x}),o(y=>{const{[p.id]:g,...b}=y;return b}),re.success("Notes saved")},m=async p=>{await Bi(`Delete referral for ${p.friend_name}?`)&&r.mutate(p.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(ql,{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(zo,{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"},...GIe.map(p=>({v:p.value,l:p.label}))].map(p=>e.jsx("button",{onClick:()=>i(p.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===p.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:p.l},p.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center",children:[e.jsx(zo,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once your closed clients refer friends from their portal, they'll show up here."})]})}):e.jsx("div",{className:"space-y-3",children:c.map(p=>{var b,v;const x=GIe.find(k=>k.value===p.status),y=(b=p.client_portals)==null?void 0:b.slug,g=p.referrer_name||((v=p.client_portals)==null?void 0:v.client_name)||"Anonymous client";return e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:p.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(ra,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:g})," ·"," ",I4n(p.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"outline",className:x==null?void 0:x.className,children:(x==null?void 0:x.label)||p.status}),e.jsxs(vs,{value:p.status,onValueChange:k=>u(p,k),children:[e.jsx(gs,{className:"h-8 w-[130px] text-xs",children:e.jsx(bs,{})}),e.jsx(ys,{children:GIe.map(k=>e.jsx(Je,{value:k.value,className:"text-xs",children:k.label},k.value))})]})]})]})}),e.jsxs(Re,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[p.friend_interest&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:R4n[p.friend_interest]||p.friend_interest}),p.friend_email&&e.jsxs("a",{href:`mailto:${p.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(on,{className:"h-3 w-3"}),p.friend_email]}),p.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${p.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(pa,{className:"h-3 w-3"}),p.friend_phone]}),e.jsxs("a",{href:`sms:${p.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Yd,{className:"h-3 w-3"}),"Text"]})]})]}),p.friend_message&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-3 text-sm",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Note from referrer"}),e.jsxs("p",{className:"italic text-foreground",children:['"',p.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[p.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ds,{value:l[p.id],onChange:k=>o(C=>({...C,[p.id]:k.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:()=>h(p),children:"Save"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>o(k=>{const{[p.id]:C,...T}=k;return T}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(k=>({...k,[p.id]:p.agent_notes||""})),className:"text-sm text-left w-full p-2 rounded border border-dashed border-input hover:border-primary/50 hover:bg-muted/30 transition-colors",children:p.agent_notes||e.jsx("span",{className:"text-muted-foreground italic",children:"Click to add notes..."})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[y&&e.jsxs("a",{href:`/portal/${y}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary inline-flex items-center gap-1",children:[e.jsx(Tr,{className:"h-3 w-3"}),"View source portal"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>m(p),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]})]},p.id)})})]})}function aBt({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=JU.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(be,{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(du,{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(qe,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(qe,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(qe,{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(pa,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(on,{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(Ql,{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(ra,{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(oi,{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(ma,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(n0,{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(kp,{className:"w-3.5 h-3.5"})}),n&&e.jsx(B,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(Rn,{className:"w-3.5 h-3.5"})})]})]})}function iBt({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=S_s(),[c,d]=j.useState({}),[u,h]=j.useState(!1),m=j.useRef(null),p=async g=>{if(!g.type.startsWith("image/")){re.error("Please select an image");return}if(g.size>5*1024*1024){re.error("Image must be under 5MB");return}h(!0);try{const b=g.name.split(".").pop()||"png",v=`${r}/${a||i||"misc"}/${Date.now()}.${b}`,{error:k}=await U.storage.from("vendor-logos").upload(v,g,{upsert:!0,contentType:g.type});if(k)throw k;const{data:C}=U.storage.from("vendor-logos").getPublicUrl(v);d(T=>({...T,logo_url:C.publicUrl})),re.success("Logo uploaded")}catch(b){re.error(b.message||"Upload failed")}finally{h(!1)}};j.useEffect(()=>{s&&d(n||{owner_type:r,owner_brokerage_id:r==="brokerage"&&a||null,owner_user_id:r==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,n,r,a,i]);const x=(g,b)=>d(v=>({...v,[g]:b})),y=async()=>{var g;if(!((g=c.name)!=null&&g.trim())){re.error("Name is required");return}try{await o.mutateAsync(c),re.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(b){re.error(b.message||"Failed to save vendor")}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:n?"Edit Vendor":"Add Vendor"})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Contact Name *"}),e.jsx(ye,{value:c.name||"",onChange:g=>x("name",g.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Company"}),e.jsx(ye,{value:c.company||"",onChange:g=>x("company",g.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(vs,{value:c.category,onValueChange:g=>x("category",g),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:JU.map(g=>e.jsx(Je,{value:g.value,children:g.label},g.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:c.phone||"",onChange:g=>x("phone",g.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{type:"email",value:c.email||"",onChange:g=>x("email",g.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Website"}),e.jsx(ye,{value:c.website||"",onChange:g=>x("website",g.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Logo"}),e.jsx("input",{ref:m,type:"file",accept:"image/*",className:"hidden",onChange:g=>{var v;const b=(v=g.target.files)==null?void 0:v[0];b&&p(b),g.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[c.logo_url?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:c.logo_url,alt:"Vendor logo",className:"h-14 w-14 rounded-md object-cover border"}),e.jsx("button",{type:"button",onClick:()=>x("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(dr,{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(Ja,{className:"h-5 w-5"})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var g;return(g=m.current)==null?void 0:g.click()},disabled:u,children:[u?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ja,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Address"}),e.jsx(ye,{value:c.address||"",onChange:g=>x("address",g.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{rows:3,value:c.description||"",onChange:g=>x("description",g.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Primary Action"}),e.jsxs(vs,{value:c.action_type,onValueChange:g=>x("action_type",g),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:j_s.map(g=>e.jsx(Je,{value:g.value,children:g.label},g.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Booking URL (Calendly etc.)"}),e.jsx(ye,{value:c.booking_url||"",onChange:g=>x("booking_url",g.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Compliance Disclosure (optional)"}),e.jsx(Ds,{rows:2,value:c.disclosure_text||"",onChange:g=>x("disclosure_text",g.target.value),placeholder:"e.g. Agent receives no compensation for this referral."})]}),e.jsxs("div",{className:"flex items-center justify-between md:col-span-2 border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(Mn,{checked:!!c.is_active,onCheckedChange:g=>x("is_active",g)})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(Mn,{checked:!!c.is_featured,onCheckedChange:g=>x("is_featured",g)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(Mn,{checked:!!c.is_required,onCheckedChange:g=>x("is_required",g)})]})]})]}),e.jsxs(Nr,{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 oBt({embedded:s=!1}={}){const t=ei(),{brokerageId:n}=Ns(),{data:r,isLoading:a}=k_s(),{data:i={}}=j3t("agent",t),l=_3t(),o=C_s(),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,p]=j.useState(""),[x,y]=j.useState("all"),g=(r==null?void 0:r.vendors)||[],b=(r==null?void 0:r.selections)||[],v=j.useMemo(()=>{const O=new Map;return b.forEach($=>O.set($.vendor_id,$.is_visible)),O},[b]),k=j.useMemo(()=>g.filter(O=>!(x!=="all"&&O.category!==x||m&&!`${O.name} ${O.company||""}`.toLowerCase().includes(m.toLowerCase()))),[g,m,x]),C=k.filter(O=>O.owner_type==="agent"),T=k.filter(O=>O.owner_type==="brokerage"),M=async O=>{if(await Bi("Delete this vendor?"))try{await l.mutateAsync(O),re.success("Vendor deleted")}catch($){re.error($.message)}},P=async(O,$)=>{try{await o.mutateAsync({vendorId:O,isVisible:$})}catch(q){re.error(q.message)}},L=O=>O.is_required?!0:v.get(O.id)??O.owner_type==="agent",I=e.jsxs("div",{className:s?"space-y-6":"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(kx,{className:"w-6 h-6 text-primary"}),"My Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Curate trusted partners that show up in your client portals — inspector, lender, movers and more."})]}),e.jsxs(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(Js,{className:"w-4 h-4 mr-2"})," Add Personal Vendor"]})]}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Fr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:O=>p(O.target.value)})]}),e.jsxs("select",{value:x,onChange:O=>y(O.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),JU.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(fa,{defaultValue:n?"all":"personal",children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"all",children:["All (",k.length,")"]}),n&&e.jsxs(ss,{value:"brokerage",children:["From Brokerage (",T.length,")"]}),e.jsxs(ss,{value:"personal",children:["My Personal (",C.length,")"]})]}),e.jsx(ns,{value:"all",className:"mt-4",children:e.jsx(WIe,{vendors:k,isVisibleInPortals:L,onToggle:P,onEdit:O=>{d(O),h(!0)},onDelete:M,userId:t,clicks:i})}),n&&e.jsx(ns,{value:"brokerage",className:"mt-4",children:T.length===0?e.jsx(ygt,{icon:e.jsx(yn,{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(WIe,{vendors:T,isVisibleInPortals:L,onToggle:P,userId:t,clicks:i})}),e.jsx(ns,{value:"personal",className:"mt-4",children:C.length===0?e.jsx(ygt,{icon:e.jsx(kx,{className:"w-12 h-12"}),title:"No personal vendors yet",desc:"Add your trusted inspector, lender, mover — they'll show in every client portal you create.",action:e.jsxs(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(Js,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(WIe,{vendors:C,isVisibleInPortals:L,onToggle:P,onEdit:O=>{d(O),h(!0)},onDelete:M,userId:t,clicks:i})})]}),e.jsx(iBt,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?I:e.jsx(Vs,{children:I})}function WIe({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(aBt,{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 ygt({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 D4n(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=Ns(),{data:a=[],isLoading:i}=N_s(s),{data:l={}}=j3t("brokerage",s),o=_3t(),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,p]=j.useState(""),[x,y]=j.useState("all");if(r)return e.jsx(Vs,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx(Vs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const g=a.filter(v=>!(x!=="all"&&v.category!==x||m&&!`${v.name} ${v.company||""}`.toLowerCase().includes(m.toLowerCase()))),b=async v=>{if(await Bi("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(v),re.success("Vendor deleted")}catch(k){re.error(k.message)}};return e.jsx(Vs,{children:e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Ni,{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(Js,{className:"w-4 h-4 mr-2"})," Add Vendor"]})]}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Fr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:v=>p(v.target.value)})]}),e.jsxs("select",{value:x,onChange:v=>y(v.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),JU.map(v=>e.jsx("option",{value:v.value,children:v.label},v.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):g.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(Ni,{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(Js,{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:g.map(v=>e.jsx(aBt,{vendor:v,onEdit:()=>{d(v),h(!0)},onDelete:()=>b(v.id),clickCount:l[v.id]},v.id))}),e.jsx(iBt,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const O4n=[{value:"overview",label:"Portals",icon:r0},{value:"vendors",label:"Vendors",icon:fN},{value:"referrals",label:"Referrals",icon:zo},{value:"branding",label:"Branding",icon:Ac},{value:"questions",label:"Onboarding",icon:zp}];function F4n(){const[s,t]=dc(),n=s.get("tab")||"overview",[r,a]=j.useState(n),[i,l]=j.useState(!1),[o,c]=j.useState(!1);return j.useEffect(()=>{t(d=>{const u=new URLSearchParams(d);return u.set("tab",r),u},{replace:!0})},[r,t]),e.jsxs(Vs,{children:[e.jsx(ql,{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(yn,{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(_K,{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(Yn,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(fa,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(xa,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:O4n.map(d=>e.jsxs(ss,{value:d.value,className:"gap-2",children:[e.jsx(d.icon,{className:"w-4 h-4"}),d.label]},d.value))}),e.jsx(ns,{value:"overview",className:"mt-6",children:e.jsx(tBt,{})}),e.jsx(ns,{value:"vendors",className:"mt-6",children:e.jsx(z4n,{})}),e.jsx(ns,{value:"referrals",className:"mt-6",children:e.jsx(B4n,{})}),e.jsx(ns,{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(Ac,{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(ic,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(ns,{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(zp,{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(ic,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(eBt,{open:i,onOpenChange:l}),e.jsx(Qzt,{open:o,onOpenChange:c})]})}function z4n(){return e.jsx(oBt,{embedded:!0})}function B4n(){return e.jsx(rBt,{})}const d7=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function $4n(s){return mt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("client_portals").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return{portal:null,deal:null};const{data:r,error:a}=await U.from("deal_pipeline").select("deal_name, contact_id").eq("id",t.deal_id).maybeSingle();if(a)throw a;let i=null;if(r!=null&&r.contact_id){const{data:l,error:o}=await U.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",r.contact_id).maybeSingle();if(o)throw o;i=l}return{portal:t,deal:r?{deal_name:r.deal_name,contact_id:r.contact_id,contact:i}:null}},enabled:!!s})}function U4n(){const{portalId:s}=$i(),t=Hn(),n=ei(),{data:r,isLoading:a}=$4n(s),{data:i=[]}=j0n(s),{data:l=[]}=nBt(),o=Eq(),c=ERt(),d=MRt(),u=LRt(),[h,m]=j.useState(!1),[p,x]=j.useState(!1),[y,g]=j.useState(!1),[b,v]=j.useState(!1),k=(r==null?void 0:r.portal)??null,C=(r==null?void 0:r.deal)??null,T=j.useMemo(()=>k?l.filter(ee=>ee.portal_id===k.id):[],[l,k==null?void 0:k.id]);if(a)return e.jsx(Vs,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!k)return e.jsx(Vs,{children:e.jsxs("div",{className:"max-w-3xl mx-auto p-8 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold mb-2",children:"Portal not found"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"This portal may have been deleted or you don't have access to it."}),e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs(Yn,{to:"/mission-control/client-portals",children:[e.jsx(_a,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const M=q5(k.slug),P=(C==null?void 0:C.deal_name)||"Untitled deal",L=C==null?void 0:C.contact,I=L?`${L.first_name||""} ${L.last_name||""}`.trim():"",O=!!k.archived_at,$=()=>{navigator.clipboard.writeText(M),re.success("Portal link copied!")},q=async ee=>{try{await o.mutateAsync({id:k.id,is_enabled:ee}),re.success(ee?"Portal enabled":"Portal disabled")}catch{re.error("Failed to update")}},W=async()=>{try{await c.mutateAsync(k.id),re.success("Portal archived")}catch{re.error("Failed to archive")}},G=async()=>{try{await d.mutateAsync(k.id),re.success("Portal restored")}catch{re.error("Failed to restore")}},K=async()=>{try{await u.mutateAsync({id:k.id,dealId:k.deal_id}),re.success("Portal deleted"),t("/mission-control/client-portals")}catch{re.error("Failed to delete")}};return e.jsxs(Vs,{children:[e.jsx(ql,{children:e.jsxs("title",{children:[P," — Client Portal"]})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{children:e.jsx(B,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(Yn,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(_a,{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(yn,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:P}),e.jsx(qe,{variant:"outline",className:O?"bg-muted text-muted-foreground":k.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:O?"Archived":k.is_enabled?"Active":"Disabled"}),e.jsx(qe,{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(Eo,{className:"w-3.5 h-3.5"}),k.client_name||I||"No client name set",(L==null?void 0:L.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(on,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:L.email})]}),(L==null?void 0:L.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(pa,{className:"w-3.5 h-3.5"}),L.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:M})})]}),!O&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(Mn,{checked:k.is_enabled,onCheckedChange:q})]})]}),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(ja,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(B,{onClick:()=>window.open(M,"_blank"),variant:"outline",size:"sm",children:[e.jsx(Tr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(B,{onClick:()=>g(!0),size:"sm",children:[e.jsx(Dr,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(B,{onClick:()=>x(!0),variant:"outline",size:"sm",children:[e.jsx(v5,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(B,{onClick:()=>m(!0),variant:"outline",size:"sm",children:[e.jsx(ic,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[O?e.jsxs(B,{onClick:G,variant:"outline",size:"sm",children:[e.jsx(zT,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(B,{onClick:W,variant:"ghost",size:"sm",children:[e.jsx(gm,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx(B,{onClick:()=>v(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(hre,{icon:v5,label:"Updates Posted",value:i.length}),e.jsx(hre,{icon:zo,label:"Referrals",value:T.length}),e.jsx(hre,{icon:ra,label:"Inspection",value:k.inspection_date?d7(k.inspection_date):"—"}),e.jsx(hre,{icon:ra,label:"Appraisal",value:k.appraisal_date?d7(k.appraisal_date):"—"})]}),e.jsxs(fa,{defaultValue:"updates",className:"w-full",children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"updates",children:["Updates (",i.length,")"]}),e.jsxs(ss,{value:"referrals",children:["Referrals (",T.length,")"]}),e.jsx(ss,{value:"branding",children:"Branding"}),e.jsx(ss,{value:"details",children:"Details"})]}),e.jsx(ns,{value:"updates",className:"mt-4",children:e.jsx(be,{children:e.jsxs(Re,{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:()=>x(!0),children:[e.jsx(v5,{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(v5,{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(ee=>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:ee.title}),ee.is_stage_change&&e.jsx(qe,{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:d7(ee.created_at)}),ee.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:ee.content}),ee.video_url&&e.jsxs("a",{href:ee.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(Zr,{className:"w-3 h-3"})," View video"]})]})})},ee.id))})]})})}),e.jsx(ns,{value:"referrals",className:"mt-4",children:e.jsx(be,{children:e.jsxs(Re,{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(zo,{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(ee=>e.jsx(Yn,{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:ee.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ee.friend_email||ee.friend_phone||"No contact info"," · ",d7(ee.created_at)]})]}),e.jsx(qe,{variant:"outline",className:"text-xs capitalize",children:ee.status})]})},ee.id))})]})})}),e.jsx(ns,{value:"branding",className:"mt-4",children:e.jsx(be,{children:e.jsx(Re,{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(Ac,{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(ic,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(ns,{value:"details",className:"mt-4",children:e.jsx(be,{children:e.jsxs(Re,{className:"p-6 space-y-4",children:[e.jsx(BC,{label:"Visibility",value:k.visibility}),e.jsx(BC,{label:"Onboarding Required",value:k.require_onboarding?"Yes":"No"}),e.jsx(BC,{label:"Allow Spouse",value:k.allow_spouse?"Yes":"No"}),e.jsx(BC,{label:"Notify Client on Updates",value:k.notify_client?"Yes":"No"}),e.jsx(BC,{label:"Show Post-Close Tips",value:k.show_post_close_tips?"Yes":"No"}),e.jsx(BC,{label:"Slug",value:k.slug,mono:!0}),e.jsx(BC,{label:"Created",value:d7(k.created_at)}),e.jsx(BC,{label:"Last Updated",value:d7(k.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(B,{variant:"outline",onClick:()=>m(!0),children:[e.jsx(ic,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(sYe,{open:h,onOpenChange:m,portal:k,dealOwnerId:n||""}),e.jsx(nYe,{open:p,onOpenChange:x,portalId:k.id,portalSlug:k.slug,notifyClient:k.notify_client}),e.jsx(rYe,{open:y,onOpenChange:g,portal:k,dealName:P}),e.jsx(Nl,{open:b,onOpenChange:v,children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Permanently delete this portal?"}),e.jsx(xl,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:K,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function hre({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 BC({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 CBe=[{value:"video_intro",label:"Video Intro",icon:Zr,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:w3,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:wf,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:Rc,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:zd,description:"Links to your social profiles"}],q4n=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],V4n={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function lBt({cardId:s}){const{data:t,isLoading:n}=Scs(s),r=Ccs(),a=Acs(),i=Tcs(),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(null);if(n)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(gn,{className:"h-16 w-full"}),e.jsx(gn,{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:V4n[c]||{}},{onSuccess:()=>{o(!1),d("")}})},p=v=>{a.mutate({id:v.id,is_visible:!v.is_visible})},x=(v,k)=>{if(!t)return;const C=t.findIndex(P=>P.id===v.id),T=k==="up"?C-1:C+1;if(T<0||T>=t.length)return;const M=t[T];a.mutate({id:v.id,sort_order:M.sort_order}),a.mutate({id:M.id,sort_order:v.sort_order})},y=async v=>{await Bi("Remove this block from this card?")&&i.mutate(v.id)},g=(v,k)=>{a.mutate({id:v.id,config:k},{onSuccess:()=>h(null)})},b=v=>CBe.find(k=>k.value===v);return e.jsxs("div",{className:"space-y-3",children:[!t||t.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-muted-foreground mb-4 text-sm",children:"No blocks yet. Add a block to customize this card."}),e.jsxs(B,{size:"sm",onClick:()=>o(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((v,k)=>{const C=b(v.block_type),T=(C==null?void 0:C.icon)||wf;return e.jsx(be,{className:v.is_visible?"":"opacity-50",children:e.jsx(Re,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fp,{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:(C==null?void 0:C.label)||v.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:H4n(v)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>x(v,"up"),disabled:k===0,children:e.jsx(Gm,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>x(v,"down"),disabled:k===t.length-1,children:e.jsx(tx,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>p(v),children:v.is_visible?e.jsx(ma,{className:"h-3 w-3"}):e.jsx(n0,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>h(v),children:"Edit"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>y(v),children:e.jsx(Rn,{className:"h-3 w-3"})})]})]})})},v.id)}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(Fs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:CBe.map(v=>{const k=v.icon;return e.jsxs("button",{onClick:()=>d(v.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===v.value?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[e.jsx(k,{className:"h-5 w-5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:v.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v.description})]})]},v.value)})}),e.jsxs(Nr,{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(G4n,{block:u,onSave:v=>g(u,v),onClose:()=>h(null)})]})}function H4n(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 G4n({block:s,onSave:t,onClose:n}){const[r,a]=j.useState(s.config),i=CBe.find(l=>l.value===s.block_type);return e.jsx(Fs,{open:!0,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsxs(zs,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(W4n,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(K4n,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(Y4n,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(Z4n,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(X4n,{config:r,onChange:a}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(B,{onClick:()=>t(r),children:"Save"})]})]})})}function W4n({config:s,onChange:t,cardId:n}){var p,x;const[r,a]=j.useState(""),[i,l]=j.useState((p=s.video_url)!=null&&p.includes("youtube")||(x=s.video_url)!=null&&x.includes("youtu.be")?"youtube":"library"),{data:o}=mt({queryKey:["card-owner",n],queryFn:async()=>{const{data:y}=await U.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:g}=await U.from("agent_videos").select("id, title, bunny_video_id, thumbnail_url, playback_url, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(g)throw g;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 g=(k=y.playback_url)==null?void 0:k.match(/\/(?:play|embed)\/(\d+)\//),v=`https://iframe.mediadelivery.net/embed/${g?g[1]:"570924"}/${y.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:v,bunny_video_id:y.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(fa,{value:i,onValueChange:l,children:[e.jsxs(xa,{className:"w-full",children:[e.jsx(ss,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(ss,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(ns,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{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(gn,{className:"h-14 w-full"}),e.jsx(gn,{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:g=>{var b;g.currentTarget.style.display="none",(b=g.currentTarget.nextElementSibling)==null||b.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${y.thumbnail_url?"hidden":""}`,children:e.jsx(Zr,{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(da,{className:"h-4 w-4 text-primary flex-shrink-0"})]},y.id))})})]}),e.jsx(ns,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(se,{children:"YouTube URL"}),e.jsx(ye,{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 K4n({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(be,{children:e.jsxs(Re,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(se,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),n.length>1&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(Rn,{className:"h-3 w-3"})})]}),e.jsx(ye,{placeholder:"Client name",value:l.name,onChange:c=>r(o,"name",c.target.value)}),e.jsx(ye,{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(Js,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function Y4n({config:s,onChange:t}){const n=s.tags||[],[r,a]=j.useState(""),i=o=>{t({...s,tags:n.includes(o)?n.filter(c=>c!==o):[...n,o]})},l=()=>{r.trim()&&!n.includes(r.trim())&&(t({...s,tags:[...n,r.trim()]}),a(""))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:q4n.map(o=>e.jsx("button",{onClick:()=>i(o),className:`px-3 py-1.5 text-xs rounded-full border transition-colors ${n.includes(o)?"bg-primary text-primary-foreground border-primary":"bg-muted border-border hover:bg-muted/80"}`,children:o},o))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{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(se,{className:"text-xs text-muted-foreground mb-1 block",children:["Selected (",n.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(o=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 text-xs bg-primary/10 text-primary rounded-full",children:[o,e.jsx("button",{onClick:()=>i(o),className:"hover:text-destructive",children:"×"})]},o))})]})]})}function Z4n({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(ye,{placeholder:"Button label",value:l.label,onChange:c=>r(o,"label",c.target.value)}),e.jsx(ye,{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(Rn,{className:"h-3 w-3"})})]},o)),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const vgt=[{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 X4n({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=vgt.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=YDe[c],u=vgt.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(ye,{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(Rn,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground mb-2 block",children:"Add a platform"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(c=>{const d=YDe[c.value];return e.jsxs("button",{onClick:()=>r(c.value),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full border border-border bg-muted hover:bg-muted/80 transition-colors",children:[(d==null?void 0:d.icon)&&e.jsx("svg",{viewBox:"0 0 24 24",width:12,height:12,fill:d.color,children:e.jsx("path",{d:d.icon})}),c.label]},c.value)})})]}),n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Tap a platform above to add your social media profile."})]})}function Q4n({slug:s,agentName:t}){const n=j.useRef(null),r=`https://cards.relevelup.com/${s}`,a=j.useCallback(()=>{var h;const i=(h=n.current)==null?void 0:h.querySelector("svg");if(!i)return;const l=document.createElement("canvas"),o=1024;l.width=o,l.height=o;const c=l.getContext("2d");if(!c)return;const d=new XMLSerializer().serializeToString(i),u=new Image;u.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(u,0,0,o,o);const m=document.createElement("a");m.download=`${s}-qr-code.png`,m.href=l.toDataURL("image/png"),m.click(),re.success("QR code downloaded!")},u.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(d)))},[s]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-sm font-medium",children:"QR Code"}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{ref:n,className:"bg-white p-3 rounded-lg border shadow-sm shrink-0",children:e.jsx(PN,{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(ii,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function KIe(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 J4n(){const{user:s}=Ns(),{data:t,isLoading:n}=jcs(s==null?void 0:s.id),r=Tq(),[a,i]=j.useState(null),l=j.useMemo(()=>a||(t?KIe(t):null),[a,t]);if(n)return e.jsx(Vs,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(gn,{className:"h-8 w-48"}),e.jsx(gn,{className:"h-32 w-full"}),e.jsx(gn,{className:"h-32 w-full"})]})});if(!t)return e.jsx(Vs,{children:e.jsx(t3n,{userId:s==null?void 0:s.id})});const o=l||KIe(t),c=d=>{i(u=>{const h=u||KIe(t);return typeof d=="function"?d(h):d})};return e.jsx(Vs,{children:e.jsxs("div",{className:"flex gap-6 items-start",children:[e.jsxs("div",{className:`${r?"w-full":"flex-1 min-w-0"} max-w-2xl p-4 space-y-6 animate-fade-in`,children:[e.jsx(s3n,{card:t}),e.jsx(i3n,{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(Cj,{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(e3n,{card:t,form:o})})]})})]})})}function e3n({card:s,form:t}){const{data:n}=mt({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await U.from("profiles").select("name, email, phone, avatar_url, brokerage_id").eq("id",s.user_id).single();let i=(a==null?void 0:a.avatar_url)||null;if(!i){const{data:l}=await U.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=U.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),r=j.useMemo(()=>({...s,is_published:t.is_published,theme:t.theme,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,custom_cta_url:s.custom_cta_url,show_photo:t.show_photo,show_bio:t.show_bio,show_video:s.show_video,show_credentials:t.show_credentials,show_social_links:t.show_social_links,show_save_contact:t.show_save_contact,show_leave_review:t.show_leave_review,show_refer_friend:t.show_refer_friend,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,display_email:t.display_email||null,social_links:s.social_links||[],profile:{name:(n==null?void 0:n.name)||null,email:t.display_email||(n==null?void 0:n.email)||null,phone:(n==null?void 0:n.phone)||null,brokerage_id:(n==null?void 0:n.brokerage_id)||null},brokerage_name:t.brokerage_display_name||null,avatar_url:(n==null?void 0:n.avatar_url)||null}),[s,t,n]);return e.jsx("div",{className:"transform scale-[0.85] origin-top",children:e.jsx(rqe,{card:r})})}function t3n({userId:s}){var c;const[t,n]=j.useState(""),r=r5t(),{data:a}=mt({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await U.from("profiles").select("name").eq("id",s).single();return d},enabled:!!s}),i=((c=a==null?void 0:a.name)==null?void 0:c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||"",l=()=>{if(!s)return;const d=(t.trim()||i).toLowerCase().replace(/[^a-z0-9-]/g,"-");if(!d){re.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>re.success("Your digital card has been created!")})},o=[{icon:Ql,title:"Shareable Link",desc:"One link that works everywhere"},{icon:jf,title:"Lead Capture",desc:"Collect leads automatically"},{icon:_f,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:Ac,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(yn,{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(be,{className:"shadow-lg border-2",children:[e.jsxs(Ft,{className:"text-center pb-2",children:[e.jsx(Ut,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(fr,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Re,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Your Card URL"}),e.jsxs("div",{className:"flex items-center gap-0 mt-1.5",children:[e.jsx("span",{className:"inline-flex items-center px-3 h-10 rounded-l-md border border-r-0 bg-muted text-sm text-muted-foreground whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(ye,{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(yn,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function s3n({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),re.success("Card link copied!")};return e.jsx("div",{className:"rounded-xl border bg-card p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:"My Digital Card"}),e.jsx(qe,{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(Ql,{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(ja,{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 n3n({userId:s}){const t=as(),n=j.useRef(null),[r,a]=j.useState(!1),[i,l]=j.useState(""),{data:o,isLoading:c}=mt({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:$}=await U.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let q=($==null?void 0:$.avatar_url)||null;if(!q){const{data:W}=await U.storage.from("avatars").list(`${s}`);if(W&&W.length>0){const{data:G}=U.storage.from("avatars").getPublicUrl(`${s}/${W[0].name}`);q=`${G.publicUrl}?t=${Date.now()}`,await U.from("profiles").update({avatar_url:q}).eq("id",s)}}return{...$,avatar_url:q}}}),[d,u]=j.useState(null),[h,m]=j.useState(null),[p,x]=j.useState(null),[y,g]=j.useState(!1),b=d??(o==null?void 0:o.name)??"",v=h??(o==null?void 0:o.phone)??"",k=p??(o==null?void 0:o.email)??"",C=o==null?void 0:o.avatar_url,T=((o==null?void 0:o.name)||"A").split(" ").map($=>$[0]).join("").toUpperCase().slice(0,2),M=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),P=vt({mutationFn:async $=>{const{error:q}=await U.from("profiles").update($).eq("id",s);if(q)throw q},onSuccess:()=>{t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),re.success("Profile updated!")},onError:()=>re.error("Failed to update profile")}),L=()=>{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),p!==null&&p!==(o==null?void 0:o.email)&&($.email=p),Object.keys($).length===0){re.info("No changes to save");return}P.mutate($)},I=$=>{var G;const q=(G=$.target.files)==null?void 0:G[0];if(!q)return;if(!q.type.startsWith("image/")){re.error("Please select an image file");return}const W=new FileReader;W.onloadend=()=>{l(W.result),a(!0)},W.readAsDataURL(q),$.target.value=""},O=async $=>{g(!0);try{const{data:q}=await U.storage.from("avatars").list(`${s}`);q&&q.length>0&&await U.storage.from("avatars").remove(q.map(J=>`${s}/${J.name}`));const W=`${s}/avatar.jpg`,{error:G}=await U.storage.from("avatars").upload(W,$,{upsert:!0,contentType:"image/jpeg"});if(G)throw G;const{data:K}=U.storage.from("avatars").getPublicUrl(W),ee=K.publicUrl+"?t="+Date.now();await U.from("profiles").update({avatar_url:ee}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),re.success("Photo updated!")}catch{re.error("Failed to upload photo")}finally{g(!1)}};return c?e.jsx(gn,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(be,{className:M?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Re,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(se,{className:"text-sm font-semibold",children:"Profile Info"}),M&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(po,{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(Ra,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(Fi,{src:C||void 0,alt:b}),e.jsx(Da,{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(s0,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:I})]}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:y?"Uploading...":C?"Tap to change photo":"Add a profile photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo appears on your card, profile, and community posts"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(ye,{value:b,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(se,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(ye,{value:v,onChange:$=>m($.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(ye,{value:k,onChange:$=>x($.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:L,disabled:P.isPending,className:"w-full",children:P.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(xHe,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:O,aspectRatio:1})]})}function r3n({form:s,setForm:t,userId:n}){const[r,a]=j.useState(null),[i,l]=j.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=j.useState(s.team_logo_url?"logo":"name"),d=p=>{l(p),t(p==="name"?x=>({...x,brokerage_logo_url:""}):x=>({...x,brokerage_display_name:""}))},u=p=>{c(p),t(p==="name"?x=>({...x,team_logo_url:""}):x=>({...x,team_name:""}))},h=async(p,x)=>{var g;const y=(g=p.target.files)==null?void 0:g[0];if(y){if(!y.type.startsWith("image/")){re.error("Please select an image file");return}a(x);try{const b=y.name.split(".").pop()||"png",k=`${n}/${x==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${b}`,{error:C}=await U.storage.from("card-logos").upload(k,y,{upsert:!0});if(C)throw C;const{data:T}=U.storage.from("card-logos").getPublicUrl(k),M=T.publicUrl+"?t="+Date.now();t(x==="brokerage_logo_url"?P=>({...P,[x]:M,brokerage_display_name:""}):P=>({...P,[x]:M,team_name:""})),re.success("Logo uploaded!")}catch{re.error("Failed to upload logo")}finally{a(null),p.target.value=""}}},m=p=>{t(x=>({...x,[p]:""}))};return e.jsx(be,{children:e.jsxs(Re,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-semibold",children:"Brokerage & Team Branding"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Choose either a name or a logo for each — not both."})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(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(se,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(ye,{value:s.brokerage_display_name,onChange:p=>t(x=>({...x,brokerage_display_name:p.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.brokerage_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${s.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>m("brokerage_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(s0,{className:"h-3.5 w-3.5"}),r==="brokerage_logo_url"?"Uploading...":s.brokerage_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:p=>h(p,"brokerage_logo_url"),disabled:r!==null})]})]}),s.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.brokerage_logo_size||56,"px"]})]}),e.jsx(Qf,{value:[s.brokerage_logo_size||56],onValueChange:([p])=>t(x=>({...x,brokerage_logo_size:p})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(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(se,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(ye,{value:s.team_name,onChange:p=>t(x=>({...x,team_name:p.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Team Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.team_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.team_logo_url,alt:"Team logo",style:{height:`${s.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>m("team_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(s0,{className:"h-3.5 w-3.5"}),r==="team_logo_url"?"Uploading...":s.team_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:p=>h(p,"team_logo_url"),disabled:r!==null})]})]}),s.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.team_logo_size||56,"px"]})]}),e.jsx(Qf,{value:[s.team_logo_size||56],onValueChange:([p])=>t(x=>({...x,team_logo_size:p})),min:24,max:120,step:4})]})]})]})]})})}function a3n({form:s,setForm:t}){const n={accent:"#ff5722",dark:"#1a1a2e",button:"#ff5722"},r=s.bold_theme_colors||n,a=(o,c)=>{t(d=>({...d,bold_theme_colors:{...n,...d.bold_theme_colors,[o]:c}}))},i=()=>{t(o=>({...o,bold_theme_colors:null}))},l=[{key:"accent",label:"Accent Color",desc:"Page background, icons, highlights"},{key:"dark",label:"Dark Color",desc:"Header background, action buttons, social icons"},{key:"button",label:"CTA Button Color",desc:"Main call-to-action button"}];return e.jsxs("div",{className:"space-y-3 p-4 rounded-xl border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(Ac,{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(ye,{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 i3n({card:s,form:t,setForm:n}){var y;const r=a5t(),a=as(),{data:i}=i5t(s.id),[l,o]=j.useState(s.slug),[c,d]=j.useState(!1),[u,h]=j.useState("idle"),m=j.useRef(JSON.stringify(t)),p=j.useRef(null);j.useEffect(()=>{const g=JSON.stringify(t);if(g!==m.current)return p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{h("saving"),r.mutate({id:s.id,...t,is_published:!0,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,bold_theme_colors:t.bold_theme_colors||null,display_email:t.display_email||null},{onSuccess:()=>{m.current=g,h("saved"),setTimeout(()=>h("idle"),2e3)},onError:()=>h("idle")})},1500),()=>{p.current&&clearTimeout(p.current)}},[t]);const x=async()=>{const g=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!g){re.error("Please enter a valid URL");return}if(g===s.slug){re.info("No changes to save");return}d(!0);try{const{data:b}=await U.from("agent_cards").select("id").eq("slug",g).neq("id",s.id).maybeSingle();if(b){re.error("This URL is already taken. Try another one.");return}const{error:v}=await U.from("agent_cards").update({slug:g}).eq("id",s.id);if(v)throw v;o(g),a.invalidateQueries({queryKey:["agent-card"]}),re.success("Card address updated!")}catch{re.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(fa,{defaultValue:"content",children:[e.jsxs(xa,{className:"w-full h-11 p-1",children:[e.jsxs(ss,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ty,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(ss,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ma,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(ss,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(jf,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(ss,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(hg,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(ss,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(lu,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(ns,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(n3n,{userId:s.user_id}),e.jsx(r3n,{form:t,setForm:n,userId:s.user_id}),e.jsx(be,{children:e.jsxs(Re,{className:"p-5 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-semibold",children:"Card Status"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Toggle your card on or off"})]}),e.jsx(Mn,{checked:t.is_published,onCheckedChange:g=>n(b=>({...b,is_published:g}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(ye,{value:l,onChange:g=>o(g.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:x,disabled:c||l===s.slug,className:"shrink-0",children:c?"Saving...":"Update"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is your unique card URL. Only letters, numbers, and dashes allowed."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(ye,{value:t.display_email,onChange:g=>n(b=>({...b,display_email:g.target.value})),placeholder:"you@yourbusiness.com",className:"h-11",type:"email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional — use a different email on your card instead of your sign-in email."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(vs,{value:t.theme,onValueChange:g=>n(b=>({...b,theme:g})),children:[e.jsx(gs,{className:"h-11",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(Je,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(Je,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(Je,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(a3n,{form:t,setForm:n}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(ye,{value:t.title,onChange:g=>n(b=>({...b,title:g.target.value})),placeholder:"e.g. Luxury Real Estate Specialist",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown below your name on the card"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(ye,{value:t.positioning_statement,onChange:g=>n(b=>({...b,positioning_statement:g.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Ds,{value:t.bio,onChange:g=>n(b=>({...b,bio:g.target.value})),placeholder:"A short intro about you and what makes you different...",rows:3})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(ye,{value:t.review_snippet,onChange:g=>n(b=>({...b,review_snippet:g.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(ye,{value:t.review_source_url,onChange:g=>n(b=>({...b,review_source_url:g.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(ye,{value:t.booking_url,onChange:g=>n(b=>({...b,booking_url:g.target.value})),placeholder:"https://calendly.com/your-link",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to show a built-in lead form instead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(ye,{value:t.custom_cta_label,onChange:g=>n(b=>({...b,custom_cta_label:g.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(ns,{value:"sections",className:"mt-4",children:e.jsx(be,{children:e.jsx(Re,{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:g,label:b,desc:v})=>e.jsxs("div",{className:"flex items-center justify-between py-4 first:pt-0 last:pb-0",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(se,{className:"text-sm font-medium",children:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v})]}),e.jsx(Mn,{checked:t[g],onCheckedChange:k=>n(C=>({...C,[g]:k}))})]},g))})})}),e.jsx(ns,{value:"blocks",className:"mt-4",children:e.jsx(lBt,{cardId:s.id})}),e.jsx(ns,{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:ma,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:lu,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:Sl,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(g=>e.jsx(be,{className:"overflow-hidden",children:e.jsxs(Re,{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 ${g.color}`,children:e.jsx(g.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:g.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:g.value})]})},g.label))}),i&&i.leads.length>0&&e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"Recent Leads"})}),e.jsx(Re,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(g=>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:g.name}),g.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:g.phone})]}),g.intent&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:g.intent})]},g.id))})]}),(!i||i.leads.length===0)&&e.jsx(be,{children:e.jsxs(Re,{className:"p-8 text-center",children:[e.jsx(lu,{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(ns,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(be,{children:e.jsx(Re,{className:"p-6",children:e.jsx(Q4n,{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 o3n(){const s=as(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,x]=j.useState(null),[y,g]=j.useState(null),[b,v]=j.useState(0),[k,C]=j.useState(""),[T,M]=j.useState(!1),{data:P,isLoading:L}=mt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:ue,error:oe}=await U.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(oe)throw oe;return ue}}),I=vt({mutationFn:async ue=>{const{data:oe,error:ie}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:ue}});if(ie)throw ie;if(oe!=null&&oe.error)throw new Error(oe.error);return oe},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),re.success("BoldTrail connected successfully!")},onError:ue=>{re.error(ue.message||"Failed to connect BoldTrail")}}),O=vt({mutationFn:async()=>{const{data:ue,error:oe}=await U.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(oe)throw oe;return ue},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("BoldTrail disconnected")},onError:()=>re.error("Failed to disconnect")}),$=vt({mutationFn:async ue=>{const{data:oe,error:ie}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:ue}});if(ie)throw ie;if(oe!=null&&oe.error)throw new Error(oe.error);return oe},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("Sync direction saved")},onError:ue=>{re.error(ue.message||"Failed to save sync direction")}}),q=vt({mutationFn:async()=>{const{data:ue,error:oe}=await U.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(oe)throw oe;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 oe=ue.detected_name||ue.detected_email||`ID ${ue.kvcore_user_id}`;re.success(`Detected your BoldTrail account: ${oe}`)}else if(ue.candidates&&ue.candidates.length>0){const oe=ue.candidates.slice(0,5).map(ie=>`${ie.id} (${ie.count} contacts)`).join(", ");re.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${oe}. Pick yours and enter it below.`,{duration:12e3}),M(!0)}else re.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),M(!0)},onError:ue=>re.error(ue.message||"Detection failed")}),W=vt({mutationFn:async ue=>{const{data:oe,error:ie}=await U.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...ue}});if(ie)throw ie;if(oe!=null&&oe.error)throw new Error(oe.error);return oe},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("Settings saved"),M(!1)},onError:ue=>re.error(ue.message||"Failed to save settings")}),G=vt({mutationFn:async()=>{const{data:ue,error:oe}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(oe)throw oe;if(ue!=null&&ue.error)throw new Error(ue.error);return ue},onSuccess:ue=>{x(null),c(ue),a(!0)},onError:ue=>{re.error(ue.message||"Failed to generate sync preview")}}),K=vt({mutationFn:async()=>{g("Initializing sync..."),v(5);const{data:ue,error:oe}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:le}});if(oe)throw oe;if(ue!=null&&ue.error)throw new Error(ue.error);const ie=ue;let de=ie.sync_log_id,we=ie.next_phase,je=ie.next_offset,xe=ie.push_total||0,fe=ie.pull_total||0,Se=0,Ee=0;for(;we!=="finalize";){const Be=xe+fe;we==="fetch_bt"?g("Fetching BoldTrail contacts..."):we==="analyze"?(g("Analyzing contacts..."),v(15)):we==="push"?(g(`Pushing contacts to BoldTrail... (${Se}/${xe})`),v(Be>0?Se/Be*100:0)):we==="pull"&&(g(`Pulling contacts from BoldTrail... (${Ee}/${fe})`),v(Be>0?(xe+Ee)/Be*100:0));const{data:Ne,error:Ge}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:we,offset:je,sync_log_id:de,sync_direction:le}});if(Ge)throw Ge;if(Ne!=null&&Ne.error)throw new Error(Ne.error);const _e=Ne;Se+=_e.chunk_pushed||0,Ee+=_e.chunk_pulled||0,_e.push_total!==void 0&&(xe=_e.push_total||0),_e.pull_total!==void 0&&(fe=_e.pull_total||0),_e.progress&&g(_e.progress),we==="pull"&&fe>0?v(Math.min(95,Ee/fe*100)):we==="push"&&xe>0&&v(Math.min(95,Se/xe*100)),we=_e.next_phase,je=_e.next_offset}g("Finalizing sync..."),v(95);const{data:Le,error:De}=await U.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:de,sync_direction:le}});if(De)throw De;return v(100),Le},onSuccess:ue=>{g(null),v(0),a(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["contacts"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),re.success(`Sync complete! Pushed ${ue.contacts_pushed||0}, pulled ${ue.contacts_pulled||0}, skipped ${ue.contacts_skipped||0} duplicates.`)},onError:ue=>{g(null),v(0),re.error(ue.message||"Sync failed")}}),ee=P==null?void 0:P.connected,J=(P==null?void 0:P.sync_direction)||"bidirectional",le=p??J;return e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsx(Ft,{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(_x,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["BoldTrail",ee&&e.jsx(qe,{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(vh,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(fr,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Re,{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(To,{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(To,{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(To,{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"})]}),ee?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("div",{className:"rounded-lg border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"BoldTrail Connected"}),(P==null?void 0:P.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(P.last_sync_at).toLocaleString(),P.last_sync_status&&e.jsx(qe,{variant:P.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:P.last_sync_status})]}),(P==null?void 0:P.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[P.boldtrail_contact_count," contacts in BoldTrail"]}),(P==null?void 0:P.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:P.last_sync_message})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect BoldTrail?"}),e.jsx(xl,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>O.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(bN,{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(Mn,{checked:!!(P!=null&&P.sync_only_owned),onCheckedChange:ue=>W.mutate({sync_only_owned:ue}),disabled:W.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Your BoldTrail Agent ID"}),T?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"number",placeholder:"e.g. 12345",value:k,onChange:ue=>C(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:()=>M(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(P==null?void 0:P.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>q.mutate(),disabled:q.isPending,children:[q.isPending?e.jsx(Ki,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var ue;C(((ue=P==null?void 0:P.kvcore_user_id)==null?void 0:ue.toString())??""),M(!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(rSe,{value:J,onChange:ue=>$.mutate(ue)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(B,{onClick:()=>G.mutate(),disabled:G.isPending||K.isPending,variant:"outline",className:"gap-2",children:[G.isPending?e.jsx(Ki,{className:"h-4 w-4 animate-spin"}):e.jsx(ma,{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(ye,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:ue=>n(ue.target.value),className:"flex-1"}),e.jsxs(B,{onClick:()=>I.mutate(t),disabled:!t||t.length<10||I.isPending,children:[I.isPending?e.jsx(Ki,{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(Fs,{open:r,onOpenChange:ue=>{K.isPending||a(ue)},children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(_x,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(kr,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const ue=le==="pull_only"?0:o.to_push,oe=le==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(rSe,{value:le,onChange:x,size:"sm"}),o.owner_filter_active&&e.jsxs("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-2 text-xs text-emerald-900 flex items-start gap-2",children:[e.jsx(bN,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Owner filter is on. Only contacts assigned to your BoldTrail account",o.kvcore_user_id?` (ID ${o.kvcore_user_id})`:""," will be synced.",o.boldtrail_total_brokerage!=null&&e.jsxs(e.Fragment,{children:[" Brokerage total: ",e.jsx("strong",{children:o.boldtrail_total_brokerage.toLocaleString()}),"."]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${le==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:ue}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Gm,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${le==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:oe}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(tx,{className:"h-3 w-3"})," Pull to Agent OS"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-muted-foreground",children:o.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",o.agent_os_total," contacts · BoldTrail: ",o.boldtrail_total," contacts"]}),K.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(qi,{value:b||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:y||"Sync in progress..."})]}),ue>0&&e.jsxs(i0,{open:d,onOpenChange:u,children:[e.jsx(o0,{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(Gm,{className:"h-3 w-3 text-emerald-600"}),ue," contacts to push to BoldTrail"]}),e.jsx(Po,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(l0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((ie,de)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ie.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ie.email})]},de)),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"]})]})})]}),oe>0&&e.jsxs(i0,{open:h,onOpenChange:m,children:[e.jsx(o0,{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(tx,{className:"h-3 w-3 text-blue-600"}),oe," contacts to pull from BoldTrail"]}),e.jsx(Po,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(l0,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((ie,de)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:ie.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:ie.email})]},de)),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&&oe===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:K.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>K.mutate(),disabled:K.isPending||ue===0&&oe===0,className:"gap-2",children:[K.isPending?e.jsx(Ki,{className:"h-4 w-4 animate-spin"}):e.jsx(_x,{className:"h-4 w-4"}),K.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx($s,{className:"p-6 pb-0",children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(_x,{className:"h-5 w-5 text-emerald-600"}),"How BoldTrail Sync Works"]})}),e.jsx("div",{className:"px-6 pb-6",children:e.jsx("video",{src:"/videos/BoldTrailIntegration.mp4",controls:!0,autoPlay:!0,className:"w-full rounded-lg",controlsList:"nodownload"})})]})})]})}const u7=async s=>{const{data:t,error:n}=await U.functions.invoke("lofty-sync",{body:s});if(n)throw new Error(n.message);if(t!=null&&t.error)throw new Error(typeof t.error=="string"?t.error:JSON.stringify(t.error));return t};function l3n(){const s=as(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),[d,u]=j.useState(null),[h,m]=j.useState(null),{data:p,isLoading:x}=mt({queryKey:["lofty-status"],queryFn:async()=>await u7({action:"status"})}),y=()=>s.invalidateQueries({queryKey:["lofty-status"]}),g=vt({mutationFn:async()=>u7({action:"save_token",api_token:t.trim()}),onSuccess:M=>{re.success(M!=null&&M.contact_count?`Connected to Lofty — ${M.contact_count} contacts found`:"Connected to Lofty"),n(""),y()},onError:M=>re.error(M.message)}),b=vt({mutationFn:async()=>u7({action:"disconnect"}),onSuccess:()=>{re.success("Lofty disconnected"),y()},onError:M=>re.error(M.message)}),v=vt({mutationFn:async M=>u7({action:"save_settings",...M}),onSuccess:()=>y(),onError:M=>re.error(M.message)}),k=vt({mutationFn:async()=>u7({action:"detect_owner"}),onSuccess:M=>{const P=(M==null?void 0:M.candidates)||[];m(P),P.length===0?re.info("No assigned-agent IDs found on your Lofty contacts."):P.length===1?(v.mutate({lofty_user_id:P[0].id}),re.success(`Using Lofty agent ID ${P[0].id}`)):re.success("Pick which Lofty agent ID is yours below.")},onError:M=>re.error(M.message)}),C=async()=>{l(!0),c(2),u("Starting Lofty sync…");try{let M="start",P=0,L=null,I=0;for(;M&&I<400;){I++;const O=await u7({action:"sync",phase:M,offset:P,sync_log_id:L});L=O.sync_log_id||L,O.progress&&u(O.progress),c($=>Math.min(95,$+4)),M=O.next_phase,P=O.next_offset||0,M||(c(100),u(O.message||"Sync complete"),re.success(O.message||"Lofty sync complete"))}}catch(M){re.error(M.message||"Lofty sync failed"),u(null)}finally{l(!1),setTimeout(()=>c(0),2500),y()}},T=!!(p!=null&&p.connected);return e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:["Lofty",T?e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(To,{className:"h-3 w-3"})," Connected"]}):e.jsx(qe,{variant:"outline",children:"Not connected"})]}),e.jsx(fr,{children:"Sync your Lofty (formerly Chime) contacts — names, emails, phones, address, source, stage, tags and notes — into Agent OS."})]}),T&&e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon","aria-label":"Disconnect Lofty",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect Lofty?"}),e.jsx(xl,{children:"Your API key and sync settings will be removed. Contacts already imported into Agent OS stay put."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>b.mutate(),children:"Disconnect"})]})]})]})]})}),e.jsx(Re,{className:"space-y-5",children:x?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):T?e.jsxs("div",{className:"space-y-5",children:[e.jsx(rSe,{value:(p==null?void 0:p.sync_direction)||"pull_only",onChange:M=>v.mutate({sync_direction:M}),size:"sm"}),e.jsxs("div",{className:"space-y-3 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Only my contacts"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip team/brokerage contacts assigned to other Lofty agents."})]}),e.jsx(Mn,{checked:!!(p!=null&&p.sync_only_owned),onCheckedChange:M=>v.mutate({sync_only_owned:M})})]}),(p==null?void 0:p.sync_only_owned)&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>k.mutate(),disabled:k.isPending,children:[k.isPending?e.jsx(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Bn,{className:"h-3.5 w-3.5"}),"Detect my Lofty agent ID"]}),(p==null?void 0:p.lofty_user_id)&&e.jsxs(qe,{variant:"secondary",children:["Agent ID ",p.lofty_user_id]})]}),h&&h.length>1&&e.jsx("div",{className:"flex flex-wrap gap-2",children:h.map(M=>e.jsxs(B,{size:"sm",variant:(p==null?void 0:p.lofty_user_id)===M.id?"default":"outline",onClick:()=>v.mutate({lofty_user_id:M.id}),children:[M.id," · ",M.count," contacts"]},M.id))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Import notes"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pull each contact's Lofty notes into their Agent OS notes (deduped)."})]}),e.jsx(Mn,{checked:!!(p!=null&&p.import_notes),onCheckedChange:M=>v.mutate({import_notes:M})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"lofty-tags",className:"text-sm",children:"Tag filter (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{id:"lofty-tags",placeholder:((p==null?void 0:p.pull_tag_filter)||[]).join(", ")||"e.g. Sphere, Buyer",value:r,onChange:M=>a(M.target.value)}),e.jsx(B,{variant:"outline",onClick:()=>v.mutate({pull_tag_filter:r.split(",").map(M=>M.trim()).filter(Boolean)}),children:"Save"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to import every contact. Comma-separated Lofty tags."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{onClick:C,disabled:i,children:[i?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ki,{className:"h-4 w-4"}),i?"Syncing…":"Sync Now"]}),(p==null?void 0:p.last_sync_at)&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last sync ",new Date(p.last_sync_at).toLocaleString("en-US",{timeZone:"America/New_York"})]})]}),(i||o>0)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(qi,{value:o}),d&&e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),(p==null?void 0:p.last_sync_message)&&!i&&e.jsx("p",{className:"text-xs text-muted-foreground",children:p.last_sync_message})]}),((p==null?void 0:p.logs)||[]).length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:"Recent syncs"}),e.jsx("div",{className:"space-y-1",children:p.logs.map(M=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:new Date(M.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsxs("span",{children:[M.contacts_pulled," imported · ",M.contacts_pushed," pushed ·"," ",M.contacts_skipped," skipped"]}),e.jsx(qe,{variant:M.status==="completed"?"secondary":"destructive",children:M.status})]},M.id))})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"lofty-key",children:"Lofty API Key"}),e.jsx(ye,{id:"lofty-key",type:"password",placeholder:"Paste your Lofty API key",value:t,onChange:M=>n(M.target.value),autoComplete:"off"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["In Lofty go to ",e.jsx("strong",{children:"Settings → Integrations → API Key Management"})," and create a key with contact access."]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{onClick:()=>g.mutate(),disabled:t.trim().length<10||g.isPending,children:[g.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(R5,{className:"h-4 w-4"}),"Connect Lofty"]}),e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"https://developer.lofty.com/",target:"_blank",rel:"noreferrer",children:["Lofty API docs ",e.jsx(Tr,{className:"ml-1 h-3 w-3"})]})})]})]})})]})}function c3n(){const s=as(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(null),{data:d,isLoading:u}=mt({queryKey:["fub-status"],queryFn:async()=>{const{data:y,error:g}=await U.functions.invoke("followupboss-sync",{body:{action:"status"}});if(g)throw g;return y}}),h=vt({mutationFn:async y=>{const{data:g,error:b}=await U.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:y}});if(b)throw b;if(g!=null&&g.error)throw new Error(g.error);return g},onSuccess:()=>{re.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:y=>re.error(y.message)}),m=vt({mutationFn:async()=>{const{error:y}=await U.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(y)throw y},onSuccess:()=>{re.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),p=vt({mutationFn:async y=>{const{error:g}=await U.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:y}});if(g)throw g},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),x=async()=>{a(!0),l(0),c("Pulling from FUB…");let y=0,g=0,b=0,v=0;try{for(;;){const{data:M,error:P}=await U.functions.invoke("followupboss-sync",{body:{action:"sync",offset:y}});if(P)throw P;if(M!=null&&M.error)throw new Error(M.error);g+=M.chunk_created||0,b+=M.chunk_updated||0,v+=M.chunk_skipped||0,y=M.next_offset;const L=M.total?Math.min(100,Math.round(y/M.total*100)):100;if(l(L),c(`Pulling · ${y} / ${M.total||"?"}`),M.done)break;await new Promise(I=>setTimeout(I,400))}let k=0,C=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let M=0;for(l(0),c("Pushing to FUB…");;){const{data:P,error:L}=await U.functions.invoke("followupboss-sync",{body:{action:"push",offset:M}});if(L)throw L;if(P!=null&&P.error)throw new Error(P.error);k+=P.chunk_pushed||0,C+=P.chunk_failed||0,M=P.next_offset;const I=P.total?Math.min(100,Math.round(M/P.total*100)):100;if(l(I),c(`Pushing · ${M} / ${P.total||"?"}`),P.done)break;await new Promise(O=>setTimeout(O,400))}}const T=k||C?` · pushed ${k}${C?`, ${C} failed`:""}`:"";re.success(`Sync complete · ${g} new, ${b} updated${v?`, ${v} skipped`:""}${T}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(k){re.error(k.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(R5,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(qe,{variant:"default",className:"ml-1",children:[e.jsx(To,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(fr,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Re,{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(Mn,{checked:d.sync_direction==="bidirectional",onCheckedChange:y=>p.mutate(y?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(qi,{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:x,disabled:r,children:[e.jsx(Ki,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect Follow Up Boss?"}),e.jsx(xl,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(ye,{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 d3n(){var G;const s=as(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),[d,u]=j.useState(null),[h,m]=j.useState(!1),[p,x]=j.useState(null),[y,g]=j.useState(!1),[b,v]=j.useState(new Set),{data:k,isLoading:C}=mt({queryKey:["cloze-status"],queryFn:async()=>{const{data:K,error:ee}=await U.functions.invoke("cloze-sync",{body:{action:"status"}});if(ee)throw ee;return K}}),T=vt({mutationFn:async()=>{const{data:K,error:ee}=await U.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(ee)throw ee;if(K!=null&&K.error)throw new Error(K.error);return K},onSuccess:()=>{re.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:K=>re.error(K.message)}),M=vt({mutationFn:async()=>{const{error:K}=await U.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(K)throw K},onSuccess:()=>{re.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),P=vt({mutationFn:async K=>{const{error:ee}=await U.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:K}});if(ee)throw ee},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),L=vt({mutationFn:async K=>{const{error:ee}=await U.functions.invoke("cloze-sync",{body:{action:"set_scope",...K}});if(ee)throw ee},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),I=async()=>{g(!0);try{const{data:K,error:ee}=await U.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(ee)throw ee;if(K!=null&&K.error)throw new Error(K.error);x(K.segments||[]),v(new Set((k==null?void 0:k.selected_segments)||[])),m(!0)}catch(K){re.error(K.message||"Failed to load segments")}finally{g(!1)}},O=async()=>{const K=Array.from(b);await L.mutateAsync({sync_scope:"segments",selected_segments:K}),re.success(`Saved · ${K.length} segment(s) selected`),m(!1)},$=async()=>{const K=(k==null?void 0:k.sync_direction)||"pull_only";l(!0),c(0);try{if(K==="pull_only"||K==="bidirectional"){u("Pulling from Cloze…");let ee=0,J=0,le=0;for(;;){const{data:ue,error:oe}=await U.functions.invoke("cloze-sync",{body:{action:"sync",offset:ee}});if(oe)throw oe;if(ue!=null&&ue.error)throw new Error(ue.error);if(J+=ue.chunk_created||0,le+=ue.chunk_updated||0,ee=ue.next_offset,u(`Pulling · ${J+le} contacts processed`),c(ue.done?100:Math.min(95,(J+le)%200/2)),ue.done)break;await new Promise(ie=>setTimeout(ie,300))}re.success(`Pulled · ${J} new, ${le} updated`)}if(K==="push_only"||K==="bidirectional"){c(0),u("Pushing to Cloze…");let ee=0,J=0,le=0;for(;;){const{data:ue,error:oe}=await U.functions.invoke("cloze-sync",{body:{action:"push",offset:ee}});if(oe)throw oe;if(ue!=null&&ue.error)throw new Error(ue.error);J+=ue.chunk_pushed||0,le+=ue.chunk_failed||0,ee=ue.next_offset;const ie=ue.total?Math.min(100,Math.round(ee/ue.total*100)):100;if(c(ie),u(`Pushing · ${ee} / ${ue.total||"?"}`),ue.done)break;await new Promise(de=>setTimeout(de,300))}re.success(`Pushed · ${J}${le?`, ${le} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(ee){re.error(ee.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},q=(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(be,{children:[e.jsx(Ft,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(R5,{className:"h-5 w-5 text-primary"}),"Cloze",(k==null?void 0:k.connected)&&e.jsxs(qe,{variant:"default",className:"ml-1",children:[e.jsx(To,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(fr,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(Re,{className:"space-y-4",children:C?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(vs,{value:k.sync_direction||"pull_only",onValueChange:K=>P.mutate(K),disabled:i||P.isPending,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(Je,{value:"push_only",children:"Push to Cloze"}),e.jsx(Je,{value:"bidirectional",children:"Two-way sync"})]})]})]})}),e.jsxs("div",{className:"rounded-lg border px-3 py-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"What to sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:q==="all"?"All Cloze contacts.":`${W} segment${W===1?"":"s"} selected.`})]}),e.jsxs(vs,{value:q,onValueChange:K=>{K==="all"?L.mutate({sync_scope:"all",selected_segments:[]}):(L.mutate({sync_scope:"segments",selected_segments:k.selected_segments||[]}),I())},disabled:i||L.isPending,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All contacts"}),e.jsx(Je,{value:"segments",children:"Selected segments"})]})]})]}),q==="segments"&&e.jsxs("div",{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:I,disabled:y,children:[e.jsx(dK,{className:"h-4 w-4 mr-2"}),y?"Loading segments…":"Choose segments"]}),h&&p&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"max-h-96 overflow-y-auto rounded-md border divide-y",children:[p.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-3",children:"No segments found in your Cloze account."}),p.map(K=>{const ee=b.has(K.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(wi,{checked:ee,onCheckedChange:J=>{const le=new Set(b);J?le.add(K.id):le.delete(K.id),v(le)}}),e.jsx("span",{className:"flex-1 text-sm",children:K.name}),K.count!=null&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:K.count})]},K.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:O,disabled:L.isPending,children:["Save selection (",b.size,")"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(qi,{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(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsxs(B,{disabled:i,children:[e.jsx(Ki,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Preview sync"}),e.jsx(xl,{asChild:!0,children:e.jsx(u3n,{segments:p})})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:$,children:"Start Sync"})]})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:i,children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect Cloze?"}),e.jsx(xl,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>M.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"cloze-email",children:"Cloze Account Email"}),e.jsx(ye,{id:"cloze-email",type:"email",placeholder:"you@example.com",value:r,onChange:K=>a(K.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{htmlFor:"cloze-key",children:"Cloze API Key"}),e.jsx(ye,{id:"cloze-key",type:"password",placeholder:"Your personal Cloze API key",value:t,onChange:K=>n(K.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:["Generate one in Cloze → Settings → API Keys.",e.jsxs("a",{href:"https://app.cloze.com/app/#/settings/apikeys",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-0.5 text-primary hover:underline",children:["Open ",e.jsx(Tr,{className:"h-3 w-3"})]})]})]}),e.jsx(B,{onClick:()=>T.mutate(),disabled:!t.trim()||!r.trim()||T.isPending,children:T.isPending?"Connecting…":"Connect Cloze"})]})})]})}function u3n({segments:s}){var h;const[t,n]=j.useState(!0),[r,a]=j.useState(null),[i,l]=j.useState(null);if(j.useEffect(()=>{(async()=>{try{const{data:m,error:p}=await U.functions.invoke("cloze-sync",{body:{action:"preview"}});if(p)throw p;if(m!=null&&m.error)throw new Error(m.error);a(m)}catch(m){l(m.message||"Could not load preview")}finally{n(!1)}})()},[]),t)return e.jsx("span",{className:"text-sm",children:"Calculating…"});if(i)return e.jsx("span",{className:"text-sm text-destructive",children:i});const o=new Map((s||[]).map(m=>[m.id,m.name])),c=r.total_incoming??0,d=r.already_synced??0,u=Math.max(0,c-d);return e.jsxs("div",{className:"space-y-3 text-sm text-foreground",children:[e.jsxs("div",{className:"rounded-md border p-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{children:["Contacts in Cloze (",r.scope==="segments"?"selected segments":"all",")"]}),e.jsx("strong",{children:c.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Already linked to Cloze in your CRM"}),e.jsx("span",{children:d.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Estimated new contacts"}),e.jsxs("strong",{children:["~",u.toLocaleString()]})]})]}),r.scope==="segments"&&((h=r.segment_counts)==null?void 0:h.length)>0&&e.jsx("div",{className:"rounded-md border p-3 space-y-1 max-h-40 overflow-auto",children:r.segment_counts.map(m=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:o.get(m.id)||m.id}),e.jsx("span",{className:"text-muted-foreground",children:m.total})]},m.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.note})]})}function h3n(){const s=as(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(null),{data:d,isLoading:u}=mt({queryKey:["boomtown-status"],queryFn:async()=>{const{data:y,error:g}=await U.functions.invoke("boomtown-sync",{body:{action:"status"}});if(g)throw g;return y}}),h=vt({mutationFn:async y=>{const{data:g,error:b}=await U.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:y}});if(b)throw b;if(g!=null&&g.error)throw new Error(g.error);return g},onSuccess:()=>{re.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:y=>re.error(y.message)}),m=vt({mutationFn:async()=>{const{error:y}=await U.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(y)throw y},onSuccess:()=>{re.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),p=vt({mutationFn:async y=>{const{error:g}=await U.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:y}});if(g)throw g},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),x=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let y=0,g=0,b=0,v=0;try{for(;;){const{data:M,error:P}=await U.functions.invoke("boomtown-sync",{body:{action:"sync",offset:y}});if(P)throw P;if(M!=null&&M.error)throw new Error(M.error);g+=M.chunk_created||0,b+=M.chunk_updated||0,v+=M.chunk_skipped||0,y=M.next_offset;const L=M.total?Math.min(100,Math.round(y/M.total*100)):100;if(l(L),c(`Pulling · ${y} / ${M.total||"?"}`),M.done)break;await new Promise(I=>setTimeout(I,400))}let k=0,C=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let M=0;for(l(0),c("Pushing to Boomtown…");;){const{data:P,error:L}=await U.functions.invoke("boomtown-sync",{body:{action:"push",offset:M}});if(L)throw L;if(P!=null&&P.error)throw new Error(P.error);k+=P.chunk_pushed||0,C+=P.chunk_failed||0,M=P.next_offset;const I=P.total?Math.min(100,Math.round(M/P.total*100)):100;if(l(I),c(`Pushing · ${M} / ${P.total||"?"}`),P.done)break;await new Promise(O=>setTimeout(O,400))}}const T=k||C?` · pushed ${k}${C?`, ${C} failed`:""}`:"";re.success(`Sync complete · ${g} new, ${b} updated${v?`, ${v} skipped`:""}${T}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(k){re.error(k.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(R5,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs(qe,{variant:"default",className:"ml-1",children:[e.jsx(To,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(fr,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(Re,{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(Mn,{checked:d.sync_direction==="bidirectional",onCheckedChange:y=>p.mutate(y?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(qi,{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:x,disabled:r,children:[e.jsx(Ki,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect Boomtown?"}),e.jsx(xl,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{htmlFor:"boomtown-key",children:"Boomtown API Key"}),e.jsx(ye,{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 cBt(){const s=Hn(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState("Test from ReLevelUp"),[o,c]=j.useState(!1),{data:d,isLoading:u}=mt({queryKey:["ses-config"],queryFn:async()=>{const p=await iX();return(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},body:JSON.stringify({action:"check_config"})})).json()}}),h=async()=>{if(!t||!r){re.error("Please fill in From and To email addresses");return}c(!0);try{const p=await iX(),y=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},body:JSON.stringify({action:"test_send",to:t,from_email:r,subject:i,body_html:"

Test Email

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

If you received this, SES is configured correctly! 🎉

"})})).json();y.success?re.success(`Test email sent! Message ID: ${y.messageId}`):re.error(y.error||"Failed to send test email")}catch(p){re.error(p.message||"Failed to send test email")}finally{c(!1)}},m=(d==null?void 0:d.configured)===!0;return e.jsxs(be,{children:[e.jsx(Ft,{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(on,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(fr,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(qe,{variant:m?"default":"secondary",children:u?"Checking...":m?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(To,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(po,{className:"h-3 w-3"})," Not Configured"]})})]})}),m&&e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Send Test Email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Verify your SES setup by sending a test email. The "From" address must be verified in SES or belong to a verified domain.'}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"From Email"}),e.jsx(ye,{placeholder:"notifications@mail.relevelup.com",value:r,onChange:p=>a(p.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"To Email"}),e.jsx(ye,{placeholder:"your@email.com",value:t,onChange:p=>n(p.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(ye,{value:i,onChange:p=>l(p.target.value),className:"text-sm"})]})]}),e.jsxs(B,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(B,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(jh,{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(Re,{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 YIe(s){const t=await iX(),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 m3n({status:s}){return s==="verified"?e.jsxs(qe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(qe,{variant:"secondary",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(qe,{variant:"destructive",children:[e.jsx(po,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(qe,{variant:"outline",children:[e.jsx(po,{className:"h-3 w-3 mr-1"})," Not started"]})}function dBt({brokerageId:s,onVerifiedSelect:t}){const n=as(),[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),{data:p,isLoading:x}=mt({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:v,error:k}=await U.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(k)throw k;return v||[]}}),y=vt({mutationFn:async()=>YIe({action:"request_verification",brokerage_id:s,email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),re.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:v=>re.error(v.message)}),g=async v=>{var k,C;u(v.id);try{const T=await YIe({action:"check_status",sender_id:v.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((k=T.sender)==null?void 0:k.status)==="verified"?re.success(`${v.email} is verified! 🎉`):re.info(`Status: ${((C=T.sender)==null?void 0:C.status)||"unknown"}`)}catch(T){re.error(T.message)}finally{u(null)}},b=vt({mutationFn:async v=>YIe({action:"delete",sender_id:v}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),re.success("Sender removed"),m(null)},onError:v=>re.error(v.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Verified Sender Addresses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Verify any email address (yours or your brokerage's) so recruiting emails can be sent from that address. Anyone managing this brokerage can use these senders."})]}),x?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):p&&p.length>0?e.jsx("div",{className:"space-y-2",children:p.map(v=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(on,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:v.email}),e.jsx(m3n,{status:v.status})]}),v.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',v.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[v.status==="verified"&&t&&e.jsx(B,{size:"sm",variant:"outline",onClick:()=>t(v.email),children:"Use"}),v.status!=="verified"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>g(v),disabled:d===v.id,title:"Refresh status from AWS",children:d===v.id?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ki,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(v),className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})]})]},v.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Email Address *"}),e.jsx(ye,{type:"email",value:r,onChange:v=>a(v.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(ye,{value:i,onChange:v=>l(v.target.value),placeholder:"John at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask AWS to send a verification email to this address. The owner must click the link before this sender can be used."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>y.mutate(),disabled:!r.trim()||y.isPending,children:[y.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(on,{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(Js,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Nl,{open:!!h,onOpenChange:v=>!v&&m(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Remove this sender?"}),e.jsxs(xl,{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(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>h&&b.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function ZIe(s){const t=await iX(),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 p3n({status:s}){return s==="verified"?e.jsxs(qe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(qe,{variant:"secondary",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(qe,{variant:"destructive",children:[e.jsx(po,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(qe,{variant:"outline",children:[e.jsx(po,{className:"h-3 w-3 mr-1"})," Not started"]})}function f3n({userId:s,onVerifiedSelect:t}){const n=as(),[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),{data:p,isLoading:x}=mt({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:v,error:k}=await U.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(k)throw k;return v||[]}}),y=vt({mutationFn:async()=>ZIe({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),re.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:v=>re.error(v.message)}),g=async v=>{var k,C;u(v.id);try{const T=await ZIe({action:"check_status",sender_id:v.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((k=T.sender)==null?void 0:k.status)==="verified"?re.success(`${v.email} is verified! 🎉`):re.info(`Status: ${((C=T.sender)==null?void 0:C.status)||"unknown"}`)}catch(T){re.error(T.message)}finally{u(null)}},b=vt({mutationFn:async v=>ZIe({action:"delete",sender_id:v}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),re.success("Sender removed"),m(null)},onError:v=>re.error(v.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Your Verified Sender Addresses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Verify your email address with Amazon so mass emails can be sent ",e.jsx("em",{children:"from"})," you. Add an address, then click the verification link Amazon sends to that inbox."]})]}),x?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):p&&p.length>0?e.jsx("div",{className:"space-y-2",children:p.map(v=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(on,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:v.email}),e.jsx(p3n,{status:v.status})]}),v.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',v.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[v.status==="verified"&&t&&e.jsx(B,{size:"sm",variant:"outline",onClick:()=>t(v.email),children:"Use"}),v.status!=="verified"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>g(v),disabled:d===v.id,title:"Refresh status from AWS",children:d===v.id?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ki,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>m(v),className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})]})]},v.id))}):e.jsx("div",{className:"text-xs text-muted-foreground py-2 italic",children:"No verified senders yet. Add one below."}),o?e.jsxs("div",{className:"rounded-lg border p-4 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Email Address *"}),e.jsx(ye,{type:"email",value:r,onChange:v=>a(v.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(ye,{value:i,onChange:v=>l(v.target.value),placeholder:"Jane at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask Amazon to send a verification email to this address. You must click the link before this sender can be used in a campaign."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>y.mutate(),disabled:!r.trim()||y.isPending,children:[y.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(on,{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(Js,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Nl,{open:!!h,onOpenChange:v=>!v&&m(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Remove this sender?"}),e.jsxs(xl,{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(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>h&&b.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function x3n(){var C,T,M,P,L;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=Ns(),i=a||((C=r==null?void 0:r[0])==null?void 0:C.id)||null,l=(t||n)&&!!i,o=as(),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,p]=j.useState(""),{data:x}=mt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:I,error:O}=await U.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(O)throw O;return I}}),{data:y}=mt({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:I,error:O}=await U.from("profiles").select("email, name").eq("id",s.id).single();if(O)throw O;return I}}),g=((T=x==null?void 0:x.reply_to_email)==null?void 0:T.trim())||((M=y==null?void 0:y.email)==null?void 0:M.trim())||"",b=((P=x==null?void 0:x.display_name)==null?void 0:P.trim())||((L=y==null?void 0:y.name)==null?void 0:L.trim())||"";j.useEffect(()=>{c||(h(g),p(b))},[c,g,b]);const v=vt({mutationFn:async()=>{if(!s||!u.trim())throw new Error("Please enter a reply-to email");const I={reply_to_email:u.trim(),display_name:m.trim()||null,updated_at:new Date().toISOString()};if(x){const{error:O}=await U.from("mass_email_settings").update(I).eq("user_id",s.id);if(O)throw O}else{const{error:O}=await U.from("mass_email_settings").insert({user_id:s.id,...I});if(O)throw O}},onSuccess:()=>{o.invalidateQueries({queryKey:["mass-email-settings",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-ready",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-settings-check",s==null?void 0:s.id]}),re.success("Reply-to email saved!"),d(!1)},onError:I=>re.error(I.message)}),k=!!g;return e.jsxs(be,{children:[e.jsx(Ft,{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(Dr,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Mass Email",k?e.jsxs(qe,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(To,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(qe,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(fr,{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(Re,{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:b||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:g})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(Za,{className:"h-3 w-3 mr-1"})," Edit"]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Display Name"}),e.jsx(ye,{placeholder:"e.g. 🏡 Karen Hall",value:m,onChange:I=>p(I.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"How your name appears in the recipient's inbox"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(ye,{type:"email",placeholder:"your@email.com",value:u,onChange:I=>h(I.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!u.trim(),children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{d(!1),h(g),p(b)},children:[e.jsx(dr,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(Xl,{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(a0,{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(f3n,{userId:s.id,onVerifiedSelect:I=>{h(I),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(Xl,{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(a0,{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(dBt,{brokerageId:i})]})]})]})]})}function g3n({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 y3n(){const s=Hn(),{isAdmin:t,user:n}=Ns(),{actingAsAgent:r,effectiveUserId:a}=J4e(),i=as(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),{scopeUserId:m,isDelegated:p}=g3n({authUserId:n==null?void 0:n.id,actingAsUserId:(r==null?void 0:r.id)??a}),{data:x,isLoading:y}=mt({queryKey:["gmail-integration",m],enabled:!!m&&!p,queryFn:async()=>{const{data:O,error:$}=await U.from("gmail_integrations").select("*").eq("user_id",m).maybeSingle();if($)throw $;return O}}),{data:g}=mt({queryKey:["social-accounts",m],enabled:!!m&&!p,queryFn:async()=>{const{data:O,error:$}=await U.from("social_accounts").select("*").eq("user_id",m).order("created_at",{ascending:!1});if($)throw $;return O}}),b=async()=>{if(p){re.error("Account connections must be made by the agent from their own login.");return}o(!0);try{const{data:O,error:$}=await U.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if($)throw $;if(O!=null&&O.authUrl)window.location.href=O.authUrl;else throw new Error("Failed to get authorization URL")}catch(O){console.error("Gmail OAuth error:",O),re.error("Failed to start Gmail connection"),o(!1)}},v=async O=>{if(p){re.error("Account connections must be made by the agent from their own login.");return}d(!0);try{sessionStorage.setItem("social-connect-return-to",window.location.pathname);const{data:$,error:q}=await U.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:O}});if(q)throw q;if($!=null&&$.authUrl)window.location.href=$.authUrl;else throw new Error("Failed to get authorization URL")}catch($){console.error("Meta OAuth error:",$),re.error("Failed to start connection. Make sure Meta App credentials are configured."),d(!1)}},k=async()=>{if(p){re.error("Account connections must be made by the agent from their own login.");return}h(!0);try{const{data:O,error:$}=await U.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if($)throw $;if(O!=null&&O.authUrl)window.location.href=O.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(O){console.error("LinkedIn OAuth error:",O),re.error("Failed to start LinkedIn connection. Please try again."),h(!1)}},C=vt({mutationFn:async O=>{const{error:$}=await U.from("gmail_integrations").delete().eq("id",O).eq("user_id",m);if($)throw $},onSuccess:()=>{i.invalidateQueries({queryKey:["gmail-integration",m]}),re.success("Gmail disconnected")},onError:()=>{re.error("Failed to disconnect Gmail")}}),T=vt({mutationFn:async O=>{const{error:$}=await U.from("social_accounts").delete().eq("id",O).eq("user_id",m);if($)throw $},onSuccess:()=>{i.invalidateQueries({queryKey:["social-accounts",m]}),re.success("Account disconnected")},onError:()=>{re.error("Failed to disconnect account")}}),M=!p&&!!(x!=null&&x.is_active),P=(g==null?void 0:g.filter(O=>O.platform==="facebook"))||[],L=(g==null?void 0:g.filter(O=>O.platform==="instagram"))||[],I=(g==null?void 0:g.filter(O=>O.platform==="linkedin"))||[];return e.jsx(Vs,{children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6 animate-fade-in",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Integrations"}),e.jsx("p",{className:"text-muted-foreground",children:"Connect third-party services to supercharge your Agent OS workflow."})]}),p&&e.jsx(be,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Ft,{className:"flex flex-row items-start gap-3 space-y-0",children:[e.jsx(du,{className:"h-5 w-5 text-amber-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-base",children:"Connected accounts are hidden"}),e.jsxs(fr,{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(be,{children:[e.jsx(Ft,{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(UT,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:"ChatGPT"}),e.jsx(fr,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]})]})}),e.jsx(Re,{children:e.jsxs(B,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(Xa,{className:"h-4 w-4 ml-1"})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{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(on,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Gmail",M&&e.jsx(qe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(fr,{children:"Send emails directly from your contact pages and auto-log them as touchpoints."})]})]})}),e.jsx(Re,{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(To,{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(To,{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(To,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Quick compose from any contact detail page"})]}),M?e.jsxs("div",{className:"flex items-center justify-between mt-4 p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:x.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect Gmail?"}),e.jsx(xl,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>C.mutate(x.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(B,{className:"mt-4",onClick:b,disabled:l||y,children:[l?e.jsx(Ki,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(on,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(Xa,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{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(sx,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Facebook",P.length>0&&e.jsx(qe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(fr,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(Re,{className:"space-y-3",children:[P.length>0&&e.jsx("div",{className:"space-y-2",children:P.map(O=>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(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:O.profile_picture_url||""}),e.jsx(Da,{children:e.jsx(sx,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:O.page_name||O.platform_username||"Facebook Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Facebook Page"})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect Facebook?"}),e.jsx(xl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>T.mutate(O.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},O.id))}),e.jsxs(B,{onClick:()=>v("facebook"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(Ki,{className:"h-4 w-4 animate-spin"}):e.jsx(Js,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{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(vm,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Instagram",L.length>0&&e.jsx(qe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(fr,{children:"Connect an Instagram Business or Creator account to schedule and publish posts. Personal accounts are not supported by Meta's API."})]})]})}),e.jsxs(Re,{className:"space-y-3",children:[L.length>0&&e.jsx("div",{className:"space-y-2",children:L.map(O=>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(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:O.profile_picture_url||""}),e.jsx(Da,{children:e.jsx(vm,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:["@",O.platform_username||"Instagram Account"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Instagram account"})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect Instagram?"}),e.jsx(xl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>T.mutate(O.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},O.id))}),e.jsxs(B,{onClick:()=>v("instagram"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(Ki,{className:"h-4 w-4 animate-spin"}):e.jsx(Js,{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(be,{children:[e.jsx(Ft,{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(ry,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["LinkedIn",I.length>0&&e.jsx(qe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(fr,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(Re,{className:"space-y-3",children:[I.length>0&&e.jsx("div",{className:"space-y-2",children:I.map(O=>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(Ra,{className:"h-8 w-8",children:[e.jsx(Fi,{src:O.profile_picture_url||""}),e.jsx(Da,{children:e.jsx(ry,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:O.platform_username||"LinkedIn Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected LinkedIn profile"})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect LinkedIn?"}),e.jsx(xl,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>T.mutate(O.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},O.id))}),e.jsxs(B,{onClick:k,disabled:u,variant:"outline",className:"gap-2",children:[u?e.jsx(Ki,{className:"h-4 w-4 animate-spin"}):e.jsx(Js,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(o3n,{}),e.jsx(l3n,{}),e.jsx(c3n,{}),e.jsx(d3n,{}),e.jsx(h3n,{}),e.jsx(x3n,{}),t&&e.jsx(cBt,{})]})})}const v3n="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function b3n(){const[s,t]=j.useState(null),[n,r]=j.useState(!1),[a,i]=j.useState(0),[l,o]=j.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",u=window.location.hostname.startsWith("id-preview--"),h=async g=>{const b=new Uint8Array(await g.slice(0,4).arrayBuffer());return b[0]===80&&b[1]===75&&b[2]===3&&b[3]===4||b[0]===80&&b[1]===75&&b[2]===5&&b[3]===6||b[0]===80&&b[1]===75&&b[2]===7&&b[3]===8},m=g=>{const b=document.createElement("a");b.href=g,b.download="levelup-extension.zip",b.rel="noopener noreferrer",b.target="_blank",document.body.appendChild(b),b.click(),b.remove()},p=async()=>{o(!0);try{if(u){m(`${d}?v=${Date.now()}`);return}const g=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!g.ok)throw new Error(`Download failed (${g.status})`);const b=await g.blob();if(!await h(b)){m(`${d}?v=${Date.now()}`);return}const v=new Blob([b],{type:"application/zip"}),k=URL.createObjectURL(v),C=document.createElement("a");C.href=k,C.download="levelup-extension.zip",document.body.appendChild(C),C.click(),C.remove(),setTimeout(()=>URL.revokeObjectURL(k),1e3)}catch(g){re.error(g.message||"Download failed")}finally{o(!1)}},x=async()=>{r(!0);try{await U.auth.refreshSession();const{data:g}=await U.auth.getSession();if(!g.session){re.error("Your session has expired. Please sign in again.");return}const{data:b,error:v}=await U.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${g.session.access_token}`}});if(v)throw v;t(b.code),i(b.expires_in||300);const k=setInterval(()=>{i(C=>C<=1?(clearInterval(k),t(null),0):C-1)},1e3)}catch(g){console.error("generateCode error",g),re.error("We couldn't generate a pairing code",{description:"Please refresh the page and try again. If it still fails, sign out and sign back in, then click Generate pairing code.",duration:8e3})}finally{r(!1)}},y=()=>{s&&(navigator.clipboard.writeText(s),re.success("Copied"))};return e.jsx(Vs,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(ql,{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(IR,{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(be,{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(v3n,"_blank","noopener,noreferrer"),children:[e.jsx(IR,{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(be,{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(ja,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(B,{onClick:x,variant:"outline",className:"flex-1",children:[e.jsx(Ki,{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(da,{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:x,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(Ki,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(be,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Eu,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h2",{className:"text-base font-semibold text-muted-foreground",children:"Manual install (advanced)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you prefer to load the extension unpacked, or the Web Store is unavailable, download the ZIP below."}),e.jsxs("ol",{className:"text-sm space-y-2 list-decimal list-inside text-muted-foreground",children:[e.jsx("li",{children:e.jsx(B,{variant:"link",className:"h-auto p-0 text-sm",onClick:p,disabled:l,children:"Download the extension ZIP"})}),e.jsx("li",{children:"Unzip the downloaded file"}),e.jsxs("li",{children:["Open"," ",e.jsx("code",{className:"px-1.5 py-0.5 rounded bg-muted text-foreground",children:"chrome://extensions"})," ","in Chrome, Edge, Brave, or Arc"]}),e.jsxs("li",{children:["Turn on ",e.jsx("b",{className:"text-foreground",children:"Developer mode"})," (top-right toggle)"]}),e.jsxs("li",{children:["Click ",e.jsx("b",{className:"text-foreground",children:"Load unpacked"})," and pick the unzipped folder"]}),e.jsx("li",{children:"Pin the LevelUp icon to your toolbar"})]})]})]})})}function _3n(){const[s]=dc(),t=Hn(),[n,r]=j.useState("loading"),[a,i]=j.useState("Connecting your Gmail account...");return j.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),re.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),re.error("No authorization code received");return}try{const{data:h,error:m}=await U.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:u}});if(m)throw m;if(h!=null&&h.success)r("success"),i(h.message||"Gmail connected successfully!"),re.success("Gmail connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Gmail OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Gmail"),re.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(Ft,{className:"text-center",children:[n==="loading"&&e.jsx(Wt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(To,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Rd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Ut,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(fr,{children:a})]}),e.jsx(Re,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function w3n(){const s=Hn();return j.useEffect(()=>{const t=setTimeout(()=>{s("/mission-control/integrations",{replace:!0})},1500);return()=>clearTimeout(t)},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Finishing Canva connection…"})]})})}function j3n(){const[s]=dc(),t=Hn(),[n,r]=j.useState("loading"),a=j.useRef(!1),[i,l]=j.useState("Processing your connection...");return j.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var m;const c=s.get("code"),d=s.get("error"),u=s.get("error_description"),h=s.get("state");if(d){r("error"),l(u||"Authorization was denied"),re.error("Connection failed: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),re.error("No authorization code received");return}try{const{data:p,error:x}=await U.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h,callbackPath:"/mission-control/integrations/meta/callback"}});if(p&&p.success===!1)throw new Error(p.error||"Failed to connect accounts");if(x){let y=x.message||"Failed to connect accounts";try{const g=x.context;if(g&&typeof g.json=="function"){const b=await g.json();b!=null&&b.error&&(y=b.error)}}catch{}throw new Error(y)}if(p!=null&&p.success)r("success"),l(`Successfully connected ${((m=p.accounts)==null?void 0:m.length)||0} account(s)!`),re.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),r("error"),l(p instanceof Error?p.message:"Failed to connect accounts"),re.error("Failed to connect: "+(p instanceof Error?p.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(Ft,{className:"text-center",children:[n==="loading"&&e.jsx(Wt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(To,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Rd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Ut,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(fr,{children:i})]}),e.jsx(Re,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const uBt=new Date().getFullYear(),N3n=Array.from({length:5},(s,t)=>uBt-t);function k3n(){const[s,t]=j.useState(uBt),n=Hn(),{data:r,isLoading:a}=a5s();return a?e.jsx(Vs,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(gn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(gn,{className:"h-24"},i))}),e.jsx(gn,{className:"h-96"})]})}):e.jsx(Vs,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Scorecard Admin"}),e.jsx("p",{className:"text-muted-foreground",children:"View agent performance and scorecards"})]}),e.jsxs(vs,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(gs,{className:"w-[120px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:N3n.map(i=>e.jsx(Je,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Agents Tracking"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(r==null?void 0:r.length)||0})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ol,{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(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Agents with Scorecards"}),e.jsx(fr,{children:"Click to view individual agent scorecards"})]}),e.jsx(Re,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ol,{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(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:r.map(i=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:i.name}),e.jsx(xt,{className:"text-muted-foreground",children:i.email}),e.jsx(xt,{className:"text-right",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n(`/admin/scorecard/${i.id}`),children:[e.jsx(ma,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const hBt=new Date().getFullYear(),S3n=Array.from({length:10},(s,t)=>hBt-t);function bgt(){var y;const{userId:s}=$i(),t=Hn(),r=$d().pathname.startsWith("/mission-control"),[a,i]=j.useState(hBt),{data:l,isLoading:o}=mt({queryKey:["agent-profile",s],queryFn:async()=>{const{data:g,error:b}=await U.from("profiles").select("id, name, email").eq("id",s).single();if(b)throw b;return g},enabled:!!s}),{data:c,isLoading:d}=SVe(a,s),{yearStats:u,lifetimeStats:h,isLoading:m,showCommission:p}=oAt(a,s),{data:x}=iAt(a,s);return o?e.jsx(Vs,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(gn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(g=>e.jsx(gn,{className:"h-24"},g))})]})}):e.jsx(Vs,{title:`${l==null?void 0:l.name}'s Scorecard`,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t(r?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(_a,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:l==null?void 0:l.name}),e.jsx("p",{className:"text-muted-foreground",children:l==null?void 0:l.email})]})]}),e.jsxs(vs,{value:String(a),onValueChange:g=>i(Number(g)),children:[e.jsx(gs,{className:"w-[120px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:S3n.map(g=>e.jsx(Je,{value:String(g),children:g},g))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ia,{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(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[u.buyerCount,"/",u.sellerCount]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Od,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Su(u.totalVolume,!0)})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(kl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg Price"})]}),e.jsx("p",{className:"text-2xl font-bold",children:Su(u.averagePrice,!0)})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(cu,{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)||"-"})]})})]}),x&&e.jsx(vzt,{goals:x,stats:u,year:a,showCommission:p}),e.jsxs(fa,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"transactions",children:"Transactions"}),e.jsx(ss,{value:"charts",children:"Charts"}),e.jsxs(ss,{value:"map",children:[e.jsx(oi,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(ns,{value:"transactions",children:e.jsx(ZKe,{transactions:c||[],showCommission:p,isLoading:d})}),e.jsx(ns,{value:"charts",children:e.jsx(XKe,{stats:u,year:a})}),e.jsx(ns,{value:"map",children:e.jsx(QKe,{transactions:c||[],isLoading:d})})]})]})})}function C3n(){const s=as(),[t,n]=j.useState(""),[r,a]=j.useState("all"),[i,l]=j.useState(null);D3t();const{data:o,refetch:c}=mt({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:I}=await U.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(I==null?void 0:I.enabled)??!1}}),{data:d,isLoading:u}=mt({queryKey:["admin-listings"],queryFn:async()=>{const{data:I,error:O}=await U.from("listings").select(` *, agent:profiles!listings_agent_id_fkey(id, name, email), photos:listing_photos(id, photo_url, is_primary) `).order("created_at",{ascending:!1});if(O)throw O;return I}}),{data:h}=mt({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:I}=await U.from("listings").select("id, is_approved, status"),{data:O}=await U.from("listing_shares").select("id"),{data:$}=await U.from("listing_views").select("id"),{count:q}=await U.from("listing_leads").select("id",{count:"exact",head:!0}),W=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:G}=await U.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",W);return{total:(I==null?void 0:I.length)||0,pending:(I==null?void 0:I.filter(K=>!K.is_approved).length)||0,active:(I==null?void 0:I.filter(K=>K.status==="active").length)||0,totalShares:(O==null?void 0:O.length)||0,totalViews:($==null?void 0:$.length)||0,totalLeads:q||0,leadsLast7:G||0}}}),{data:m}=mt({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const I={};let O=0;const $=1e3;for(;;){const{data:q,error:W}=await U.from("listing_leads").select("listing_id").range(O,O+$-1);if(W)throw W;if(!q||q.length===0)break;for(const G of q)G.listing_id&&(I[G.listing_id]=(I[G.listing_id]||0)+1);if(q.length<$)break;O+=$}return I}}),{data:p,isLoading:x}=mt({queryKey:["admin-listing-leads",i==null?void 0:i.listingId],enabled:!!i,queryFn:async()=>{const{data:I,error:O}=await U.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(O)throw O;return I}}),y=async(I,O,$="submit_url")=>{try{const{data:{session:q}}=await U.auth.getSession();if(!q)return;const{data:W,error:G}=await U.functions.invoke("google-indexing",{body:{action:$,listing_id:I,listing_slug:O}});if(G)throw G;if((W==null?void 0:W.configured)===!1)return;W!=null&&W.success&&re.success("Submitted to Google for indexing")}catch(q){console.error("Google indexing submission failed:",q)}},g=vt({mutationFn:async()=>{const{data:{session:I}}=await U.auth.getSession();if(!I)throw new Error("Not authenticated");const{data:O,error:$}=await U.functions.invoke("google-indexing",{body:{action:"submit_all"}});if($)throw $;return O},onSuccess:I=>{if((I==null?void 0:I.configured)===!1){re.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}re.success(`Submitted ${(I==null?void 0:I.succeeded)||0} URLs to Google (${(I==null?void 0:I.failed)||0} failed)`)},onError:I=>{re.error("Failed to submit to Google"),console.error(I)}}),b=vt({mutationFn:async({id:I,approved:O,slug:$})=>{const{error:q}=await U.from("listings").update({is_approved:O}).eq("id",I);if(q)throw q;return{id:I,approved:O,slug:$}},onSuccess:I=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),re.success(I.approved?"Listing approved":"Listing unapproved"),I.approved?y(I.id,I.slug||null,"submit_url"):y(I.id,I.slug||null,"remove_url")}}),v=vt({mutationFn:async({id:I,featured:O})=>{const{error:$}=await U.from("listings").update({is_featured:O}).eq("id",I);if($)throw $},onSuccess:(I,{featured:O})=>{s.invalidateQueries({queryKey:["admin-listings"]}),re.success(O?"Listing featured":"Listing unfeatured")}}),k=vt({mutationFn:async I=>{const{error:O}=await U.from("listings").delete().eq("id",I);if(O)throw O},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),re.success("Listing deleted")}}),C=vt({mutationFn:async I=>{const{error:O}=await U.from("feature_flags").update({enabled:I}).eq("key","listing_exchange_enabled");if(O)throw O},onSuccess:()=>{c(),re.success("Feature flag updated")}}),T=o??!1,M=d==null?void 0:d.filter(I=>{var q,W,G,K;const O=((q=I.city)==null?void 0:q.toLowerCase().includes(t.toLowerCase()))||((G=(W=I.agent)==null?void 0:W.name)==null?void 0:G.toLowerCase().includes(t.toLowerCase()))||((K=I.property_address)==null?void 0:K.toLowerCase().includes(t.toLowerCase())),$=r==="all"||r==="pending"&&!I.is_approved||r==="approved"&&I.is_approved;return O&&$}),P=I=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(I),L=I=>{const O={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 O[I]||O.active};return e.jsxs(Vs,{title:"Listing Exchange Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage community listings"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>g.mutate(),disabled:g.isPending,className:"gap-2",children:[g.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ql,{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(Mn,{checked:T,onCheckedChange:I=>C.mutate(I)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ni,{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(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kl,{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(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Pending Review"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.pending)||0})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ma,{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(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zd,{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(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sl,{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(be,{children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by city, address, or agent...",value:t,onChange:I=>n(I.target.value),className:"pl-9"})]}),e.jsx(fa,{value:r,onValueChange:I=>a(I),children:e.jsxs(xa,{children:[e.jsx(ss,{value:"all",children:"All"}),e.jsx(ss,{value:"pending",children:"Pending"}),e.jsx(ss,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{children:["Listings (",(M==null?void 0:M.length)||0,")"]})}),e.jsx(Re,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Price"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-center",children:"Approved"}),e.jsx(Tt,{className:"text-center",children:"Featured"}),e.jsx(Tt,{children:"Views"}),e.jsx(Tt,{children:"Shares"}),e.jsx(Tt,{children:"Leads"}),e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{})]})}),e.jsx(za,{children:u?e.jsx(un,{children:e.jsx(xt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(M==null?void 0:M.length)===0?e.jsx(un,{children:e.jsx(xt,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):M==null?void 0:M.map(I=>{var O,$,q,W,G;return e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[($=(O=I.photos)==null?void 0:O[0])!=null&&$.photo_url?e.jsx("img",{src:I.photos[0].photo_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(Ni,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:I.property_address||`${I.city}, ${I.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(q=I.property_type)==null?void 0:q.replace("_"," ")})]})]})}),e.jsx(xt,{children:e.jsx("p",{className:"text-sm",children:((W=I.agent)==null?void 0:W.name)||"Unknown"})}),e.jsx(xt,{className:"font-medium",children:P(I.price)}),e.jsx(xt,{children:e.jsx(qe,{variant:"outline",className:L(I.status),children:(G=I.status)==null?void 0:G.replace("_"," ")})}),e.jsx(xt,{className:"text-center",children:e.jsx(Mn,{checked:I.is_approved??!1,onCheckedChange:K=>b.mutate({id:I.id,approved:K,slug:I.slug})})}),e.jsx(xt,{className:"text-center",children:e.jsx(Mn,{checked:I.is_featured??!1,onCheckedChange:K=>v.mutate({id:I.id,featured:K})})}),e.jsx(xt,{children:I.view_count||0}),e.jsx(xt,{children:I.share_count||0}),e.jsx(xt,{children:((m==null?void 0:m[I.id])??0)>0?e.jsx(B,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:I.id,label:I.property_address||`${I.city}, ${I.state}`}),children:m==null?void 0:m[I.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:Bs(new Date(I.created_at),"MMM d, yyyy")}),e.jsx(xt,{children:e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(Hy,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[e.jsxs(wa,{onClick:()=>window.open(`/mission-control/listings/${I.id}`,"_blank"),children:[e.jsx(ma,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(wa,{onClick:()=>v.mutate({id:I.id,featured:!I.is_featured}),children:[e.jsx(Wa,{className:"h-4 w-4 mr-2"}),I.is_featured?"Unfeature":"Feature"]}),e.jsxs(wa,{className:"text-destructive",onClick:async()=>{await Bi("Are you sure you want to delete this listing?")&&k.mutate(I.id)},children:[e.jsx(dr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},I.id)})})]})})})]})]}),e.jsx(Fs,{open:!!i,onOpenChange:I=>!I&&l(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Leads from listing"}),e.jsx(kr,{children:i==null?void 0:i.label})]}),x?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(Wt,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!p||p.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Captured"})]})}),e.jsx(za,{children:p.map(I=>{var O;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:[I.first_name,I.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(xt,{children:I.email}),e.jsx(xt,{children:I.phone||"—"}),e.jsx(xt,{children:e.jsx(qe,{variant:"outline",children:(O=I.lead_type)==null?void 0:O.replace("_"," ")})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:Bs(new Date(I.created_at),"MMM d, yyyy h:mm a")})]},I.id)})})]})]})})]})}function A3n(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function T3n(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),{data:l,isLoading:o}=mt({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const h=[];let m=0;const p=1e3;for(;;){const{data:x,error:y}=await U.from("listing_leads").select(` id, listing_id, agent_id, referred_by_agent_id, first_name, last_name, email, phone, lead_type, showing_mode, preferred_date, preferred_time, message, created_at, listing:listings!listing_leads_listing_id_fkey(id, slug, property_address, city, state, price), agent:profiles!listing_leads_agent_id_fkey(id, name, email), referrer:profiles!listing_leads_referred_by_agent_id_fkey(id, name, email) `).order("created_at",{ascending:!1}).range(m,m+p-1);if(y)throw y;if(!x||x.length===0||(h.push(...x),x.length{if(!l)return[];const h=n==="all"?0:Date.now()-parseInt(n)*24*60*60*1e3,m=s.trim().toLowerCase();return l.filter(p=>{var y,g,b,v,k,C;return h&&new Date(p.created_at).getTime(){const h=c.length,m=c.filter(y=>y.lead_type==="showing_request").length,p=new Set(c.map(y=>y.agent_id)).size,x=new Set(c.map(y=>y.listing_id)).size;return{total:h,showings:m,uniqueAgents:p,uniqueListings:x}},[c]),u=()=>{const m=[["Date","Name","Email","Phone","Type","Showing Date","Property","City","Price","Assigned Agent","Agent Email","Referred By","Message"],...c.map(g=>{var b,v,k,C,T,M;return[Bs(new Date(g.created_at),"yyyy-MM-dd HH:mm"),`${g.first_name||""} ${g.last_name||""}`.trim(),g.email,g.phone||"",g.lead_type,g.preferred_date?`${g.preferred_date} ${g.preferred_time||""}`:"",((b=g.listing)==null?void 0:b.property_address)||"",((v=g.listing)==null?void 0:v.city)||"",(k=g.listing)!=null&&k.price?String(g.listing.price):"",((C=g.agent)==null?void 0:C.name)||"",((T=g.agent)==null?void 0:T.email)||"",((M=g.referrer)==null?void 0:M.name)||"",(g.message||"").replace(/[\r\n]+/g," ")]})].map(g=>g.map(b=>`"${String(b).replace(/"/g,'""')}"`).join(",")).join(` `),p=new Blob([m],{type:"text/csv"}),x=URL.createObjectURL(p),y=document.createElement("a");y.href=x,y.download=`listing-leads-${Bs(new Date,"yyyy-MM-dd")}.csv`,y.click(),URL.revokeObjectURL(x)};return e.jsx(Vs,{title:"Listing Leads",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Leads"}),e.jsx("p",{className:"text-muted-foreground",children:"All leads submitted through the public listings site"})]}),e.jsxs(B,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(ii,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sl,{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(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ra,{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(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ia,{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(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sl,{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(be,{children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search name, email, property, agent...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:a,onValueChange:h=>i(h),children:[e.jsx(gs,{className:"w-full sm:w-48",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Types"}),e.jsx(Je,{value:"info_request",children:"Info Request"}),e.jsx(Je,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(vs,{value:n,onValueChange:h=>r(h),children:[e.jsx(gs,{className:"w-full sm:w-40",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Time"}),e.jsx(Je,{value:"7",children:"Last 7 days"}),e.jsx(Je,{value:"30",children:"Last 30 days"}),e.jsx(Je,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{children:["Leads (",c.length,")"]})}),e.jsx(Re,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"Lead"}),e.jsx(Tt,{children:"Contact"}),e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Assigned To"}),e.jsx(Tt,{children:"Referred By"}),e.jsx(Tt,{children:"Message"})]})}),e.jsx(za,{children:o?e.jsx(un,{children:e.jsx(xt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No leads found"})}):c.map(h=>{var m,p;return e.jsxs(un,{children:[e.jsxs(xt,{className:"whitespace-nowrap text-sm",children:[Bs(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:Bs(new Date(h.created_at),"h:mm a")})]}),e.jsx(xt,{children:e.jsx("div",{className:"font-medium",children:`${h.first_name||""} ${h.last_name||""}`.trim()||"—"})}),e.jsx(xt,{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(on,{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(pa,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(xt,{children:h.listing?e.jsxs(Yn,{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(", ")," · ",A3n(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(xt,{children:[e.jsx(qe,{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(xt,{children:[e.jsx("div",{className:"text-sm font-medium",children:((m=h.agent)==null?void 0:m.name)||"—"}),((p=h.agent)==null?void 0:p.email)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:h.agent.email})]}),e.jsx(xt,{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(xt,{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(ro,{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 h7={new_listing_alerts:{label:"New Listing Alerts",icon:Nx,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:UR,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:mo,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:Fr,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:Op,color:"bg-emerald-100 text-emerald-800"}},_gt=[{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 wgt(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function E3n(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState("30d"),[l,o]=j.useState("all"),[c,d]=j.useState("");j.useEffect(()=>{let p=!1;return(async()=>{r(!0);let x=U.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const y=_gt.find(v=>v.key===a);if(y&&y.days>0){const v=new Date(Date.now()-y.days*864e5).toISOString();x=x.gte("created_at",v)}const{data:g,error:b}=await x;p||(b?(console.error(b),t([])):t(g||[]),r(!1))})(),()=>{p=!0}},[a]);const u=j.useMemo(()=>s.filter(p=>{if(l!=="all"&&p.lead_type!==l)return!1;if(c){const x=c.toLowerCase();if(![p.email,p.first_name,p.last_name,p.phone,p.source_page,p.referrer].filter(Boolean).join(" ").toLowerCase().includes(x))return!1}return!0}),[s,l,c]),h=j.useMemo(()=>{const p=u.length,x=new Set(u.map(g=>g.email.toLowerCase())).size,y={};return u.forEach(g=>{y[g.lead_type]=(y[g.lead_type]||0)+1}),{total:p,uniqueEmails:x,byType:y}},[u]),m=()=>{const x=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(v=>{var C;const k=[wgt(v.created_at),((C=h7[v.lead_type])==null?void 0:C.label)||v.lead_type,v.email,v.first_name||"",v.last_name||"",v.phone||"",v.listing_id||"",v.source_page||"",v.referrer||"",v.criteria?JSON.stringify(v.criteria):""].map(T=>`"${String(T).replace(/"/g,'""')}"`);x.push(k.join(","))});const y=new Blob([x.join(` `)],{type:"text/csv"}),g=URL.createObjectURL(y),b=document.createElement("a");b.href=g,b.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,b.click(),URL.revokeObjectURL(g)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(ql,{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(Yn,{to:"/admin",children:e.jsxs(B,{variant:"ghost",size:"sm",children:[e.jsx(_a,{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(ii,{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(be,{children:e.jsxs(Re,{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(h7).map(p=>{const x=h7[p],y=x.icon;return e.jsx(be,{children:e.jsxs(Re,{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"}),x.label]}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.byType[p]||0})]})},p)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(vs,{value:a,onValueChange:p=>i(p),children:[e.jsx(gs,{className:"w-[160px] bg-white",children:e.jsx(bs,{})}),e.jsx(ys,{children:_gt.map(p=>e.jsx(Je,{value:p.key,children:p.label},p.key))})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-[200px] bg-white",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All lead types"}),Object.keys(h7).map(p=>e.jsx(Je,{value:p,children:h7[p].label},p))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{placeholder:"Search name, email, phone…",value:c,onChange:p=>d(p.target.value),className:"pl-9 bg-white"})]}),e.jsxs("div",{className:"ml-auto text-sm text-slate-500",children:[u.length," ",u.length===1?"lead":"leads"]})]}),e.jsx(be,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500",children:[e.jsx("th",{className:"px-4 py-3",children:"Date"}),e.jsx("th",{className:"px-4 py-3",children:"Type"}),e.jsx("th",{className:"px-4 py-3",children:"Contact"}),e.jsx("th",{className:"px-4 py-3",children:"Phone"}),e.jsx("th",{className:"px-4 py-3",children:"Details"}),e.jsx("th",{className:"px-4 py-3",children:"Source"})]})}),e.jsx("tbody",{children:n?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"Loading…"})}):u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"No leads yet in this range."})}):u.map(p=>{const x=h7[p.lead_type],y=x==null?void 0:x.icon,g=[p.first_name,p.last_name].filter(Boolean).join(" ")||"—";return e.jsxs("tr",{className:"border-b hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-slate-600 text-xs",children:wgt(p.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs(qe,{className:`${(x==null?void 0:x.color)||""} font-normal`,variant:"secondary",children:[y?e.jsx(y,{className:"h-3 w-3 mr-1"}):null,(x==null?void 0:x.label)||p.lead_type]})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium text-slate-900",children:g}),e.jsxs("a",{href:`mailto:${p.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(on,{className:"h-3 w-3"}),p.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:p.phone?e.jsxs("a",{href:`tel:${p.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(pa,{className:"h-3 w-3"}),p.phone]}):e.jsx("span",{className:"text-slate-400 text-xs",children:"—"})}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-600 max-w-xs",children:[p.listing_id&&e.jsxs("div",{className:"mb-0.5",children:["Listing: ",e.jsxs("span",{className:"font-mono text-[10px]",children:[p.listing_id.slice(0,8),"…"]})]}),p.criteria&&Object.keys(p.criteria).length>0&&e.jsx("div",{className:"text-slate-500 line-clamp-2",children:Object.entries(p.criteria).map(([b,v])=>`${b}: ${v}`).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-500 max-w-xs truncate",children:[p.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(Tr,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p.source_page})]}),p.referrer&&e.jsxs("div",{className:"text-slate-400 truncate",children:["from ",p.referrer]})]})]},p.id)})})]})})})]})]})}const M3n=()=>{var h,m;const[s,t]=j.useState(""),[n,r]=j.useState(null),{data:a,isLoading:i}=mt({queryKey:["membership-reviews"],queryFn:async()=>{const{data:p,error:x}=await U.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(x)throw x;const y=(p==null?void 0:p.map(v=>v.user_id))||[],{data:g}=await U.from("profiles").select("id, name, email").in("id",y);return p==null?void 0:p.map(v=>({...v,profiles:(g==null?void 0:g.find(k=>k.id===v.user_id))||null}))}}),l=a==null?void 0:a.filter(p=>{var y,g,b,v,k;const x=s.toLowerCase();return((g=(y=p.profiles)==null?void 0:y.name)==null?void 0:g.toLowerCase().includes(x))||((v=(b=p.profiles)==null?void 0:b.email)==null?void 0:v.toLowerCase().includes(x))||((k=p.review_text)==null?void 0:k.toLowerCase().includes(x))}),o=a!=null&&a.length?(a.reduce((p,x)=>p+x.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((p,x)=>(p[x.rating]=(p[x.rating]||0)+1,p),{}),d=(a==null?void 0:a.filter(p=>p.posted_to_google).length)||0,u=p=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(x=>e.jsx(Wa,{className:Et("h-4 w-4",p>=x?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},x))});return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{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(be,{children:e.jsxs(Ft,{className:"pb-2",children:[e.jsx(fr,{children:"Total Reviews"}),e.jsx(Ut,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(be,{children:e.jsxs(Ft,{className:"pb-2",children:[e.jsx(fr,{children:"Average Rating"}),e.jsxs(Ut,{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(be,{children:e.jsxs(Ft,{className:"pb-2",children:[e.jsx(fr,{children:"5-Star Reviews"}),e.jsx(Ut,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(be,{children:e.jsxs(Ft,{className:"pb-2",children:[e.jsx(fr,{children:"Posted to Google"}),e.jsxs(Ut,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(Tr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or review...",value:s,onChange:p=>t(p.target.value),className:"pl-9"})]}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Member"}),e.jsx(Tt,{children:"Rating"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Tt,{children:"Google"}),e.jsx(Tt,{children:"Date"})]})}),e.jsx(za,{children:i?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(p=>{var x,y;return e.jsxs(un,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(p),children:[e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((x=p.profiles)==null?void 0:x.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(y=p.profiles)==null?void 0:y.email})]})}),e.jsx(xt,{children:u(p.rating)}),e.jsx(xt,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:p.review_text||"-"})}),e.jsx(xt,{children:p.posted_to_google?e.jsx(qe,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(qe,{variant:"outline",children:"No"})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:Bs(new Date(p.created_at),"MMM d, yyyy")})]},p.id)})})]})})}),e.jsx(Fs,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx($s,{children:e.jsx(zs,{children:"Review Details"})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:((h=n.profiles)==null?void 0:h.name)||"Unknown Member"}),((m=n.profiles)==null?void 0:m.email)&&e.jsxs("a",{href:`mailto:${n.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(on,{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(ra,{className:"h-4 w-4"}),Bs(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs(qe,{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(qe,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},jgt={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},L3n={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 P3n(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("all"),[l,o]=j.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:p,error:x}=await U.from("lead_notification_log").select("*").gte("created_at",m).order("created_at",{ascending:!1}).limit(2e3);if(x)throw x;return p||[]}}),u=j.useMemo(()=>{const m=s.trim().toLowerCase();return(c||[]).filter(p=>n!=="all"&&p.source!==n||a!=="all"&&p.status!==a?!1:m?[p.agent_name,p.agent_email,p.lead_name,p.lead_email,p.lead_phone,p.subject].some(x=>(x||"").toLowerCase().includes(m)):!0)},[c,s,n,a]),h=j.useMemo(()=>{const m=u.length,p=u.filter(g=>g.status==="sent"||g.status==="backfilled").length,x=u.filter(g=>g.status==="failed").length,y=new Set(u.map(g=>g.agent_user_id).filter(Boolean)).size;return{total:m,sent:p,failed:x,agents:y}},[u]);return e.jsx(Vs,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(oh,{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(be,{children:e.jsxs(Re,{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(be,{children:e.jsxs(Re,{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(be,{children:e.jsxs(Re,{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(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Unique Agents"}),e.jsx("div",{className:"text-2xl font-bold",children:h.agents})]})})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agent or lead name, email, phone…",value:s,onChange:m=>t(m.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:n,onValueChange:r,children:[e.jsx(gs,{className:"w-full md:w-48",children:e.jsx(bs,{placeholder:"Source"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Sources"}),Object.entries(jgt).map(([m,p])=>e.jsx(Je,{value:m,children:p},m))]})]}),e.jsxs(vs,{value:a,onValueChange:i,children:[e.jsx(gs,{className:"w-full md:w-40",children:e.jsx(bs,{placeholder:"Status"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Statuses"}),e.jsx(Je,{value:"sent",children:"Sent"}),e.jsx(Je,{value:"backfilled",children:"Backfilled"}),e.jsx(Je,{value:"failed",children:"Failed"})]})]}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"w-full md:w-36",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"1",children:"Last 24h"}),e.jsx(Je,{value:"7",children:"Last 7 days"}),e.jsx(Je,{value:"14",children:"Last 14 days"}),e.jsx(Je,{value:"30",children:"Last 30 days"})]})]})]}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"When"}),e.jsx(Tt,{children:"Source"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Lead"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(za,{children:d?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(un,{children:e.jsx(xt,{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(xt,{className:"whitespace-nowrap text-sm",children:Bs(new Date(m.created_at),"MMM d, yyyy h:mm a")}),e.jsx(xt,{children:e.jsx(qe,{variant:"secondary",children:jgt[m.source]||m.source})}),e.jsxs(xt,{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(xt,{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(on,{className:"h-3 w-3"}),m.lead_email]}),m.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pa,{className:"h-3 w-3"}),m.lead_phone]})]})]}),e.jsxs(xt,{children:[e.jsx(qe,{className:L3n[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 I3n=[{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"}],R3n=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 D3n(){const s=as(),{user:t}=Ns(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(!1),{data:c,isLoading:d}=mt({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:L,error:I}=await U.from("weekly_digest_settings").select("*").single();if(I)throw I;return L}}),{data:u,isLoading:h}=mt({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:L,error:I}=await U.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(I)throw I;return L}}),{data:m}=mt({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:L,error:I}=await U.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(I)throw I;return L||0}}),{data:p,refetch:x}=mt({queryKey:["digest-queue-status"],queryFn:async()=>{const L=new Date;L.setUTCHours(0,0,0,0);const[I,O,$,q]=await Promise.all([U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",L.toISOString()),U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",L.toISOString()),U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",L.toISOString()),U.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",L.toISOString())]);return{pending:I.count||0,processing:O.count||0,sent:$.count||0,failed:q.count||0,total:(I.count||0)+(O.count||0)+($.count||0)+(q.count||0)}},refetchInterval:5e3});j.useEffect(()=>{if(p&&(p.pending>0||p.processing>0)){const L=setInterval(()=>{x(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval(L)}},[p,x,s]);const{data:y=0}=mt({queryKey:["digest-today-failed-count"],queryFn:async()=>{const L=new Date;L.setUTCHours(0,0,0,0);const{count:I,error:O}=await U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",L.toISOString());if(O)throw O;return I||0}}),g=vt({mutationFn:async L=>{const{error:I}=await U.from("weekly_digest_settings").update(L).eq("id",c==null?void 0:c.id);if(I)throw I},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),re.success("Settings updated")},onError:L=>{re.error("Failed to update settings: "+L.message)}}),b=async()=>{r(!0);try{const{data:L,error:I}=await U.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(I)throw I;L.queued?re.success(`${L.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):L.sent!==void 0&&re.success(`Digest sent! ${L.sent} emails delivered, ${L.failed} failed`),x(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(L){re.error("Failed to send digest: "+L.message)}finally{r(!1)}},v=async()=>{var L,I,O,$,q,W;if(!(t!=null&&t.email)){re.error("No email found for your account");return}i(!0);try{const{data:G,error:K}=await U.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(K)throw K;const ee=G==null?void 0:G.resendId,J=G==null?void 0:G.resendDetails,le=J==null?void 0:J.status,ue=((L=J==null?void 0:J.body)==null?void 0:L.status)||((O=(I=J==null?void 0:J.body)==null?void 0:I.data)==null?void 0:O.status),oe=((q=($=J==null?void 0:J.body)==null?void 0:$.error)==null?void 0:q.message)||((W=J==null?void 0:J.body)==null?void 0:W.message);re.success(ee?`Preview accepted by email provider (id: ${ee})${le?`, status check: ${le}`:""}${ue?`, provider: ${ue}`:""}${oe?` (${oe})`:""}. 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){re.error("Failed to send preview: "+G.message)}finally{i(!1)}},k=async()=>{o(!0);try{const{data:L,error:I}=await U.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(I)throw I;L.queued===0||L.sent===0&&L.failed===0&&!L.queued?re.info("No failed emails to retry"):L.queued?re.success(`${L.queued} emails queued for retry!`):re.success(`Retry complete! ${L.sent} emails delivered, ${L.failed} failed`),x(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(L){re.error("Failed to retry: "+L.message)}finally{o(!1)}},C=p!=null&&p.total?Math.round((p.sent+p.failed)/p.total*100):0,T=((p==null?void 0:p.pending)||0)>0||((p==null?void 0:p.processing)||0)>0,{data:M}=mt({queryKey:["digest-delivery-stats"],queryFn:async()=>{var W,G;const L=new Date;L.setUTCHours(0,0,0,0);const[I,O,$,q]=await Promise.all([U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",L.toISOString()),U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",L.toISOString()),U.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",L.toISOString()),U.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:I.count||0,totalFailed:O.count||0,agentOsEngaged:$.count||0,lastSent:((G=(W=q.data)==null?void 0:W[0])==null?void 0:G.sent_at)||null}},refetchInterval:T?5e3:!1}),P={totalSent:(M==null?void 0:M.totalSent)||0,totalFailed:(M==null?void 0:M.totalFailed)||0,lastSent:M==null?void 0:M.lastSent,agentOsEngaged:(M==null?void 0:M.agentOsEngaged)||0};return d?e.jsx(Vs,{title:"Weekly Digest",description:"Manage automated weekly email digests",children:e.jsxs("div",{className:"animate-pulse space-y-4",children:[e.jsx("div",{className:"h-32 bg-muted rounded-lg"}),e.jsx("div",{className:"h-64 bg-muted rounded-lg"})]})}):e.jsx(Vs,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(fa,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(ic,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(ss,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(ol,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(ns,{value:"settings",className:"space-y-6",children:[T&&p&&e.jsx(be,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Re,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(Wt,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Sending emails..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[p.sent.toLocaleString()," sent, ",p.pending.toLocaleString()," pending",p.failed>0&&`, ${p.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[C,"%"]})]}),e.jsx(qi,{value:C,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Processing ~80 emails per minute. Estimated time remaining: ~",Math.ceil(p.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(Bn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:m}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(be,{children:e.jsx(Re,{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(Rr,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-destructive/10",children:e.jsx(Rd,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(be,{children:e.jsx(Re,{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(Vr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.lastSent?Bs(new Date(P.lastSent),"MMM d"):"Never"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last Sent"})]})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(fr,{children:"Configure when the digest is sent"})]}),e.jsxs(Re,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(Mn,{checked:c==null?void 0:c.is_enabled,onCheckedChange:L=>g.mutate({is_enabled:L})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Cron Frequency"}),e.jsxs(vs,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:L=>g.mutate({cron_frequency:L}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(Je,{value:"hourly",children:"Hourly (checks every hour)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(c==null?void 0:c.cron_frequency)==="hourly"?"Cron runs every hour; digest sends when day & hour match.":"Cron runs once daily at the selected hour (UTC)."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Day of Week"}),e.jsxs(vs,{value:String(c==null?void 0:c.send_day),onValueChange:L=>g.mutate({send_day:parseInt(L)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:I3n.map(L=>e.jsx(Je,{value:L.value,children:L.label},L.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Time (UTC)"}),e.jsxs(vs,{value:String(c==null?void 0:c.send_hour),onValueChange:L=>g.mutate({send_hour:parseInt(L)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:R3n.map(L=>e.jsx(Je,{value:L.value,children:L.label},L.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{onClick:v,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(ma,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(B,{onClick:b,disabled:n,className:"flex-1",children:[e.jsx(Dr,{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(Ki,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${y} Failed`]})]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx($r,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(fr,{children:"Choose what to include in the digest"})]}),e.jsxs(Re,{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($r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"New Resources"})]}),e.jsx(Mn,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:L=>g.mutate({include_new_resources:L})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Community Highlights"})]}),e.jsx(Mn,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:L=>g.mutate({include_community_posts:L})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ol,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Agent OS Stats"})]}),e.jsx(Mn,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:L=>g.mutate({include_agent_os_stats:L})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ra,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Upcoming Events"})]}),e.jsx(Mn,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:L=>g.mutate({include_upcoming_events:L})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(uu,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(se,{children:"Goals Progress"})]}),e.jsx(Mn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:L=>g.mutate({include_goals_progress:L})})]})]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Custom Introduction"}),e.jsx(fr,{children:"Personalize the intro message (optional)"})]}),e.jsx(Re,{children:e.jsx(Ds,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:L=>g.mutate({custom_intro_text:L.target.value||null}),rows:3})})]})]}),e.jsx(ns,{value:"stats",children:e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(fr,{children:"Recent digest emails sent to members"})]}),e.jsx(Re,{children:h?e.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map(L=>e.jsx("div",{className:"h-12 bg-muted rounded"},L))}):u&&u.length>0?e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Sent At"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Resources"}),e.jsx(Tt,{children:"Agent OS"})]})}),e.jsx(za,{children:u.map(L=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:L.email_sent_to}),e.jsx(xt,{children:Bs(new Date(L.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(xt,{children:e.jsx(qe,{variant:L.delivery_status==="sent"?"default":"destructive",children:L.delivery_status})}),e.jsx(xt,{children:L.resources_count}),e.jsx(xt,{children:L.has_agent_os_activity?e.jsx(qe,{variant:"secondary",children:"Active"}):e.jsx(qe,{variant:"outline",children:"Not Started"})})]},L.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(on,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No digests sent yet"}),e.jsx("p",{className:"text-sm",children:"Send your first digest to see delivery stats"})]})})]})})]})})}const O3n={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 F3n(){var de,we,je;const s=as(),[t,n]=j.useState(""),[r,a]=j.useState(null),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(!0),[y,g]=j.useState(!1),[b,v]=j.useState(""),[k,C]=j.useState(null),{data:T,isLoading:M}=mt({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:xe,error:fe}=await U.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(fe)throw fe;const Se=(xe==null?void 0:xe.map(De=>De.user_id))||[],{data:Ee}=await U.from("profiles").select("id, name, email").in("id",Se),Le=new Map((Ee==null?void 0:Ee.map(De=>[De.id,{name:De.name,email:De.email}]))||[]);return xe==null?void 0:xe.map(De=>({...De,profile:Le.get(De.user_id)||null}))}}),{data:P}=mt({queryKey:["all-profiles-for-points",T],queryFn:async()=>{const fe=[];let Se=0;for(;;){const{data:Ee,error:Le}=await U.from("profiles").select("id, name, email").order("name").range(Se,Se+1e3-1);if(Le)throw Le;if(fe.push(...Ee),!Ee||Ee.length<1e3)break;Se+=1e3}return fe}}),I=((P==null?void 0:P.filter(xe=>!(T!=null&&T.some(fe=>fe.user_id===xe.id))))||[]).filter(xe=>{var Se,Ee;if(!b)return!0;const fe=b.toLowerCase();return((Se=xe.name)==null?void 0:Se.toLowerCase().includes(fe))||((Ee=xe.email)==null?void 0:Ee.toLowerCase().includes(fe))}),{data:O,isLoading:$}=mt({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:xe,error:fe}=await U.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(fe)throw fe;return xe},enabled:!!(r!=null&&r.user_id)&&o}),{data:q}=mt({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:xe,error:fe}=await U.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(fe)throw fe;return xe},enabled:!!(r!=null&&r.user_id)}),W=vt({mutationFn:async({userId:xe,points:fe,reason:Se})=>{const{error:Ee}=await U.from("agent_points").insert({user_id:xe,points:fe,reason:Se});if(Ee)throw Ee;const{data:Le}=await U.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",xe).maybeSingle(),De=((Le==null?void 0:Le.total_points)||0)+fe,Be=((Le==null?void 0:Le.spendable_points)||0)+fe,{error:Ne}=await U.from("agent_attendance_stats").upsert({user_id:xe,total_points:Math.max(0,De),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(""),re.success(p?"Points awarded successfully!":"Points deducted successfully!")},onError:xe=>{console.error("Error modifying points:",xe),re.error("Failed to modify points")}}),G=()=>{if(!r||!d||!h){re.error("Please fill in all fields");return}const xe=parseInt(d);if(isNaN(xe)||xe<=0){re.error("Please enter a valid positive number");return}W.mutate({userId:r.user_id,points:p?xe:-xe,reason:h})},K=()=>{if(!k||!d||!h){re.error("Please fill in all fields");return}const xe=parseInt(d);if(isNaN(xe)||xe<=0){re.error("Please enter a valid positive number");return}W.mutate({userId:k.id,points:xe,reason:h},{onSuccess:()=>{g(!1),C(null),v("")}})},ee=(xe,fe)=>{a(xe),x(fe),l(!0)},J=xe=>{a(xe),c(!0)},le=T==null?void 0:T.filter(xe=>{var Le,De,Be,Ne;const fe=((De=(Le=xe.profile)==null?void 0:Le.name)==null?void 0:De.toLowerCase())||"",Se=((Ne=(Be=xe.profile)==null?void 0:Be.email)==null?void 0:Ne.toLowerCase())||"",Ee=t.toLowerCase();return fe.includes(Ee)||Se.includes(Ee)}),ue=(T==null?void 0:T.reduce((xe,fe)=>xe+fe.total_points,0))||0,oe=(T==null?void 0:T.length)||0,ie=oe>0?Math.round(ue/oe):0;return M?e.jsx(Vs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(gn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(xe=>e.jsx(gn,{className:"h-24"},xe))}),e.jsx(gn,{className:"h-96"})]})}):e.jsx(Vs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Agent Points Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Track, view, and manage agent gamification points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Bn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:oe}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ll,{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(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(kl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Average Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:ie}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"per agent"})]})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between",children:[e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:t,onChange:xe=>n(xe.target.value),className:"pl-10"})]}),e.jsxs(B,{onClick:()=>g(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Agent Leaderboard"}),e.jsx(fr,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Re,{children:!le||le.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ll,{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(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Total Points"}),e.jsx(Tt,{className:"text-center",children:"Spendable"}),e.jsx(Tt,{className:"text-center",children:"Events"}),e.jsx(Tt,{className:"text-center",children:"Streak"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:le.map((xe,fe)=>{var Se,Ee,Le,De;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:fe<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${fe===0?"bg-yellow-100 text-yellow-700":fe===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:fe+1}):e.jsx("span",{className:"text-muted-foreground",children:fe+1})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ra,{className:"h-8 w-8",children:e.jsx(Da,{children:((Ee=(Se=xe.profile)==null?void 0:Se.name)==null?void 0:Ee.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Le=xe.profile)==null?void 0:Le.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(De=xe.profile)==null?void 0:De.email})]})]})}),e.jsx(xt,{className:"text-center",children:e.jsxs(qe,{variant:"secondary",className:"font-bold",children:[e.jsx(Wa,{className:"h-3 w-3 mr-1"}),xe.total_points]})}),e.jsx(xt,{className:"text-center",children:e.jsxs(qe,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(zo,{className:"h-3 w-3 mr-1"}),xe.spendable_points||0]})}),e.jsx(xt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ra,{className:"h-3 w-3 text-muted-foreground"}),xe.total_events_attended]})}),e.jsx(xt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Fd,{className:"h-3 w-3 text-orange-500"}),xe.current_streak]})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ee(xe,!0),title:"Award points",children:e.jsx(Js,{className:"h-4 w-4 text-green-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ee(xe,!1),title:"Deduct points",children:e.jsx(gN,{className:"h-4 w-4 text-red-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>J(xe),title:"View history",children:e.jsx(GT,{className:"h-4 w-4"})})]})})]},xe.user_id)})})]})})]}),e.jsx(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:p?"Award Points":"Deduct Points"}),e.jsxs(kr,{children:[p?"Award":"Deduct"," points ",p?"to":"from"," ",((de=r==null?void 0:r.profile)==null?void 0:de.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"points",children:"Points Amount"}),e.jsx(ye,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:xe=>u(xe.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"reason",children:"Reason"}),e.jsx(Ds,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:xe=>m(xe.target.value)})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:G,disabled:W.isPending,className:p?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:W.isPending?"Saving...":p?"Award Points":"Deduct Points"})]})]})}),e.jsx(Fs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs($s,{children:[e.jsxs(zs,{children:["Point History: ",(we=r==null?void 0:r.profile)==null?void 0:we.name]}),e.jsx(kr,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(fa,{defaultValue:"history",className:"w-full",children:[e.jsxs(xa,{className:"grid w-full grid-cols-2",children:[e.jsx(ss,{value:"history",children:"Point History"}),e.jsx(ss,{value:"badges",children:"Badges"})]}),e.jsx(ns,{value:"history",className:"mt-4",children:$?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(xe=>e.jsx(gn,{className:"h-12"},xe))}):!O||O.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(GT,{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:O.map(xe=>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:xe.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Bs(new Date(xe.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(qe,{variant:xe.points>=0?"default":"destructive",className:xe.points>=0?"bg-green-100 text-green-800":"",children:[xe.points>=0?"+":"",xe.points]})]},xe.id))})}),e.jsx(ns,{value:"badges",className:"mt-4",children:!q||q.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(cu,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No badges earned yet"})]}):e.jsx("div",{className:"grid grid-cols-2 gap-3",children:q.map(xe=>e.jsxs("div",{className:`p-3 rounded-lg ${O3n[xe.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cu,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:xe.badge_name})]}),xe.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:xe.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",Bs(new Date(xe.earned_at),"MMM d, yyyy")]})]},xe.id))})})]})]})}),e.jsx(Fs,{open:y,onOpenChange:xe=>{g(xe),xe||(C(null),v(""),u(""),m(""))},children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Award Points to New Agent"}),e.jsx(kr,{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(Ra,{className:"h-10 w-10",children:e.jsx(Da,{children:((je=k.name)==null?void 0:je.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:()=>C(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(ye,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:xe=>u(xe.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Ds,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:xe=>m(xe.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:b,onChange:xe=>v(xe.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:I.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(Bn,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:b?"No matching agents found":"All agents already have points"})]}):I.slice(0,20).map(xe=>{var fe;return e.jsxs("button",{onClick:()=>C(xe),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(Ra,{className:"h-8 w-8",children:e.jsx(Da,{children:((fe=xe.name)==null?void 0:fe.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:xe.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:xe.email})]})]},xe.id)})})]})}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),k&&e.jsxs(B,{onClick:K,disabled:W.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function z3n(){const{data:s,isLoading:t}=wcs(),[n,r]=j.useState(null),[a,i]=j.useState(!1),[l,o]=j.useState(""),[c,d]=j.useState("all"),[u,h]=j.useState("newest"),[m,p]=j.useState("table"),x=j.useMemo(()=>(s==null?void 0:s.map(k=>k.user_id))||[],[s]),y=j.useMemo(()=>(s==null?void 0:s.map(k=>k.id))||[],[s]),{data:g}=mt({queryKey:["card-profiles-lookup",x],queryFn:async()=>{if(x.length===0)return{};const{data:k}=await U.from("profiles").select("id, name, email").in("id",x),C={};return k==null||k.forEach(T=>{C[T.id]={name:T.name||"",email:T.email||""}}),C},enabled:x.length>0}),{data:b}=mt({queryKey:["card-stats-all",y],queryFn:async()=>{if(y.length===0)return{};const k={};y.forEach(M=>{k[M]={views:0,leads:0}});const{data:C}=await U.from("agent_card_interactions").select("card_id").in("card_id",y).eq("interaction_type","card_view");C==null||C.forEach(M=>{k[M.card_id]&&k[M.card_id].views++});const{data:T}=await U.from("agent_card_leads").select("card_id").in("card_id",y);return T==null||T.forEach(M=>{k[M.card_id]&&k[M.card_id].leads++}),k},enabled:y.length>0}),v=j.useMemo(()=>{if(!s)return[];let k=[...s];if(c==="live"?k=k.filter(C=>C.is_published):c==="draft"&&(k=k.filter(C=>!C.is_published)),l.trim()){const C=l.toLowerCase();k=k.filter(T=>{var P,L;const M=g==null?void 0:g[T.user_id];return T.slug.toLowerCase().includes(C)||((P=M==null?void 0:M.name)==null?void 0:P.toLowerCase().includes(C))||((L=M==null?void 0:M.email)==null?void 0:L.toLowerCase().includes(C))})}return u==="newest"?k.sort((C,T)=>new Date(T.created_at).getTime()-new Date(C.created_at).getTime()):u==="oldest"?k.sort((C,T)=>new Date(C.created_at).getTime()-new Date(T.created_at).getTime()):u==="name"?k.sort((C,T)=>{var M,P;return(((M=g==null?void 0:g[C.user_id])==null?void 0:M.name)||"").localeCompare(((P=g==null?void 0:g[T.user_id])==null?void 0:P.name)||"")}):u==="slug"?k.sort((C,T)=>C.slug.localeCompare(T.slug)):u==="views_desc"?k.sort((C,T)=>{var M,P;return(((M=b==null?void 0:b[T.id])==null?void 0:M.views)||0)-(((P=b==null?void 0:b[C.id])==null?void 0:P.views)||0)}):u==="views_asc"?k.sort((C,T)=>{var M,P;return(((M=b==null?void 0:b[C.id])==null?void 0:M.views)||0)-(((P=b==null?void 0:b[T.id])==null?void 0:P.views)||0)}):u==="leads_desc"?k.sort((C,T)=>{var M,P;return(((M=b==null?void 0:b[T.id])==null?void 0:M.leads)||0)-(((P=b==null?void 0:b[C.id])==null?void 0:P.leads)||0)}):u==="leads_asc"&&k.sort((C,T)=>{var M,P;return(((M=b==null?void 0:b[C.id])==null?void 0:M.leads)||0)-(((P=b==null?void 0:b[T.id])==null?void 0:P.leads)||0)}),k},[s,c,l,u,g]);return e.jsxs(Vs,{title:"Digital Agent Cards",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Digital Agent Cards"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage agent digital business cards"})]}),e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Create Card"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or slug...",value:l,onChange:k=>o(k.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:c,onValueChange:d,children:[e.jsx(gs,{className:"w-full sm:w-36",children:e.jsx(bs,{placeholder:"Status"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All Status"}),e.jsx(Je,{value:"live",children:"Live"}),e.jsx(Je,{value:"draft",children:"Draft"})]})]}),e.jsxs(vs,{value:u,onValueChange:h,children:[e.jsx(gs,{className:"w-full sm:w-44",children:e.jsx(bs,{placeholder:"Sort by"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"newest",children:"Newest First"}),e.jsx(Je,{value:"oldest",children:"Oldest First"}),e.jsx(Je,{value:"name",children:"Name A–Z"}),e.jsx(Je,{value:"slug",children:"Slug A–Z"}),e.jsx(Je,{value:"views_desc",children:"Most Views"}),e.jsx(Je,{value:"views_asc",children:"Fewest Views"}),e.jsx(Je,{value:"leads_desc",children:"Most Leads"}),e.jsx(Je,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx(B,{variant:m==="table"?"default":"ghost",size:"sm",onClick:()=>p("table"),className:"rounded-r-none",children:e.jsx(oz,{className:"h-4 w-4"})}),e.jsx(B,{variant:m==="grid"?"default":"ghost",size:"sm",onClick:()=>p("grid"),className:"rounded-l-none",children:e.jsx(r0,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",v.length," of ",s.length," cards"]}),t?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(k=>e.jsx(gn,{className:"h-48"},k))}):v.length>0?m==="table"?e.jsx(B3n,{cards:v,cardProfiles:g,cardStats:b,onEdit:r,sortBy:u,setSortBy:h}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:v.map(k=>e.jsx($3n,{card:k,onEdit:()=>r(k),stats:b==null?void 0:b[k.id]},k.id))}):s&&s.length>0?e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Fr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No matching cards"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Try adjusting your search or filters"})]})}):e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Bn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No cards yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first digital agent card"}),e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(U3n,{open:a,onOpenChange:i}),n&&e.jsx(q3n,{card:n,open:!!n,onOpenChange:k=>!k&&r(null)})]})}function B3n({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(tx,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(Gm,{className:"h-3 w-3"}):e.jsx(_x,{className:"h-3 w-3 opacity-40"});return e.jsx(be,{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(Gm,{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(qe,{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(Za,{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),re.success("Link copied!")},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",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 $3n({card:s,onEdit:t,stats:n}){const[r,a]=j.useState(null);j.useEffect(()=>{(async()=>{const{data:c}=await U.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await U.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:h}=U.storage.from("avatars").getPublicUrl(`${s.user_id}/${u[0].name}`);d=h.publicUrl}}catch{}a({name:(c==null?void 0:c.name)||"Unknown",avatar_url:d})})()},[s.user_id]);const i=`https://cards.relevelup.com/${s.slug}`,l=()=>{navigator.clipboard.writeText(i),re.success("Link copied!")};return e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:(r==null?void 0:r.avatar_url)||void 0}),e.jsx(Da,{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(qe,{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(ma,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.views)??0," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.leads)??0," leads"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(Za,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:l,children:e.jsx(ja,{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 U3n({open:s,onOpenChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=r5t(),h=l.trim(),{data:m}=mt({queryKey:["profiles-search-for-cards",h],queryFn:async()=>{let v=U.from("profiles").select("id, name, email").order("name").limit(50);h.length>=2&&(v=v.or(`name.ilike.%${h}%,email.ilike.%${h}%`));const{data:k}=await v;return k||[]},enabled:s}),[p,x]=j.useState(null),y=(m==null?void 0:m.find(v=>v.id===n))||p,g=()=>{if(!n||!a.trim()){re.error("Select an agent and enter a slug");return}u.mutate({user_id:n,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),r(""),i(""),o("")}})},b=v=>{var C;r(v),d(!1);const k=m==null?void 0:m.find(T=>T.id===v);k&&(x(k),i(((C=k.name)==null?void 0:C.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Create Agent Card"}),e.jsx(kr,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Agent"}),e.jsxs(lc,{open:c,onOpenChange:d,children:[e.jsx(cc,{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(fb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Jl,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Sb,{shouldFilter:!1,children:[e.jsx(Cb,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(Ab,{children:[e.jsx(Tb,{children:"No agents found."}),e.jsx(Eb,{children:(m||[]).map(v=>e.jsxs(Yy,{value:v.id,onSelect:b,children:[e.jsx(da,{className:Et("mr-2 h-4 w-4",n===v.id?"opacity-100":"opacity-0")}),v.name," (",v.email,")"]},v.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"URL Slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"/card/"}),e.jsx(ye,{value:a,onChange:v=>i(v.target.value),placeholder:"john-doe"})]})]}),e.jsx(B,{onClick:g,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function q3n({card:s,open:t,onOpenChange:n}){const r=a5t(),{data:a}=i5t(s.id),i=as(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState(""),[x,y]=j.useState(s.slug),[g,b]=j.useState(!1),[v,k]=j.useState({is_published:s.is_published,theme:s.theme,title:s.title||"",positioning_statement:s.positioning_statement||"",bio:s.bio||"",review_snippet:s.review_snippet||"",review_source_url:s.review_source_url||"",booking_url:s.booking_url||"",custom_cta_label:s.custom_cta_label||"",custom_cta_url:s.custom_cta_url||"",show_photo:s.show_photo,show_bio:s.show_bio,show_credentials:s.show_credentials,show_social_links:s.show_social_links,show_save_contact:s.show_save_contact,show_leave_review:s.show_leave_review,show_refer_friend:s.show_refer_friend,brokerage_display_name:s.brokerage_display_name||"",brokerage_logo_url:s.brokerage_logo_url||"",brokerage_logo_size:s.brokerage_logo_size||56,team_name:s.team_name||"",team_logo_url:s.team_logo_url||"",team_logo_size:s.team_logo_size||56});j.useEffect(()=>{t&&(async()=>{try{const{data:O}=await U.storage.from("avatars").list(`${s.user_id}`);if(O&&O.length>0){const{data:$}=U.storage.from("avatars").getPublicUrl(`${s.user_id}/${O[0].name}`);o(`${$.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const C=I=>{var q;const O=(q=I.target.files)==null?void 0:q[0];if(!O)return;if(!O.type.startsWith("image/")){re.error("Please select an image file");return}if(O.size>5*1024*1024){re.error("Image must be under 5MB");return}const $=new FileReader;$.onloadend=()=>{p($.result),h(!0)},$.readAsDataURL(O),I.target.value=""},T=async I=>{d(!0);try{const{data:O}=await U.storage.from("avatars").list(`${s.user_id}`);O&&O.length>0&&await U.storage.from("avatars").remove(O.map(K=>`${s.user_id}/${K.name}`));const $=`${s.user_id}/avatar.jpg`,{error:q}=await U.storage.from("avatars").upload($,I,{upsert:!0,contentType:"image/jpeg"});if(q)throw q;const{data:W}=U.storage.from("avatars").getPublicUrl($),G=`${W.publicUrl}?t=${Date.now()}`;o(G),await U.from("profiles").update({avatar_url:G}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),re.success("Photo updated!")}catch(O){re.error(O.message||"Upload failed")}finally{d(!1)}},M=async()=>{const I=x.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!I){re.error("Please enter a valid URL");return}if(I===s.slug){re.info("No changes to save");return}b(!0);try{const{data:O}=await U.from("agent_cards").select("id").eq("slug",I).neq("id",s.id).maybeSingle();if(O){re.error("This URL is already taken. Try another one.");return}const{error:$}=await U.from("agent_cards").update({slug:I}).eq("id",s.id);if($)throw $;y(I),i.invalidateQueries({queryKey:["agent-cards-admin"]}),re.success("Card address updated!")}catch{re.error("Failed to update card address")}finally{b(!1)}},P=async(I,O)=>{var q;const $=(q=I.target.files)==null?void 0:q[0];if($){if(!$.type.startsWith("image/")){re.error("Please select an image file");return}try{const W=$.name.split(".").pop()||"png",G=O==="brokerage_logo_url"?"brokerage-logo":"team-logo",K=`${s.user_id}/${G}.${W}`,{error:ee}=await U.storage.from("card-logos").upload(K,$,{upsert:!0});if(ee)throw ee;const{data:J}=U.storage.from("card-logos").getPublicUrl(K),le=J.publicUrl+"?t="+Date.now();k(O==="brokerage_logo_url"?ue=>({...ue,[O]:le,brokerage_display_name:""}):ue=>({...ue,[O]:le,team_name:""})),re.success("Logo uploaded!")}catch{re.error("Failed to upload logo")}finally{I.target.value=""}}},L=()=>{r.mutate({id:s.id,...v,title:v.title||null,positioning_statement:v.positioning_statement||null,bio:v.bio||null,review_snippet:v.review_snippet||null,review_source_url:v.review_source_url||null,booking_url:v.booking_url||null,custom_cta_label:v.custom_cta_label||null,custom_cta_url:v.custom_cta_url||null,brokerage_display_name:v.brokerage_display_name||null,brokerage_logo_url:v.brokerage_logo_url||null,brokerage_logo_size:v.brokerage_logo_size,team_name:v.team_name||null,team_logo_url:v.team_logo_url||null,team_logo_size:v.team_logo_size},{onSuccess:()=>n(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(Fs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Edit Agent Card"}),e.jsxs(kr,{children:["/card/",s.slug]})]}),e.jsxs(fa,{defaultValue:"content",children:[e.jsxs(xa,{className:"w-full",children:[e.jsx(ss,{value:"content",className:"flex-1",children:"Content"}),e.jsx(ss,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(ss,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(ss,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(ns,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Published"}),e.jsx(Mn,{checked:v.is_published,onCheckedChange:I=>k(O=>({...O,is_published:I}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(Ra,{className:"h-16 w-16",children:[e.jsx(Fi,{src:l||void 0}),e.jsx(Da,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:C,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(Wt,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(ye,{value:x,onChange:I=>y(I.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:M,disabled:g||x===s.slug,className:"shrink-0",children:g?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Theme"}),e.jsxs(vs,{value:v.theme,onValueChange:I=>k(O=>({...O,theme:I})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(Je,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(Je,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(Je,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Title / Tagline"}),e.jsx(ye,{value:v.title,onChange:I=>k(O=>({...O,title:I.target.value})),placeholder:"e.g. Luxury Real Estate Specialist"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Shown below the agent's name on the card"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Positioning Statement"}),e.jsx(ye,{value:v.positioning_statement,onChange:I=>k(O=>({...O,positioning_statement:I.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Bio"}),e.jsx(Ds,{value:v.bio,onChange:I=>k(O=>({...O,bio:I.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Review Snippet"}),e.jsx(ye,{value:v.review_snippet,onChange:I=>k(O=>({...O,review_snippet:I.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Review Source URL"}),e.jsx(ye,{value:v.review_source_url,onChange:I=>k(O=>({...O,review_source_url:I.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(ye,{value:v.booking_url,onChange:I=>k(O=>({...O,booking_url:I.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Custom CTA Label (optional)"}),e.jsx(ye,{value:v.custom_cta_label,onChange:I=>k(O=>({...O,custom_cta_label:I.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Custom CTA URL (optional)"}),e.jsx(ye,{value:v.custom_cta_url,onChange:I=>k(O=>({...O,custom_cta_url:I.target.value})),placeholder:"https://example.com/landing"})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ye,{value:v.brokerage_display_name,onChange:I=>k(O=>({...O,brokerage_display_name:I.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!v.brokerage_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[v.brokerage_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:v.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${v.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>k(I=>({...I,brokerage_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(Ja,{className:"h-3.5 w-3.5"}),v.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:I=>P(I,"brokerage_logo_url")})]})]}),v.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v.brokerage_logo_size||56,"px"]})]}),e.jsx(Qf,{value:[v.brokerage_logo_size||56],onValueChange:([I])=>k(O=>({...O,brokerage_logo_size:I})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(se,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ye,{value:v.team_name,onChange:I=>k(O=>({...O,team_name:I.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!v.team_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[v.team_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:v.team_logo_url,alt:"Team logo",style:{height:`${v.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>k(I=>({...I,team_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(Ja,{className:"h-3.5 w-3.5"}),v.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:I=>P(I,"team_logo_url")})]})]}),v.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v.team_logo_size||56,"px"]})]}),e.jsx(Qf,{value:[v.team_logo_size||56],onValueChange:([I])=>k(O=>({...O,team_logo_size:I})),min:24,max:120,step:4})]})]})]})]}),e.jsx(ns,{value:"sections",className:"space-y-4 mt-4",children:[{key:"show_photo",label:"Show Photo",hint:"Photo is pulled from the agent's profile."},{key:"show_bio",label:"Show Bio"},{key:"show_credentials",label:"Show Credentials"},{key:"show_social_links",label:"Show Social Links"},{key:"show_save_contact",label:"Save Contact Button"},{key:"show_leave_review",label:"Leave Review Button"},{key:"show_refer_friend",label:"Refer a Friend Button"}].map(({key:I,label:O,hint:$})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(se,{children:O}),$&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[$," ",I==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(Mn,{checked:v[I],onCheckedChange:q=>k(W=>({...W,[I]:q}))})]},I))}),e.jsx(ns,{value:"blocks",className:"mt-4",children:e.jsx(lBt,{cardId:s.id})}),e.jsx(ns,{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(be,{children:e.jsxs(Re,{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(be,{children:e.jsxs(Re,{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(be,{children:e.jsxs(Re,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.leads.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Leads"})]})})]}),a.leads.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Recent Leads"}),e.jsx("div",{className:"space-y-2",children:a.leads.slice(0,5).map(I=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:I.name}),I.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",I.phone]}),I.intent&&e.jsx(qe,{variant:"secondary",className:"ml-2 text-xs",children:I.intent})]},I.id))})]})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No analytics data yet"})})]}),e.jsx(B,{onClick:L,disabled:r.isPending,className:"w-full mt-4",children:r.isPending?"Saving...":"Save Changes"})]})}),e.jsx(xHe,{open:u,onClose:()=>h(!1),imageSrc:m,onCropComplete:T,aspectRatio:1})]})}const Uz={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"},iYe={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 oYe(s=!0){return mt({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=U.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});s&&(t=t.eq("is_active",!0));const{data:n,error:r}=await t;if(r)throw r;return n}})}function V3n(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("marketplace_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),re.success("Category created successfully")},onError:t=>{re.error("Failed to create category: "+t.message)}})}function H3n(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("marketplace_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),re.success("Category updated successfully")},onError:t=>{re.error("Failed to update category: "+t.message)}})}function G3n(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("marketplace_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),re.success("Category deleted successfully")},onError:t=>{re.error("Failed to delete category: "+t.message)}})}function mBt(s,t=!0){return mt({queryKey:["marketplace-products",s,t],queryFn:async()=>{let n=U.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).order("sort_order",{ascending:!0});s&&(n=n.eq("category_id",s)),t&&(n=n.eq("is_active",!0));const{data:r,error:a}=await n;if(a)throw a;return r}})}function W3n(s){return mt({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:n}=await U.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function K3n(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("marketplace_products").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),re.success("Product created successfully")},onError:t=>{re.error("Failed to create product: "+t.message)}})}function Y3n(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("marketplace_products").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.id]}),re.success("Product updated successfully")},onError:t=>{re.error("Failed to update product: "+t.message)}})}function Z3n(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("marketplace_products").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),re.success("Product deleted successfully")},onError:t=>{re.error("Failed to delete product: "+t.message)}})}function X3n(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("marketplace_product_images").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]})}})}function Q3n(){const s=as();return vt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await U.from("marketplace_product_images").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),re.success("Image deleted successfully")},onError:t=>{re.error("Failed to delete image: "+t.message)}})}function J3n(){const s=as();return vt({mutationFn:async({imageId:t,productId:n})=>{const{error:r}=await U.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",n);if(r)throw r;const{error:a}=await U.from("marketplace_product_images").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),re.success("Primary image updated")},onError:t=>{re.error("Failed to set primary image: "+t.message)}})}function eCn(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("marketplace_product_variants").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]}),re.success("Variant added successfully")}})}function tCn(){const s=as();return vt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await U.from("marketplace_product_variants").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),re.success("Variant deleted successfully")}})}function sCn(){const s=as();return vt({mutationFn:async({productId:t,videoUrl:n})=>{await U.from("marketplace_product_videos").delete().eq("product_id",t);const{data:r,error:a}=await U.from("marketplace_product_videos").insert({product_id:t,video_url:n}).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.productId]}),re.success("Video updated successfully")}})}function nCn(s){const{isAdmin:t}=Ns();return mt({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let n=U.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:r,error:a}=await n;if(a)throw a;if(t&&r){const i=[...new Set(r.map(c=>c.user_id))],{data:l}=await U.from("profiles").select("id, name, email").in("id",i),o=new Map((l==null?void 0:l.map(c=>[c.id,c]))||[]);return r.map(c=>({...c,user:o.get(c.user_id)}))}return r}})}function rCn(){const{user:s}=Ns();return mt({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await U.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("user_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function aCn(s){return mt({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:n}=await U.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function iCn(){const s=as(),{user:t}=Ns();return vt({mutationFn:async({orderId:n,status:r,notes:a,trackingNumber:i,trackingUrl:l,previousStatus:o})=>{const c={status:r};i!==void 0&&(c.tracking_number=i),l!==void 0&&(c.tracking_url=l);const{error:d}=await U.from("marketplace_orders").update(c).eq("id",n);if(d)throw d;const{error:u}=await U.from("marketplace_order_status_history").insert({order_id:n,status:r,notes:a,created_by:t==null?void 0:t.id});if(u)throw u;if(["shipped","in_production","processing","completed"].includes(r)&&r!==o)try{await U.functions.invoke("marketplace-order-notify",{body:{orderId:n,notificationType:r==="shipped"?"shipped":"status_update",newStatus:r,trackingNumber:i,trackingUrl:l}})}catch(m){console.error("Failed to send notification email:",m)}},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",r.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),re.success("Order status updated")},onError:n=>{re.error("Failed to update order: "+n.message)}})}function oCn(){const s=as();return vt({mutationFn:async({itemId:t,proofUrl:n,proofNotes:r,orderId:a})=>{const{error:i}=await U.from("marketplace_order_items").update({proof_url:n,proof_notes:r,proof_status:"pending"}).eq("id",t);if(i)throw i;await U.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await U.functions.invoke("marketplace-order-notify",{body:{orderId:a,notificationType:"proof_ready"}})}catch(l){console.error("Failed to send proof notification:",l)}return a},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),re.success("Proof uploaded & customer notified")}})}function lCn(){const s=as();return vt({mutationFn:async({itemId:t,orderId:n})=>{const{error:r}=await U.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),re.success("Proof approved")}})}function cCn(){const s=as();return vt({mutationFn:async({itemId:t,orderId:n,reason:r})=>{const{error:a}=await U.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),re.success("Proof rejected - please upload a new proof")}})}function dCn(){const{data:s,isLoading:t}=oYe(!1),n=V3n(),r=H3n(),a=G3n(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),h=()=>{u({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},m=y=>{c(y),u({name:y.name,description:y.description||"",image_url:y.image_url||"",sort_order:y.sort_order,is_active:y.is_active}),l(!0)},p=async y=>{y.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},x=async y=>{await Bi("Are you sure you want to delete this category?")&&await a.mutateAsync(y)};return t?e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(gn,{className:"h-8 w-48"})}),e.jsx(Re,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(y=>e.jsx(gn,{className:"h-12 w-full"},y))})})]}):e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{children:"Categories"}),e.jsxs(Fs,{open:i,onOpenChange:y=>{l(y),y||h()},children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:p,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Name"}),e.jsx(ye,{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(se,{htmlFor:"description",children:"Description"}),e.jsx(Ds,{id:"description",value:d.description,onChange:y=>u({...d,description:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"image_url",children:"Image URL"}),e.jsx(ye,{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(se,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(ye,{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(Mn,{id:"is_active",checked:d.is_active,onCheckedChange:y=>u({...d,is_active:y})}),e.jsx(se,{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(Re,{children:s&&s.length>0?e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Sort Order"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:s.map(y=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:y.name}),e.jsx(xt,{className:"max-w-xs truncate",children:y.description}),e.jsx(xt,{children:y.sort_order}),e.jsx(xt,{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(xt,{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(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>x(y.id),disabled:a.isPending,children:e.jsx(Rn,{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 uCn(){var ie,de;const{data:s,isLoading:t}=mBt(void 0,!1),{data:n}=oYe(!1),r=K3n(),a=Y3n(),i=Z3n(),l=X3n(),o=Q3n(),c=J3n(),d=eCn(),u=tCn(),h=sCn(),[m,p]=j.useState(!1),[x,y]=j.useState(!1),[g,b]=j.useState(!1),[v,k]=j.useState(null),[C,T]=j.useState(null),[M,P]=j.useState(!1),[L,I]=j.useState({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),[O,$]=j.useState({name:"",price_adjustment:0}),[q,W]=j.useState(""),G=()=>{I({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),k(null)},K=we=>{k(we),I({name:we.name,description:we.description||"",base_price:Number(we.base_price),shipping_fee:Number(we.shipping_fee),category_id:we.category_id||"",allow_artwork_upload:we.allow_artwork_upload,requires_proof_approval:we.requires_proof_approval,is_active:we.is_active,sort_order:we.sort_order}),p(!0)},ee=async we=>{we.preventDefault();const je={...L,category_id:L.category_id||null};v?await a.mutateAsync({id:v.id,...je}):await r.mutateAsync(je),p(!1),G()},J=async we=>{await Bi("Are you sure you want to delete this product?")&&await i.mutateAsync(we)},le=async we=>{if(!C||!we.target.files||we.target.files.length===0)return;P(!0);const je=we.target.files[0],xe=je.name.split(".").pop(),fe=`products/${C.id}/${Date.now()}.${xe}`;try{const{error:Se}=await U.storage.from("marketplace").upload(fe,je);if(Se)throw Se;const{data:{publicUrl:Ee}}=U.storage.from("marketplace").getPublicUrl(fe);await l.mutateAsync({product_id:C.id,image_url:Ee,is_primary:!C.images||C.images.length===0}),re.success("Image uploaded successfully")}catch(Se){re.error("Failed to upload image: "+Se.message)}finally{P(!1)}},ue=async we=>{we.preventDefault(),C&&(await d.mutateAsync({product_id:C.id,name:O.name,price_adjustment:O.price_adjustment}),$({name:"",price_adjustment:0}))},oe=async()=>{!C||!q||(await h.mutateAsync({productId:C.id,videoUrl:q}),W(""))};return t?e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(gn,{className:"h-8 w-48"})}),e.jsx(Re,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(we=>e.jsx(gn,{className:"h-64 w-full"},we))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{children:"Products"}),e.jsxs(Fs,{open:m,onOpenChange:we=>{p(we),we||G()},children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:v?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:ee,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"name",children:"Product Name"}),e.jsx(ye,{id:"name",value:L.name,onChange:we=>I({...L,name:we.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"category",children:"Category"}),e.jsxs(vs,{value:L.category_id,onValueChange:we=>I({...L,category_id:we}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select category"})}),e.jsx(ys,{children:n==null?void 0:n.map(we=>e.jsx(Je,{value:we.id,children:we.name},we.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"description",children:"Description"}),e.jsx(Ds,{id:"description",value:L.description,onChange:we=>I({...L,description:we.target.value}),rows:4})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(ye,{id:"base_price",type:"number",step:"0.01",min:"0",value:L.base_price,onChange:we=>I({...L,base_price:parseFloat(we.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(ye,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:L.shipping_fee,onChange:we=>I({...L,shipping_fee:parseFloat(we.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(ye,{id:"sort_order",type:"number",value:L.sort_order,onChange:we=>I({...L,sort_order:parseInt(we.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{id:"allow_artwork_upload",checked:L.allow_artwork_upload,onCheckedChange:we=>I({...L,allow_artwork_upload:we})}),e.jsx(se,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{id:"requires_proof_approval",checked:L.requires_proof_approval,onCheckedChange:we=>I({...L,requires_proof_approval:we})}),e.jsx(se,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{id:"is_active",checked:L.is_active,onCheckedChange:we=>I({...L,is_active:we})}),e.jsx(se,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:r.isPending||a.isPending,children:v?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Re,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(we=>{var je,xe;return e.jsxs(be,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[we.images&&we.images.length>0?e.jsx("img",{src:((je=we.images.find(fe=>fe.is_primary))==null?void 0:je.image_url)||we.images[0].image_url,alt:we.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"}),!we.is_active&&e.jsx(qe,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Re,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:we.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((xe=we.category)==null?void 0:xe.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(we.base_price).toFixed(2)]}),Number(we.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(we.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[we.allow_artwork_upload&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),we.requires_proof_approval&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"Proof Required"}),we.variants&&we.variants.length>0&&e.jsxs(qe,{variant:"outline",className:"text-xs",children:[we.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>K(we),children:[e.jsx(Za,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{T(we),y(!0)},children:[e.jsx(a1,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{T(we),b(!0)},children:[e.jsx(wf,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>J(we.id),children:e.jsx(Rn,{className:"h-3 w-3 text-destructive"})})]})]})]},we.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(Fs,{open:x,onOpenChange:y,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx($s,{children:e.jsxs(zs,{children:["Manage Images - ",C==null?void 0:C.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(ie=C==null?void 0:C.images)==null?void 0:ie.map(we=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:we.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),we.is_primary&&e.jsx(qe,{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:[!we.is_primary&&e.jsx(B,{variant:"secondary",size:"icon",onClick:async()=>{var je;await c.mutateAsync({imageId:we.id,productId:C.id}),T({...C,images:(je=C.images)==null?void 0:je.map(xe=>({...xe,is_primary:xe.id===we.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 xe;await o.mutateAsync({id:we.id,productId:C.id});const je=s==null?void 0:s.find(fe=>fe.id===C.id);je&&T({...je,images:(xe=je.images)==null?void 0:xe.filter(fe=>fe.id!==we.id)})},disabled:o.isPending,children:e.jsx(Rn,{className:"h-4 w-4"})})]})]},we.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:le,className:"hidden",id:"image-upload",disabled:M}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(a1,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:M?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(se,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(ye,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:q,onChange:we=>W(we.target.value)}),e.jsxs(B,{onClick:oe,disabled:!q,children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Set Video"]})]}),(C==null?void 0:C.video)&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Current video: ",C.video.video_url]})]})]})]})}),e.jsx(Fs,{open:g,onOpenChange:b,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsxs(zs,{children:["Manage Variants - ",C==null?void 0:C.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:ue,className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Variant name (e.g., 500 count)",value:O.name,onChange:we=>$({...O,name:we.target.value}),required:!0}),e.jsx(ye,{type:"number",step:"0.01",placeholder:"Price adj.",value:O.price_adjustment,onChange:we=>$({...O,price_adjustment:parseFloat(we.target.value)||0}),className:"w-32"}),e.jsx(B,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(de=C==null?void 0:C.variants)==null?void 0:de.map(we=>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:we.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(we.price_adjustment)>=0?"+":"","$",Number(we.price_adjustment).toFixed(2)]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:we.id,productId:C.id}),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]},we.id)),(!(C!=null&&C.variants)||C.variants.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:'No variants yet. Add variants like "250 count", "500 count", etc.'})]})]})]})})]})}const hCn=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function mCn(){var y,g,b;const{data:s,isLoading:t}=nCn(),n=iCn(),r=oCn(),[a,i]=j.useState(null),[l,o]=j.useState(!1),[c,d]=j.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[u,h]=j.useState(!1),m=v=>{i(v),d({status:v.status,notes:"",trackingNumber:v.tracking_number||"",trackingUrl:v.tracking_url||""}),o(!0)},p=async()=>{a&&(await n.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},x=async(v,k)=>{if(!a||!v.target.files||v.target.files.length===0)return;h(!0);const C=v.target.files[0],T=C.name.split(".").pop(),M=`proofs/${a.id}/${k}/${Date.now()}.${T}`;try{const{error:P}=await U.storage.from("marketplace").upload(M,C);if(P)throw P;const{data:{publicUrl:L}}=U.storage.from("marketplace").getPublicUrl(M);await r.mutateAsync({itemId:k,proofUrl:L,orderId:a.id}),re.success("Proof uploaded successfully")}catch(P){re.error("Failed to upload proof: "+P.message)}finally{h(!1)}};return t?e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(gn,{className:"h-8 w-48"})}),e.jsx(Re,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(v=>e.jsx(gn,{className:"h-16 w-full"},v))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Orders"})}),e.jsx(Re,{children:s&&s.length>0?e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Order #"}),e.jsx(Tt,{children:"Customer"}),e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"Total"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:s.map(v=>{var k,C;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-mono",children:v.order_number}),e.jsx(xt,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((k=v.user)==null?void 0:k.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(C=v.user)==null?void 0:C.email})]})}),e.jsx(xt,{children:Bs(new Date(v.created_at),"MMM d, yyyy")}),e.jsxs(xt,{className:"font-bold",children:["$",Number(v.total).toFixed(2)]}),e.jsx(xt,{children:e.jsx(qe,{className:iYe[v.status],children:Uz[v.status]})}),e.jsx(xt,{className:"text-right",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>m(v),children:[e.jsx(ma,{className:"h-4 w-4 mr-1"}),"View"]})})]},v.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(Fs,{open:l,onOpenChange:o,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsxs(zs,{children:["Order ",a==null?void 0:a.order_number]})}),a&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Customer"}),e.jsx("p",{children:(y=a.user)==null?void 0:y.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(g=a.user)==null?void 0:g.email})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Shipping Address"}),e.jsx("p",{children:a.shipping_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.shipping_address,e.jsx("br",{}),a.shipping_city,", ",a.shipping_state," ",a.shipping_zip]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Order Items"}),e.jsx("div",{className:"space-y-3",children:(b=a.items)==null?void 0:b.map(v=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v.product_name}),v.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:v.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(v.unit_price).toFixed(2)," x ",v.quantity]})]}),v.artwork_url&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Customer Artwork:"}),e.jsx("a",{href:v.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Artwork"})]}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Proof Status: "}),e.jsx(qe,{variant:v.proof_status==="approved"?"default":"secondary",children:v.proof_status||"No proof yet"})]}),v.proof_url?e.jsx("a",{href:v.proof_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Proof"}):e.jsxs("div",{children:[e.jsx("input",{type:"file",accept:"image/*,.pdf",onChange:k=>x(k,v.id),className:"hidden",id:`proof-${v.id}`,disabled:u}),e.jsx("label",{htmlFor:`proof-${v.id}`,children:e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(Ja,{className:"h-4 w-4 mr-1"}),u?"Uploading...":"Upload Proof"]})})})]})]})})]},v.id))})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Subtotal"}),e.jsxs("span",{children:["$",Number(a.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(a.shipping_total).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between font-bold text-lg mt-2",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(a.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Update Order Status"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:c.status,onValueChange:v=>d({...c,status:v}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:hCn.map(v=>e.jsx(Je,{value:v,children:Uz[v]},v))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Tracking Number"}),e.jsx(ye,{value:c.trackingNumber,onChange:v=>d({...c,trackingNumber:v.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Tracking URL"}),e.jsx(ye,{value:c.trackingUrl,onChange:v=>d({...c,trackingUrl:v.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Notes (optional)"}),e.jsx(Ds,{value:c.notes,onChange:v=>d({...c,notes:v.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(B,{onClick:p,disabled:n.isPending,className:"w-full",children:[e.jsx(Eu,{className:"h-4 w-4 mr-2"}),"Update Status"]})]})]}),a.status_history&&a.status_history.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Status History"}),e.jsx("div",{className:"space-y-2",children:a.status_history.map(v=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx(qe,{variant:"outline",children:Uz[v.status]}),v.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:v.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:Bs(new Date(v.created_at),"MMM d, h:mm a")})]},v.id))})]})]})]})})]})}function pCn(){const[s,t]=j.useState("products"),n=Hn();return e.jsx(Vs,{title:"Marketplace Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Marketplace Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage products, categories, and orders"})]}),e.jsxs(B,{variant:"outline",onClick:()=>n("/marketplace"),children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(fa,{value:s,onValueChange:t,children:[e.jsxs(xa,{className:"grid w-full grid-cols-3",children:[e.jsxs(ss,{value:"products",className:"flex items-center gap-2",children:[e.jsx(Eu,{className:"h-4 w-4"}),"Products"]}),e.jsxs(ss,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(ny,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(ss,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(ib,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(ns,{value:"products",children:e.jsx(uCn,{})}),e.jsx(ns,{value:"categories",children:e.jsx(dCn,{})}),e.jsx(ns,{value:"orders",children:e.jsx(mCn,{})})]})]})})}function pBt(){return mt({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await U.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function fCn(s){return mt({queryKey:["reward-items",s],queryFn:async()=>{let t=U.from("reward_store_items").select(` *, category:reward_store_categories(*) `).order("created_at",{ascending:!1});const{data:n,error:r}=await t;if(r)throw r;return n}})}function xCn(s){return mt({queryKey:["active-reward-items",s],queryFn:async()=>{let t=U.from("reward_store_items").select(` *, category:reward_store_categories(*) `).eq("is_active",!0).order("created_at",{ascending:!1});s&&(t=t.eq("category_id",s));const{data:n,error:r}=await t;if(r)throw r;return n}})}function gCn(s){return mt({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).eq("user_id",s).order("purchased_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function yCn(){return mt({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await U.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).order("purchased_at",{ascending:!1});if(t)throw t;if(!s||s.length===0)return[];const n=[...new Set(s.map(l=>l.user_id))],{data:r,error:a}=await U.from("profiles").select("id, name, email").in("id",n);if(a)throw a;const i=new Map((r==null?void 0:r.map(l=>[l.id,l]))||[]);return s.map(l=>({...l,user:i.get(l.user_id)||null}))}})}function vCn(s){return mt({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:n}=await U.from("agent_attendance_stats").select("spendable_points").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return(t==null?void 0:t.spendable_points)||0},enabled:!!s})}function bCn(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.rpc("purchase_reward_item",{p_item_id:t});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error||"Purchase failed");return a},onSuccess:()=>{s.invalidateQueries({queryKey:["user-purchases"]}),s.invalidateQueries({queryKey:["spendable-points"]}),s.invalidateQueries({queryKey:["active-reward-items"]}),s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["homereel-credits"]})}})}function _Cn(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("reward_store_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function wCn(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("reward_store_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function jCn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("reward_store_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function NCn(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("reward_store_items").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function kCn(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("reward_store_items").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function SCn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("reward_store_items").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function CCn(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function XIe(s,t){const n=CCn(s);if(n)try{const{data:r,error:a}=await U.storage.from(n.bucket).download(n.path);if(a){console.error("Error downloading file:",a),re.error("Failed to download file");return}const i=URL.createObjectURL(r),l=document.createElement("a");l.href=i,l.download=t||n.path.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("Download error:",r),re.error("Failed to download file")}else try{const a=await(await fetch(s)).blob(),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=t||s.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("External download error:",r),re.error("Failed to download file")}}function fBt(){return mt({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await U.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function ACn(){const s=as();return vt({mutationFn:async({id:t,points:n,is_active:r})=>{const a={points:n};r!==void 0&&(a.is_active=r);const{data:i,error:l}=await U.from("point_reward_settings").update(a).eq("id",t).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["point-reward-settings"]})}})}function TCn(){const{user:s}=Ns(),[t,n]=j.useState("items"),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(null),[y,g]=j.useState(!1),[b,v]=j.useState(null),[k,C]=j.useState(""),[T,M]=j.useState(""),[P,L]=j.useState(null),[I,O]=j.useState(""),[$,q]=j.useState("file"),[W,G]=j.useState(""),[K,ee]=j.useState(""),[J,le]=j.useState(""),[ue,oe]=j.useState(!0),[ie,de]=j.useState(null),[we,je]=j.useState(!1),[xe,fe]=j.useState(!1),Se=j.useRef(null),Ee=j.useRef(null),{data:Le,isLoading:De}=pBt(),{data:Be,isLoading:Ne}=fCn(),{data:Ge,isLoading:_e}=yCn(),{data:Oe,isLoading:Ae}=fBt(),Xe=_Cn(),Ue=wCn(),Ze=jCn(),Qe=NCn(),Ye=kCn(),nt=SCn(),rt=ACn(),[Fe,dt]=j.useState({}),Dt=jt=>{jt?(l(jt),c(jt.name),u(jt.description||""),m(jt.icon||"")):(l(null),c(""),u(""),m("")),a(!0)},pt=async()=>{if(!o.trim()){re.error("Please enter a category name");return}try{i?(await Ue.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),re.success("Category updated successfully")):(await Xe.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Le==null?void 0:Le.length)||0)+1}),re.success("Category created successfully")),a(!1)}catch(jt){console.error("Error saving category:",jt),re.error("Failed to save category")}},zt=async()=>{if(p)try{await Ze.mutateAsync(p),re.success("Category deleted successfully"),x(null)}catch(jt){console.error("Error deleting category:",jt),re.error("Failed to delete category")}},Gt=jt=>{var Qs;jt?(v(jt),C(jt.name),M(jt.description||""),L(jt.category_id),O(jt.points_cost.toString()),q(jt.item_type),G(jt.file_url||""),ee(jt.preview_image_url||""),le(((Qs=jt.max_quantity)==null?void 0:Qs.toString())||""),oe(jt.is_active)):(v(null),C(""),M(""),L(null),O(""),q("file"),G(""),ee(""),le(""),oe(!0)),g(!0)},qs=async(jt,Qs)=>{Qs==="file"?je(!0):fe(!0);try{const cn=jt.name.split(".").pop(),qt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${cn}`,Gs=`${Qs==="file"?"items":"previews"}/${qt}`,{error:Ls}=await U.storage.from("reward-store").upload(Gs,jt);if(Ls)throw Ls;const{data:{publicUrl:sn}}=U.storage.from("reward-store").getPublicUrl(Gs);Qs==="file"?G(sn):ee(sn),re.success("File uploaded successfully")}catch(cn){console.error("Error uploading file:",cn),re.error("Failed to upload file")}finally{Qs==="file"?je(!1):fe(!1)}},As=async()=>{if(!k.trim()){re.error("Please enter an item name");return}if(!I||parseInt(I)<0){re.error("Please enter a valid points cost");return}try{const jt={name:k,description:T||null,category_id:P,points_cost:parseInt(I),item_type:$,file_url:W||null,preview_image_url:K||null,max_quantity:J?parseInt(J):null,current_quantity:J?parseInt(J):null,is_active:ue,created_by:s==null?void 0:s.id};b?(await Ye.mutateAsync({id:b.id,...jt,current_quantity:b.max_quantity!==(J?parseInt(J):null)?J?parseInt(J):null:b.current_quantity}),re.success("Item updated successfully")):(await Qe.mutateAsync(jt),re.success("Item created successfully")),g(!1)}catch(jt){console.error("Error saving item:",jt),re.error("Failed to save item")}},Bt=async()=>{if(ie)try{await nt.mutateAsync(ie),re.success("Item deleted successfully"),de(null)}catch(jt){console.error("Error deleting item:",jt),re.error("Failed to delete item")}},At=async(jt,Qs)=>{const cn=Fe[jt];if(cn===void 0||cn===Qs.toString())return;const qt=parseInt(cn);if(isNaN(qt)||qt<0){re.error("Please enter a valid positive number");return}try{await rt.mutateAsync({id:jt,points:qt}),re.success("Points updated successfully"),dt(Gs=>{const Ls={...Gs};return delete Ls[jt],Ls})}catch(Gs){console.error("Error updating points:",Gs),re.error("Failed to update points")}};return De||Ne||_e||Ae?e.jsx(Vs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(gn,{className:"h-8 w-64"}),e.jsx(gn,{className:"h-96"})]})}):e.jsxs(Vs,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Reward Store Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage store items that agents can purchase with their points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Eu,{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(jt=>jt.is_active).length)||0," active"]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(ny,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Le==null?void 0:Le.length)||0})]})}),e.jsx(be,{children:e.jsxs(Re,{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((jt,Qs)=>jt+Qs.points_cost,0)/Be.length):0," pts"]})]})})]}),e.jsxs(fa,{value:t,onValueChange:n,children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"items",children:"Items"}),e.jsx(ss,{value:"categories",children:"Categories"}),e.jsx(ss,{value:"purchases",children:"Purchases"}),e.jsx(ss,{value:"point-settings",children:"Point Settings"})]}),e.jsx(ns,{value:"items",className:"mt-4",children:e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Store Items"}),e.jsx(fr,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(B,{onClick:()=>Gt(),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Re,{children:!Be||Be.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(zo,{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(Tt,{children:"Item"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{className:"text-center",children:"Cost"}),e.jsx(Tt,{className:"text-center",children:"Type"}),e.jsx(Tt,{className:"text-center",children:"Quantity"}),e.jsx(Tt,{className:"text-center",children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:Be.map(jt=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[jt.preview_image_url?e.jsx("img",{src:jt.preview_image_url,alt:jt.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(zo,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:jt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:jt.description||"No description"})]})]})}),e.jsx(xt,{children:jt.category?e.jsx(qe,{variant:"outline",children:jt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(xt,{className:"text-center",children:e.jsxs(qe,{variant:"secondary",className:"font-bold",children:[e.jsx(Wa,{className:"h-3 w-3 mr-1"}),jt.points_cost]})}),e.jsx(xt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[jt.item_type==="file"?e.jsx($r,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(vc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:jt.item_type})]})}),e.jsx(xt,{className:"text-center",children:jt.max_quantity!==null?e.jsxs("span",{className:jt.current_quantity===0?"text-red-500":"",children:[jt.current_quantity,"/",jt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(xt,{className:"text-center",children:e.jsx(qe,{variant:jt.is_active?"default":"secondary",children:jt.is_active?"Active":"Inactive"})}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Gt(jt),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>de(jt.id),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})})]},jt.id))})]})})]})}),e.jsx(ns,{value:"categories",className:"mt-4",children:e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Categories"}),e.jsx(fr,{children:"Organize your store items into categories"})]}),e.jsxs(B,{onClick:()=>Dt(),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Re,{children:!Le||Le.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ny,{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(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"text-center",children:"Items"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(za,{children:Le.map(jt=>e.jsxs(un,{children:[e.jsxs(xt,{className:"font-medium",children:[jt.icon&&e.jsx("span",{className:"mr-2",children:jt.icon}),jt.name]}),e.jsx(xt,{className:"text-muted-foreground",children:jt.description||"—"}),e.jsx(xt,{className:"text-center",children:(Be==null?void 0:Be.filter(Qs=>Qs.category_id===jt.id).length)||0}),e.jsx(xt,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Dt(jt),children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>x(jt.id),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]})})]},jt.id))})]})})]})}),e.jsx(ns,{value:"purchases",className:"mt-4",children:e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ib,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(fr,{children:"View all reward redemptions by agents"})]}),e.jsx(Re,{children:!Ge||Ge.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ib,{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(Tt,{children:"Date"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Item"}),e.jsx(Tt,{className:"text-center",children:"Points Spent"})]})}),e.jsx(za,{children:Ge.map(jt=>{var Qs,cn,qt,Gs;return e.jsxs(un,{children:[e.jsx(xt,{className:"text-muted-foreground",children:Bs(new Date(jt.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(xt,{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(Eo,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Qs=jt.user)==null?void 0:Qs.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((cn=jt.user)==null?void 0:cn.email)||"—"})]})]})}),e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(qt=jt.item)!=null&&qt.preview_image_url?e.jsx("img",{src:jt.item.preview_image_url,alt:jt.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(zo,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((Gs=jt.item)==null?void 0:Gs.name)||"Deleted item"})]})}),e.jsx(xt,{className:"text-center",children:e.jsxs(qe,{variant:"secondary",className:"font-bold",children:[e.jsx(Wa,{className:"h-3 w-3 mr-1"}),jt.points_spent]})})]},jt.id)})})]})})]})})]})]}),e.jsx(Fs,{open:r,onOpenChange:a,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:i?"Edit Category":"Add Category"}),e.jsx(kr,{children:i?"Update the category details":"Create a new category for your store items"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"categoryName",children:"Name"}),e.jsx(ye,{id:"categoryName",value:o,onChange:jt=>c(jt.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Ds,{id:"categoryDescription",value:d,onChange:jt=>u(jt.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(ye,{id:"categoryIcon",value:h,onChange:jt=>m(jt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{onClick:pt,disabled:Xe.isPending||Ue.isPending,children:Xe.isPending||Ue.isPending?"Saving...":"Save"})]})]})}),e.jsx(Fs,{open:y,onOpenChange:g,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:b?"Edit Item":"Add Item"}),e.jsx(kr,{children:b?"Update the item details":"Create a new reward item for agents to purchase"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemName",children:"Name *"}),e.jsx(ye,{id:"itemName",value:k,onChange:jt=>C(jt.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemDescription",children:"Description"}),e.jsx(Ds,{id:"itemDescription",value:T,onChange:jt=>M(jt.target.value),placeholder:"Describe the item..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(vs,{value:P||"none",onValueChange:jt=>L(jt==="none"?null:jt),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select category"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No category"}),Le==null?void 0:Le.map(jt=>e.jsxs(Je,{value:jt.id,children:[jt.icon&&`${jt.icon} `,jt.name]},jt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(ye,{id:"itemPointsCost",type:"number",min:"0",value:I,onChange:jt=>O(jt.target.value),placeholder:"e.g., 100"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemType",children:"Type"}),e.jsxs(vs,{value:$,onValueChange:q,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"file",children:"File Download"}),e.jsx(Je,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(ye,{id:"itemMaxQuantity",type:"number",min:"1",value:J,onChange:jt=>le(jt.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:W,onChange:jt=>G(jt.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 jt;return(jt=Se.current)==null?void 0:jt.click()},disabled:we,children:e.jsx(Ja,{className:"h-4 w-4"})}),e.jsx("input",{ref:Se,type:"file",className:"hidden",onChange:jt=>{var cn;const Qs=(cn=jt.target.files)==null?void 0:cn[0];Qs&&qs(Qs,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:K,onChange:jt=>ee(jt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>{var jt;return(jt=Ee.current)==null?void 0:jt.click()},disabled:xe,children:e.jsx(ac,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ee,type:"file",accept:"image/*",className:"hidden",onChange:jt=>{var cn;const Qs=(cn=jt.target.files)==null?void 0:cn[0];Qs&&qs(Qs,"preview")}})]}),K&&e.jsx("img",{src:K,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mn,{id:"itemIsActive",checked:ue,onCheckedChange:oe}),e.jsx(se,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx(B,{onClick:As,disabled:Qe.isPending||Ye.isPending,children:Qe.isPending||Ye.isPending?"Saving...":"Save"})]})]})}),e.jsx(Nl,{open:!!p,onOpenChange:()=>x(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete Category"}),e.jsx(xl,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:zt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Nl,{open:!!ie,onOpenChange:()=>de(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete Item"}),e.jsx(xl,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:Bt,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(be,{className:"mt-4",children:[e.jsx(Ft,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ic,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(Ut,{children:"Point Reward Settings"}),e.jsx(fr,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Re,{children:!Oe||Oe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ic,{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(Tt,{children:"Action"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"text-center w-32",children:"Points"}),e.jsx(Tt,{className:"text-right w-24",children:"Save"})]})}),e.jsx(za,{children:Oe.map(jt=>e.jsxs(un,{children:[e.jsx(xt,{children:e.jsx("p",{className:"font-medium",children:jt.action_name})}),e.jsx(xt,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:jt.description})}),e.jsx(xt,{className:"text-center",children:e.jsx(ye,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:Fe[jt.id]??jt.points.toString(),onChange:Qs=>dt(cn=>({...cn,[jt.id]:Qs.target.value}))})}),e.jsx(xt,{className:"text-right",children:e.jsx(B,{size:"sm",variant:"outline",disabled:Fe[jt.id]===void 0||Fe[jt.id]===jt.points.toString()||rt.isPending,onClick:()=>At(jt.id,jt.points),children:e.jsx(Jo,{className:"h-4 w-4"})})})]},jt.id))})]})})]})]})}const Ngt=()=>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"})]}),kgt=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function ECn(){const s=as(),[t,n]=j.useState(!1),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:u}=mt({queryKey:["canva-integration"],queryFn:async()=>{const{data:v,error:k}=await U.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(k)throw k;return v}}),{data:h}=mt({queryKey:["brokerages-list"],queryFn:async()=>{const{data:v,error:k}=await U.from("brokerages").select("id, name").order("name");if(k)throw k;return v}}),{data:m}=mt({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:v,error:k}=await U.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(k)throw k;return v}}),p=async()=>{var v;n(!0);try{const{data:k}=await U.auth.getSession(),C=(v=k==null?void 0:k.session)==null?void 0:v.access_token;if(!C)throw new Error("Not authenticated");const P=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"get_auth_url"})}),L=await P.json();if(!P.ok||L!=null&&L.error)throw new Error((L==null?void 0:L.error)||"Failed to get authorization URL");if(L!=null&&L.authUrl){localStorage.setItem("canva_code_verifier",L.codeVerifier),localStorage.setItem("canva_oauth_state",L.state);const I=window.open(L.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!I){re.error("Popup was blocked. Please allow popups for this site and try again."),n(!1);return}const O=q=>{var W,G;q.origin===window.location.origin&&(((W=q.data)==null?void 0:W.type)==="canva-oauth-success"?(window.removeEventListener("message",O),re.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1)):((G=q.data)==null?void 0:G.type)==="canva-oauth-error"&&(window.removeEventListener("message",O),re.error("Canva connection failed: "+(q.data.error||"Unknown error")),n(!1)))};window.addEventListener("message",O);const $=setInterval(()=>{I.closed&&(clearInterval($),window.removeEventListener("message",O),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 C=(k==null?void 0:k.message)||"";C.includes("CANVA_CLIENT_ID")?re.error("Canva app credentials not configured yet."):re.error(C||"Failed to start Canva connection"),n(!1)}},x=vt({mutationFn:async v=>{var I;const{data:k}=await U.auth.getSession(),C=(I=k==null?void 0:k.session)==null?void 0:I.access_token;if(!C)throw new Error("Not authenticated");const P=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:v})}),L=await P.json();if(!P.ok||L!=null&&L.error)throw new Error((L==null?void 0:L.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),re.success("Canva disconnected")},onError:v=>{re.error(v.message||"Failed to disconnect Canva")}}),y=vt({mutationFn:async v=>{const{error:k}=await U.from("canva_brokerage_folders").insert({brokerage_id:v.brokerage_id,folder_id:v.folder_id.trim(),folder_name:v.folder_name.trim(),folder_type:v.folder_type,description:v.description.trim()||null,sort_order:(m==null?void 0:m.length)||0});if(k)throw k},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),re.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>re.error("Failed to add folder")}),g=vt({mutationFn:async v=>{const{error:k}=await U.from("canva_brokerage_folders").delete().eq("id",v);if(k)throw k},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),re.success("Folder removed")},onError:()=>re.error("Failed to remove folder")}),b=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsx(Ft,{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(Ngt,{})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Canva Connect",b&&e.jsx(qe,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(qe,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(fr,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(Re,{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(To,{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(To,{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(To,{className:"h-4 w-4 mt-0.5 text-primary shrink-0"}),e.jsx("span",{children:"Multiple folders per brokerage (templates, brand assets, listings)"})]}),e.jsxs("div",{className:"mt-4 p-3 rounded-lg bg-muted border border-dashed",children:[e.jsx("p",{className:"text-xs font-medium text-foreground mb-1",children:"Canva App Redirect URL"}),e.jsx("code",{className:"text-xs text-muted-foreground break-all select-all",children:"https://dashboard.relevelup.com/canva-callback.html"})]}),b?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:d.canva_team_id?`Team: ${d.canva_team_id}`:"Canva Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.expires_at?`Token expires ${new Date(d.expires_at).toLocaleDateString()}`:"Platform integration active"})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect Canva?"}),e.jsx(xl,{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(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>x.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-center justify-between p-3 text-sm font-medium hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ny,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",m&&m.length>0&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:m.length})]}),r?e.jsx(Qy,{className:"h-4 w-4"}):e.jsx(Po,{className:"h-4 w-4"})]}),r&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[m&&m.length>0?m.map(v=>{var k,C;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md bg-muted/50 text-sm",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium truncate",children:v.folder_name}),e.jsx(qe,{variant:"outline",className:"text-xs shrink-0",children:((k=kgt.find(T=>T.value===v.folder_type))==null?void 0:k.label)||v.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(C=v.brokerages)==null?void 0:C.name," · ID: ",e.jsx("span",{className:"font-mono",children:v.folder_id})]})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>g.mutate(v.id),children:e.jsx(dr,{className:"h-3.5 w-3.5"})})]},v.id)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No folders mapped yet"}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(Js,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs(B,{className:"mt-4",onClick:p,disabled:t||u,children:[t?e.jsx(Ki,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(Ngt,{})}),"Connect Canva",e.jsx(Xa,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Add Brokerage Folder Mapping"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Brokerage"}),e.jsxs(vs,{value:o.brokerage_id,onValueChange:v=>c(k=>({...k,brokerage_id:v})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a brokerage…"})}),e.jsx(ys,{children:h==null?void 0:h.map(v=>e.jsx(Je,{value:v.id,children:v.name},v.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Canva Folder ID"}),e.jsx(ye,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:v=>c(k=>({...k,folder_id:v.target.value}))}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Found in the Canva folder URL: canva.com/folder/",e.jsx("strong",{children:"FOLDER_ID"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Folder Display Name"}),e.jsx(ye,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:v=>c(k=>({...k,folder_name:v.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Folder Type"}),e.jsxs(vs,{value:o.folder_type,onValueChange:v=>c(k=>({...k,folder_type:v})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:kgt.map(v=>e.jsx(Je,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(ye,{placeholder:"What's in this folder?",value:o.description,onChange:v=>c(k=>({...k,description:v.target.value}))})]})]}),e.jsxs(Nr,{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(Ki,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function MCn(){const s=Hn();return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(oh,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(be,{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(zd,{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(Xa,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(ECn,{}),e.jsx(cBt,{})]})})}const Sgt=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(sx,{className:t}):s==="instagram"?e.jsx(vm,{className:t}):s==="linkedin"?e.jsx(ry,{className:t}):s==="google"?e.jsx(on,{className:t}):null},LCn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function PCn(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(""),[l,o]=j.useState("all");j.useEffect(()=>{(async()=>{r(!0);const{data:m,error:p}=await U.rpc("admin_get_social_connections");if(p){re.error(p.message),r(!1);return}t(m||[]),r(!1)})()},[]);const c=j.useMemo(()=>{const m=a.trim().toLowerCase();return s.filter(p=>l!=="all"&&p.platform!==l?!1:m?(p.user_name||"").toLowerCase().includes(m)||(p.user_email||"").toLowerCase().includes(m)||(p.page_name||"").toLowerCase().includes(m)||(p.platform_username||"").toLowerCase().includes(m):!0)},[s,a,l]),d=j.useMemo(()=>{const m=new Map;return s.forEach(p=>{const x=m.get(p.user_id)||{name:p.user_name,email:p.user_email,platforms:new Set,count:0};x.platforms.add(p.platform),x.count+=1,m.set(p.user_id,x)}),Array.from(m.entries()).map(([p,x])=>({user_id:p,...x}))},[s]),u=j.useMemo(()=>{const m=new Map;return s.forEach(p=>m.set(p.platform,(m.get(p.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(m.entries())}},[s,d]),h=m=>m&&new Date(m).getTime()e.jsxs(be,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[Sgt(m)," ",m]}),e.jsx("div",{className:"text-2xl font-bold",children:p})]},m))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(ye,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:m=>i(m.target.value),className:"md:max-w-md"}),e.jsxs(vs,{value:l,onValueChange:o,children:[e.jsx(gs,{className:"md:w-48",children:e.jsx(bs,{placeholder:"All platforms"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All platforms"}),e.jsx(Je,{value:"facebook",children:"Facebook"}),e.jsx(Je,{value:"instagram",children:"Instagram"}),e.jsx(Je,{value:"linkedin",children:"LinkedIn"}),e.jsx(Je,{value:"google",children:"Google"})]})]})]}),e.jsx(be,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Platform"}),e.jsx(Tt,{children:"Page / Account"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Connected"})]})}),e.jsx(za,{children:c.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(m=>{const p=h(m.token_expires_at);return e.jsxs(un,{children:[e.jsxs(xt,{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(xt,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[Sgt(m.platform)," ",m.platform]})}),e.jsxs(xt,{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(xt,{children:m.is_active?p?e.jsxs(qe,{variant:"destructive",className:"gap-1",children:[e.jsx(po,{className:"h-3 w-3"})," Expired"]}):e.jsx(qe,{children:"Active"}):e.jsx(qe,{variant:"secondary",children:"Inactive"})}),e.jsx(xt,{className:"text-sm text-muted-foreground",children:LCn(m.created_at)})]},m.id)})})]})})]})})}const ICn={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 sG(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function RCn(){var $,q,W,G,K;const s=as(),[t,n]=j.useState("Test Push"),[r,a]=j.useState("Testing web push notification"),[i,l]=j.useState("/community"),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[p,x]=j.useState(null),[y,g]=j.useState(null),{data:b,isLoading:v}=mt({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:ee,error:J}=await U.from("push_notification_settings").select("*").order("setting_key");if(J)throw J;return ee}}),{data:k,isLoading:C}=mt({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:ee,error:J}=await U.from("push_subscriptions").select("*",{count:"exact",head:!0});if(J)throw J;return{totalSubscriptions:ee||0}}}),T=vt({mutationFn:async({settingKey:ee,isEnabled:J})=>{const{error:le}=await U.from("push_notification_settings").update({is_enabled:J}).eq("setting_key",ee);if(le)throw le},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),re.success("Notification setting updated")},onError:ee=>{re.error("Failed to update setting: "+ee.message)}}),M=j.useMemo(()=>{var ee,J;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((ee=h.serviceWorker)==null?void 0:ee.activeState)??"unknown"} · sub=${(J=h.subscription)!=null&&J.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);j.useEffect(()=>{let ee=!0;const J=async()=>{var ie,de,we,je,xe,fe,Se;const ue="serviceWorker"in navigator&&"PushManager"in window,oe={isSupported:ue,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((ie=navigator.serviceWorker)!=null&&ie.controller)};if(!ue){ee&&m(oe);return}try{const{data:Ee,error:Le}=await U.functions.invoke("get-vapid-public-key",{body:{}});if(Le)throw Le;oe.vapidPublicKey=Ee==null?void 0:Ee.vapidPublicKey;const Be=(await navigator.serviceWorker.getRegistrations()).find(Ne=>{var _e,Oe,Ae;return(((_e=Ne.active)==null?void 0:_e.scriptURL)||((Oe=Ne.waiting)==null?void 0:Oe.scriptURL)||((Ae=Ne.installing)==null?void 0:Ae.scriptURL)||"").includes("/sw.js")});if(Be){oe.pushWorkerScriptUrl=((de=Be.active)==null?void 0:de.scriptURL)||((we=Be.waiting)==null?void 0:we.scriptURL)||((je=Be.installing)==null?void 0:je.scriptURL),oe.serviceWorker={scope:Be.scope,activeState:(xe=Be.active)==null?void 0:xe.state};const Ne=await Be.pushManager.getSubscription();if(Ne){const Ge=Ne.toJSON();oe.subscription={endpoint:Ge.endpoint,p256dh:(fe=Ge.keys)==null?void 0:fe.p256dh,auth:(Se=Ge.keys)==null?void 0:Se.auth}}}}catch(Ee){oe.error=(Ee==null?void 0:Ee.message)||String(Ee)}ee&&m(oe)};J();const le=window.setInterval(J,4e3);return()=>{ee=!1,window.clearInterval(le)}},[]);const P=async()=>{if(typeof Notification>"u"){re.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){re.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),re.success("Triggered a local notification (not push).")}catch(ee){re.error(`Local notification failed: ${(ee==null?void 0:ee.message)||String(ee)}`)}},L=async()=>{c(!0),x(null);try{const{data:ee,error:J}=await U.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(J)throw J;x({sent:ee==null?void 0:ee.sent,failed:ee==null?void 0:ee.failed,expiredCleaned:ee==null?void 0:ee.expiredCleaned,vapidPublicKey:ee==null?void 0:ee.vapidPublicKey}),(ee==null?void 0:ee.sent)>0?re.success(`Test notification sent to ${ee.sent} subscriber(s)`):(ee==null?void 0:ee.failed)>0?re.warning(`Notification failed for ${ee.failed} subscriber(s). ${ee.expired||0} expired subscriptions cleaned up.`):re.info("No active subscriptions to send to")}catch(ee){console.error("Error sending test notification:",ee),x({error:(ee==null?void 0:ee.message)||String(ee)}),re.error("Failed to send test notification: "+(ee.message||"Unknown error"))}finally{c(!1)}},I=async()=>{u(!0),g(null);try{const{data:ee,error:J}=await U.functions.invoke("generate-vapid-keys",{body:{}});if(J)throw J;const le=ee==null?void 0:ee.publicKey,ue=ee==null?void 0:ee.privateKey;if(!le||!ue)throw new Error("generate-vapid-keys did not return keys");g({publicKey:le,privateKey:ue}),re.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(ee){console.error("Error generating VAPID keys:",ee),re.error("Failed to generate VAPID keys: "+((ee==null?void 0:ee.message)||"Unknown error"))}finally{u(!1)}},O=vt({mutationFn:async()=>{const{error:ee}=await U.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(ee)throw ee},onSuccess:()=>{re.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:ee=>{re.error("Failed to clear subscriptions: "+ee.message)}});return e.jsx(Vs,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(fr,{children:"Current active push notification subscriptions"})]}),e.jsx(Re,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:C?"...":(k==null?void 0:k.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(ic,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(fr,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Re,{children:v?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:b==null?void 0:b.map(ee=>{const J=ICn[ee.setting_key]||{label:ee.setting_key,icon:"🔔"};return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:J.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:J.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:ee.description})]})]}),e.jsx(Mn,{checked:ee.is_enabled,onCheckedChange:le=>T.mutate({settingKey:ee.setting_key,isEnabled:le}),disabled:T.isPending})]},ee.id)})})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Nx,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(fr,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Re,{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:M}),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?sG(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?sG(h.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((q=h.serviceWorker)==null?void 0:q.activeState)??"none"]})]})]}),e.jsxs("div",{className:"space-y-1 sm:col-span-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Current browser subscription"}),e.jsxs("div",{className:"rounded-md border bg-background p-2 font-mono text-xs",children:[e.jsxs("div",{children:["endpoint: ",(W=h.subscription)!=null&&W.endpoint?sG(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(G=h.subscription)!=null&&G.p256dh?sG(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(K=h.subscription)!=null&&K.auth?sG(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(B,{variant:"outline",onClick:P,children:"Local notification test"}),e.jsx(B,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(ye,{id:"test-title",value:t,onChange:ee=>n(ee.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(Ds,{id:"test-body",value:r,onChange:ee=>a(ee.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(ye,{id:"test-url",value:i,onChange:ee=>l(ee.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:L,disabled:o||!t||!r,className:"w-full sm:w-auto",children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),p&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Last send debug"}),p.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",p.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",p.sent??0," sent, ",p.failed??0," failed, ",p.expiredCleaned??0," expired cleaned"]}),p.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:p.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Rn,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(fr,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Re,{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:()=>O.mutate(),disabled:O.isPending,children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"}),O.isPending?"Clearing...":"Clear All Subscriptions"]}),e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"VAPID key rotation helper"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:"If you suspect the backend public/private keys don’t match, generate a fresh pair, update backend secrets, then clear subscriptions and have users re-enable push."}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(B,{variant:"outline",onClick:I,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),y&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"text-muted-foreground",children:["Copy these into backend secrets ",e.jsx("span",{className:"font-mono",children:"VAPID_PUBLIC_KEY"})," and ",e.jsx("span",{className:"font-mono",children:"VAPID_PRIVATE_KEY"}),"."]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Public key"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:y.publicKey})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Private key (keep secret)"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:y.privateKey})]})]})]})]})]})]})})}function DCn(){const{toast:s}=pi(),[t,n]=j.useState([]),[r,a]=j.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=j.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=FJ("presentation_count","desc"),h=u(t,{name:x=>{var y;return((y=x.name)==null?void 0:y.toLowerCase())||""},presentations:x=>x.presentation_count,views:x=>x.total_views,leads:x=>x.total_leads,cta_clicks:x=>x.total_cta_clicks,conversion:x=>x.total_views>0?x.total_leads/x.total_views*100:0});j.useEffect(()=>{m()},[]);const m=async()=>{try{l(!0);const{data:x,error:y}=await U.rpc("get_admin_presentation_stats");if(y)throw y;if(!x||x.length===0){l(!1);return}const g=x.map(T=>T.owner_user_id),{data:b,error:v}=await U.from("profiles").select("id, name, email, avatar_url").in("id",g);if(v)throw v;const k=new Map((b==null?void 0:b.map(T=>[T.id,T]))||[]),C=x.map(T=>{const M=k.get(T.owner_user_id);return{owner_user_id:T.owner_user_id,name:(M==null?void 0:M.name)||"Unknown",email:(M==null?void 0:M.email)||"",avatar_url:(M==null?void 0:M.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(C),n(C),a({totalPresentations:C.reduce((T,M)=>T+M.presentation_count,0),totalViews:C.reduce((T,M)=>T+M.total_views,0),totalLeads:C.reduce((T,M)=>T+M.total_leads,0),totalCtaClicks:C.reduce((T,M)=>T+M.total_cta_clicks,0),agentsUsing:C.length})}catch(x){console.error("Error loading presentation stats:",x),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},p=[{label:"Agents Using",value:r.agentsUsing,icon:Bn,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:yb,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:ma,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:Sl,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:lu,color:"text-rose-600"}];return e.jsx(Vs,{title:"Presentation Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Presentation Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track Smart Presentations usage and engagement across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:p.map(x=>e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:x.label}),e.jsx(x.icon,{className:`h-4 w-4 ${x.color}`})]}),e.jsx(Re,{children:i?e.jsx(gn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:x.value.toLocaleString()})})]},x.label))}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(kl,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Re,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((x,y)=>e.jsx(gn,{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(Wu,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Wu,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Wu,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Wu,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Wu,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Wu,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(za,{children:h.map(x=>{var g,b;const y=x.total_views>0?(x.total_leads/x.total_views*100).toFixed(1):"0.0";return e.jsxs(un,{children:[e.jsx(xt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:x.avatar_url?e.jsx("img",{src:x.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((b=(g=x.name)==null?void 0:g.charAt(0))==null?void 0:b.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:x.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:x.email})]})]})}),e.jsx(xt,{className:"text-center font-medium",children:x.presentation_count}),e.jsx(xt,{className:"text-center",children:x.total_views.toLocaleString()}),e.jsx(xt,{className:"text-center",children:x.total_leads>0?e.jsx(qe,{variant:"secondary",children:x.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(xt,{className:"text-center",children:x.total_cta_clicks}),e.jsx(xt,{className:"text-center",children:e.jsxs("span",{className:Number(y)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[y,"%"]})})]},x.owner_user_id)})})]})})]})]})})}const QIe=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—",OCn=s=>s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`;function FCn(){const{toast:s}=pi(),[t,n]=j.useState(!0),[r,a]=j.useState([]),[i,l]=j.useState({}),[o,c]=j.useState("");j.useEffect(()=>{(async()=>{try{n(!0);const g=[],b=1e3;for(let C=0;;C+=b){const{data:T,error:M}=await U.from("listing_presentations").select("id, owner_user_id, title, status, property_address_line1, city, state, list_price, template_id, last_generated_at, created_at, updated_at").order("created_at",{ascending:!1}).range(C,C+b-1);if(M)throw M;if(g.push(...T??[]),!T||T.lengthC.owner_user_id))),k={};for(let C=0;C{k[M.id]={name:M.name??"Unknown",email:M.email??""}})}l(k)}catch(g){console.error(g),s({title:"Error",description:"Failed to load presentation data",variant:"destructive"})}finally{n(!1)}})()},[s]);const d=j.useMemo(()=>{const y=Date.now(),g=y-7*24*60*60*1e3,b=y-30*24*60*60*1e3;return{total:r.length,generated:r.filter(v=>!!v.last_generated_at).length,agents:new Set(r.map(v=>v.owner_user_id)).size,thisWeek:r.filter(v=>new Date(v.created_at).getTime()>=g).length,thisMonth:r.filter(v=>new Date(v.created_at).getTime()>=b).length}},[r]),u=j.useMemo(()=>{const y=new Map;return r.forEach(g=>{const b=i[g.owner_user_id],v=y.get(g.owner_user_id)??{user_id:g.owner_user_id,name:(b==null?void 0:b.name)??"Unknown",email:(b==null?void 0:b.email)??"",total:0,generated:0,last_activity:g.updated_at};v.total+=1,g.last_generated_at&&(v.generated+=1),new Date(g.updated_at)>new Date(v.last_activity)&&(v.last_activity=g.updated_at),y.set(g.owner_user_id,v)}),Array.from(y.values()).sort((g,b)=>b.total-g.total)},[r,i]),h=o.trim().toLowerCase(),m=h?u.filter(y=>y.name.toLowerCase().includes(h)||y.email.toLowerCase().includes(h)):u,p=h?r.filter(y=>{const g=i[y.owner_user_id];return(y.title??"").toLowerCase().includes(h)||(y.property_address_line1??"").toLowerCase().includes(h)||(y.city??"").toLowerCase().includes(h)||((g==null?void 0:g.name)??"").toLowerCase().includes(h)||((g==null?void 0:g.email)??"").toLowerCase().includes(h)}):r,x=[{label:"Total presentations",value:d.total,icon:$r,sub:"All time"},{label:"Agents using it",value:d.agents,icon:Bn,sub:"Created at least one"},{label:"PDFs generated",value:d.generated,icon:yn,sub:"Rendered at least once"},{label:"Created last 30 days",value:d.thisMonth,icon:ym,sub:`${d.thisWeek} in last 7 days`}];return e.jsx(Vs,{title:"Listing Presentation Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{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(gn,{className:"h-28 w-full"},y))}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:x.map(y=>e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:y.label}),e.jsx(y.icon,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Re,{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(Fr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{className:"pl-9",placeholder:"Search agents, addresses, titles...",value:o,onChange:y=>c(y.target.value)})]}),e.jsxs(fa,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"agents",children:["By agent (",m.length,")"]}),e.jsxs(ss,{value:"all",children:["All presentations (",p.length,")"]})]}),e.jsx(ns,{value:"agents",children:e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-right",children:"Presentations"}),e.jsx(Tt,{className:"text-right",children:"Generated"}),e.jsx(Tt,{children:"Last activity"})]})}),e.jsxs(za,{children:[m.map(y=>e.jsxs(un,{children:[e.jsxs(xt,{children:[e.jsx("div",{className:"font-medium",children:y.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:y.email})]}),e.jsx(xt,{className:"text-right font-semibold",children:y.total}),e.jsx(xt,{className:"text-right",children:y.generated}),e.jsx(xt,{children:QIe(y.last_activity)})]},y.user_id)),!t&&m.length===0&&e.jsx(un,{children:e.jsx(xt,{colSpan:4,className:"py-10 text-center text-muted-foreground",children:"No agents have created a listing presentation yet."})})]})]})})})}),e.jsx(ns,{value:"all",children:e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Presentation"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Price"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Created"}),e.jsx(Tt,{children:"Last generated"})]})}),e.jsxs(za,{children:[p.slice(0,300).map(y=>{var g,b;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:y.title||"Untitled"}),e.jsxs(xt,{children:[e.jsx("div",{children:((g=i[y.owner_user_id])==null?void 0:g.name)??"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:((b=i[y.owner_user_id])==null?void 0:b.email)??""})]}),e.jsx(xt,{className:"text-sm",children:[y.property_address_line1,y.city,y.state].filter(Boolean).join(", ")||"—"}),e.jsx(xt,{children:OCn(y.list_price)}),e.jsx(xt,{children:e.jsx(qe,{variant:y.last_generated_at?"default":"secondary",children:y.last_generated_at?"Generated":y.status||"Draft"})}),e.jsx(xt,{children:QIe(y.created_at)}),e.jsx(xt,{children:QIe(y.last_generated_at)})]},y.id)}),!t&&p.length===0&&e.jsx(un,{children:e.jsx(xt,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No presentations found."})})]})]})})})})]})]})})}const fY="listing_revival";function zCn(){const{user:s,loading:t,isAdmin:n}=Ns(),{data:r}=mt({queryKey:["feature-entitlement",fY,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await U.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",fY).maybeSingle();if(i)throw i;return{tier:(a==null?void 0:a.tier)??null}}});return{hasAccess:!0,tier:n?"admin":(r==null?void 0:r.tier)??null,isLoading:t}}const BCn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—";function $Cn(){var u,h;const{user:s}=Ns(),t=as(),[n,r]=j.useState(""),a=mt({queryKey:["lr-admin-stats"],queryFn:async()=>{const{data:m,error:p}=await U.rpc("get_admin_listing_revival_stats");if(p)throw p;return m??[]}}),i=mt({queryKey:["lr-admin-members",n],queryFn:async()=>{let m=U.from("profiles").select("id, name, email").order("name").limit(200);if(n.trim()){const v=`%${n.trim()}%`;m=m.or(`email.ilike.${v},name.ilike.${v}`)}const{data:p,error:x}=await m;if(x)throw x;const y=(p??[]).map(v=>v.id),{data:g}=await U.from("feature_entitlements").select("user_id, enabled, tier").eq("feature_key",fY).in("user_id",y.length?y:["00000000-0000-0000-0000-000000000000"]),b=new Map((g??[]).map(v=>[v.user_id,v]));return(p??[]).map(v=>{var k;return{user_id:v.id,name:v.name,email:v.email,enabled:!!((k=b.get(v.id))!=null&&k.enabled)}})}}),l=vt({mutationFn:async({userId:m,enabled:p})=>{const{error:x}=await U.from("feature_entitlements").upsert({user_id:m,feature_key:fY,enabled:p,tier:"member",enabled_by:s.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(x)throw x;await U.from("feature_entitlement_audit").insert({feature_key:fY,target_user_id:m,action:p?"grant":"revoke",performed_by:s.id})},onSuccess:(m,p)=>{t.invalidateQueries({queryKey:["lr-admin-members"]}),re.success(p.enabled?"Access granted":"Access revoked")},onError:m=>re.error(m.message)}),o=mt({queryKey:["lr-admin-stat-profiles",(a.data??[]).length],enabled:!!((u=a.data)!=null&&u.length),queryFn:async()=>{const m=(a.data??[]).map(x=>x.owner_user_id),{data:p}=await U.from("profiles").select("id, name, email").in("id",m);return new Map((p??[]).map(x=>[x.id,x]))}}),c=j.useMemo(()=>{const m=a.data??[];return{agents:m.length,campaigns:m.reduce((p,x)=>p+Number(x.campaign_count),0),leads:m.reduce((p,x)=>p+Number(x.lead_count),0),hot:m.reduce((p,x)=>p+Number(x.hot_lead_count),0)}},[a.data]),d=[{label:"Agents using it",value:c.agents,icon:Bn},{label:"Campaigns built",value:c.campaigns,icon:yn},{label:"Seller leads",value:c.leads,icon:oy},{label:"Hot leads",value:c.hot,icon:Fd}];return e.jsxs(Vs,{title:"Listing Revival Admin",children:[e.jsx(oh,{title:"Listing Revival",description:"Track adoption, campaign output and seller leads — and control who gets access."}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4 mt-6",children:d.map(m=>e.jsx(be,{children:e.jsxs(Re,{className:"p-5 flex items-center gap-4",children:[e.jsx("div",{className:"rounded-xl bg-amber-500/15 text-amber-600 p-3",children:e.jsx(m.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:a.isLoading?"—":m.value}),e.jsx("div",{className:"text-xs text-muted-foreground uppercase tracking-wider",children:m.label})]})]})},m.label))}),e.jsxs(fa,{defaultValue:"usage",className:"mt-6",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"usage",children:"Agent usage"}),e.jsx(ss,{value:"access",children:"Access"})]}),e.jsx(ns,{value:"usage",className:"mt-4",children:e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Usage by agent"})}),e.jsx(Re,{children:a.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(gn,{className:"h-10 w-full"},m))}):(h=a.data)!=null&&h.length?e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-right",children:"Campaigns"}),e.jsx(Tt,{className:"text-right",children:"Live pages"}),e.jsx(Tt,{className:"text-right",children:"Leads"}),e.jsx(Tt,{className:"text-right",children:"Hot"}),e.jsx(Tt,{className:"text-right",children:"Engagement"}),e.jsx(Tt,{className:"text-right",children:"Last activity"})]})}),e.jsx(za,{children:[...a.data].sort((m,p)=>Number(p.campaign_count)-Number(m.campaign_count)).map(m=>{var x;const p=(x=o.data)==null?void 0:x.get(m.owner_user_id);return e.jsxs(un,{children:[e.jsxs(xt,{children:[e.jsx("div",{className:"font-medium",children:(p==null?void 0:p.name)??"Agent"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(p==null?void 0:p.email)??m.owner_user_id.slice(0,8)})]}),e.jsx(xt,{className:"text-right tabular-nums",children:m.campaign_count}),e.jsx(xt,{className:"text-right tabular-nums",children:m.published_count}),e.jsx(xt,{className:"text-right tabular-nums",children:m.lead_count}),e.jsx(xt,{className:"text-right",children:Number(m.hot_lead_count)>0?e.jsx(qe,{className:"bg-red-500/15 text-red-600 hover:bg-red-500/15",children:m.hot_lead_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(xt,{className:"text-right tabular-nums",children:m.event_count}),e.jsx(xt,{className:"text-right text-sm text-muted-foreground",children:BCn(m.last_activity)})]},m.owner_user_id)})})]}):e.jsx("p",{className:"text-sm text-muted-foreground py-6",children:"No campaigns have been created yet."})})]})}),e.jsx(ns,{value:"access",className:"mt-4",children:e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Who can use Listing Revival"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Fr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{className:"pl-9",placeholder:"Search agents by name or email",value:n,onChange:m=>r(m.target.value)})]}),i.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(gn,{className:"h-10 w-full"},m))}):e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{className:"text-right",children:"Access"})]})}),e.jsx(za,{children:(i.data??[]).map(m=>e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium",children:m.name??"—"}),e.jsx(xt,{className:"text-muted-foreground",children:m.email??"—"}),e.jsx(xt,{className:"text-right",children:e.jsx(Mn,{checked:m.enabled,onCheckedChange:p=>l.mutate({userId:m.user_id,enabled:p})})})]},m.user_id))})]})]})]})})]})]})}function UCn(){const{toast:s}=pi(),[t,n]=j.useState([]),[r,a]=j.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=j.useState(!0);j.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:u}=await U.rpc("get_admin_guest_book_stats");if(u)throw u;if(!d||d.length===0){l(!1);return}const h=d.map(g=>g.agent_id),{data:m,error:p}=await U.from("profiles").select("id, name, email, avatar_url").in("id",h);if(p)throw p;const x=new Map((m==null?void 0:m.map(g=>[g.id,g]))||[]),y=d.map(g=>{const b=x.get(g.agent_id);return{agent_id:g.agent_id,name:(b==null?void 0:b.name)||"Unknown",email:(b==null?void 0:b.email)||"",avatar_url:(b==null?void 0:b.avatar_url)||null,open_house_count:Number(g.open_house_count),total_visitors:Number(g.total_visitors),total_leads:Number(g.total_leads),active_count:Number(g.active_count)}});y.sort((g,b)=>b.total_visitors-g.total_visitors),n(y),a({totalOpenHouses:y.reduce((g,b)=>g+b.open_house_count,0),totalVisitors:y.reduce((g,b)=>g+b.total_visitors,0),totalLeads:y.reduce((g,b)=>g+b.total_leads,0),activeOpenHouses:y.reduce((g,b)=>g+b.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:Bn,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:ia,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:To,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:ma,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:Sl,color:"text-rose-600"}];return e.jsx(Vs,{title:"Guest Book Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Guest Book Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track open house sign-in usage and lead generation across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:c.map(d=>e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Ut,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Re,{children:i?e.jsx(gn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(kl,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Re,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(gn,{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(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Open Houses"}),e.jsx(Tt,{className:"text-center",children:"Active"}),e.jsx(Tt,{className:"text-center",children:"Visitors"}),e.jsx(Tt,{className:"text-center",children:"Leads"}),e.jsx(Tt,{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(xt,{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(xt,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(xt,{className:"text-center",children:d.active_count>0?e.jsx(qe,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(xt,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(xt,{className:"text-center",children:d.total_leads>0?e.jsx(qe,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(xt,{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 qCn(){const[s]=dc(),t=Hn(),[n,r]=j.useState("loading"),a=j.useRef(!1),[i,l]=j.useState("Processing connection...");return j.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{const c=s.get("code"),d=s.get("error"),u=s.get("error_description"),h=s.get("state");if(d){r("error"),l(u||"Authorization was denied"),re.error("Failed to connect: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),re.error("Failed to connect: No authorization code");return}try{const{data:m,error:p}=await U.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h}});if(m&&m.success===!1)throw new Error(m.error||"Failed to connect accounts");if(p){let x=p.message||"Failed to connect accounts";try{const y=p.context;if(y&&typeof y.json=="function"){const g=await y.json();g!=null&&g.error&&(x=g.error)}}catch{}throw new Error(x)}if(m!=null&&m.success)r("success"),l(m.message||"Accounts connected successfully!"),re.success(m.message||"Social accounts connected!");else throw new Error((m==null?void 0:m.error)||"Failed to connect accounts")}catch(m){console.error("Callback error:",m),r("error"),l(m.message||"Failed to complete connection"),re.error(m.message||"Failed to connect accounts")}})()},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(Ft,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[n==="loading"&&e.jsx(Wt,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(To,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx(Rd,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(Ut,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(fr,{children:i})]}),e.jsx(Re,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function VCn(){const s=as(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState([]),o=j.useRef(null),{data:c,isLoading:d}=mt({queryKey:["prospect-emails"],queryFn:async()=>{const{data:v,error:k}=await U.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(k)throw k;return v}}),u=(c==null?void 0:c.filter(v=>v.status==="live_lead"))||[],h={total:(c==null?void 0:c.length)||0,sent:(c==null?void 0:c.filter(v=>v.status==="sent").length)||0,converted:(c==null?void 0:c.filter(v=>v.status==="converted").length)||0,liveLeads:u.length,conversionRate:c!=null&&c.length?Math.round(c.filter(v=>v.status==="converted").length/c.length*100):0},m=vt({mutationFn:async v=>{const{data:k,error:C}=await U.functions.invoke("send-prospect-email",{body:{emails:v}});if(C)throw C;return k},onSuccess:v=>{s.invalidateQueries({queryKey:["prospect-emails"]}),re.success(`${v.sent} email${v.sent>1?"s":""} sent successfully!`),n(""),a(""),l([])},onError:v=>{re.error("Failed to send: "+v.message)}}),p=vt({mutationFn:async()=>{var T,M;const{data:{user:v}}=await U.auth.getUser();if(!(v!=null&&v.email))throw new Error("Could not get your email");const{data:k,error:C}=await U.functions.invoke("send-prospect-email",{body:{emails:[{email:v.email,first_name:(M=(T=v.user_metadata)==null?void 0:T.name)==null?void 0:M.split(" ")[0]}],test_mode:!0}});if(C)throw C;return k},onSuccess:()=>{re.success("Test email sent to your inbox!")},onError:v=>{re.error("Failed to send test: "+v.message)}}),x=vt({mutationFn:async()=>{const{data:v,error:k}=await U.functions.invoke("send-prospect-email",{body:{mode:"live_leads"}});if(k)throw k;return v},onSuccess:v=>{s.invalidateQueries({queryKey:["prospect-emails"]}),re.success(`${v.sent} live lead invite${v.sent===1?"":"s"} sent!`)},onError:v=>{re.error("Failed to send live lead invites: "+v.message)}}),y=()=>{if(!t.trim()){re.error("Please enter an email address");return}if(c==null?void 0:c.find(k=>k.email.toLowerCase()===t.trim().toLowerCase())){re.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},g=v=>{var T;const k=(T=v.target.files)==null?void 0:T[0];if(!k)return;const C=new FileReader;C.onload=M=>{var $,q;const L=(($=M.target)==null?void 0:$.result).split(` `).filter(W=>W.trim()),I=[],O=(q=L[0])!=null&&q.toLowerCase().includes("email")?1:0;for(let W=O;WJ.trim().replace(/"/g,"")),K=G[0],ee=G[1];K&&K.includes("@")&&I.push({email:K,first_name:ee||void 0})}l(I),re.success(`${I.length} entries loaded from CSV`)},C.readAsText(k),o.current&&(o.current.value="")},b=()=>{if(i.length===0){re.error("No entries to send");return}const v=new Set((c==null?void 0:c.map(C=>C.email.toLowerCase()))||[]),k=i.filter(C=>!v.has(C.email.toLowerCase()));if(k.length===0){re.error("All emails have already been prospected");return}k.length0&&e.jsxs(be,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(iy,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx(qe,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(fr,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(Re,{children:e.jsxs(B,{onClick:()=>x.mutate(),disabled:x.isPending,className:"gap-2",children:[x.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(uu,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(fr,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Send a beautiful free trial invitation email to potential members"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>p.mutate(),disabled:p.isPending,className:"gap-2 ml-4 shrink-0",children:[p.isPending?e.jsx(Wt,{className:"h-3 w-3 animate-spin"}):e.jsx(on,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Re,{children:e.jsxs(fa,{defaultValue:"single",children:[e.jsxs(xa,{className:"mb-4",children:[e.jsxs(ss,{value:"single",children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(ss,{value:"bulk",children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(ns,{value:"single",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(ye,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:v=>n(v.target.value),onKeyDown:v=>v.key==="Enter"&&y()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(se,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(ye,{id:"prospect-name",placeholder:"First name (optional)",value:r,onChange:v=>a(v.target.value),onKeyDown:v=>v.key==="Enter"&&y()})]}),e.jsxs(B,{onClick:y,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(ns,{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:g,className:"hidden"}),e.jsxs(B,{variant:"outline",onClick:()=>{var v;return(v=o.current)==null?void 0:v.click()},className:"gap-2",children:[e.jsx($r,{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(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(dr,{className:"h-4 w-4"}),"Clear"]})]}),e.jsxs("div",{className:"max-h-40 overflow-y-auto border rounded-lg p-3 bg-muted/30 text-sm font-mono space-y-1",children:[i.slice(0,20).map((v,k)=>e.jsxs("div",{className:"text-muted-foreground",children:[v.email,v.first_name?` — ${v.first_name}`:""]},k)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(B,{onClick:b,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(fr,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Re,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((v,k)=>e.jsx(gn,{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(v=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 text-sm font-medium text-foreground",children:v.email}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:v.first_name||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:Bs(new Date(v.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:v.status==="converted"?e.jsxs(qe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"}),"Converted"]}):v.status==="live_lead"?e.jsxs(qe,{className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 border-0 gap-1",children:[e.jsx(iy,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:v.converted_at?Bs(new Date(v.converted_at),"MMM d, yyyy"):"—"})]},v.id))})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(uu,{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 vee(s){const t=as(),{toast:n}=pi(),r=mt({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await U.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=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:p}=await U.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(u,u+c-1);if(p)throw p;d=d.concat(m),h=m.length===c,u+=c}return d},enabled:!!s}),i=vt({mutationFn:async c=>{const{data:{user:d}}=await U.auth.getUser();if(!d)throw new Error("Not authenticated");const u={first_name:c.first_name||"",last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,current_brokerage:c.current_brokerage||null,license_number:c.license_number||null,experience_years:c.experience_years??null,annual_production:c.annual_production||null,source:c.source||"manual",notes:c.notes||null,stage_id:c.stage_id||null,brokerage_id:s,created_by:d.id,address:c.address||null,city:c.city||null,state:c.state||null,zip_code:c.zip_code||null,last_year_volume:c.last_year_volume||null,last_year_transactions:c.last_year_transactions??null,avg_sale_price:c.avg_sale_price||null,specialties:c.specialties||null,linkedin_url:c.linkedin_url||null,website_url:c.website_url||null,instagram_handle:c.instagram_handle||null,facebook_url:c.facebook_url||null,birthday:c.birthday||null,spouse_name:c.spouse_name||null,interests:c.interests||null,referred_by:c.referred_by||null},{data:h,error:m}=await U.from("recruit_prospects").insert(u).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect added"})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),l=vt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await U.from("recruit_prospects").update({...d,updated_at:new Date().toISOString()}).eq("id",c).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),o=vt({mutationFn:async c=>{const{error:d}=await U.from("recruit_prospects").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect removed"})}});return{stages:r.data||[],prospects:a.data||[],isLoading:r.isLoading||a.isLoading,addProspect:i,updateProspect:l,deleteProspect:o}}function HCn(s){const t=as(),{toast:n}=pi(),r=mt({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await U.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=vt({mutationFn:async i=>{const{data:{user:l}}=await U.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await U.from("recruit_activities").insert({...i,created_by:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-activities",s]}),n({title:"Activity logged"})},onError:i=>n({title:"Error",description:i.message,variant:"destructive"})});return{activities:r.data||[],isLoading:r.isLoading,addActivity:a}}const Cgt=(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 xBt({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=j.useState(Cgt(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(Cgt(r,n)),t(!1)};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(fa,{defaultValue:"basic",className:"w-full",children:[e.jsxs(xa,{className:"grid w-full grid-cols-4",children:[e.jsx(ss,{value:"basic",children:"Basic Info"}),e.jsx(ss,{value:"production",children:"Production"}),e.jsx(ss,{value:"social",children:"Social & Web"}),e.jsx(ss,{value:"personal",children:"Personal"})]}),e.jsxs(ns,{value:"basic",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"First Name *"}),e.jsx(ye,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last Name"}),e.jsx(ye,{value:l.last_name,onChange:c("last_name")})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Current Brokerage"}),e.jsx(ye,{value:l.current_brokerage,onChange:c("current_brokerage")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"License #"}),e.jsx(ye,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Experience (years)"}),e.jsx(ye,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Address"}),e.jsx(ye,{placeholder:"Street address",value:l.address,onChange:c("address")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"City"}),e.jsx(ye,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(ye,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Zip"}),e.jsx(ye,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Pipeline Stage"}),e.jsxs(vs,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:n.map(u=>e.jsx(Je,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Referred By"}),e.jsx(ye,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(ns,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Annual Production Volume"}),e.jsx(ye,{placeholder:"e.g. $5M, 20 transactions",value:l.annual_production,onChange:c("annual_production")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Last Year Volume"}),e.jsx(ye,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last Year Transactions"}),e.jsx(ye,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Avg Sale Price"}),e.jsx(ye,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Specialties / Niche"}),e.jsx(ye,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(ns,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"LinkedIn URL"}),e.jsx(ye,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Website URL"}),e.jsx(ye,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Instagram Handle"}),e.jsx(ye,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Facebook URL"}),e.jsx(ye,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(ns,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Birthday"}),e.jsx(ye,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Spouse / Partner Name"}),e.jsx(ye,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Interests / Hobbies"}),e.jsx(ye,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ds,{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 vTe(){const{user:s}=Ns();return mt({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,n]=await Promise.all([U.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),U.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]);return{massEmail:t.data?{email:t.data.email,displayName:t.data.display_name}:null,gmail:n.data?{email:n.data.gmail_email}:null}}})}function lYe({value:s,onChange:t}){const{data:n,isLoading:r}=vTe();return e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Send from"}),e.jsxs(vs,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ni,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(Je,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(WT,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(Je,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(on,{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 gBt({open:s,onOpenChange:t,recruitVideoId:n,brokerageId:r,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState("default"),[y,g]=j.useState(!1),b=as(),{data:v}=vTe();j.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),m(o||""),x(v!=null&&v.massEmail?"mass_email":v!=null&&v.gmail?"gmail":"default"))},[s,c,o,v==null?void 0:v.massEmail,v==null?void 0:v.gmail]);const k=async()=>{var C,T;if(!i){re.error("This prospect has no email address on file.");return}g(!0);try{const{data:M,error:P}=await U.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[n],brokerage_id:r,subject_override:d.trim()||void 0,message_override:h.trim()||void 0,send_via:p}});if(P)throw P;if(((M==null?void 0:M.sent)??0)>0)re.success(`Email sent to ${i}`),b.invalidateQueries({queryKey:["recruit-videos"]}),b.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const I=((T=(C=M==null?void 0:M.results)==null?void 0:C[0])==null?void 0:T.error)||"Failed to send";re.error(I)}}catch(M){re.error((M==null?void 0:M.message)||"Failed to send email")}finally{g(!1)}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"To"}),e.jsx(ye,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(lYe,{value:p,onChange:x}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(ye,{value:d,onChange:C=>u(C.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(Ds,{value:h,onChange:C=>m(C.target.value),rows:5,placeholder:`Hi ${c}, wanted to share a quick video...`,className:"mt-1"})]}),l&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Video: ",e.jsx("span",{className:"font-medium",children:l})]})]}),e.jsxs(Nr,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function S5(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const ABe=[{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 GCn(s){return mt({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("recruit_videos").select(` *, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("brokerage_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function WCn(s){return mt({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("recruit_videos").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("prospect_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function yBt(){const s=as(),{toast:t}=pi();return vt({mutationFn:async n=>{const{data:{user:r}}=await U.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await U.from("recruit_videos").insert({prospect_id:n.prospect_id,video_id:n.video_id,brokerage_id:n.brokerage_id,message:n.message||null,created_by:r.id}).select("*, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token)").single();if(i)throw i;return a},onSuccess:n=>{s.invalidateQueries({queryKey:["recruit-videos"]}),s.invalidateQueries({queryKey:["recruit-videos-prospect",n.prospect_id]}),t({title:"Video linked to prospect"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function vBt(){const s=as();return vt({mutationFn:async({id:t,sent_via:n})=>{const{error:r}=await U.from("recruit_videos").update({sent_at:new Date().toISOString(),sent_via:n,updated_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-videos"]})}})}function bBt(s){return mt({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("recruit_video_scripts").select("*").or(`brokerage_id.eq.${s},is_global.eq.true`).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function KCn(){const s=as(),{toast:t}=pi();return vt({mutationFn:async n=>{const{data:{user:r}}=await U.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await U.from("recruit_video_scripts").insert({...n,created_by:r.id}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]}),t({title:"Script saved"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function YCn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("recruit_video_scripts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function ZCn({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var K;const{data:a=[],isLoading:i}=WCn(s),{data:l=[]}=bBt(r),o=yBt(),c=hS();vBt();const[d,u]=j.useState("idle"),[h,m]=j.useState(0),[p,x]=j.useState(0),[y,g]=j.useState(""),[b,v]=j.useState(""),[k,C]=j.useState(!1),[T,M]=j.useState(null),[P,L]=j.useState(null),[I,O]=j.useState(null),$=((K=l.find(ee=>ee.id===y))==null?void 0:K.script_text)||"",q=()=>{u("idle"),m(0),x(0),g(""),v("")},W=j.useCallback(async(ee,J)=>{u("uploading");try{const le=`Recruiting: ${t}`,{videoId:ue,libraryId:oe}=await w6(le),{uploadUrl:ie,apiKey:de}=await j6(ue),we=new XMLHttpRequest;we.upload.onprogress=Be=>{Be.lengthComputable&&m(Be.loaded/Be.total*100)},await new Promise((Be,Ne)=>{we.onload=()=>we.status>=200&&we.status<300?Be():Ne(new Error("Upload failed")),we.onerror=()=>Ne(new Error("Upload failed")),we.open("PUT",ie),we.setRequestHeader("AccessKey",de),we.send(ee)}),u("processing");let je=0;const xe=Date.now(),fe=9e4,Se=`https://iframe.mediadelivery.net/embed/${oe}/${ue}`;for(;je<4&&(await new Promise(Ne=>setTimeout(Ne,3e3)),!(Date.now()-xe>fe));){const Be=await $j(ue);if(je=Be.status,x(Be.encodeProgress||0),je===5||je===6)throw new Error("Video processing failed")}const Ee=await $j(ue),Le=(Ee.storageSize||ee.size)/(1024*1024),De=await c.mutateAsync({bunny_video_id:ue,playback_url:Ee.directPlayUrl||Se,thumbnail_url:Ee.thumbnailUrl,preview_url:Ee.previewUrl||null,duration_seconds:Ee.length||J,file_size_mb:Le,title:le,status:je>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:De.id,brokerage_id:r,message:b||void 0}),u("done"),re.success("Video recorded and linked to prospect!"),setTimeout(()=>{C(!1),q()},1500)}catch(le){re.error(le.message||"Failed to upload video"),u("record")}},[s,t,r,b,c,o]),G=ee=>{ee&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${ee}`),re.success("Share link copied"))};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-1.5",children:[e.jsx(Zr,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(Fs,{open:k,onOpenChange:ee=>{!ee&&(d==="uploading"||d==="processing")||(C(ee),ee||q())},children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx($s,{children:e.jsxs(zs,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(vs,{value:y,onValueChange:g,children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{placeholder:"No script — speak freely"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No script"}),l.map(ee=>{var J;return e.jsx(Je,{value:ee.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[ee.title,e.jsx(qe,{variant:"outline",className:"text-[9px] ml-1",children:(J=ABe.find(le=>le.value===ee.category))==null?void 0:J.label})]})},ee.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(se,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Ds,{value:b,onChange:ee=>v(ee.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(Zr,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(k6,{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(qi,{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(qi,{value:p,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(p),"%"]})]}),d==="done"&&e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(fd,{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(ee=>{var J;return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-md border text-sm",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:S5(ee.video)?e.jsx("img",{src:S5(ee.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(Zr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-xs truncate",children:((J=ee.video)==null?void 0:J.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[ee.view_count>0?e.jsxs(qe,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(ma,{className:"h-2.5 w-2.5 mr-0.5"}),ee.view_count]}):ee.sent_at?e.jsxs(qe,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Dr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(qe,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Vr,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Bs(new Date(ee.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(ee.share_token),title:"Copy link",children:e.jsx(ja,{className:"h-3 w-3"})}),e.jsxs(B,{variant:ee.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var le;M(ee.id),L(((le=ee.video)==null?void 0:le.title)||null),O(ee.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(on,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:ee.sent_at?"Resend":"Email"})]})]})]},ee.id)})}),T&&e.jsx(gBt,{open:!!T,onOpenChange:ee=>{ee||M(null)},recruitVideoId:T,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:P,defaultMessage:I})]})}function XCn({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=mt({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=U.from("recruit_email_templates").select("id,brokerage_id,category,title,subject,body,sort_order").eq("is_active",!0).order("sort_order");s?i=i.or(`brokerage_id.is.null,brokerage_id.eq.${s}`):i=i.is("brokerage_id",null);const{data:l,error:o}=await i;if(o)throw o;return l}}),a=n.reduce((i,l)=>{var o;return(i[o=l.category]||(i[o]=[])).push(l),i},{});return e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx($r,{className:"h-4 w-4"}),"Use Template",e.jsx(Po,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(xd,{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(Wt,{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(uy,{}),e.jsx(TE,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(wa,{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(qe,{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 QCn({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=Ns(),o=(a||"").split(" ")[0]||"there",[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState("default"),[x,y]=j.useState(!1),[g,b]=j.useState(null),[v,k]=j.useState(!1),C=as(),{data:T}=vTe();j.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const $=T!=null&&T.massEmail?"mass_email":T!=null&&T.gmail?"gmail":"default";p($),b(null),k(!1)}},[s,o,T==null?void 0:T.massEmail,T==null?void 0:T.gmail]);const{data:M=[],isLoading:P}=mt({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:$,error:q}=await U.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, touch_type, created_at, share_token").eq("owner_user_id",l.id).eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(q)throw q;return $??[]},enabled:s&&!!(l!=null&&l.id)}),L=M.find($=>$.id===g)||null,I=async()=>{var $,q;if(!i){re.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){re.error("Subject and message are required.");return}y(!0);try{if(g){const{data:W}=await U.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",g).maybeSingle();let G=W==null?void 0:W.id;if(!G){const{data:le,error:ue}=await U.from("recruit_videos").insert({prospect_id:n,video_id:g,brokerage_id:r,message:u.trim(),created_by:l.id}).select("id").single();if(ue)throw ue;G=le.id}const{data:K,error:ee}=await U.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(ee)throw ee;if(((K==null?void 0:K.sent)??0)>0)re.success(`Email sent to ${i}`),C.invalidateQueries({queryKey:["recruit-videos"]}),C.invalidateQueries({queryKey:["recruit-videos-prospect",n]}),C.invalidateQueries({queryKey:["recruit-activities",n]}),C.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const le=((q=($=K==null?void 0:K.results)==null?void 0:$[0])==null?void 0:q.error)||"Failed to send";re.error(le)}}else{const{data:W,error:G}=await U.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:n,brokerage_id:r,subject:c.trim(),message:u.trim(),send_via:m}});if(G)throw G;W!=null&&W.success?(re.success(`Email sent to ${i}`),C.invalidateQueries({queryKey:["recruit-activities",n]}),C.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):re.error((W==null?void 0:W.error)||"Failed to send")}}catch(W){re.error((W==null?void 0:W.message)||"Failed to send email")}finally{y(!1)}},O=$=>{const q=W=>W.replace(/\[First Name\]/gi,o);d(q($.subject)),h(q($.body)),re.success(`Loaded "${$.title}"`)};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"To"}),e.jsx(ye,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(lYe,{value:m,onChange:p}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(XCn,{brokerageId:r,onSelect:O})]}),e.jsx(ye,{value:c,onChange:$=>d($.target.value)}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Message"}),e.jsx(Ds,{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(se,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"})," Include a video"]}),L?e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{b(null),k(!1)},children:[e.jsx(dr,{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:v?"Hide library":"Pick from library"})]}),L&&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:S5(L)?e.jsx("img",{src:S5(L),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(Zr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:L.title||"Untitled video"})]}),!L&&v&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:P?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Wt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):M.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."}):M.map($=>e.jsxs("button",{type:"button",onClick:()=>{b($.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:S5($)?e.jsx("img",{src:S5($),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(Zr,{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))}),L&&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(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:x,children:"Cancel"}),e.jsxs(B,{onClick:I,disabled:x||!i,children:[x?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function JCn(s){return mt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("recruit_campaign_sends").select("id, prospect_id, subject, email_number, status, sent_at, opened_at, clicked_at, error_message, created_at").eq("prospect_id",s).neq("status","failed").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}const Agt=[{value:"call",label:"Phone Call",icon:pa},{value:"email",label:"Email",icon:on},{value:"text",label:"Text Message",icon:ro},{value:"meeting",label:"Meeting",icon:ra},{value:"note",label:"Note",icon:$r},{value:"campaign_email",label:"Campaign Email",icon:Dr}];function c_({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 mre({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 im({label:s,value:t,onChange:n,type:r="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:s}),e.jsx(ye,{type:r,value:t,onChange:i=>n(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function _Bt({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=HCn((s==null?void 0:s.id)||null),{data:d=[]}=JCn((s==null?void 0:s.id)||null),[u,h]=j.useState({type:"note",title:"",description:""}),[m,p]=j.useState(!1),[x,y]=j.useState(!1),[g,b]=j.useState({}),[v,k]=j.useState(!1);if(!s)return null;const C=()=>{var G,K;b({first_name:s.first_name||"",last_name:s.last_name||"",email:s.email||"",phone:s.phone||"",current_brokerage:s.current_brokerage||"",license_number:s.license_number||"",experience_years:((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:((K=s.last_year_transactions)==null?void 0:K.toString())||"",avg_sale_price:s.avg_sale_price||"",specialties:s.specialties||"",annual_production:s.annual_production||"",linkedin_url:s.linkedin_url||"",website_url:s.website_url||"",instagram_handle:s.instagram_handle||"",facebook_url:s.facebook_url||"",birthday:s.birthday||"",spouse_name:s.spouse_name||"",interests:s.interests||"",referred_by:s.referred_by||""}),y(!0)},T=()=>{const G={id:s.id};for(const[K,ee]of Object.entries(g))K==="experience_years"||K==="last_year_transactions"?G[K]=ee?parseInt(ee):null:G[K]=ee||null;i(G),y(!1)},M=()=>y(!1),P=G=>K=>b(ee=>({...ee,[G]:K})),L=()=>{u.title.trim()&&(c.mutate({prospect_id:s.id,activity_type:u.type,title:u.title,description:u.description||null}),h({type:"note",title:"",description:""}),p(!1))},I=t.find(G=>G.id===s.stage_id),O=s.address||s.city||s.state,$=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,q=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,W=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(v1,{open:r,onOpenChange:G=>{G||y(!1),a(G)},children:[e.jsx(rv,{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(Lb,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(Pb,{className:"text-xl",children:[s.first_name," ",s.last_name]}),I&&e.jsx(qe,{variant:"outline",style:{borderColor:I.color,color:I.color},className:"mt-1",children:I.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[x?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:M,children:e.jsx(dr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"default",size:"icon",onClick:T,children:e.jsx(Jo,{className:"h-4 w-4"})})]}):e.jsx(B,{variant:"ghost",size:"icon",onClick:C,title:"Edit prospect",children:e.jsx(Za,{className:"h-4 w-4"})}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete prospect?"}),e.jsx(xl,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!x&&e.jsxs("div",{className:"space-y-2 text-sm",children:[s.email&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground min-w-0",children:[e.jsx(on,{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(on,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(pa,{className:"h-3.5 w-3.5"})," ",s.phone]}),O&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(oi,{className:"h-3.5 w-3.5"}),[s.address,s.city,s.state,s.zip_code].filter(Boolean).join(", ")]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(vs,{value:s.stage_id||"",onValueChange:G=>i({id:s.id,stage_id:G}),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:t.map(G=>e.jsx(Je,{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(fa,{defaultValue:"details",className:"w-full",children:[e.jsxs(xa,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(ss,{value:"details",className:"text-xs",children:"Details"}),e.jsx(ss,{value:"production",className:"text-xs",children:"Production"}),e.jsx(ss,{value:"social",className:"text-xs",children:"Social"}),e.jsx(ss,{value:"personal",className:"text-xs",children:"Personal"})]}),x?e.jsxs(e.Fragment,{children:[e.jsxs(ns,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(im,{label:"First Name",value:g.first_name,onChange:P("first_name")}),e.jsx(im,{label:"Last Name",value:g.last_name,onChange:P("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(im,{label:"Email",value:g.email,onChange:P("email"),type:"email"}),e.jsx(im,{label:"Phone",value:g.phone,onChange:P("phone")})]}),e.jsx(im,{label:"Current Brokerage",value:g.current_brokerage,onChange:P("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(im,{label:"License #",value:g.license_number,onChange:P("license_number")}),e.jsx(im,{label:"Experience (years)",value:g.experience_years,onChange:P("experience_years"),type:"number"})]}),e.jsx(im,{label:"Address",value:g.address,onChange:P("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(im,{label:"City",value:g.city,onChange:P("city")}),e.jsx(im,{label:"State",value:g.state,onChange:P("state")}),e.jsx(im,{label:"Zip",value:g.zip_code,onChange:P("zip_code")})]}),e.jsx(im,{label:"Source",value:g.source,onChange:P("source")}),e.jsx(im,{label:"Referred By",value:g.referred_by,onChange:P("referred_by")}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Notes"}),e.jsx(Ds,{value:g.notes,onChange:G=>b(K=>({...K,notes:G.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(ns,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(im,{label:"Annual Production",value:g.annual_production,onChange:P("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(im,{label:"Last Year Volume",value:g.last_year_volume,onChange:P("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(im,{label:"Last Year Transactions",value:g.last_year_transactions,onChange:P("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(im,{label:"Avg Sale Price",value:g.avg_sale_price,onChange:P("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(im,{label:"Specialties / Niche",value:g.specialties,onChange:P("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(ns,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(im,{label:"LinkedIn URL",value:g.linkedin_url,onChange:P("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(im,{label:"Website URL",value:g.website_url,onChange:P("website_url"),type:"url",placeholder:"https://..."}),e.jsx(im,{label:"Instagram Handle",value:g.instagram_handle,onChange:P("instagram_handle"),placeholder:"@handle"}),e.jsx(im,{label:"Facebook URL",value:g.facebook_url,onChange:P("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(ns,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(im,{label:"Birthday",value:g.birthday,onChange:P("birthday"),type:"date"}),e.jsx(im,{label:"Spouse / Partner",value:g.spouse_name,onChange:P("spouse_name")}),e.jsx(im,{label:"Interests / Hobbies",value:g.interests,onChange:P("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ns,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(c_,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(c_,{label:"License #",value:s.license_number}),e.jsx(c_,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(c_,{label:"Referred By",value:s.referred_by}),e.jsx(c_,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(ns,{value:"production",className:"mt-3",children:$?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(c_,{label:"Annual Production",value:s.annual_production}),e.jsx(c_,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(c_,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(c_,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(c_,{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(ns,{value:"social",className:"mt-3",children:q?e.jsxs("div",{className:"space-y-2",children:[e.jsx(mre,{label:"LinkedIn",url:s.linkedin_url,icon:ry}),e.jsx(mre,{label:"Website",url:s.website_url,icon:Ql}),s.instagram_handle&&e.jsx(mre,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:vm}),e.jsx(mre,{label:"Facebook",url:s.facebook_url,icon:sx})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(ns,{value:"personal",className:"mt-3",children:W?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(c_,{label:"Birthday",value:s.birthday?Bs(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:zo}),e.jsx(c_,{label:"Spouse / Partner",value:s.spouse_name,icon:mo}),e.jsx("div",{className:"col-span-2",children:e.jsx(c_,{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(ZCn,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(Xl,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Activity Log"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>p(!m),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),m&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(vs,{value:u.type,onValueChange:G=>h(K=>({...K,type:G})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Agt.map(G=>e.jsx(Je,{value:G.value,children:G.label},G.value))})]}),e.jsx(ye,{placeholder:"Subject / Title",value:u.title,onChange:G=>h(K=>({...K,title:G.target.value}))}),e.jsx(Ds,{placeholder:"Details (optional)",value:u.description,onChange:G=>h(K=>({...K,description:G.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx(B,{size:"sm",onClick:L,disabled:!u.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const G=[...o.map(K=>({type:"manual",data:K,date:K.created_at})),...d.map(K=>({type:"campaign_email",data:K,date:K.sent_at||K.created_at}))].sort((K,ee)=>new Date(ee.date).getTime()-new Date(K.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(K=>{if(K.type==="manual"){const J=K.data,le=Agt.find(oe=>oe.value===J.activity_type),ue=(le==null?void 0:le.icon)||$r;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(ue,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:J.title}),J.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:J.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Bs(new Date(J.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${J.id}`)}const ee=K.data;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Dr,{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 #",ee.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:ee.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[ee.status==="failed"?e.jsx(qe,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(Dr,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),ee.opened_at?e.jsxs(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(ma,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",Bs(new Date(ee.opened_at),"MMM d, h:mm a")]}):ee.status!=="failed"?e.jsx(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,ee.clicked_at&&e.jsxs(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(ag,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",Bs(new Date(ee.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Bs(new Date(ee.sent_at||ee.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${ee.id}`)})})()})]})]})})}),e.jsx(QCn,{open:v,onOpenChange:k,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const eAn=["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 wBt({open:s,onOpenChange:t,brokerageId:n,stages:r}){var O;const{toast:a}=pi(),i=as(),l=j.useRef(null),[o,c]=j.useState([]),[d,u]=j.useState([]),[h,m]=j.useState({}),[p,x]=j.useState(((O=r[0])==null?void 0:O.id)||""),[y,g]=j.useState(!1),[b,v]=j.useState("upload"),[k,C]=j.useState(0),T=()=>{c([]),u([]),m({}),v("upload"),C(0)},M=$=>{var G;const q=(G=$.target.files)==null?void 0:G[0];if(!q)return;const W=new FileReader;W.onload=K=>{var de;const J=((de=K.target)==null?void 0:de.result).split(/\r?\n/).filter(we=>we.trim());if(J.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const le=P(J[0]);u(le);const ue={},oe=new Set;le.forEach((we,je)=>{const xe=we.toLowerCase().replace(/[^a-z0-9]/g,"");let fe=null;/^firstname$/.test(xe)||xe==="first"?fe="first_name":/^lastname$/.test(xe)||xe==="last"?fe="last_name":/^email$/.test(xe)||xe==="emailaddress"?fe="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(xe)?fe="phone":/officename|currentbrokerage|brokerage|company/.test(xe)?fe="current_brokerage":/membernumber|licensenumber|license/.test(xe)?fe="license_number":/experienceyears|yearsexperience/.test(xe)?fe="experience_years":/^totalvolume$|annualproduction/.test(xe)?fe="annual_production":/^address$/.test(xe)?fe="address":/^city$/.test(xe)?fe="city":/^state$/.test(xe)?fe="state":/^postalcode$|^zip$|^zipcode$/.test(xe)?fe="zip_code":/listsidevolume|lastyearvolume/.test(xe)?fe="last_year_volume":/^totalcount$|lastyeartransactions/.test(xe)?fe="last_year_transactions":/avgsaleprice|averageprice/.test(xe)?fe="avg_sale_price":/linkedin/.test(xe)?fe="linkedin_url":/website/.test(xe)?fe="website_url":/specialt/.test(xe)?fe="specialties":/referr/.test(xe)?fe="referred_by":/^notes$|^note$/.test(xe)&&(fe="notes"),fe&&!oe.has(fe)&&(ue[String(je)]=fe,oe.add(fe))}),m(ue);const ie=J.slice(1).map(we=>{const je=P(we),xe={};return le.forEach((fe,Se)=>{xe[String(Se)]=je[Se]||""}),xe});c(ie),v("map")},W.readAsText(q)},P=$=>{const q=[];let W="",G=!1;for(const K of $)K==='"'?G=!G:K===","&&!G?(q.push(W.trim()),W=""):W+=K;return q.push(W.trim()),q},L=async()=>{g(!0);try{const{data:{user:$}}=await U.auth.getUser();if(!$)throw new Error("Not authenticated");const q=o.map(G=>{const K={brokerage_id:n,created_by:$.id,stage_id:p,source:"csv_import",first_name:"Unknown"},ee=K;return Object.entries(h).forEach(([J,le])=>{var oe;const ue=(oe=G[J])==null?void 0:oe.trim();ue&&(le==="experience_years"||le==="last_year_transactions"?ee[le]=parseInt(ue.replace(/[^0-9.-]/g,""))||null:le==="annual_production"||le==="last_year_volume"||le==="avg_sale_price"?ee[le]=ue.replace(/[^0-9.$,.-]/g,""):ee[le]=ue)}),K});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`,q=new Blob([$],{type:"text/csv"}),W=URL.createObjectURL(q),G=document.createElement("a");G.href=W,G.download="recruit-prospects-template.csv",G.click(),URL.revokeObjectURL(W)};return e.jsx(Fs,{open:s,onOpenChange:$=>{$||T(),t($)},children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Import Prospects from CSV"})}),b==="upload"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx(pN,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Upload a CSV file with prospect data"}),e.jsx("input",{ref:l,type:"file",accept:".csv",className:"hidden",onChange:M}),e.jsxs(B,{onClick:()=>{var $;return($=l.current)==null?void 0:$.click()},children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(B,{variant:"link",className:"text-xs",onClick:I,children:"Download CSV template"})]}),b==="map"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," rows found"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:"Import to stage:"}),e.jsxs(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{})}),e.jsx(ys,{children:r.map($=>e.jsx(Je,{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(Tt,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Tt,{className:"w-[160px]",children:"Map To"}),e.jsx(Tt,{children:"Preview"})]})}),e.jsx(za,{children:d.map(($,q)=>{var W;return e.jsxs(un,{children:[e.jsx(xt,{className:"font-medium text-xs",children:$}),e.jsx(xt,{children:e.jsxs(vs,{value:h[String(q)]||"skip",onValueChange:G=>m(K=>({...K,[String(q)]:G==="skip"?"":G})),children:[e.jsx(gs,{className:"h-8 text-xs",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"skip",children:"— Skip —"}),eAn.map(G=>e.jsx(Je,{value:G,children:G.replace(/_/g," ")},G))]})]})}),e.jsx(xt,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((W=o[0])==null?void 0:W[String(q)])||"—"})]},q)})})]})}),!Object.values(h).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(po,{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:L,disabled:y||!Object.values(h).includes("first_name"),children:y?"Importing...":`Import ${o.length} Prospects`})]})]}),b==="done"&&e.jsxs("div",{className:"text-center py-6 space-y-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-green-500/10 flex items-center justify-center mx-auto",children:e.jsx(da,{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 jBt({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=vee(s),[o,c]=j.useState(!1),[d,u]=j.useState(),[h,m]=j.useState(null),[p,x]=j.useState(!1),[y,g]=j.useState(!1),[b,v]=j.useState(null);if(r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const k=I=>n.filter(O=>O.stage_id===I),C=(I,O)=>{v(O),I.dataTransfer.effectAllowed="move"},T=I=>{I.preventDefault(),I.dataTransfer.dropEffect="move"},M=(I,O)=>{I.preventDefault(),b&&(i.mutate({id:b,stage_id:O}),v(null))},P=I=>{u(I),c(!0)},L=I=>{m(I),x(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[n.length," prospect",n.length!==1?"s":""]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>g(!0),children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(Js,{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(I=>{const O=k(I.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:T,onDrop:$=>M($,I.id),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:I.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:I.name}),e.jsx(qe,{variant:"secondary",className:"text-xs h-5 px-1.5",children:O.length})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>P(I.id),children:e.jsx(Js,{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:O.map($=>e.jsx(be,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:I.color},draggable:!0,onDragStart:q=>C(q,$.id),onClick:()=>L($),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Fp,{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(Eo,{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(Ni,{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(on,{className:"h-3 w-3 text-muted-foreground"}),$.phone&&e.jsx(pa,{className:"h-3 w-3 text-muted-foreground"}),$.experience_years!=null&&e.jsxs(qe,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[$.experience_years,"yr"]})]})]})]})},$.id))})]},I.id)})}),e.jsx(KU,{orientation:"horizontal"})]}),e.jsx(xBt,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:I=>a.mutate(I),isSubmitting:a.isPending}),e.jsx(_Bt,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:x,onUpdate:I=>{i.mutate(I),m(O=>O?{...O,...I}:null)},onDelete:I=>l.mutate(I)}),e.jsx(wBt,{open:y,onOpenChange:g,brokerageId:s,stages:t})]})}function MSe({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=vee(s),{user:o}=Ns(),c=as(),[d,u]=j.useState(!1),[h,m]=j.useState(null),[p,x]=j.useState(!1),[y,g]=j.useState(!1),[b,v]=j.useState(""),[k,C]=j.useState("all"),[T,M]=j.useState("all"),[P,L]=j.useState("all"),[I,O]=j.useState(null),[$,q]=j.useState("asc"),[W,G]=j.useState(new Set),[K,ee]=j.useState(!1),[J,le]=j.useState(""),ue=j.useMemo(()=>{const Ne=new Set;return n.forEach(Ge=>{Ge.current_brokerage&&Ne.add(Ge.current_brokerage)}),Array.from(Ne).sort()},[n]),{data:oe=[]}=mt({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:Ne,error:Ge}=await U.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:ie=[]}=mt({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Ge=[],_e=0;for(;;){const{data:Oe,error:Ae}=await U.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(_e,_e+1e3-1);if(Ae)throw Ae;if(Ge=Ge.concat(Oe??[]),!Oe||Oe.length<1e3)break;_e+=1e3}return Ge}}),de=j.useMemo(()=>{const Ne=new Map;return ie.forEach(Ge=>{Ne.has(Ge.prospect_id)||Ne.set(Ge.prospect_id,new Set),Ne.get(Ge.prospect_id).add(Ge.campaign_id)}),Ne},[ie]),we=Ne=>{I===Ne?q(Ge=>Ge==="asc"?"desc":"asc"):(O(Ne),q("asc"))},je=({column:Ne})=>I!==Ne?e.jsx(_x,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):$==="asc"?e.jsx(Gm,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(tx,{className:"h-3.5 w-3.5 ml-1 text-primary"}),xe=Ne=>t.find(Ge=>Ge.id===Ne),fe=j.useMemo(()=>{let Ne=n.filter(Ge=>{var Ue,Ze,Qe;const _e=!b||`${Ge.first_name} ${Ge.last_name}`.toLowerCase().includes(b.toLowerCase())||((Ue=Ge.email)==null?void 0:Ue.toLowerCase().includes(b.toLowerCase()))||((Ze=Ge.current_brokerage)==null?void 0:Ze.toLowerCase().includes(b.toLowerCase())),Oe=k==="all"||Ge.stage_id===k,Ae=T==="all"||Ge.current_brokerage===T;let Xe=!0;return P==="in_campaign"?Xe=de.has(Ge.id):P==="not_in_campaign"?Xe=!de.has(Ge.id):P!=="all"&&(Xe=((Qe=de.get(Ge.id))==null?void 0:Qe.has(P))??!1),_e&&Oe&&Ae&&Xe});return I&&(Ne=[...Ne].sort((Ge,_e)=>{var Ue,Ze;let Oe=null,Ae=null;switch(I){case"name":Oe=`${Ge.first_name} ${Ge.last_name||""}`.toLowerCase(),Ae=`${_e.first_name} ${_e.last_name||""}`.toLowerCase();break;case"stage":Oe=((Ue=xe(Ge.stage_id))==null?void 0:Ue.sort_order)??999,Ae=((Ze=xe(_e.stage_id))==null?void 0:Ze.sort_order)??999;break;case"brokerage":Oe=(Ge.current_brokerage||"").toLowerCase(),Ae=(_e.current_brokerage||"").toLowerCase();break;case"experience":Oe=Ge.experience_years??-1,Ae=_e.experience_years??-1;break;case"production":Oe=(Ge.annual_production||"").toLowerCase(),Ae=(_e.annual_production||"").toLowerCase();break;case"source":Oe=(Ge.source||"").toLowerCase(),Ae=(_e.source||"").toLowerCase();break;default:return 0}if(Oe===Ae)return 0;if(Oe==null)return 1;if(Ae==null)return-1;const Xe=Oe0&&fe.every(Ne=>W.has(Ne.id)),Ee=fe.some(Ne=>W.has(Ne.id)),Le=()=>{G(Se?new Set:new Set(fe.map(Ne=>Ne.id)))},De=Ne=>{G(Ge=>{const _e=new Set(Ge);return _e.has(Ne)?_e.delete(Ne):_e.add(Ne),_e})},Be=vt({mutationFn:async()=>{if(!J||!(o!=null&&o.id))throw new Error("Select a campaign");const Ne=new Set(ie.filter(Oe=>Oe.campaign_id===J).map(Oe=>Oe.prospect_id)),Ge=Array.from(W).filter(Oe=>!Ne.has(Oe)).map(Oe=>({prospect_id:Oe,campaign_id:J,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:_e}=await U.from("recruit_campaign_assignments").insert(Ge);if(_e)throw _e;return Ge.length},onSuccess:Ne=>{re.success(`${Ne} prospect(s) added to campaign`),ee(!1),G(new Set),le(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:Ne=>re.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(Fr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search prospects...",value:b,onChange:Ne=>v(Ne.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[W.size>0&&e.jsxs(B,{variant:"secondary",onClick:()=>ee(!0),className:"gap-1.5",children:[e.jsx(Dr,{className:"h-4 w-4"})," Add ",W.size," to Campaign"]}),e.jsxs(B,{variant:"outline",onClick:()=>g(!0),children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>u(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Nj,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(vs,{value:k,onValueChange:C,children:[e.jsx(gs,{className:"w-[160px] h-8 text-xs",children:e.jsx(bs,{placeholder:"All stages"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All stages"}),t.map(Ne=>e.jsx(Je,{value:Ne.id,children:Ne.name},Ne.id))]})]}),e.jsxs(vs,{value:T,onValueChange:M,children:[e.jsxs(gs,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Ni,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(bs,{placeholder:"All brokerages"})]}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All brokerages"}),ue.map(Ne=>e.jsx(Je,{value:Ne,children:Ne},Ne))]})]}),e.jsxs(vs,{value:P,onValueChange:L,children:[e.jsxs(gs,{className:"w-[200px] h-8 text-xs",children:[e.jsx(on,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(bs,{placeholder:"Campaign status"})]}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All contacts"}),e.jsx(Je,{value:"in_campaign",children:"In any campaign"}),e.jsx(Je,{value:"not_in_campaign",children:"Not in any campaign"}),oe.map(Ne=>e.jsxs(Je,{value:Ne.id,children:["In: ",Ne.name]},Ne.id))]})]}),(k!=="all"||T!=="all"||P!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{C("all"),M("all"),L("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(Tt,{className:"w-[40px]",children:e.jsx(wi,{checked:Se,onCheckedChange:Le,"aria-label":"Select all",...Ee&&!Se?{"data-state":"indeterminate"}:{}})}),e.jsx(Tt,{className:"cursor-pointer select-none",onClick:()=>we("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(je,{column:"name"})]})}),e.jsx(Tt,{className:"cursor-pointer select-none",onClick:()=>we("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(je,{column:"stage"})]})}),e.jsx(Tt,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>we("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(je,{column:"brokerage"})]})}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Tt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>we("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(je,{column:"experience"})]})}),e.jsx(Tt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>we("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(je,{column:"production"})]})}),e.jsx(Tt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Tt,{className:"w-[50px]"})]})}),e.jsx(za,{children:fe.length===0?e.jsx(un,{children:e.jsx(xt,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):fe.map(Ne=>{const Ge=xe(Ne.stage_id),_e=de.get(Ne.id),Oe=(_e==null?void 0:_e.size)??0;return e.jsxs(un,{className:"cursor-pointer",onClick:()=>{m(Ne),x(!0)},children:[e.jsx(xt,{onClick:Ae=>Ae.stopPropagation(),children:e.jsx(wi,{checked:W.has(Ne.id),onCheckedChange:()=>De(Ne.id),"aria-label":`Select ${Ne.first_name}`})}),e.jsxs(xt,{className:"font-medium",children:[Ne.first_name," ",Ne.last_name]}),e.jsx(xt,{children:Ge?e.jsxs(qe,{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(xt,{className:"hidden md:table-cell",children:Ne.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(Ni,{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(xt,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Ne.email&&e.jsx(on,{className:"h-3.5 w-3.5 text-muted-foreground"}),Ne.phone&&e.jsx(pa,{className:"h-3.5 w-3.5 text-muted-foreground"}),!Ne.email&&!Ne.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(xt,{className:"hidden lg:table-cell",children:Ne.experience_years!=null?`${Ne.experience_years} yr`:"—"}),e.jsx(xt,{className:"hidden lg:table-cell",children:Ne.annual_production||"—"}),e.jsx(xt,{className:"hidden lg:table-cell",children:Oe>0?e.jsxs(qe,{variant:"secondary",className:"text-xs",children:[Oe," campaign",Oe>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(xt,{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(Rn,{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 · "]}),fe.length," of ",n.length," prospects"]}),e.jsx(Fs,{open:K,onOpenChange:ee,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx($s,{children:e.jsx(zs,{children:"Add to Campaign"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Add ",e.jsx("span",{className:"font-medium text-foreground",children:W.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Campaign"}),e.jsxs(vs,{value:J,onValueChange:le,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a campaign..."})}),e.jsx(ys,{children:oe.map(Ne=>e.jsxs(Je,{value:Ne.id,children:[Ne.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",Ne.warmth_level,")"]})]},Ne.id))})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>ee(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>Be.mutate(),disabled:!J||Be.isPending,children:Be.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(xBt,{open:d,onOpenChange:u,stages:t,onSubmit:Ne=>a.mutate(Ne),isSubmitting:a.isPending}),e.jsx(_Bt,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:x,onUpdate:Ne=>{i.mutate(Ne),m(Ge=>Ge?{...Ge,...Ne}:null)},onDelete:Ne=>l.mutate(Ne)}),e.jsx(wBt,{open:y,onOpenChange:g,brokerageId:s,stages:t})]})}function NBt({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=vee(s),a=j.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(b=>b.name==="Signed"),o=t.find(b=>b.name==="Onboarded"),c=n.filter(b=>b.stage_id===(l==null?void 0:l.id)||b.stage_id===(o==null?void 0:o.id)).length,d=i>0?(c/i*100).toFixed(1):"0",u=new Date,h=i>0?Math.round(n.reduce((b,v)=>b+Fj(u,new Date(v.created_at)),0)/i):0,m=t.map(b=>({...b,count:n.filter(v=>v.stage_id===b.id).length})),p={};n.forEach(b=>{const v=b.source||"unknown";p[v]=(p[v]||0)+1});const x=Object.entries(p).sort((b,v)=>v[1]-b[1]),y=new Date;y.setDate(y.getDate()-30);const g=n.filter(b=>new Date(b.created_at)>=y).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:m,bySrc:x,recentCount:g}},[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(be,{children:e.jsx(Re,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-500/10 flex items-center justify-center",children:e.jsx(Bn,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Prospects"})]})]})})}),e.jsx(be,{children:e.jsx(Re,{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(kl,{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(be,{children:e.jsx(Re,{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(Vr,{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(be,{children:e.jsx(Re,{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(uu,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Re,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Re,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(qe,{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 tAn=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function kBt({brokerageId:s}){const{toast:t}=pi(),{user:n}=Ns(),r=as(),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),{data:m=[],isLoading:p}=mt({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:C,error:T}=await U.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(T)throw T;return C}}),x=vt({mutationFn:async C=>{if(C.id){const{error:T}=await U.from("recruit_email_templates").update({category:C.category,title:C.title,subject:C.subject,body:C.body}).eq("id",C.id);if(T)throw T}else{const{error:T}=await U.from("recruit_email_templates").insert({brokerage_id:s,category:C.category||"Outreach",title:C.title,subject:C.subject,body:C.body,created_by:n==null?void 0:n.id,sort_order:100});if(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:C=>t({title:"Save failed",description:C.message,variant:"destructive"})}),y=vt({mutationFn:async C=>{const{error:T}=await U.from("recruit_email_templates").delete().eq("id",C);if(T)throw T},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:C=>t({title:"Delete failed",description:C.message,variant:"destructive"})}),g=(C,T)=>{navigator.clipboard.writeText(C),i(T),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},b=()=>{h({category:"Outreach",title:"",subject:"",body:""}),d(!0)},v=C=>{h(C),d(!0)},k=Array.from(new Set(m.map(C=>C.category)));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pre-built and custom recruiting templates. Built-in templates are global; your custom ones are private to this brokerage."}),e.jsxs(B,{onClick:b,size:"sm",className:"gap-1.5",children:[e.jsx(Js,{className:"h-4 w-4"})," New Template"]})]}),p?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Wt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):k.map(C=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4"})," ",C]}),m.filter(T=>T.category===C).map(T=>{const M=T.brokerage_id!==null;return e.jsxs(be,{className:`transition-all ${l===T.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(Ft,{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(Ut,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:T.title}),!M&&e.jsx(qe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),M&&e.jsx(qe,{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(qe,{variant:"outline",className:"text-[10px] shrink-0",children:T.category})]})}),l===T.id&&e.jsxs(Re,{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:()=>g(T.subject,T.id+"-s"),children:[a===T.id+"-s"?e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ja,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>g(T.body,T.id+"-b"),children:[a===T.id+"-b"?e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ja,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),M&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>v(T),children:[e.jsx(Za,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:async()=>{await Bi("Delete this template?")&&y.mutate(T.id)},children:[e.jsx(Rn,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},T.id)})]},C)),e.jsx(Fs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx($s,{children:e.jsx(zs,{children:u!=null&&u.id?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Title"}),e.jsx(ye,{value:(u==null?void 0:u.title)||"",onChange:C=>h(T=>({...T,title:C.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(u==null?void 0:u.category)||"Outreach",onChange:C=>h(T=>({...T,category:C.target.value})),className:"mt-1 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:tAn.map(C=>e.jsx("option",{value:C,children:C},C))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject"}),e.jsx(ye,{value:(u==null?void 0:u.subject)||"",onChange:C=>h(T=>({...T,subject:C.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Body"}),e.jsx(Ds,{value:(u==null?void 0:u.body)||"",onChange:C=>h(T=>({...T,body:C.target.value})),rows:12,className:"mt-1 font-sans",placeholder:`Hi [First Name], ... Best, [Your Name]`}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Available placeholders: [First Name], [Your Name], [Brokerage Name]"})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>x.mutate(u||{}),disabled:x.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[x.isPending&&e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const Tgt={call:pa,email:on,text:ro,meeting:ra,note:$r};function SBt({brokerageId:s}){const{data:t,isLoading:n}=mt({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:r,error:a}=await U.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(r==null?void 0:r.map(p=>p.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await U.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...r.map(p=>p.created_by),...(l||[]).map(p=>p.created_by)])],{data:d}=await U.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(p=>[p.id,p])),h=kK(new Date,30);return{recruiters:c.map(p=>{var v,k;const x=(l||[]).filter(C=>C.created_by===p),y=x.filter(C=>new Date(C.created_at)>=h),g={};y.forEach(C=>{g[C.activity_type]=(g[C.activity_type]||0)+1});const b=r.filter(C=>C.created_by===p).length;return{id:p,name:((v=u[p])==null?void 0:v.name)||"Unknown",email:((k=u[p])==null?void 0:k.email)||"",totalActivities:x.length,recentActivities:y.length,byType:g,prospectsCreated:b}}).sort((p,x)=>x.recentActivities-p.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Re,{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(Eo,{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]||$r;return e.jsxs(qe,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Recent Activity"})}),e.jsx(Re,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=Tgt[r.activity_type]||$r;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:Bs(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 CBt({brokerageId:s}){const{toast:t}=pi(),n=as(),[r,a]=j.useState(!1),[i,l]=j.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=mt({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:g,error:b}=await U.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(b)throw b;return g}}),d=[...new Set(o.map(g=>g.referred_by))],{data:u=[]}=mt({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:g}=await U.from("profiles").select("id, name, email").in("id",d);return g||[]},enabled:d.length>0}),h=Object.fromEntries(u.map(g=>[g.id,g])),m=vt({mutationFn:async g=>{const{data:{user:b}}=await U.auth.getUser();if(!b)throw new Error("Not authenticated");const{error:v}=await U.from("recruit_referrals").insert({brokerage_id:s,referred_by:b.id,referee_first_name:g.first_name,referee_last_name:g.last_name||null,referee_email:g.email||null,referee_phone:g.phone||null,referee_current_brokerage:g.current_brokerage||null,notes:g.notes||null});if(v)throw v},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-referrals",s]}),t({title:"Referral submitted!"}),l({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),a(!1)},onError:g=>t({title:"Error",description:g.message,variant:"destructive"})}),p=vt({mutationFn:async({id:g,status:b,incentive_status:v})=>{const k={updated_at:new Date().toISOString()};b&&(k.status=b),v&&(k.incentive_status=v);const{error:C}=await U.from("recruit_referrals").update(k).eq("id",g);if(C)throw C},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),x=g=>g==="approved"||g==="signed"?e.jsx(da,{className:"h-3 w-3"}):g==="rejected"?e.jsx(Rd,{className:"h-3 w-3"}):e.jsx(Vr,{className:"h-3 w-3"}),y=g=>g==="approved"||g==="signed"||g==="paid"?"bg-green-500/10 text-green-600 border-green-200":g==="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(Js,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(be,{className:"py-12 text-center",children:[e.jsx(Sl,{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(g=>{var b;return e.jsx(be,{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:[g.referee_first_name," ",g.referee_last_name]}),e.jsxs(qe,{variant:"outline",className:y(g.status),children:[x(g.status)," ",g.status]}),g.incentive_status&&e.jsxs(qe,{variant:"outline",className:y(g.incentive_status),children:[e.jsx(zo,{className:"h-3 w-3 mr-1"})," ",g.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[g.referee_email&&e.jsx("p",{children:g.referee_email}),g.referee_phone&&e.jsx("p",{children:g.referee_phone}),g.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",g.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((b=h[g.referred_by])==null?void 0:b.name)||"Unknown"," • ",Bs(new Date(g.created_at),"MMM d, yyyy")]})]}),g.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:g.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(vs,{value:g.status,onValueChange:v=>p.mutate({id:g.id,status:v}),children:[e.jsx(gs,{className:"h-7 text-xs w-[110px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"pending",children:"Pending"}),e.jsx(Je,{value:"contacted",children:"Contacted"}),e.jsx(Je,{value:"approved",children:"Approved"}),e.jsx(Je,{value:"signed",children:"Signed"}),e.jsx(Je,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(vs,{value:g.incentive_status||"pending",onValueChange:v=>p.mutate({id:g.id,incentive_status:v}),children:[e.jsx(gs,{className:"h-7 text-xs w-[100px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"pending",children:"Unpaid"}),e.jsx(Je,{value:"paid",children:"Paid"}),e.jsx(Je,{value:"n/a",children:"N/A"})]})]})]})]})},g.id)})}),e.jsx(Fs,{open:r,onOpenChange:a,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault(),m.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"First Name *"}),e.jsx(ye,{required:!0,value:i.first_name,onChange:g=>l(b=>({...b,first_name:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last Name"}),e.jsx(ye,{value:i.last_name,onChange:g=>l(b=>({...b,last_name:g.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{type:"email",value:i.email,onChange:g=>l(b=>({...b,email:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:i.phone,onChange:g=>l(b=>({...b,phone:g.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Current Brokerage"}),e.jsx(ye,{value:i.current_brokerage,onChange:g=>l(b=>({...b,current_brokerage:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ds,{value:i.notes,onChange:g=>l(b=>({...b,notes:g.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 ABt({brokerageId:s}){const{toast:t}=pi(),n=as(),[r,a]=j.useState(!1),{data:i}=mt({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:m,error:p}=await U.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(p)throw p;return m}}),{data:l=[]}=mt({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:m,error:p}=await U.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(p)throw p;return m}}),o=vt({mutationFn:async m=>{const{error:p}=await U.from("brokerages").update({recruit_form_enabled:m}).eq("id",s);if(p)throw p},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=vt({mutationFn:async({id:m,status:p})=>{const{error:x}=await U.from("recruit_interest_submissions").update({status:p}).eq("id",m);if(x)throw x},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-interest-submissions",s]})}),d=`https://bestbrokerage.relevelup.com/join-brokerage/${(i==null?void 0:i.recruit_form_slug)||""}`,u=()=>{navigator.clipboard.writeText(d),a(!0),t({title:"Link copied!"}),setTimeout(()=>a(!1),2e3)},h=m=>m==="contacted"||m==="converted"?"bg-green-500/10 text-green-600":m==="dismissed"?"bg-red-500/10 text-red-600":"bg-blue-500/10 text-blue-600";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Enable Public Form"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Allow agents to express interest in joining via a public link"})]}),e.jsx(Mn,{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(da,{className:"h-3.5 w-3.5"}):e.jsx(ja,{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(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Re,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Sl,{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(qe,{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(on,{className:"h-3 w-3"}),m.email]}),m.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pa,{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:Bs(new Date(m.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(vs,{value:m.status,onValueChange:p=>c.mutate({id:m.id,status:p}),children:[e.jsx(gs,{className:"h-7 text-xs w-[110px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"new",children:"New"}),e.jsx(Je,{value:"contacted",children:"Contacted"}),e.jsx(Je,{value:"converted",children:"Converted"}),e.jsx(Je,{value:"dismissed",children:"Dismissed"})]})]})]},m.id))})})]})]})}function TBt({brokerageId:s}){const{toast:t}=pi(),n=as(),[r,a]=j.useState(!1),[i,l]=j.useState({prospect_id:"",title:"",description:"",due_date:Bs(jd(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=j.useState("pending"),{data:d=[]}=mt({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:T,error:M}=await U.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(M)throw M;return T}}),{data:u=[],isLoading:h}=mt({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const T=d.map(L=>L.id);if(!T.length)return[];const{data:M,error:P}=await U.from("recruit_follow_ups").select("*").in("prospect_id",T).order("due_date");if(P)throw P;return M},enabled:d.length>0}),m=Object.fromEntries(d.map(T=>[T.id,T])),p=vt({mutationFn:async T=>{const{data:{user:M}}=await U.auth.getUser();if(!M)throw new Error("Not authenticated");const{error:P}=await U.from("recruit_follow_ups").insert({prospect_id:T.prospect_id,assigned_to:M.id,title:T.title,description:T.description||null,due_date:new Date(T.due_date).toISOString()});if(P)throw P},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:Bs(jd(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:T=>t({title:"Error",description:T.message,variant:"destructive"})}),x=vt({mutationFn:async({id:T,completed:M})=>{const{error:P}=await U.from("recruit_follow_ups").update({completed_at:M?new Date().toISOString():null}).eq("id",T);if(P)throw P},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),y=u.filter(T=>o==="pending"?!T.completed_at:o==="completed"?!!T.completed_at:!0),g=y.filter(T=>!T.completed_at&&F5(new Date(T.due_date))&&!Jg(new Date(T.due_date))),b=y.filter(T=>!T.completed_at&&Jg(new Date(T.due_date))),v=y.filter(T=>!T.completed_at&&!F5(new Date(T.due_date))&&!Jg(new Date(T.due_date))),k=y.filter(T=>!!T.completed_at),C=T=>{const M=m[T.prospect_id],P=!T.completed_at&&F5(new Date(T.due_date))&&!Jg(new Date(T.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(wi,{checked:!!T.completed_at,onCheckedChange:L=>x.mutate({id:T.id,completed:L}),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:[M&&e.jsxs(qe,{variant:"secondary",className:"text-[10px]",children:[M.first_name," ",M.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${P?"text-destructive font-medium":""}`,children:[P?e.jsx(po,{className:"h-3 w-3"}):e.jsx(ra,{className:"h-3 w-3"}),Bs(new Date(T.due_date),"MMM d, h:mm a")]}),T.is_automated&&e.jsx(qe,{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"&&g.length+b.length+v.length>0&&`(${g.length+b.length+v.length})`]},T))}),e.jsxs(B,{size:"sm",onClick:()=>a(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&g.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(po,{className:"h-3.5 w-3.5"})," Overdue (",g.length,")"]}),g.map(C)]}),o!=="completed"&&b.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-amber-600 flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3.5 w-3.5"})," Today (",b.length,")"]}),b.map(C)]}),o!=="completed"&&v.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(ra,{className:"h-3.5 w-3.5"})," Upcoming (",v.length,")"]}),v.map(C)]}),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(da,{className:"h-3.5 w-3.5"})," Completed (",k.length,")"]}),k.map(C)]}),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(Fs,{open:r,onOpenChange:a,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:T=>{T.preventDefault(),p.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Prospect *"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",required:!0,value:i.prospect_id,onChange:T=>l(M=>({...M,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(se,{children:"Task *"}),e.jsx(ye,{required:!0,value:i.title,onChange:T=>l(M=>({...M,title:T.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Details"}),e.jsx(Ds,{value:i.description,onChange:T=>l(M=>({...M,description:T.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due Date *"}),e.jsx(ye,{type:"datetime-local",required:!0,value:i.due_date,onChange:T=>l(M=>({...M,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:p.isPending,children:"Schedule"})]})]})]})})]})}const sAn=[{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 EBt({brokerageId:s}){const{toast:t}=pi(),n=as(),[r,a]=j.useState(null),{data:i,isLoading:l}=mt({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:g,error:b}=await U.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(b)throw b;return g}}),[o,c]=j.useState({brokerage_id:s,hero_headline:"Join Our Team",hero_subtext:"Take your real estate career to the next level.",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",benefits:sAn,testimonials:[],gallery_images:[],calculator_enabled:!1,calculator_config:{headline:"See What You Could Earn With Us",subtext:"Confidential 60-second calculator — no signup required.",commission_split_pct:80,cap_amount:16e3,post_cap_split_pct:100,monthly_fee:99,transaction_fee:0,show_email_capture:!0,email_capture_label:"Want the full breakdown? Enter your email."},lead_magnet_enabled:!1,lead_magnet_config:{title:"Get the Full Comp Plan PDF",description:"See exactly how splits, caps, and fees work — no call required.",button_text:"Email Me the PDF",pdf_url:null},form_style:"classic",confidential_messaging:!0});j.useEffect(()=>{i&&c({id:i.id,brokerage_id:i.brokerage_id,hero_headline:i.hero_headline,hero_subtext:i.hero_subtext||"",hero_image_url:i.hero_image_url,logo_url:i.logo_url,primary_color:i.primary_color,accent_color:i.accent_color,benefits:i.benefits||[],testimonials:i.testimonials||[],gallery_images:i.gallery_images||[],calculator_enabled:i.calculator_enabled??!1,calculator_config:i.calculator_config||{},lead_magnet_enabled:i.lead_magnet_enabled??!1,lead_magnet_config:i.lead_magnet_config||{},form_style:i.form_style||"classic",confidential_messaging:i.confidential_messaging??!0})},[i]);const d=vt({mutationFn:async()=>{const g={brokerage_id:s,hero_headline:o.hero_headline,hero_subtext:o.hero_subtext,hero_image_url:o.hero_image_url,logo_url:o.logo_url,primary_color:o.primary_color,accent_color:o.accent_color,benefits:JSON.parse(JSON.stringify(o.benefits)),testimonials:JSON.parse(JSON.stringify(o.testimonials)),gallery_images:JSON.parse(JSON.stringify(o.gallery_images)),calculator_enabled:o.calculator_enabled,calculator_config:JSON.parse(JSON.stringify(o.calculator_config)),lead_magnet_enabled:o.lead_magnet_enabled,lead_magnet_config:JSON.parse(JSON.stringify(o.lead_magnet_config)),form_style:o.form_style,confidential_messaging:o.confidential_messaging,updated_at:new Date().toISOString()};if(o.id){const{error:b}=await U.from("recruit_landing_page_settings").update(g).eq("id",o.id);if(b)throw b}else{const{error:b}=await U.from("recruit_landing_page_settings").insert(g);if(b)throw b}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:g=>t({title:"Error",description:g.message,variant:"destructive"})}),u=async(g,b)=>{const v=g.name.split(".").pop(),k=`${s}/${b}-${Date.now()}.${v}`,{error:C}=await U.storage.from("recruit-landing").upload(k,g);if(C)throw C;const{data:{publicUrl:T}}=U.storage.from("recruit-landing").getPublicUrl(k);return T},h=async(g,b)=>{var k;const v=(k=g.target.files)==null?void 0:k[0];if(v){a(b);try{const C=await u(v,b);c(T=>({...T,[b]:C})),t({title:"Image uploaded!"})}catch(C){t({title:"Upload failed",description:C.message,variant:"destructive"})}finally{a(null)}}},m=async g=>{var v;const b=(v=g.target.files)==null?void 0:v[0];if(b){a("gallery");try{const k=await u(b,"gallery");c(C=>({...C,gallery_images:[...C.gallery_images,k]})),t({title:"Gallery image added!"})}catch(k){t({title:"Upload failed",description:k.message,variant:"destructive"})}finally{a(null)}}},p=async(g,b)=>{var k;const v=(k=g.target.files)==null?void 0:k[0];if(v){a(`testimonial-${b}`);try{const C=await u(v,`testimonial-${b}`);c(T=>{const M=[...T.testimonials];return M[b]={...M[b],photo_url:C},{...T,testimonials:M}})}catch(C){t({title:"Upload failed",description:C.message,variant:"destructive"})}finally{a(null)}}},{data:x}=mt({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:g,error:b}=await U.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(b)throw b;return g}}),y=`https://bestbrokerage.relevelup.com/join-brokerage/${(x==null?void 0:x.recruit_form_slug)||""}`;return l?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[(x==null?void 0:x.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Live page:"}),e.jsx("code",{className:"text-xs flex-1 truncate",children: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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Branding"})}),e.jsx(Re,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.logo_url&&e.jsx("img",{src:o.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="logo_url",children:e.jsxs("span",{children:[e.jsx(Ja,{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:g=>h(g,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.primary_color,onChange:g=>c(b=>({...b,primary_color:g.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:o.primary_color,onChange:g=>c(b=>({...b,primary_color:g.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.accent_color,onChange:g=>c(b=>({...b,accent_color:g.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:o.accent_color,onChange:g=>c(b=>({...b,accent_color:g.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Hero Section"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Headline"}),e.jsx(ye,{value:o.hero_headline,onChange:g=>c(b=>({...b,hero_headline:g.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Subtext"}),e.jsx(Ds,{value:o.hero_subtext,onChange:g=>c(b=>({...b,hero_subtext:g.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Background Image"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.hero_image_url&&e.jsx("img",{src:o.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(Ja,{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:g=>h(g,"hero_image_url")})]}),o.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(g=>({...g,hero_image_url:null})),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(g=>({...g,benefits:[...g.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Re,{className:"space-y-3",children:[o.benefits.map((g,b)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Fp,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(ye,{value:g.icon,onChange:v=>{const k=[...o.benefits];k[b]={...g,icon:v.target.value},c(C=>({...C,benefits:k}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ye,{value:g.title,onChange:v=>{const k=[...o.benefits];k[b]={...g,title:v.target.value},c(C=>({...C,benefits:k}))},placeholder:"Benefit title"}),e.jsx(ye,{value:g.description,onChange:v=>{const k=[...o.benefits];k[b]={...g,description:v.target.value},c(C=>({...C,benefits:k}))},placeholder:"Short description"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(v=>({...v,benefits:v.benefits.filter((k,C)=>C!==b)})),children:e.jsx(Rn,{className:"h-3.5 w-3.5 text-destructive"})})]},b)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{className:"text-base",children:"Testimonials"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(g=>({...g,testimonials:[...g.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Re,{className:"space-y-3",children:[o.testimonials.map((g,b)=>{var v;return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[g.photo_url?e.jsx("img",{src:g.photo_url,alt:g.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded-full bg-muted flex items-center justify-center text-xs text-muted-foreground",children:((v=g.name)==null?void 0:v[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:r===`testimonial-${b}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:k=>p(k,b)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ye,{value:g.name,onChange:k=>{const C=[...o.testimonials];C[b]={...g,name:k.target.value},c(T=>({...T,testimonials:C}))},placeholder:"Name"}),e.jsx(ye,{value:g.role,onChange:k=>{const C=[...o.testimonials];C[b]={...g,role:k.target.value},c(T=>({...T,testimonials:C}))},placeholder:"Role / Title"})]}),e.jsx(Ds,{value:g.quote,onChange:k=>{const C=[...o.testimonials];C[b]={...g,quote:k.target.value},c(T=>({...T,testimonials:C}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(k=>({...k,testimonials:k.testimonials.filter((C,T)=>T!==b)})),children:e.jsx(Rn,{className:"h-3.5 w-3.5 text-destructive"})})]},b)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{size:"sm",variant:"outline",asChild:!0,disabled:r==="gallery",children:e.jsxs("span",{children:[e.jsx(ac,{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(Re,{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((g,b)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:g,alt:`Gallery ${b+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(v=>({...v,gallery_images:v.gallery_images.filter((k,C)=>C!==b)})),children:e.jsx(Rn,{className:"h-3 w-3"})})]},b))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Application Form Style"}),e.jsxs(vs,{value:o.form_style,onValueChange:g=>c(b=>({...b,form_style:g})),children:[e.jsx(gs,{className:"mt-1.5",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(Je,{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(du,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(se,{children:"Show Confidentiality Badges"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Adds "100% Confidential" + "No spam" trust signals around the form.'})]})]}),e.jsx(Mn,{checked:o.confidential_messaging,onCheckedChange:g=>c(b=>({...b,confidential_messaging:g}))})]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(P5,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(Mn,{checked:o.calculator_enabled,onCheckedChange:g=>c(b=>({...b,calculator_enabled:g}))})]}),o.calculator_enabled&&e.jsxs(Re,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highest-converting recruiting tool. Agents enter their GCI and instantly see what they'd earn at your brokerage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Calculator Headline"}),e.jsx(ye,{value:o.calculator_config.headline||"",onChange:g=>c(b=>({...b,calculator_config:{...b.calculator_config,headline:g.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subtext"}),e.jsx(ye,{value:o.calculator_config.subtext||"",onChange:g=>c(b=>({...b,calculator_config:{...b.calculator_config,subtext:g.target.value}})),placeholder:"Confidential 60-second calculator"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(ye,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:g=>c(b=>({...b,calculator_config:{...b.calculator_config,commission_split_pct:parseFloat(g.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 80 for an 80/20"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(ye,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:g=>c(b=>({...b,calculator_config:{...b.calculator_config,cap_amount:parseFloat(g.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Annual cap to brokerage"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(ye,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:g=>c(b=>({...b,calculator_config:{...b.calculator_config,post_cap_split_pct:parseFloat(g.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 95 for 95/5 after cap, 100 for 100%"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(ye,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:g=>c(b=>({...b,calculator_config:{...b.calculator_config,monthly_fee:parseFloat(g.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(ye,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:g=>c(b=>({...b,calculator_config:{...b.calculator_config,transaction_fee:parseFloat(g.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Multiplied by # of transactions"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm",children:"Capture email at end of calculator"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"After seeing results, agents can request a full breakdown via email."})]}),e.jsx(Mn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:g=>c(b=>({...b,calculator_config:{...b.calculator_config,show_email_capture:g}}))})]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(jj,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(Mn,{checked:o.lead_magnet_enabled,onCheckedChange:g=>c(b=>({...b,lead_magnet_enabled:g}))})]}),o.lead_magnet_enabled&&e.jsxs(Re,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Captures emails from agents not ready to talk. Offer a comp plan PDF, recruiting deck, or guide."}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Title"}),e.jsx(ye,{value:o.lead_magnet_config.title||"",onChange:g=>c(b=>({...b,lead_magnet_config:{...b.lead_magnet_config,title:g.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Description"}),e.jsx(Ds,{rows:2,value:o.lead_magnet_config.description||"",onChange:g=>c(b=>({...b,lead_magnet_config:{...b.lead_magnet_config,description:g.target.value}})),placeholder:"See exactly how splits, caps, and fees work..."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Button Text"}),e.jsx(ye,{value:o.lead_magnet_config.button_text||"",onChange:g=>c(b=>({...b,lead_magnet_config:{...b.lead_magnet_config,button_text:g.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ye,{value:o.lead_magnet_config.pdf_url||"",onChange:g=>c(b=>({...b,lead_magnet_config:{...b.lead_magnet_config,pdf_url:g.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(Ja,{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 g=>{var v;const b=(v=g.target.files)==null?void 0:v[0];if(b){a("lead_magnet_pdf");try{const k=await u(b,"lead-magnet");c(C=>({...C,lead_magnet_config:{...C.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(nAn,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function nAn({brokerageId:s}){const{data:t=[]}=mt({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:n,error:r}=await U.from("recruit_lead_magnet_downloads").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(100);if(r)throw r;return n}});return t.length===0?null:e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(ii,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Re,{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:[Bs(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function MBt({brokerageId:s,trigger:t,initialProspectId:n,open:r,onOpenChange:a}){const[i,l]=j.useState(!1),o=r??i,c=a??l,[d,u]=j.useState("pick-recipients"),[h,m]=j.useState(new Set(n?[n]:[])),[p,x]=j.useState("all"),[y,g]=j.useState(""),[b,v]=j.useState(null),[k,C]=j.useState(""),[T,M]=j.useState(0),[P,L]=j.useState(0),[I,O]=j.useState(""),[$,q]=j.useState(""),{data:W}=vTe(),[G,K]=j.useState("default");j.useEffect(()=>{K(W!=null&&W.massEmail?"mass_email":W!=null&&W.gmail?"gmail":"default")},[W==null?void 0:W.massEmail,W==null?void 0:W.gmail]);const[ee,J]=j.useState(null),{prospects:le,stages:ue}=vee(s),oe=yBt(),ie=hS(),{data:de=[]}=mt({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:Ne,error:Ge}=await U.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, created_at, owner_user_id, share_token").eq("touch_type","recruiting").eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Ge)throw Ge;return Ne??[]},enabled:o&&d==="pick-video"}),we=j.useCallback(()=>{u("pick-recipients"),m(new Set(n?[n]:[])),x("all"),g(""),v(null),C(""),M(0),L(0),O(""),q(""),K("default"),J(null)},[n]),je=Ne=>{!Ne&&(d==="uploading"||d==="processing"||d==="sending")||(c(Ne),Ne||setTimeout(we,200))},xe=j.useMemo(()=>le.filter(Ne=>{if(!Ne.email||p!=="all"&&Ne.stage_id!==p)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}),[le,p,y]),fe=Ne=>{m(Ge=>{const _e=new Set(Ge);return _e.has(Ne)?_e.delete(Ne):_e.add(Ne),_e})},Se=()=>{h.size===xe.length?m(new Set):m(new Set(xe.map(Ne=>Ne.id)))},Ee=j.useCallback(async(Ne,Ge)=>{u("uploading");try{const _e=`Recruiting blast (${h.size} recipients)`,{videoId:Oe,libraryId:Ae}=await w6(_e),{uploadUrl:Xe,apiKey:Ue}=await j6(Oe),Ze=new XMLHttpRequest;Ze.upload.onprogress=pt=>{pt.lengthComputable&&M(pt.loaded/pt.total*100)},await new Promise((pt,zt)=>{Ze.onload=()=>Ze.status>=200&&Ze.status<300?pt():zt(new Error("Upload failed")),Ze.onerror=()=>zt(new Error("Upload failed")),Ze.open("PUT",Xe),Ze.setRequestHeader("AccessKey",Ue),Ze.send(Ne)}),u("processing");const Qe=`https://iframe.mediadelivery.net/embed/${Ae}/${Oe}`;let Ye=0;const nt=Date.now(),rt=9e4;for(;Ye<4&&(await new Promise(zt=>setTimeout(zt,3e3)),!(Date.now()-nt>rt));){const pt=await $j(Oe);if(Ye=pt.status,L(pt.encodeProgress||0),Ye===5||Ye===6)throw new Error("Video processing failed")}const Fe=await $j(Oe),dt=(Fe.storageSize||Ne.size)/(1024*1024),Dt=await ie.mutateAsync({bunny_video_id:Oe,playback_url:Fe.directPlayUrl||Qe,thumbnail_url:Fe.thumbnailUrl,preview_url:Fe.previewUrl||null,duration_seconds:Fe.length||Ge,file_size_mb:dt,title:_e,status:Ye>=4?"ready":"processing",touch_type:"recruiting"});v(Dt.id),C(_e),u("compose")}catch(_e){re.error((_e==null?void 0:_e.message)||"Failed to upload video"),u("pick-video")}},[h.size,ie]),Le=j.useCallback(async()=>{if(!(!b||h.size===0)){u("sending");try{const Ne=[];for(const Oe of h){const Ae=await oe.mutateAsync({prospect_id:Oe,video_id:b,brokerage_id:s,message:$||void 0});Ne.push(Ae.id)}const{data:Ge,error:_e}=await U.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:Ne,brokerage_id:s,subject_override:I||void 0,message_override:$||void 0,send_via:G}});if(_e)throw new Error(_e.message);J({sent:(Ge==null?void 0:Ge.sent)??0,total:(Ge==null?void 0:Ge.total)??Ne.length}),u("done"),re.success(`Sent ${(Ge==null?void 0:Ge.sent)??0} of ${(Ge==null?void 0:Ge.total)??Ne.length} videos`)}catch(Ne){re.error((Ne==null?void 0:Ne.message)||"Failed to send"),u("compose")}}},[b,h,s,$,I,G,oe]),De=h.size,Be=le.filter(Ne=>!Ne.email).length;return e.jsxs(Fs,{open:o,onOpenChange:je,children:[t&&e.jsx(Io,{asChild:!0,children:t}),e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Zr,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",De>0&&e.jsxs(qe,{variant:"secondary",className:"ml-2",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),De," ",De===1?"recipient":"recipients"]})]})}),d==="pick-recipients"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search prospects...",value:y,onChange:Ne=>g(Ne.target.value),className:"pl-9"})]}),e.jsxs(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{className:"w-48",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All stages"}),ue.map(Ne=>e.jsx(Je,{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===xe.length&&xe.length>0?"Deselect all":"Select all"," ","(",xe.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:xe.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:xe.map(Ne=>{const Ge=h.has(Ne.id),_e=ue.find(Oe=>Oe.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(wi,{checked:Ge,onCheckedChange:()=>fe(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]}),_e&&e.jsx(qe,{variant:"outline",className:"text-[10px]",style:{borderColor:_e.color,color:_e.color},children:_e.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Ne.email," ",Ne.current_brokerage&&`· ${Ne.current_brokerage}`]})]})]},Ne.id)})})}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>je(!1),children:"Cancel"}),e.jsx(B,{disabled:De===0,onClick:()=>u("pick-video"),children:"Next: Choose Video"})]})]}),d==="pick-video"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(fa,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(xa,{className:"self-start",children:[e.jsxs(ss,{value:"record",children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(ss,{value:"library",children:[e.jsx(i1,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(ns,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(wh,{className:"h-12 w-12 mx-auto text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Record a fresh video"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["Same video sent to all ",De," ",De===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(B,{onClick:()=>u("record"),children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(ns,{value:"library",className:"flex-1 overflow-auto",children:de.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:de.map(Ne=>e.jsxs("button",{onClick:()=>{v(Ne.id),C(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:S5(Ne)?e.jsx("img",{src:S5(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(Zr,{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(Nr,{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(k6,{maxDurationSeconds:600,onRecordingComplete:Ee}),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(Wt,{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(qi,{value:d==="uploading"?T:P,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?T:P),"%"]})]}),d==="compose"&&e.jsxs("div",{className:"flex-1 overflow-auto space-y-4",children:[e.jsxs("div",{className:"rounded-md border p-3 bg-muted/30 flex items-center gap-3",children:[e.jsx(Rr,{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:De})," recipient",De===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(ye,{value:I,onChange:Ne=>O(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(se,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(Ds,{value:$,onChange:Ne=>q(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(lYe,{value:G,onChange:K}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs(B,{onClick:Le,disabled:!b||De===0,children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"})," Send to ",De," ",De===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(Wt,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",De," recipient",De===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&ee&&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 ${ee.sent===ee.total?"bg-primary/10":"bg-muted"}`,children:ee.sent===ee.total?e.jsx(Rr,{className:"h-8 w-8 text-primary"}):e.jsx(po,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[ee.sent," of ",ee.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:()=>je(!1),children:"Done"})]})]})]})}function rAn(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function aAn({video:s}){return s.cta_clicked_at?e.jsx(qe,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(qe,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(ma,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(qe,{variant:"secondary",children:[e.jsx(Dr,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(qe,{variant:"outline",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"}),"Draft"]})}function LBt({brokerageId:s}){var k,C,T,M;const{data:t=[],isLoading:n}=GCn(s),{data:r=[]}=bBt(s),a=KCn(),i=YCn(),l=vBt(),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState({title:"",script_text:"",category:"general"}),[p,x]=j.useState(null),y=t.filter(P=>{var I,O,$,q;return o?`${((I=P.prospect)==null?void 0:I.first_name)||""} ${((O=P.prospect)==null?void 0:O.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((q=($=P.video)==null?void 0:$.title)==null?void 0:q.toLowerCase().includes(o.toLowerCase())):!0}),g={total:t.length,sent:t.filter(P=>P.sent_at).length,viewed:t.filter(P=>P.view_count>0).length,ctaClicked:t.filter(P=>P.cta_clicked_at).length},b=j.useCallback(P=>{if(!P)return;const L=`${window.location.origin}/recruit-video/${P}`;navigator.clipboard.writeText(L),re.success("Share link copied")},[]);j.useCallback((P,L)=>{l.mutate({id:P,sent_via:L})},[l]);const v=()=>{!h.title.trim()||!h.script_text.trim()||a.mutate({brokerage_id:s,...h},{onSuccess:()=>{m({title:"",script_text:"",category:"general"}),u(!1)}})};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Total Videos",value:g.total,icon:Zr,color:"text-primary"},{label:"Sent",value:g.sent,icon:Dr,color:"text-blue-500"},{label:"Viewed",value:g.viewed,icon:ma,color:"text-amber-500"},{label:"CTA Clicked",value:g.ctaClicked,icon:Rr,color:"text-emerald-500"}].map(P=>e.jsx(be,{children:e.jsxs(Re,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:`h-10 w-10 rounded-lg bg-muted flex items-center justify-center ${P.color}`,children:e.jsx(P.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:P.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:P.label})]})]})},P.label))}),e.jsxs(fa,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"videos",children:[e.jsx(Zr,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(ss,{value:"scripts",children:[e.jsx($r,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(ss,{value:"analytics",children:[e.jsx(ol,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(ns,{value:"videos",children:e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Ut,{className:"text-lg",children:"Video Outreach"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-64",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or title...",value:o,onChange:P=>c(P.target.value),className:"pl-9"})]}),e.jsx(MBt,{brokerageId:s,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(on,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Re,{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(Zr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No video outreach yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Record a personalized video from any prospect's profile card"})]}):e.jsx("div",{className:"space-y-3",children:y.map(P=>{var L,I,O,$,q,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:[S5(P.video)?e.jsx("img",{src:S5(P.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(Zr,{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:rAn(((L=P.video)==null?void 0:L.duration_seconds)??null)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium truncate",children:[(I=P.prospect)==null?void 0:I.first_name," ",(O=P.prospect)==null?void 0:O.last_name]}),e.jsx(aAn,{video:P})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:(($=P.video)==null?void 0:$.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Bs(new Date(P.created_at),"MMM d, yyyy"),((q=P.prospect)==null?void 0:q.current_brokerage)&&` · ${P.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>b(P.share_token),title:"Copy share link",children:e.jsx(ja,{className:"h-4 w-4"})}),e.jsxs(B,{variant:P.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>x(P),disabled:!((W=P.prospect)!=null&&W.email),title:(G=P.prospect)!=null&&G.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(on,{className:"h-4 w-4"}),P.sent_at?"Resend":"Email"]}),P.share_token&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${P.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(Tr,{className:"h-4 w-4"})})]})]},P.id)})})})]})}),e.jsx(ns,{value:"scripts",children:e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ut,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(Fs,{open:d,onOpenChange:u,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Js,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:h.title,onChange:P=>m(L=>({...L,title:P.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(vs,{value:h.category,onValueChange:P=>m(L=>({...L,category:P})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:ABe.map(P=>e.jsx(Je,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Script"}),e.jsx(Ds,{value:h.script_text,onChange:P=>m(L=>({...L,script_text:P.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx(B,{onClick:v,disabled:!h.title.trim()||!h.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Re,{children:r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx($r,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No scripts yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create teleprompter scripts for common recruiting conversations"})]}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:r.map(P=>{var I;const L=((I=ABe.find(O=>O.value===P.category))==null?void 0:I.label)||P.category;return e.jsx(be,{className:"relative group",children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(qe,{variant:"outline",className:"text-[10px] mb-2",children:L}),e.jsx("h4",{className:"font-medium text-sm",children:P.title})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(P.id),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:P.script_text}),P.is_global&&e.jsx(qe,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},P.id)})})})]})}),e.jsx(ns,{value:"analytics",children:e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Re,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:g.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:g.sent,pct:g.total?Math.round(g.sent/g.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:g.viewed,pct:g.sent?Math.round(g.viewed/g.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:g.ctaClicked,pct:g.viewed?Math.round(g.ctaClicked/g.viewed*100):0,color:"bg-emerald-500"}].map(P=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:P.label}),e.jsxs("span",{className:"font-medium",children:[P.count," (",P.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${P.color} rounded-full transition-all`,style:{width:`${P.pct}%`}})})]},P.label))}),t.filter(P=>P.view_count>0).length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h4",{className:"font-medium text-sm mb-3",children:"Most Engaged Prospects"}),e.jsx("div",{className:"space-y-2",children:t.filter(P=>P.view_count>0).sort((P,L)=>L.view_count-P.view_count).slice(0,5).map(P=>{var L,I;return e.jsxs("div",{className:"flex items-center justify-between text-sm p-2 rounded-md bg-muted/30",children:[e.jsxs("span",{className:"font-medium",children:[(L=P.prospect)==null?void 0:L.first_name," ",(I=P.prospect)==null?void 0:I.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ma,{className:"h-3.5 w-3.5"})," ",P.view_count]}),P.cta_clicked_at&&e.jsx(Rr,{className:"h-4 w-4 text-emerald-500"})]})]},P.id)})})]})]})]})})]}),p&&e.jsx(gBt,{open:!!p,onOpenChange:P=>{P||x(null)},recruitVideoId:p.id,brokerageId:s,prospectName:`${((k=p.prospect)==null?void 0:k.first_name)||""} ${((C=p.prospect)==null?void 0:C.last_name)||""}`.trim(),prospectEmail:(T=p.prospect)==null?void 0:T.email,videoTitle:(M=p.video)==null?void 0:M.title,defaultMessage:p.message})]})}function PBt({brokerageId:s}){const{toast:t}=pi(),n=as(),{stages:r,prospects:a}=vee(s),[i,l]=j.useState(!1),[o,c]=j.useState({title:"",target_count:"10",target_stage_id:"",period_start:Bs(new Date,"yyyy-MM-dd"),period_end:Bs(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:x,error:y}=await U.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(y)throw y;return x}}),h=vt({mutationFn:async x=>{const{data:{user:y}}=await U.auth.getUser();if(!y)throw new Error("Not authenticated");const{error:g}=await U.from("recruit_goals").insert({brokerage_id:s,title:x.title,target_count:parseInt(x.target_count),target_stage_id:x.target_stage_id||null,period_start:x.period_start,period_end:x.period_end,created_by:y.id});if(g)throw g},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:x=>t({title:"Error",description:x.message,variant:"destructive"})}),m=vt({mutationFn:async x=>{const{error:y}=await U.from("recruit_goals").delete().eq("id",x);if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),p=x=>{const y=r.find(b=>b.id===x.target_stage_id);return{count:a.filter(b=>Z2(new Date(b.created_at),{start:new Date(x.period_start),end:new Date(x.period_end)})?x.target_stage_id?b.stage_id===x.target_stage_id:!0:!1).length,stage: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(Js,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(be,{className:"py-12 text-center",children:[e.jsx(uu,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No goals set. Create a recruiting target to track progress."})]}):e.jsx("div",{className:"grid md:grid-cols-2 gap-4",children:d.map(x=>{const{count:y,stage:g}=p(x),b=Math.min(100,y/x.target_count*100),v=Z2(new Date,{start:new Date(x.period_start),end:new Date(x.period_end)});return e.jsxs(be,{className:v?"":"opacity-60",children:[e.jsx(Ft,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{className:"text-sm",children:x.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Bs(new Date(x.period_start),"MMM d")," – ",Bs(new Date(x.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[v?e.jsx(qe,{className:"text-[10px]",children:"Active"}):e.jsx(qe,{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(x.id),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Re,{className:"space-y-2",children:[g&&e.jsxs(qe,{variant:"outline",className:"text-[10px]",style:{borderColor:g.color,color:g.color},children:["Stage: ",g.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:["/ ",x.target_count]})]}),e.jsx(qi,{value:b,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[b.toFixed(0),"% complete"]})]})]},x.id)})}),e.jsx(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:x=>{x.preventDefault(),h.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Goal Title *"}),e.jsx(ye,{required:!0,value:o.title,onChange:x=>c(y=>({...y,title:x.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Target Count *"}),e.jsx(ye,{type:"number",min:"1",required:!0,value:o.target_count,onChange:x=>c(y=>({...y,target_count:x.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Target Stage (optional)"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",value:o.target_stage_id,onChange:x=>c(y=>({...y,target_stage_id:x.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),r.map(x=>e.jsx("option",{value:x.id,children:x.name},x.id))]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Count prospects that reach this stage"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Start Date"}),e.jsx(ye,{type:"date",required:!0,value:o.period_start,onChange:x=>c(y=>({...y,period_start:x.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"End Date"}),e.jsx(ye,{type:"date",required:!0,value:o.period_end,onChange:x=>c(y=>({...y,period_end:x.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 iAn={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function IBt({email:s,mergeValues:t=iAn,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(Fs,{open:!0,onOpenChange:()=>r(),children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs($s,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(zs,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs(qe,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(qe,{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 cYe({brokerageId:s}){const t=as(),{user:n}=Ns(),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=mt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:x,error:y}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(y)throw y;return x}}),{data:u}=mt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:x,error:y}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(y)throw y;return x}});j.useEffect(()=>{d?c({...d,merge_fields:d.merge_fields||{city:"",broker_name:""}}):u&&c(x=>({...x,merge_fields:{...x.merge_fields,brokerage_name:u.name,city:u.city||""}}))},[d,u]),j.useEffect(()=>{n!=null&&n.id&&U.from("profiles").select("recruit_cta_url").eq("id",n.id).single().then(({data:x})=>a((x==null?void 0:x.recruit_cta_url)||""))},[n==null?void 0:n.id]);const h=async()=>{if(!(n!=null&&n.id))return;l(!0);const{error:x}=await U.from("profiles").update({recruit_cta_url:r.trim()||null}).eq("id",n.id);l(!1),x?re.error(x.message):re.success("Scheduling link saved!")},m=vt({mutationFn:async()=>{const x={brokerage_id:s,sender_name:o.sender_name,sender_email:o.sender_email,reply_to_email:o.reply_to_email||null,merge_fields:o.merge_fields,updated_at:new Date().toISOString()};if(d!=null&&d.id){const{error:y}=await U.from("brokerage_recruit_settings").update(x).eq("id",d.id);if(y)throw y}else{const{error:y}=await U.from("brokerage_recruit_settings").insert(x);if(y)throw y}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),re.success("Recruiting email settings saved!")},onError:x=>re.error(x.message)}),p=(x,y)=>{c(g=>({...g,merge_fields:{...g.merge_fields,[x]: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(ra,{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(ye,{value:r,onChange:x=>a(x.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs(B,{onClick:h,disabled:i,size:"sm",children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save"]})]}),!r&&e.jsx("p",{className:"text-xs text-amber-600",children:"⚠️ No link set — the CTA button will be hidden on your video pages until you add one."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Sender Display Name"}),e.jsx(ye,{value:o.sender_name,onChange:x=>c({...o,sender_name:x.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Sender Email Address"}),e.jsx(ye,{value:o.sender_email,onChange:x=>c({...o,sender_email:x.target.value}),placeholder:"recruiting@relevelup.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Must be a verified SES identity. Verify your own address below to send from it."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(ye,{value:o.reply_to_email,onChange:x=>c({...o,reply_to_email:x.target.value}),placeholder:"jeremy@relevelup.com"})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(a0,{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(dBt,{brokerageId:s,onVerifiedSelect:x=>{c(y=>({...y,sender_email:x})),re.success(`Sender set to ${x}`)}})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Default Merge Fields"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"These values will auto-fill in campaign emails for this brokerage."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(ye,{value:o.merge_fields.brokerage_name||"",onChange:x=>p("brokerage_name",x.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"{{city}}"}),e.jsx(ye,{value:o.merge_fields.city||"",onChange:x=>p("city",x.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(ye,{value:o.merge_fields.sender_name||"",onChange:x=>p("sender_name",x.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(B,{onClick:()=>m.mutate(),disabled:m.isPending,className:"w-full",children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const oAn=AN.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",Ym(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()}}}),Egt=[{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 R0({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(Cu,{children:[e.jsx(Au,{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(ou,{side:"bottom",className:"text-xs",children:a})]})}function lAn({content:s,onChange:t}){const n=eHe({extensions:[sHe.configure({heading:{levels:[1,2,3]}}),oAn,hHe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),mHe.configure({types:["heading","paragraph"]}),pHe,rRt],content:s,editorProps:{attributes:{class:"prose prose-sm max-w-none focus:outline-none min-h-[350px] px-5 py-4",style:"font-size: 15px; line-height: 1.75; color: #1a1a1a;"}},onUpdate:({editor:i})=>{t(i.getHTML())}});j.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const r=j.useCallback(()=>{if(!n)return;const i=n.getAttributes("link").href,l=window.prompt("Enter URL",i);if(l!==null){if(l===""){n.chain().focus().extendMarkRange("link").unsetLink().run();return}n.chain().focus().extendMarkRange("link").setLink({href:l}).run()}},[n]),a=j.useCallback(i=>{n&&n.chain().focus().insertContent(`{{${i}}}`).run()},[n]);return n?e.jsx(RN,{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(R0,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:BT,tooltip:"Bold"}),e.jsx(R0,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:KT,tooltip:"Italic"}),e.jsx(R0,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:dz,tooltip:"Underline"}),e.jsx(R0,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:cK,tooltip:"Strikethrough"}),e.jsx(Xl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(R0,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:B9,tooltip:"Heading 1"}),e.jsx(R0,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:$9,tooltip:"Heading 2"}),e.jsx(R0,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:qW,tooltip:"Heading 3"}),e.jsx(Xl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(R0,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:ug,tooltip:"Bullet List"}),e.jsx(R0,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:kj,tooltip:"Numbered List"}),e.jsx(R0,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:yN,tooltip:"Blockquote"}),e.jsx(R0,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:gN,tooltip:"Divider"}),e.jsx(Xl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(R0,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:ER,tooltip:"Align Left"}),e.jsx(R0,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:TR,tooltip:"Align Center"}),e.jsx(R0,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:MR,tooltip:"Align Right"}),e.jsx(Xl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(R0,{onClick:r,active:n.isActive("link"),icon:vc,tooltip:"Insert Link"}),e.jsx(Xl,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(R0,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:aE,tooltip:"Undo"}),e.jsx(R0,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:eE,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(kd,{children:[e.jsx(Sd,{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(hz,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(xd,{align:"end",className:"w-56",children:Egt.map(i=>e.jsxs(wa,{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(QVe,{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:"}),Egt.map(i=>e.jsx(qe,{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 cAn({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(Fs,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(Os,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(kl,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(kr,{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(Dr,{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(pre,{icon:on,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(pre,{icon:ma,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(pre,{icon:lu,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(pre,{icon:hd,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(Vr,{className:"h-3 w-3"})," Last sent: ",Bs(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(be,{className:"overflow-hidden",children:e.jsxs(Re,{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(qe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(on,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(ma,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(lu,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(hd,{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 pre({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(be,{children:e.jsx(Re,{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 RBt(s){return mt({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await U.from("recruit_campaign_email_stats").select("*").eq("brokerage_id",s);if(n)throw n;const r=t??[],a={};for(const i of r){a[i.campaign_id]||(a[i.campaign_id]={campaign_id:i.campaign_id,sent:0,opened:0,clicked:0,failed:0,openRate:0,clickRate:0,byEmail:[],lastSentAt:null});const l=a[i.campaign_id];l.sent+=i.sent_count,l.opened+=i.opened_count,l.clicked+=i.clicked_count,l.failed+=i.failed_count,l.byEmail.push(i),i.last_sent_at&&(!l.lastSentAt||i.last_sent_at>l.lastSentAt)&&(l.lastSentAt=i.last_sent_at)}return Object.values(a).forEach(i=>{i.openRate=i.sent>0?i.opened/i.sent*100:0,i.clickRate=i.sent>0?i.clicked/i.sent*100:0,i.byEmail.sort((l,o)=>l.email_number-o.email_number)}),a}})}const Mgt={cold:{icon:gj,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:Aj,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:Fd,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function DBt({brokerageId:s}){var Se,Ee,Le,De;const{user:t}=Ns(),n=as(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,x]=j.useState("editor"),[y,g]=j.useState(null),[b,v]=j.useState(null),{data:k={}}=RBt(s),[C,T]=j.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:M}=mt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Be,error:Ne}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(Ne)throw Ne;return Be}}),{data:P}=mt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Be,error:Ne}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Ne)throw Ne;return Be}}),L={first_name:"Sarah",brokerage_name:((Se=P==null?void 0:P.merge_fields)==null?void 0:Se.brokerage_name)||(M==null?void 0:M.name)||"Your Brokerage",city:((Ee=P==null?void 0:P.merge_fields)==null?void 0:Ee.city)||(M==null?void 0:M.city)||"Your City",sender_name:((Le=P==null?void 0:P.merge_fields)==null?void 0:Le.sender_name)||(P==null?void 0:P.sender_name)||"Your Name"},I=Be=>Be.replace(/\{\{first_name\}\}/g,L.first_name).replace(/\{\{brokerage_name\}\}/g,L.brokerage_name).replace(/\{\{city\}\}/g,L.city).replace(/\{\{sender_name\}\}/g,L.sender_name),{data:O=[],isLoading:$}=mt({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:Be,error:Ne}=await U.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(Ne)throw Ne;return Be}}),{data:q={}}=mt({queryKey:["recruit-campaign-emails",s],enabled:O.length>0,queryFn:async()=>{const Be=O.map(Oe=>Oe.id),{data:Ne,error:Ge}=await U.from("recruit_campaign_emails").select("*").in("campaign_id",Be).order("email_number");if(Ge)throw Ge;const _e={};return Ne.forEach(Oe=>{_e[Oe.campaign_id]||(_e[Oe.campaign_id]=[]),_e[Oe.campaign_id].push(Oe)}),_e}}),W=Object.values(q).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 U.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Ne)throw Ne;return Be}}),K={};G.forEach(Be=>{K[Be.campaign_email_id]=Be.selected_subject_index});const ee=vt({mutationFn:async({campaignEmailId:Be,selectedIndex:Ne})=>{const{error:Ge}=await U.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]}),re.success("Subject line updated for your brokerage")},onError:Be=>re.error(Be.message)}),J=vt({mutationFn:async Be=>{const{error:Ne}=await U.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"]}),re.success("Email template saved!"),l(null)},onError:Be=>re.error(Be.message)}),le=vt({mutationFn:async()=>{const Be=C.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:Ne,error:Ge}=await U.from("recruit_campaigns").insert({name:C.name,slug:Be,description:C.description||null,theme:C.theme||null,goal:C.goal||null,primary_cta:C.primary_cta||"Learn more",warmth_level:C.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:C.sender_name||null,sender_email:C.sender_email||null,reply_to_email:C.reply_to_email||null,is_active:!0,sort_order:O.length+1}).select().single();if(Ge)throw Ge;const _e=[{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:Oe}=await U.from("recruit_campaign_emails").insert(_e.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(Oe)throw Oe;return Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.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=>re.error(Be.message)}),ue=vt({mutationFn:async Be=>{const{error:Ne}=await U.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"]}),re.success("Campaign settings saved!"),g(null)},onError:Be=>re.error(Be.message)}),oe=vt({mutationFn:async Be=>{var Xe,Ue;const{data:Ne}=await U.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,_e=((Ue=Ne==null?void 0:Ne[0])==null?void 0:Ue.delay_days)??0,Oe=Ge+1,{error:Ae}=await U.from("recruit_campaign_emails").insert({campaign_id:Be,email_number:Oe,title:`Email ${Oe}`,subject_line:"Hey {{first_name}}",subject_line_options:[],body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:_e+7,is_active:!0});if(Ae)throw Ae},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Email added to campaign!")},onError:Be=>re.error(Be.message)}),ie=vt({mutationFn:async Be=>{const{error:Ne}=await U.from("recruit_campaigns").delete().eq("id",Be);if(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Campaign deleted")},onError:Be=>re.error(Be.message)}),de=vt({mutationFn:async Be=>{const{error:Ne}=await U.from("recruit_campaign_emails").delete().eq("id",Be);if(Ne)throw Ne},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Email removed from campaign")},onError:Be=>re.error(Be.message)}),we=vt({mutationFn:async({emailId:Be,delay_days:Ne})=>{const{error:Ge}=await U.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"]}),re.success("Send delay updated")},onError:Be=>re.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 je=O.filter(Be=>!Be.brokerage_id),xe=O.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(ic,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(B,{size:"sm",onClick:()=>m(!0),className:"gap-1.5",children:[e.jsx(Js,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(be,{className:"border-primary/20 bg-primary/5",children:e.jsx(Re,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(yn,{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(ic,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),xe.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(GW,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:xe.map(Be=>fe(Be,!0))})]}),je.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:je.map(Be=>fe(Be,!1))})]}),O.length===0&&e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(on,{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(Js,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(cAn,{open:!!b,onClose:()=>v(null),campaignName:(b==null?void 0:b.name)||"",stat:b&&k[b.id]||null}),o&&e.jsx(IBt,{email:o,mergeValues:L,selectedSubjectIndex:K[o.id],onClose:()=>c(null)}),e.jsx(Fs,{open:!!i,onOpenChange:Be=>!Be&&l(null),children:e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs($s,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(HT,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(kr,{children:i==null?void 0:i.title})]}),i&&e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(ye,{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(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(ye,{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(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(ye,{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(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Alternative Subject Lines ",e.jsx("span",{className:"text-muted-foreground font-normal normal-case",children:"(one per line, for A/B testing)"})]}),e.jsx(Ds,{value:((De=i.subject_line_options)==null?void 0:De.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(se,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(fa,{value:p,onValueChange:Be=>x(Be),children:e.jsxs(xa,{className:"h-7",children:[e.jsx(ss,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(ss,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),p==="editor"?e.jsx(lAn,{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:[L.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:[L.first_name," "]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium w-12 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:I(i.subject_line)})]})]}),e.jsx("div",{className:"bg-white p-6",children:e.jsx("div",{className:"prose prose-sm max-w-none",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:I(i.body_html)}})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changes are saved to this campaign's templates"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs(B,{size:"sm",onClick:()=>J.mutate(i),disabled:J.isPending,className:"gap-1.5",children:[e.jsx(Jo,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(Fs,{open:h,onOpenChange:m,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Js,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(kr,{children:"Build your own recruiting email sequence with custom sender settings."})]}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(ye,{value:C.name,onChange:Be=>T({...C,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(se,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(vs,{value:C.warmth_level,onValueChange:Be=>T({...C,warmth_level:Be}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(Je,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(Je,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(ye,{value:C.primary_cta,onChange:Be=>T({...C,primary_cta:Be.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Description"}),e.jsx(Ds,{value:C.description,onChange:Be=>T({...C,description:Be.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Goal"}),e.jsx(ye,{value:C.goal,onChange:Be=>T({...C,goal:Be.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(i0,{children:[e.jsx(o0,{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(on,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(Po,{className:"h-3.5 w-3.5"})]})}),e.jsxs(l0,{className:"space-y-3 pt-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank to use brokerage defaults."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Sender Name"}),e.jsx(ye,{value:C.sender_name,onChange:Be=>T({...C,sender_name:Be.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Sender Email"}),e.jsx(ye,{value:C.sender_email,onChange:Be=>T({...C,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(se,{className:"text-xs",children:"Reply-To Email"}),e.jsx(ye,{value:C.reply_to_email,onChange:Be=>T({...C,reply_to_email:Be.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(B,{className:"w-full",disabled:!C.name.trim()||le.isPending,onClick:()=>le.mutate(),children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(Fs,{open:!!y,onOpenChange:Be=>!Be&&g(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(ic,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(kr,{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(se,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(ye,{value:y.name,onChange:Be=>g({...y,name:Be.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(vs,{value:y.warmth_level,onValueChange:Be=>g({...y,warmth_level:Be}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"cold",children:"❄️ Cold"}),e.jsx(Je,{value:"warm",children:"☀️ Warm"}),e.jsx(Je,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-medium",children:"Goal"}),e.jsx(ye,{value:y.goal||"",onChange:Be=>g({...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(on,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Sender Name"}),e.jsx(ye,{value:y.sender_name||"",onChange:Be=>g({...y,sender_name:Be.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs",children:"Sender Email"}),e.jsx(ye,{value:y.sender_email||"",onChange:Be=>g({...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(se,{className:"text-xs",children:"Reply-To Email"}),e.jsx(ye,{value:y.reply_to_email||"",onChange:Be=>g({...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(Jo,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(Fs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Default Recruiting Email Settings"}),e.jsx(kr,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(cYe,{brokerageId:s})]})})]});function fe(Be,Ne){const Ge=Mgt[Be.warmth_level]||Mgt.cold,_e=Ge.icon,Oe=q[Be.id]||[],Ae=r===Be.id,Xe=!!(Be.sender_name||Be.sender_email||Be.reply_to_email),Ue=k[Be.id];return e.jsxs(be,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(Ft,{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(_e,{className:`h-5 w-5 ${Ge.color}`})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[Be.name,e.jsx(qe,{variant:Be.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:Be.is_active?"Active":"Draft"}),Ne&&e.jsx(qe,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),Xe&&e.jsxs(qe,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(on,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(fr,{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:Ze=>{Ze.stopPropagation(),g({...Be})},children:e.jsx(ic,{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:async Ze=>{Ze.stopPropagation(),await Bi("Delete this campaign and all its emails? This cannot be undone.")&&ie.mutate(Be.id)},children:e.jsx(Rn,{className:"h-4 w-4"})}),Ue&&Ue.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(on,{className:"h-2.5 w-2.5"})," ",Ue.sent.toLocaleString()]}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${Ue.openRate.toFixed(1)}% open rate`,children:[e.jsx(ma,{className:"h-2.5 w-2.5"})," ",Ue.opened.toLocaleString()," (",Ue.openRate.toFixed(0),"%)"]}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${Ue.clickRate.toFixed(1)}% click rate`,children:[e.jsx(lu,{className:"h-2.5 w-2.5"})," ",Ue.clicked.toLocaleString()," (",Ue.clickRate.toFixed(1),"%)"]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:Ze=>{Ze.stopPropagation(),v(Be)},title:"View detailed engagement stats",children:[e.jsx(ol,{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(on,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[Oe.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Ae?e.jsx(Qy,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Po,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Ae&&e.jsxs(Re,{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(on,{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:Oe.map((Ze,Qe)=>{var Ye,nt;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[Qert.stopPropagation(),onBlur:rt=>{const Fe=parseInt(rt.target.value)||0;Fe!==Ze.delay_days&&we.mutate({emailId:Ze.id,delay_days:Fe})},onKeyDown:rt=>{rt.key==="Enter"&&rt.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),Ze.email_number===1?"Sent immediately":`Day ${Ze.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",I(((Ye=Ze.subject_line_options)==null?void 0:Ye.length)>0&&Ze.subject_line_options[K[Ze.id]??0]||Ze.subject_line)]})]}),((nt=Ze.subject_line_options)==null?void 0:nt.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(vs,{value:String(K[Ze.id]??0),onValueChange:rt=>ee.mutate({campaignEmailId:Ze.id,selectedIndex:parseInt(rt)}),children:[e.jsx(gs,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(bs,{placeholder:"Choose subject line"})}),e.jsx(ys,{children:Ze.subject_line_options.map((rt,Fe)=>e.jsxs(Je,{value:String(Fe),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[Fe===0?"Primary":`Alt ${Fe}`,":"]}),I(rt)]},Fe))})]})})]}),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(Ze),children:e.jsx(ma,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Ze}),x("editor")},children:e.jsx(Za,{className:"h-4 w-4"})}),Ne&&Oe.length>1&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async()=>{await Bi("Delete this email from the sequence?")&&de.mutate(Ze.id)},children:e.jsx(Rn,{className:"h-4 w-4"})})]})]})})]},Ze.id)})}),Ne&&e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>oe.mutate(Be.id),disabled:oe.isPending,children:[e.jsx(Js,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},Be.id)}}const Lgt={active:{icon:fd,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:ay,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:To,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:Rd,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},Pgt={sent:{icon:on,color:"text-blue-500"},opened:{icon:ma,color:"text-amber-500"},clicked:{icon:lu,color:"text-green-500"},failed:{icon:hd,color:"text-destructive"}};function OBt({brokerageId:s}){var De,Be,Ne,Ge,_e;const{user:t}=Ns(),n=as(),[r,a]=j.useState(!1),[i,l]=j.useState(""),[o,c]=j.useState(new Set),[d,u]=j.useState("assignments"),[h,m]=j.useState(null),[p,x]=j.useState(""),[y,g]=j.useState("all"),[b,v]=j.useState("all"),[k,C]=j.useState(!1),{data:T}=AAe(),{data:M={}}=mt({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:Oe,error:Ae}=await U.from("recruit_campaign_emails").select("*").order("email_number");if(Ae)throw Ae;const Xe={};return(Oe??[]).forEach(Ue=>{Xe[Ue.campaign_id]||(Xe[Ue.campaign_id]=[]),Xe[Ue.campaign_id].push(Ue)}),Xe}}),{data:P}=mt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Oe,error:Ae}=await U.from("brokerages").select("name, city, state").eq("id",s).single();if(Ae)throw Ae;return Oe}}),{data:L}=mt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Oe,error:Ae}=await U.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(Ae)throw Ae;return Oe}}),{data:I=[]}=mt({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:Oe,error:Ae}=await U.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(Ae)throw Ae;return Oe}}),O={};I.forEach(Oe=>{O[Oe.campaign_email_id]=Oe.selected_subject_index});const $={first_name:((De=h==null?void 0:h.prospect)==null?void 0:De.first_name)||"Sarah",brokerage_name:((Be=L==null?void 0:L.merge_fields)==null?void 0:Be.brokerage_name)||(P==null?void 0:P.name)||"Your Brokerage",city:((Ne=L==null?void 0:L.merge_fields)==null?void 0:Ne.city)||(P==null?void 0:P.city)||"Your City",sender_name:((Ge=L==null?void 0:L.merge_fields)==null?void 0:Ge.sender_name)||(L==null?void 0:L.sender_name)||"Your Name"},q=Oe=>{const Ae=M[Oe.campaign_id]||[],Xe=Oe.current_email_number+1;return Ae.find(Ue=>Ue.email_number===Xe)||null},{data:W=[],isLoading:G}=mt({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let Ae=[],Xe=0;for(;;){const{data:Ue,error:Ze}=await U.from("recruit_campaign_assignments").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign:recruit_campaigns(name, warmth_level) `).eq("brokerage_id",s).order("created_at",{ascending:!1}).range(Xe,Xe+1e3-1);if(Ze)throw Ze;if(Ae=Ae.concat(Ue??[]),!Ue||Ue.length<1e3)break;Xe+=1e3}return Ae}}),{data:K=[]}=mt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:Oe,error:Ae}=await U.from("recruit_campaign_sends").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign_email:recruit_campaign_emails(title, campaign_id) `).eq("brokerage_id",s).neq("status","failed").order("sent_at",{ascending:!1}).limit(500);if(Ae)throw Ae;return Oe}}),{data:ee=[]}=mt({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:Oe,error:Ae}=await U.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(Ae)throw Ae;return Oe}}),{data:J=[]}=mt({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let Ae=[],Xe=0;for(;;){const{data:Ue,error:Ze}=await U.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(Xe,Xe+1e3-1);if(Ze)throw Ze;if(Ae=Ae.concat(Ue??[]),!Ue||Ue.length<1e3)break;Xe+=1e3}return Ae}}),le=new Set(W.map(Oe=>`${Oe.prospect_id}-${Oe.campaign_id}`)),ue=vt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const Oe=new Date,Ae=Array.from(o).filter(Ue=>!le.has(`${Ue}-${i}`)).map(Ue=>({prospect_id:Ue,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:Oe.toISOString(),started_at:Oe.toISOString()}));if(Ae.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:Xe}=await U.from("recruit_campaign_assignments").insert(Ae);if(Xe)throw Xe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),re.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:Oe=>re.error(Oe.message)}),oe=vt({mutationFn:async({id:Oe,newStatus:Ae})=>{const{error:Xe}=await U.from("recruit_campaign_assignments").update({status:Ae,updated_at:new Date().toISOString()}).eq("id",Oe);if(Xe)throw Xe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),re.success("Assignment updated")}}),ie=vt({mutationFn:async()=>{const{data:Oe,error:Ae}=await U.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(Ae)throw Ae;return Oe},onSuccess:Oe=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),n.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),re.success(`Wave sent! ${Oe.sent} emails delivered, ${Oe.skipped} skipped, ${Oe.failed} failed`)},onError:Oe=>re.error(`Send failed: ${Oe.message}`)}),de=W.filter(Oe=>Oe.status==="active").length;W.filter(Oe=>Oe.status==="completed").length;const we=W.filter(Oe=>Oe.status==="active"&&Oe.next_send_at&&new Date(Oe.next_send_at)<=new Date).length,{data:je={}}=RBt(s),xe=W.reduce((Oe,Ae)=>Oe+Math.max(0,Ae.current_email_number||0),0),fe=Object.values(je).reduce((Oe,Ae)=>Oe+Ae.opened,0),Se=Object.values(je).reduce((Oe,Ae)=>Oe+Ae.clicked,0);Object.values(je).reduce((Oe,Ae)=>Oe+Ae.failed,0);const Ee=xe>0?Math.round(fe/xe*100):0,Le=xe>0?Se/xe*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:[we>0&&e.jsxs(B,{variant:"outline",onClick:()=>{ie.mutate()},disabled:ie.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(jf,{className:"h-4 w-4 mr-1"}),ie.isPending?"Sending...":`Send Next Wave (${we})`]}),e.jsxs(B,{onClick:()=>a(!0),children:[e.jsx(Dr,{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(be,{children:e.jsxs(Re,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Bn,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:W.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(fd,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:de}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(on,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:xe.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(ma,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ee,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",fe.toLocaleString(),")"]})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(lu,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Le.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",Se.toLocaleString(),")"]})]})]})})]}),e.jsxs(fa,{value:d,onValueChange:u,children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"assignments",children:["Active Drips (",de,")"]}),e.jsxs(ss,{value:"history",children:["Send History (",xe.toLocaleString(),")"]})]}),e.jsx(ns,{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(be,{children:e.jsxs(Re,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Dr,{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(Oe=>{var Ye,nt,rt,Fe;const Ae=Lgt[Oe.status]||Lgt.active,Xe=Ae.icon,Ze=(M[Oe.campaign_id]||[]).length||4,Qe=q(Oe);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(qe,{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:[(Ye=Oe.prospect)==null?void 0:Ye.first_name," ",(nt=Oe.prospect)==null?void 0:nt.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(rt=Oe.prospect)==null?void 0:rt.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Fe=Oe.campaign)==null?void 0:Fe.name," · Email ",Oe.current_email_number,"/",Ze,Oe.next_send_at&&Oe.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(Vr,{className:"h-3 w-3 inline"})," Next: ",Bs(new Date(Oe.next_send_at),"MMM d, h:mm a"),new Date(Oe.next_send_at)<=new Date&&e.jsx(qe,{variant:"outline",className:"ml-1 text-[10px] px-1 py-0 border-amber-500 text-amber-600",children:"DUE"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[Qe&&e.jsx(B,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>m(Oe),children:e.jsx(ma,{className:"h-3.5 w-3.5"})}),Oe.status==="active"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>oe.mutate({id:Oe.id,newStatus:"paused"}),children:e.jsx(ay,{className:"h-3.5 w-3.5"})}),Oe.status==="paused"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>oe.mutate({id:Oe.id,newStatus:"active"}),children:e.jsx(fd,{className:"h-3.5 w-3.5"})}),(Oe.status==="active"||Oe.status==="paused")&&e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>oe.mutate({id:Oe.id,newStatus:"cancelled"}),children:e.jsx(Rd,{className:"h-3.5 w-3.5"})})]})]},Oe.id)})})}),e.jsxs(ns,{value:"history",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Filter:"}),e.jsxs(vs,{value:y,onValueChange:g,children:[e.jsx(gs,{className:"w-[220px] h-8 text-xs",children:e.jsx(bs,{placeholder:"All campaigns"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All campaigns"}),ee.map(Oe=>e.jsx(Je,{value:Oe.id,children:Oe.name},Oe.id))]})]}),e.jsxs(vs,{value:b,onValueChange:v,children:[e.jsx(gs,{className:"w-[160px] h-8 text-xs",children:e.jsx(bs,{placeholder:"All statuses"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All statuses"}),e.jsx(Je,{value:"sent",children:"Sent (no engagement)"}),e.jsx(Je,{value:"opened",children:"Opened"}),e.jsx(Je,{value:"clicked",children:"Clicked"})]})]}),(y!=="all"||b!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{g("all"),v("all")},children:"Clear"})]}),(()=>{var Ae;const Oe=K.filter(Xe=>{var Ue;return!(y!=="all"&&((Ue=Xe.campaign_email)==null?void 0:Ue.campaign_id)!==y||b==="opened"&&!Xe.opened_at||b==="clicked"&&!Xe.clicked_at||b==="sent"&&(Xe.opened_at||Xe.clicked_at))});return Oe.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(on,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:K.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:K.length===0?"Emails will appear here once campaigns start sending":"Try clearing the filters above"})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",Oe.length," of ",K.length," recent sends",y!=="all"&&` · ${(Ae=ee.find(Xe=>Xe.id===y))==null?void 0:Ae.name}`]}),e.jsx("div",{className:"space-y-1",children:Oe.map(Xe=>{var Ye,nt,rt;const Ue=Pgt[Xe.status]||Pgt.sent,Ze=Ue.icon,Qe=(Ye=ee.find(Fe=>{var dt;return Fe.id===((dt=Xe.campaign_email)==null?void 0:dt.campaign_id)}))==null?void 0:Ye.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(Ze,{className:`h-4 w-4 flex-shrink-0 ${Ue.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(nt=Xe.prospect)==null?void 0:nt.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]}),Qe&&e.jsx(qe,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:Qe})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children: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(ma,{className:"h-3 w-3"})," ",Bs(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(lu,{className:"h-3 w-3"})," ",Bs(new Date(Xe.clicked_at),"MMM d")]}),e.jsx("span",{children:Bs(new Date(Xe.sent_at),"MMM d, h:mm a")})]})]},Xe.id)})})]})})()]})]}),e.jsx(Fs,{open:r,onOpenChange:Oe=>{a(Oe),Oe||(x(""),c(new Set),l(""))},children:e.jsxs(Os,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs($s,{className:"px-6 pt-6 pb-4",children:[e.jsx(zs,{children:"Assign Campaign to Prospects"}),e.jsx(kr,{children:"Select a campaign and choose which prospects to enroll. The first email will be sent automatically."})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 space-y-4 pb-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(vs,{value:i,onValueChange:l,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Choose a campaign..."})}),e.jsx(ys,{children:ee.map(Oe=>e.jsx(Je,{value:Oe.id,children:Oe.name},Oe.id))})]})]}),i&&(()=>{const Oe=p.toLowerCase(),Ae=J.filter(Ze=>`${Ze.first_name} ${Ze.last_name}`.toLowerCase().includes(Oe)||Ze.email.toLowerCase().includes(Oe)),Xe=Ae.filter(Ze=>!le.has(`${Ze.id}-${i}`)),Ue=Xe.length>0&&Xe.every(Ze=>o.has(Ze.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-sm font-medium",children:"2. Select Prospects"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o.size," selected"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Fr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:p,onChange:Ze=>x(Ze.target.value),className:"pl-9 h-9"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(Ue){const Ze=new Set(o);Xe.forEach(Qe=>Ze.delete(Qe.id)),c(Ze)}else{const Ze=new Set(o);Xe.forEach(Qe=>Ze.add(Qe.id)),c(Ze)}},children:[e.jsx(PR,{className:"h-3.5 w-3.5 mr-1"}),Ue?"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:p?"No prospects match your search":"No prospects found for this brokerage"}):Ae.map(Ze=>{const Qe=le.has(`${Ze.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${Qe?"opacity-40":""}`,children:[e.jsx(wi,{checked:o.has(Ze.id),disabled:Qe,onCheckedChange:Ye=>{const nt=new Set(o);Ye?nt.add(Ze.id):nt.delete(Ze.id),c(nt)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Ze.first_name," ",Ze.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ze.email})]}),Qe&&e.jsx(qe,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Ze.id)})}),Ae.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",Ae.length," of ",J.length," prospects",Xe.length0&&e.jsx(be,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Re,{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:(_e=ee.find(Oe=>Oe.id===i))==null?void 0:_e.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(Nr,{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(Dr,{className:"h-4 w-4 mr-1"}),ue.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const Oe=q(h);return Oe?e.jsx(IBt,{email:Oe,mergeValues:$,selectedSubjectIndex:O[Oe.id],onClose:()=>m(null)}):null})(),e.jsx(TAe,{open:k,onOpenChange:C,hasPending:T==null?void 0:T.hasPendingSes,pendingEmails:T==null?void 0:T.pendingEmails})]})}function FBt({brokerageId:s}){const t=as(),[n,r]=j.useState([]),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=j.useRef(!1),{data:d,isLoading:u}=mt({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:g,error:b}=await U.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(b)throw b;return g},enabled:!!s});j.useEffect(()=>{if(d){if(c.current){c.current=!1;return}r(d.map(g=>({id:g.id,name:g.name,color:g.color,sort_order:g.sort_order}))),i([]),o(!1)}},[d]);const h=vt({mutationFn:async()=>{for(const v of a){const{error:k}=await U.from("recruit_pipeline_stages").delete().eq("id",v);if(k)throw k}const g=n.filter(v=>v.id&&!v.isNew),b=n.filter(v=>!v.id||v.isNew);for(const v of g){const{error:k}=await U.from("recruit_pipeline_stages").update({name:v.name,color:v.color,sort_order:v.sort_order}).eq("id",v.id);if(k)throw k}if(b.length>0){const{error:v}=await U.from("recruit_pipeline_stages").insert(b.map(k=>({brokerage_id:s,name:k.name,color:k.color,sort_order:k.sort_order})));if(v)throw v}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),re.success("Pipeline stages saved!"),o(!1)},onError:g=>re.error(g.message)}),m=(g,b,v)=>{r(k=>k.map((C,T)=>T===g?{...C,[b]:v}:C)),o(!0)},p=()=>{const g=n.length>0?Math.max(...n.map(b=>b.sort_order)):0;r(b=>[...b,{name:"",color:"#6366f1",sort_order:g+1,isNew:!0}]),o(!0)},x=g=>{const b=n[g];b.id&&!b.isNew&&i(v=>[...v,b.id]),r(v=>v.filter((k,C)=>C!==g)),o(!0)},y=(g,b)=>{const v=g+b;if(v<0||v>=n.length)return;const k=[...n];[k[g],k[v]]=[k[v],k[g]],k.forEach((C,T)=>C.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((g,b)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("button",{type:"button",onClick:()=>y(b,-1),disabled:b===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>y(b,1),disabled:b===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Fp,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:g.color,onChange:v=>m(b,"color",v.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(ye,{value:g.name,onChange:v=>m(b,"name",v.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:b+1}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>x(b),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(Rn,{className:"h-4 w-4"})})]},g.id||`new-${b}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:p,className:"gap-1",children:[e.jsx(Js,{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(Jo,{className:"h-4 w-4"})," Save Changes"]})]}),n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No stages configured. Add stages to build your recruiting pipeline."})]})}function dAn({brokerageId:s}){const{data:t=[],isLoading:n}=mt({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:r,error:a}=await U.from("recruit_prospects").select("id, first_name, last_name, email, unsubscribed_at, unsubscribe_reason, current_brokerage").eq("brokerage_id",s).not("unsubscribed_at","is",null).order("unsubscribed_at",{ascending:!1}).limit(500);if(a)throw a;return r||[]},enabled:!!s});return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(KR,{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(qe,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(KR,{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(be,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-base",children:[r.first_name," ",r.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(on,{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(ra,{className:"h-3 w-3"}),r.unsubscribed_at&&Bs(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.unsubscribe_reason&&e.jsx(Re,{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 uAn(){var o;const[s,t]=j.useState(""),[n,r]=j.useState("board"),{data:a=[],isLoading:i}=mt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await U.from("brokerages").select("id, name").order("name");if(d)throw d;return c}}),l=s||((o=a[0])==null?void 0:o.id)||"";return i?e.jsx(Vs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsx(Vs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[a.length>1?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(vs,{value:l,onValueChange:t,children:[e.jsxs(gs,{className:"w-[280px]",children:[e.jsx(Ni,{className:"mr-2 h-4 w-4"}),e.jsx(bs,{placeholder:"Select brokerage"})]}),e.jsx(ys,{children:a.map(c=>e.jsx(Je,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(MBt,{brokerageId:l,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(Zr,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(fa,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(xa,{className:"flex-wrap h-auto gap-1",children:[e.jsx(ss,{value:"pipeline",children:"Pipeline"}),e.jsxs(ss,{value:"contacts",children:[e.jsx(Bn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(ss,{value:"video-outreach",children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(ss,{value:"follow-ups",children:"Follow-ups"}),e.jsx(ss,{value:"referrals",children:"Referrals"}),e.jsx(ss,{value:"interest",children:"Interest Form"}),e.jsx(ss,{value:"landing-page",children:"Landing Page"}),e.jsx(ss,{value:"goals",children:"Goals"}),e.jsx(ss,{value:"metrics",children:"Metrics"}),e.jsx(ss,{value:"templates",children:"Email Templates"}),e.jsxs(ss,{value:"campaigns",children:[e.jsx(on,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(ss,{value:"drip-assignments",children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(ss,{value:"activity",children:"Recruiter Activity"}),e.jsxs(ss,{value:"email-settings",children:[e.jsx(ic,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(ss,{value:"pipeline-stages",children:[e.jsx(sE,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(ss,{value:"unsubscribed",children:[e.jsx(KR,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(ns,{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(r0,{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(lz,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(jBt,{brokerageId:l}):e.jsx(MSe,{brokerageId:l})]}),e.jsx(ns,{value:"contacts",children:e.jsx(MSe,{brokerageId:l})}),e.jsx(ns,{value:"video-outreach",children:e.jsx(LBt,{brokerageId:l})}),e.jsx(ns,{value:"follow-ups",children:e.jsx(TBt,{brokerageId:l})}),e.jsx(ns,{value:"referrals",children:e.jsx(CBt,{brokerageId:l})}),e.jsx(ns,{value:"interest",children:e.jsx(ABt,{brokerageId:l})}),e.jsx(ns,{value:"landing-page",children:e.jsx(EBt,{brokerageId:l})}),e.jsx(ns,{value:"goals",children:e.jsx(PBt,{brokerageId:l})}),e.jsx(ns,{value:"metrics",children:e.jsx(NBt,{brokerageId:l})}),e.jsx(ns,{value:"templates",children:e.jsx(kBt,{brokerageId:l})}),e.jsx(ns,{value:"campaigns",children:e.jsx(DBt,{brokerageId:l})}),e.jsx(ns,{value:"drip-assignments",children:e.jsx(OBt,{brokerageId:l})}),e.jsx(ns,{value:"activity",children:e.jsx(SBt,{brokerageId:l})}),e.jsx(ns,{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(cYe,{brokerageId:l})]})}),e.jsx(ns,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(FBt,{brokerageId:l})})}),e.jsx(ns,{value:"unsubscribed",children:e.jsx(dAn,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ni,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function hAn({brokerageId:s}){const[t,n]=j.useState(""),[r,a]=j.useState("all"),{data:i,isLoading:l}=mt({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var g;const{data:d,error:u}=await U.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const h=new Map((d||[]).map(b=>[b.id,b]));if(Array.from(h.keys()).length===0)return[];const{data:p}=await U.from("recruit_videos").select("id, prospect_id, share_token, sent_at, sent_via, view_count, first_viewed_at, cta_clicked_at, video:agent_videos(title)").eq("brokerage_id",s).not("sent_at","is",null).order("sent_at",{ascending:!1}),{data:x}=await U.from("recruit_campaign_sends").select("id, prospect_id, subject, status, sent_at, opened_at, clicked_at, error_message, email_number").eq("brokerage_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}),y=[];for(const b of p||[]){const v=h.get(b.prospect_id);v&&y.push({id:`v-${b.id}`,kind:"video",prospect_id:b.prospect_id,prospect_name:`${v.first_name||""} ${v.last_name||""}`.trim()||"—",prospect_email:v.email,subject:(g=b.video)!=null&&g.title?`Video: ${b.video.title}`:"Recruiting Video",status:b.cta_clicked_at?"clicked":b.first_viewed_at?"viewed":"sent",sent_at:b.sent_at,opened_at:b.first_viewed_at,clicked_at:b.cta_clicked_at,view_count:b.view_count,share_token:b.share_token})}for(const b of x||[]){if(!b.sent_at)continue;const v=h.get(b.prospect_id);v&&y.push({id:`c-${b.id}`,kind:"campaign",prospect_id:b.prospect_id,prospect_name:`${v.first_name||""} ${v.last_name||""}`.trim()||"—",prospect_email:v.email,subject:b.subject||`Email #${b.email_number}`,status:b.status||"sent",sent_at:b.sent_at,opened_at:b.opened_at,clicked_at:b.clicked_at,error:b.error_message})}return y.sort((b,v)=>new Date(v.sent_at).getTime()-new Date(b.sent_at).getTime()),y}}),o=j.useMemo(()=>{const d=i||[];return{total:d.length,videos:d.filter(u=>u.kind==="video").length,campaigns:d.filter(u=>u.kind==="campaign").length,opened:d.filter(u=>u.opened_at).length,clicked:d.filter(u=>u.clicked_at).length}},[i]),c=j.useMemo(()=>(i||[]).filter(u=>{if(r!=="all"&&u.kind!==r)return!1;if(!t)return!0;const h=t.toLowerCase();return u.prospect_name.toLowerCase().includes(h)||(u.prospect_email||"").toLowerCase().includes(h)||u.subject.toLowerCase().includes(h)}),[i,t,r]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"Total Sent",value:o.total,icon:Dr,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:Zr,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:on,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:ma,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:lu,color:"text-emerald-500"}].map(d=>e.jsx(be,{children:e.jsxs(Re,{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(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Ut,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{value:r,onValueChange:d=>a(d),children:e.jsxs(xa,{className:"h-8",children:[e.jsx(ss,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(ss,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(ss,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search recruit, subject...",value:t,onChange:d=>n(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(Re,{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(on,{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(qe,{variant:"outline",className:"gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"}),"Video"]}):e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(on,{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(qe,{variant:"destructive",className:"gap-1",children:[e.jsx(po,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(qe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(lu,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(qe,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(ma,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Dr,{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:[Bs(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:Bs(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(ma,{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 mAn(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=Ns(),[r,a]=j.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(Vs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ni,{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(Vs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"space-y-6",children:[s.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage:"}),e.jsxs(vs,{value:i,onValueChange:n,children:[e.jsxs(gs,{className:"w-[280px]",children:[e.jsx(Ni,{className:"mr-2 h-4 w-4"}),e.jsx(bs,{placeholder:"Select brokerage"})]}),e.jsx(ys,{children:s.map(o=>e.jsx(Je,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs(fa,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(xa,{className:"flex-wrap h-auto gap-1",children:[e.jsx(ss,{value:"pipeline",children:"Pipeline"}),e.jsxs(ss,{value:"contacts",children:[e.jsx(Bn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(ss,{value:"video-outreach",children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(ss,{value:"follow-ups",children:"Follow-ups"}),e.jsx(ss,{value:"referrals",children:"Referrals"}),e.jsx(ss,{value:"interest",children:"Interest Form"}),e.jsx(ss,{value:"landing-page",children:"Landing Page"}),e.jsx(ss,{value:"goals",children:"Goals"}),e.jsx(ss,{value:"metrics",children:"Metrics"}),e.jsx(ss,{value:"templates",children:"Email Templates"}),e.jsxs(ss,{value:"campaigns",children:[e.jsx(on,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(ss,{value:"drip-assignments",children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsxs(ss,{value:"sent-emails",children:[e.jsx(WT,{className:"h-3.5 w-3.5 mr-1"}),"Sent Emails"]}),e.jsx(ss,{value:"activity",children:"Recruiter Activity"}),e.jsxs(ss,{value:"email-settings",children:[e.jsx(ic,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(ss,{value:"pipeline-stages",children:[e.jsx(sE,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(ns,{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(r0,{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(lz,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(jBt,{brokerageId:i}):e.jsx(MSe,{brokerageId:i})]}),e.jsx(ns,{value:"contacts",children:e.jsx(MSe,{brokerageId:i})}),e.jsx(ns,{value:"video-outreach",children:e.jsx(LBt,{brokerageId:i})}),e.jsx(ns,{value:"follow-ups",children:e.jsx(TBt,{brokerageId:i})}),e.jsx(ns,{value:"referrals",children:e.jsx(CBt,{brokerageId:i})}),e.jsx(ns,{value:"interest",children:e.jsx(ABt,{brokerageId:i})}),e.jsx(ns,{value:"landing-page",children:e.jsx(EBt,{brokerageId:i})}),e.jsx(ns,{value:"goals",children:e.jsx(PBt,{brokerageId:i})}),e.jsx(ns,{value:"metrics",children:e.jsx(NBt,{brokerageId:i})}),e.jsx(ns,{value:"templates",children:e.jsx(kBt,{brokerageId:i})}),e.jsx(ns,{value:"campaigns",children:e.jsx(DBt,{brokerageId:i})}),e.jsx(ns,{value:"drip-assignments",children:e.jsx(OBt,{brokerageId:i})}),e.jsx(ns,{value:"sent-emails",children:e.jsx(hAn,{brokerageId:i})}),e.jsx(ns,{value:"activity",children:e.jsx(SBt,{brokerageId:i})}),e.jsx(ns,{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(cYe,{brokerageId:i})]})}),e.jsx(ns,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(FBt,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ni,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function pAn(){const[s,t]=j.useState(""),{data:n,isLoading:r}=mt({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await U.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await U.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await U.from("brokerage_content_categories").select("id, brokerage_id"),u=c||[],h=d||[],m=o.map(p=>{const x=u.filter(b=>b.brokerage_id===p.id),y=h.filter(b=>b.brokerage_id===p.id),g=x.length>0?x.reduce((b,v)=>v.created_at>b?v.created_at:b,x[0].created_at):null;return{brokerage_id:p.id,brokerage_name:p.name,total_items:x.length,videos:x.filter(b=>b.content_type==="video").length,pdfs:x.filter(b=>b.content_type==="pdf").length,links:x.filter(b=>b.content_type==="link"||b.content_type==="canva_link").length,events:x.filter(b=>b.content_type==="event").length,graphics:x.filter(b=>b.content_type==="graphic").length,latest_item_date:g,categories:y.length}});return m.sort((p,x)=>x.total_items-p.total_items),m}}),a=(n||[]).filter(o=>o.brokerage_name.toLowerCase().includes(s.toLowerCase())),i=a.reduce((o,c)=>o+c.total_items,0),l=a.filter(o=>o.total_items>0).length;return e.jsx(Vs,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(oh,{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(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Re,{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(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Re,{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(be,{children:[e.jsx(Ft,{className:"pb-2",children:e.jsx(Ut,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Re,{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"registered"})]})]})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(be,{children:e.jsx(Re,{className:"p-0",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{className:"text-center",children:"Total"}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx($r,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Rc,{className:"h-3 w-3"})," Links"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Vc,{className:"h-3 w-3"})," Events"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ac,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Tt,{className:"text-center",children:"Categories"}),e.jsx(Tt,{children:"Last Upload"})]})}),e.jsx(za,{children:r?e.jsx(un,{children:e.jsx(xt,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(un,{children:e.jsx(xt,{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(xt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ni,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(xt,{className:"text-center",children:o.total_items>0?e.jsx(qe,{variant:"secondary",className:"font-bold",children:o.total_items}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(xt,{className:"text-center",children:o.videos||"–"}),e.jsx(xt,{className:"text-center",children:o.pdfs||"–"}),e.jsx(xt,{className:"text-center",children:o.links||"–"}),e.jsx(xt,{className:"text-center",children:o.events||"–"}),e.jsx(xt,{className:"text-center",children:o.graphics||"–"}),e.jsx(xt,{className:"text-center",children:o.categories||"–"}),e.jsx(xt,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:Bs(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const fAn=[{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(vm,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(vm,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(sx,{className:"h-4 w-4"})}],xAn=[{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:"📰"}],Rgt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),Dgt={"luxury-dark":VHe,"modern-clean":HHe,"bold-colorful":GHe,editorial:WHe};function gAn(){const[s,t]=j.useState(""),[n,r]=j.useState("address"),[a,i]=j.useState(!1),[l,o]=j.useState([]),[c,d]=j.useState(null),[u,h]=j.useState(0),[m,p]=j.useState("just-listed"),[x,y]=j.useState(["instagram-square"]),[g,b]=j.useState("luxury-dark"),[v,k]=j.useState(!1),[C,T]=j.useState(""),[M,P]=j.useState(""),[L,I]=j.useState(""),[O,$]=j.useState(!1),[q,W]=j.useState(!1),[G,K]=j.useState([]),[ee,J]=j.useState("search"),le=j.useRef({});j.useEffect(()=>{(async()=>{const{data:{user:Ee}}=await U.auth.getUser();if(!Ee)return;const{data:Le}=await U.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",Ee.id).single();if(Le){T(Le.name||""),I(Le.avatar_url||"");const De=Le.brokerages;P((De==null?void 0:De.name)||"")}})()},[]);const ue=async()=>{var Se;if(s.trim()){i(!0),o([]);try{const{data:Ee,error:Le}=await U.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Le)throw Le;if(Ee.error)throw new Error(Ee.error);o(Ee.listings||[]),((Se=Ee.listings)==null?void 0:Se.length)===0&&re.info("No listings found. Try a different search.")}catch(Ee){re.error(Ee.message||"Search failed")}finally{i(!1)}}},oe=Se=>{var Ee;d(Se),h(0),J("customize"),Se.soldDate||(Ee=Se.status)!=null&&Ee.toLowerCase().includes("sold")?p("just-sold"):p("just-listed")},ie=Se=>{y(Ee=>Ee.includes(Se)?Ee.filter(Le=>Le!==Se):[...Ee,Se])},de=j.useCallback(async()=>{if(!(!c||x.length===0)){$(!0),K([]),J("generate");try{await new Promise(Ee=>setTimeout(Ee,500));const Se=[];for(const Ee of x){const Le=`${g}-${Ee}`,De=le.current[Le];if(!De)continue;const Be=kT[Ee],Ne=await L$(De,{width:Be.width,height:Be.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Se.push({format:Ee,imageUrl:Ne})}K(Se),re.success(`Generated ${Se.length} social post${Se.length>1?"s":""}!`)}catch(Se){re.error(Se.message||"Generation failed")}finally{$(!1)}}},[c,x,g,u,v,C,M,L,m]),we=async()=>{if(!(!c||x.length===0)){$(!0),K([]),J("generate");try{const Se={...c,photos:c.photos.length>0?[c.photos[u]]:[]},Ee=[];for(const Le of x){const{data:De,error:Be}=await U.functions.invoke("generate-listing-social-post",{body:{listing:Se,postType:m,format:Le,branding:v?{enabled:!0,agentName:C,brokerage:M}:{enabled:!1}}});if(Be)throw Be;if(De.error)throw new Error(De.error);Ee.push({format:Le,imageUrl:De.imageUrl})}K(Ee),re.success(`Generated ${Ee.length} AI post${Ee.length>1?"s":""}!`)}catch(Se){re.error(Se.message||"AI generation failed")}finally{$(!1)}}},je=()=>q?we():de(),xe=(Se,Ee)=>{var De;const Le=document.createElement("a");Le.href=Se,Le.download=`${((De=c==null?void 0:c.address)==null?void 0:De.replace(/\s+/g,"-"))||"listing"}-${m}-${Ee}.png`,document.body.appendChild(Le),Le.click(),document.body.removeChild(Le)},fe=c?{listing:c,postType:m,format:"instagram-square",branding:v?{enabled:!0,agentName:C,brokerage:M,agentPhotoUrl:L||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(oh,{title:"Social Post Generator",description:"Search MLS listings and generate stunning social media posts"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsxs("button",{onClick:()=>J("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${ee==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Fr,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(Qa,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&J("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${ee==="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(yn,{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 ${ee==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(ac,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),ee==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(tAt,{})]}),e.jsx(fr,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Re,{className:"space-y-4",children:[e.jsx(fa,{value:n,onValueChange:Se=>r(Se),children:e.jsxs(xa,{children:[e.jsxs(ss,{value:"address",children:[e.jsx(oi,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(ss,{value:"mls",children:[e.jsx(wf,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{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(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Fr,{className:"h-4 w-4"})," Search"]})]})]})]}),l.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[l.length," listing",l.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:l.map((Se,Ee)=>{var Le;return e.jsx(be,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>oe(Se),children:e.jsx(Re,{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:(Le=Se.photos)!=null&&Le[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(ia,{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:Rgt(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(p3,{className:"h-3 w-3"})," ",Se.bedrooms]}),Se.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(t0,{className:"h-3 w-3"})," ",Se.bathrooms]}),Se.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(VR,{className:"h-3 w-3"})," ",Se.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Se.mlsNumber}),e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Se.status})]})]})]})})},Se.mlsNumber||Ee)})})]})]}),ee==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(be,{className:"lg:col-span-1",children:[e.jsx(Ft,{className:"pb-3",children:e.jsx(Ut,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Re,{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(Cc,{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:Rgt(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:()=>{J("search"),d(null)},children:[e.jsx(bm,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(be,{className:"lg:col-span-2",children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(fr,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Re,{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(Ac,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:q?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:q?"Uses AI credits for unique designs":"Instant, no credits used"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Use AI"}),e.jsx(Mn,{checked:q,onCheckedChange:W}),q&&e.jsx(um,{className:"h-4 w-4 text-purple-500"})]})]}),!q&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Ac,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:xAn.map(Se=>e.jsxs("button",{onClick:()=>b(Se.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${g===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(se,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:fAn.map(Se=>e.jsxs("button",{onClick:()=>p(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(se,{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:()=>ie(Se.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${x.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(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Eo,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(Mn,{checked:v,onCheckedChange:k})]}),v&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[L&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:L,alt:"Agent",className:"w-12 h-12 rounded-full object-cover border-2 border-primary/30"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Profile photo will appear on the post"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(ye,{value:C,onChange:Se=>T(Se.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(ye,{value:M,onChange:Se=>P(Se.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!q&&fe&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Preview"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:400,height:400*(kT[x[0]||"instagram-square"].height/kT[x[0]||"instagram-square"].width)},children:(()=>{const Se=Dgt[g],Ee=x[0]||"instagram-square";return e.jsx(Se,{...fe,format:Ee})})()})})]}),e.jsx(B,{onClick:je,disabled:x.length===0||O,size:"lg",className:"w-full gap-2",children:O?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-5 w-5 animate-spin"})," Generating ",x.length," post",x.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[q?e.jsx(um,{className:"h-5 w-5"}):e.jsx(yn,{className:"h-5 w-5"}),"Generate ",x.length," Social Post",x.length>1?"s":"",q&&e.jsx(qe,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),ee==="generate"&&e.jsxs("div",{className:"space-y-4",children:[O&&e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Wt,{className:"h-12 w-12 animate-spin text-primary mb-4"}),e.jsx("p",{className:"text-lg font-medium",children:"Generating your social posts..."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:q?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),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:()=>J("customize"),children:[e.jsx(bm,{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,Ee)=>{const Le=Igt.find(De=>De.value===Se.format);return e.jsxs(be,{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(Re,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Le==null?void 0:Le.icon,e.jsx("span",{className:"text-sm font-medium",children:Le==null?void 0:Le.label})]}),e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Le==null?void 0:Le.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>xe(Se.imageUrl,Se.format),children:[e.jsx(ii,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ee)})})]})]}),ee==="generate"&&!q&&c&&fe&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:x.map(Se=>{const Ee=Dgt[g],Le=kT[Se];return e.jsx("div",{style:{width:Le.width,height:Le.height},children:e.jsx(Ee,{ref:De=>{le.current[`${g}-${Se}`]=De},...fe,format:Se})},`${g}-${Se}`)})})]})})}function yAn(){return mt({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await U.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function vAn(s){return mt({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*)), access:lms_course_access(*)").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function bAn(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("lms_courses").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function zBt(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("lms_courses").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-courses-admin"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function _An(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("lms_courses").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function wAn(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("lms_modules").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function jAn(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("lms_modules").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function NAn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("lms_modules").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function kAn(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.from("lms_module_resources").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function SAn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("lms_module_resources").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function CAn(){const s=as();return vt({mutationFn:async({courseId:t,accessRules:n})=>{const{error:r}=await U.from("lms_course_access").delete().eq("course_id",t);if(r)throw r;if(n.length>0){const a=n.map(l=>({...l,course_id:t})),{error:i}=await U.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function AAn(){return mt({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await U.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function TAn(s){return mt({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*))").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function BBt(s){return mt({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("lms_progress").select("*").eq("course_id",s);if(n)throw n;return t},enabled:!!s})}function EAn(){const s=as();return vt({mutationFn:async({courseId:t,moduleId:n,userId:r})=>{const{data:a,error:i}=await U.from("lms_progress").upsert({user_id:r,course_id:t,module_id:n,completed:!0,completed_at:new Date().toISOString()},{onConflict:"user_id,module_id"}).select().single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["lms-progress"]})})}function MAn(){const{user:s}=Ns(),t=Hn(),{data:n,isLoading:r}=yAn(),a=bAn(),i=zBt(),l=_An(),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[p,x]=j.useState(!0),y=async()=>{if(!(!d.trim()||!s))try{const v=await a.mutateAsync({title:d.trim(),description:h.trim()||void 0,is_sequential:p,created_by:s.id});re.success("Course created"),c(!1),u(""),m(""),x(!0),t(`/admin/lms/${v.id}`)}catch{re.error("Failed to create course")}},g=async v=>{try{await i.mutateAsync({id:v.id,is_published:!v.is_published}),re.success(v.is_published?"Course unpublished":"Course published")}catch{re.error("Failed to update course")}},b=async v=>{if(await Bi("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(v),re.success("Course deleted")}catch{re.error("Failed to delete")}};return e.jsxs(Vs,{title:"LevelUp U - Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(Uh,{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(ol,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"New Course"]})]})]}),r?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:[1,2,3].map(v=>e.jsx(be,{className:"animate-pulse",children:e.jsxs(Ft,{children:[e.jsx("div",{className:"h-5 bg-muted rounded w-2/3"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2 mt-2"})]})},v))}):n!=null&&n.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:n.map(v=>{var M,P;const k=((P=(M=v.modules)==null?void 0:M[0])==null?void 0:P.count)??0,C=v.access||[],T=C.length===0?"No access set":C.some(L=>L.access_type==="all")?"All agents":`${C.length} rule(s)`;return e.jsxs(be,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${v.id}`),children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Ut,{className:"text-base truncate",children:v.title}),v.description&&e.jsx(fr,{className:"mt-1 line-clamp-2",children:v.description})]}),e.jsx(qe,{variant:v.is_published?"default":"secondary",className:"ml-2 shrink-0",children:v.is_published?"Published":"Draft"})]})}),e.jsxs(Re,{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(Op,{className:"h-3.5 w-3.5"}),k," module",k!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[v.is_sequential?e.jsx(kj,{className:"h-3.5 w-3.5"}):e.jsx(YR,{className:"h-3.5 w-3.5"}),v.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{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:L=>{L.stopPropagation(),g(v)},children:[v.is_published?e.jsx(n0,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"}),v.is_published?"Unpublish":"Publish"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:L=>{L.stopPropagation(),b(v.id)},children:e.jsx(Rn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"})]})]})]},v.id)})}):e.jsx(be,{className:"border-dashed",children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Op,{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(Js,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(Fs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Create New Course"}),e.jsx(kr,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Course Title"}),e.jsx(ye,{value:d,onChange:v=>u(v.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{value:h,onChange:v=>m(v.target.value),placeholder:"What will agents learn?",rows:3})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sequential Learning"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents must complete modules in order"})]}),e.jsx(Mn,{checked:p,onCheckedChange:x})]})]}),e.jsxs(Nr,{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 LAn(){const{courseId:s}=$i(),t=Hn(),{data:n,isLoading:r}=vAn(s),a=zBt(),i=wAn(),l=jAn(),o=NAn(),c=kAn(),d=SAn(),u=CAn(),{data:h}=mt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:nt}=await U.from("brokerages").select("id, name").order("name");return nt||[]}}),[m,p]=j.useState(null),[x,y]=j.useState(!1),[g,b]=j.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[v,k]=j.useState(null),[C,T]=j.useState({title:"",resource_type:"link",url:""}),[M,P]=j.useState(new Set),[L,I]=j.useState(null),[O,$]=j.useState(0),[q,W]=j.useState(!1),G=j.useRef(null),K=j.useRef(null),[ee,J]=j.useState(!1),[le,ue]=j.useState(""),[oe,ie]=j.useState(""),[de,we]=j.useState(""),[je,xe]=j.useState(!1);if(r)return e.jsx(Vs,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!n)return e.jsx(Vs,{title:"Course Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const fe=n.modules||[],Se=n.access||[],Ee=Se.some(nt=>nt.access_type==="all"),Le=Se.filter(nt=>nt.access_type==="brokerage").map(nt=>nt.brokerage_id),De=(h||[]).filter(nt=>nt.name.toLowerCase().includes(le.toLowerCase())),Be=nt=>{const rt=new Set(M);rt.has(nt)?rt.delete(nt):rt.add(nt),P(rt)},Ne=async()=>{if(!L)return null;W(!0),$(0);try{const{data:nt,error:rt}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:L.name}});if(rt)throw new Error(rt.message);const{videoId:Fe,libraryId:dt}=nt,{data:Dt,error:pt}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Fe,libraryId:dt}});if(pt)throw new Error(pt.message);const zt=new XMLHttpRequest;return await new Promise((Gt,qs)=>{zt.upload.onprogress=As=>{As.lengthComputable&&$(Math.round(As.loaded/As.total*100))},zt.onload=()=>zt.status>=200&&zt.status<300?Gt():qs(new Error(`Upload failed: ${zt.status}`)),zt.onerror=()=>qs(new Error("Upload failed")),zt.open("PUT",Dt.uploadUrl),zt.setRequestHeader("AccessKey",Dt.apiKey),zt.send(L)}),`https://iframe.mediadelivery.net/embed/${dt}/${Fe}`}catch(nt){return console.error("Bunny upload error:",nt),re.error("Video upload failed"),null}finally{W(!1),$(0)}},Ge=async()=>{if(g.title.trim())try{let nt=g.video_url.trim()||void 0;if(L){const rt=await Ne();if(!rt)return;nt=rt}await i.mutateAsync({course_id:n.id,title:g.title.trim(),description:g.description.trim()||void 0,video_url:nt,text_content:g.text_content.trim()||void 0,duration_minutes:g.duration_minutes?parseInt(g.duration_minutes):void 0,sort_order:fe.length}),re.success("Module added"),y(!1),b({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),I(null)}catch{re.error("Failed to add module")}},_e=async()=>{if(m)try{let nt=g.video_url.trim()||null;if(L){const rt=await Ne();if(!rt)return;nt=rt}await l.mutateAsync({id:m.id,title:g.title.trim(),description:g.description.trim()||null,video_url:nt,text_content:g.text_content.trim()||null,duration_minutes:g.duration_minutes?parseInt(g.duration_minutes):null}),re.success("Module updated"),p(null),I(null)}catch{re.error("Failed to update")}},Oe=async nt=>{if(await Bi("Delete this module?"))try{await o.mutateAsync(nt),re.success("Module deleted")}catch{re.error("Failed to delete")}},Ae=async nt=>{if(C.title.trim())try{await c.mutateAsync({module_id:nt,title:C.title.trim(),resource_type:C.resource_type,url:C.url.trim()||void 0}),re.success("Resource added"),k(null),T({title:"",resource_type:"link",url:""})}catch{re.error("Failed to add resource")}},Xe=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),re.success("Access updated: All brokerages / all agents")}catch{re.error("Failed to update access")}},Ue=async nt=>{const rt=Se.filter(pt=>pt.access_type==="brokerage").map(pt=>pt.brokerage_id),Fe=rt.includes(nt);let dt;Fe?dt=rt.filter(pt=>pt!==nt):dt=[...rt,nt];const Dt=dt.map(pt=>({access_type:"brokerage",brokerage_id:pt}));try{await u.mutateAsync({courseId:n.id,accessRules:Dt}),re.success(Fe?"Brokerage removed":"Brokerage added")}catch{re.error("Failed to update access")}},Ze=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),re.success("Access cleared")}catch{re.error("Failed")}},Qe=async(nt,rt)=>{const Fe=rt==="up"?nt-1:nt+1;if(!(Fe<0||Fe>=fe.length))try{await Promise.all([l.mutateAsync({id:fe[nt].id,sort_order:Fe}),l.mutateAsync({id:fe[Fe].id,sort_order:nt})])}catch{re.error("Failed to reorder")}},Ye=async()=>{try{await a.mutateAsync({id:n.id,title:oe,description:de||null}),re.success("Course updated"),xe(!1)}catch{re.error("Failed to update")}};return e.jsxs(Vs,{title:n.title,children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(_a,{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(qe,{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(kj,{className:"h-3.5 w-3.5"}):e.jsx(YR,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[fe.length," module",fe.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{ie(n.title),we(n.description||""),xe(!0)},children:[e.jsx(Za,{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(()=>re.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx(n0,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(fa,{defaultValue:"modules",className:"w-full",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"modules",children:"Modules"}),e.jsx(ss,{value:"access",children:"Access & Permissions"}),e.jsx(ss,{value:"settings",children:"Settings"})]}),e.jsxs(ns,{value:"modules",className:"mt-6 space-y-4",children:[fe.map((nt,rt)=>e.jsxs(be,{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(nt.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:Fe=>{Fe.stopPropagation(),Qe(rt,"up")},disabled:rt===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(Qy,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:Fe=>{Fe.stopPropagation(),Qe(rt,"down")},disabled:rt===fe.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(Po,{className:"h-3.5 w-3.5"})})]})}),e.jsx(qe,{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:nt.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[nt.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Zr,{className:"h-3 w-3"})," Video"]}),nt.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx($r,{className:"h-3 w-3"})," Text"]}),nt.duration_minutes&&e.jsxs("span",{children:[nt.duration_minutes," min"]}),nt.resources&&nt.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Rc,{className:"h-3 w-3"})," ",nt.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:Fe=>{var dt;Fe.stopPropagation(),p(nt),b({title:nt.title,description:nt.description||"",video_url:nt.video_url||"",text_content:nt.text_content||"",duration_minutes:((dt=nt.duration_minutes)==null?void 0:dt.toString())||""})},children:e.jsx(Za,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:Fe=>{Fe.stopPropagation(),Oe(nt.id)},children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]}),M.has(nt.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[nt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:nt.description}),nt.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:nt.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:nt.video_url})]}),nt.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:nt.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(nt.id),T({title:"",resource_type:"link",url:""})},children:[e.jsx(Js,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),nt.resources&&nt.resources.length>0?e.jsx("div",{className:"space-y-1",children:nt.resources.map(Fe=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Fe.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:Fe.title}),Fe.url&&e.jsx("a",{href:Fe.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(Fe.id),children:e.jsx(dr,{className:"h-3 w-3"})})]},Fe.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},nt.id)),e.jsxs(B,{variant:"outline",className:"w-full border-dashed",onClick:()=>{y(!0),b({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(Js,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(ns,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Re,{className:"space-y-5",children:[e.jsxs("div",{className:Et("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",Ee?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:Xe,children:[e.jsx("div",{className:Et("h-10 w-10 rounded-full flex items-center justify-center shrink-0",Ee?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(Ql,{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(Mn,{checked:Ee,onCheckedChange:Xe})]}),!Ee&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Select Brokerages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Le.length===0?"No brokerages selected — agents won't see this course":`${Le.length} brokerage${Le.length!==1?"s":""} selected`})]}),Le.length>0&&e.jsx(B,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Ze,children:"Clear all"})]}),e.jsx(ye,{placeholder:"Search brokerages...",value:le,onChange:nt=>ue(nt.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:De.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):De.map(nt=>{const rt=Le.includes(nt.id);return e.jsxs("div",{className:Et("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",rt?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>Ue(nt.id),children:[e.jsx("div",{className:Et("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(Ni,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:nt.name}),rt&&e.jsx(qe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},nt.id)})})]})]})]})}),e.jsxs(ns,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Re,{children:e.jsxs("div",{className:"flex items-start gap-6",children:[n.thumbnail_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:n.thumbnail_url,alt:"Course thumbnail",className:"w-48 h-28 object-cover rounded-lg border"}),e.jsx("button",{onClick:()=>a.mutateAsync({id:n.id,thumbnail_url:null}).then(()=>re.success("Thumbnail removed")),className:"absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(dr,{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(a1,{className:"h-8 w-8 mb-1 opacity-50"}),e.jsx("span",{className:"text-xs",children:"No thumbnail"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a thumbnail image for this course. Recommended: 800×450px (16:9)."}),e.jsx("input",{ref:K,type:"file",accept:"image/*",className:"hidden",onChange:async nt=>{var Fe;const rt=(Fe=nt.target.files)==null?void 0:Fe[0];if(!(!rt||!n)){J(!0);try{const dt=rt.name.split(".").pop(),Dt=`${n.id}/thumbnail.${dt}`,{error:pt}=await U.storage.from("lms-thumbnails").upload(Dt,rt,{upsert:!0});if(pt)throw pt;const{data:zt}=U.storage.from("lms-thumbnails").getPublicUrl(Dt),Gt=`${zt.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:Gt}),re.success("Thumbnail uploaded")}catch{re.error("Failed to upload thumbnail")}finally{J(!1),K.current&&(K.current.value="")}}}}),e.jsxs(B,{variant:"outline",size:"sm",disabled:ee,onClick:()=>{var nt;return(nt=K.current)==null?void 0:nt.click()},children:[ee?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ja,{className:"h-4 w-4 mr-2"}),ee?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Course Settings"})}),e.jsxs(Re,{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(Mn,{checked:n.is_sequential,onCheckedChange:nt=>a.mutateAsync({id:n.id,is_sequential:nt}).then(()=>re.success("Updated"))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this course visible to agents with access"})]}),e.jsx(Mn,{checked:n.is_published,onCheckedChange:nt=>a.mutateAsync({id:n.id,is_published:nt}).then(()=>re.success("Updated"))})]})]})]})]})]})]}),e.jsx(Fs,{open:x||!!m,onOpenChange:nt=>{nt||(y(!1),p(null))},children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsx(zs,{children:m?"Edit Module":"Add Module"}),e.jsx(kr,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:g.title,onChange:nt=>b(rt=>({...rt,title:nt.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{value:g.description,onChange:nt=>b(rt=>({...rt,description:nt.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:Et("border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors hover:border-primary/50",L?"border-primary bg-primary/5":"border-muted-foreground/25"),onClick:()=>{var nt;return(nt=G.current)==null?void 0:nt.click()},children:[e.jsx("input",{ref:G,type:"file",accept:"video/*",className:"hidden",onChange:nt=>{var Fe;const rt=(Fe=nt.target.files)==null?void 0:Fe[0];rt&&(I(rt),b(dt=>({...dt,video_url:""})))}}),L?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(Zr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:L.name}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:nt=>{nt.stopPropagation(),I(null)},children:e.jsx(dr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(Ja,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),q&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Wt,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",O,"%"]})]}),e.jsx(qi,{value:O,className:"h-1.5"})]}),!L&&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(ye,{value:g.video_url,onChange:nt=>b(rt=>({...rt,video_url:nt.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Text Content"}),e.jsx(Ds,{value:g.text_content,onChange:nt=>b(rt=>({...rt,text_content:nt.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Duration (minutes)"}),e.jsx(ye,{type:"number",value:g.duration_minutes,onChange:nt=>b(rt=>({...rt,duration_minutes:nt.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>{y(!1),p(null),I(null)},children:"Cancel"}),e.jsxs(B,{onClick:m?_e:Ge,disabled:!g.title.trim()||q,children:[q?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),q?"Uploading...":m?"Save Changes":"Add Module"]})]})]})}),e.jsx(Fs,{open:!!v,onOpenChange:nt=>{nt||k(null)},children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Add Resource"}),e.jsx(kr,{children:"Add a link, document, or other resource to this module"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:C.title,onChange:nt=>T(rt=>({...rt,title:nt.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Type"}),e.jsxs(vs,{value:C.resource_type,onValueChange:nt=>T(rt=>({...rt,resource_type:nt})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"link",children:"Link"}),e.jsx(Je,{value:"pdf",children:"PDF"}),e.jsx(Je,{value:"template",children:"Template"}),e.jsx(Je,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"URL"}),e.jsx(ye,{value:C.url,onChange:nt=>T(rt=>({...rt,url:nt.target.value})),placeholder:"https://..."})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>k(null),children:"Cancel"}),e.jsx(B,{onClick:()=>v&&Ae(v),disabled:!C.title.trim(),children:"Add Resource"})]})]})}),e.jsx(Fs,{open:je,onOpenChange:xe,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Edit Course"}),e.jsx(kr,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:oe,onChange:nt=>ie(nt.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{value:de,onChange:nt=>we(nt.target.value),rows:3})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>xe(!1),children:"Cancel"}),e.jsx(B,{onClick:Ye,disabled:!oe.trim(),children:"Save"})]})]})})]})}function PAn(){return mt({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await U.rpc("get_lms_stats");if(t)throw t;return s}})}function IAn(){return mt({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await U.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function RAn(s){return mt({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.rpc("get_lms_agent_progress",{p_course_id:s});if(n)throw n;return t||[]},enabled:!!s})}function DAn(){const s=Hn(),{data:t,isLoading:n}=PAn(),{data:r,isLoading:a}=IAn(),[i,l]=j.useState(null),{data:o,isLoading:c}=RAn(i),[d,u]=j.useState(""),h=r==null?void 0:r.find(x=>x.course_id===i),m=o==null?void 0:o.filter(x=>{var y,g;return!d||((y=x.agent_name)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))||((g=x.email)==null?void 0:g.toLowerCase().includes(d.toLowerCase()))}),p=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:Op,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:Rr,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:Bn,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:ll,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:kl,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:ol,color:"text-rose-500"}];return e.jsx(Vs,{title:"LevelUp U - Stats",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(_a,{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(Uh,{className:"h-7 w-7 text-primary"}),"LevelUp U — Analytics"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Track enrollment, progress, and completion across all courses"})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3",children:p.map(x=>e.jsx(be,{className:Et("transition-all",n&&"animate-pulse"),children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(x.icon,{className:Et("h-4 w-4",x.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:x.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:n?"—":x.value})]})},x.label))}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-5 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(ol,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(x=>e.jsx(be,{className:"animate-pulse",children:e.jsx(Re,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},x))}):r!=null&&r.length?e.jsx("div",{className:"space-y-2",children:r.map(x=>{const y=i===x.course_id;return e.jsx(be,{className:Et("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:x.course_id),children:e.jsxs(Re,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm text-foreground truncate",children:x.course_title}),e.jsx(qe,{variant:x.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:x.is_published?"Live":"Draft"})]})}),e.jsx(Qa,{className:Et("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:x.enrolled_agents}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Enrolled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:x.total_completions}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Completed"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:x.total_modules}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Modules"})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg. Completion"}),e.jsxs("span",{className:"font-semibold text-foreground",children:[x.avg_completion_pct,"%"]})]}),e.jsx(qi,{value:x.avg_completion_pct,className:"h-2"})]})]})},x.course_id)})}):e.jsx(be,{className:"border-dashed",children:e.jsx(Re,{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(bN,{className:"h-5 w-5 text-primary"}),h?`Agent Progress — ${h.course_title}`:"Agent Progress"]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:d,onChange:x=>u(x.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(x=>e.jsx(be,{className:"animate-pulse",children:e.jsx(Re,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},x))}):m!=null&&m.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:m.map((x,y)=>{const g=x.completion_pct>=100;return e.jsx(be,{className:Et("transition-all",g&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Et("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(Ra,{className:"h-9 w-9 shrink-0",children:[e.jsx(Fi,{src:x.avatar_url||void 0}),e.jsx(Da,{className:"text-xs bg-primary/10 text-primary",children:(x.agent_name||x.email||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:x.agent_name||x.email}),g&&e.jsxs(qe,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(Rr,{className:"h-3 w-3 mr-0.5"})," Complete"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[x.modules_completed,"/",x.total_modules," modules"]}),x.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),Bs(new Date(x.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Et("text-sm font-bold",g?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[x.completion_pct,"%"]}),e.jsx(qi,{value:x.completion_pct,className:"h-1.5 mt-1"})]})]})})},x.user_id)})}):e.jsx(be,{className:"border-dashed",children:e.jsx(Re,{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(be,{className:"border-dashed",children:e.jsxs(Re,{className:"py-16 text-center",children:[e.jsx(Bn,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Select a course to view agent progress"})]})})]})]})]})})}function OAn(){const{user:s}=Ns(),t=Hn(),{data:n,isLoading:r}=AAn();return e.jsx(Vs,{title:"LevelUp U",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/10 via-primary/5 to-background border p-8",children:[e.jsx("div",{className:"relative z-10",children:e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"h-12 w-12 rounded-xl bg-primary/15 flex items-center justify-center",children:e.jsx(Uh,{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(be,{className:"animate-pulse",children:e.jsxs(Re,{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(FAn,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(be,{className:"border-dashed",children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Op,{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 FAn({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=BBt(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(be,{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(Uh,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Re,{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(Op,{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(kj,{className:"h-3.5 w-3.5"}):e.jsx(YR,{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(qi,{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 zAn(){const{courseId:s}=$i(),t=Hn(),{user:n}=Ns(),{data:r,isLoading:a}=TAn(s),{data:i}=BBt(s),l=EAn(),[o,c]=j.useState(null),d=(r==null?void 0:r.modules)||[],u=new Set((i==null?void 0:i.filter(v=>v.completed).map(v=>v.module_id))||[]),h=u.size,m=d.length>0?Math.round(h/d.length*100):0;j.useEffect(()=>{if(d.length>0&&!o){const v=d.find(k=>!u.has(k.id));c((v==null?void 0:v.id)||d[0].id)}},[d,o,u]);const p=d.find(v=>v.id===o),x=d.findIndex(v=>v.id===o),y=(v,k)=>{if(!(r!=null&&r.is_sequential)||k===0)return!1;for(let C=0;C{if(!(!p||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:p.id,userId:n.id}),re.success("Module completed! 🎉"),x{const k=v.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(k)return`https://www.youtube.com/embed/${k[1]}`;const C=v.match(/vimeo\.com\/(\d+)/);if(C)return`https://player.vimeo.com/video/${C[1]}`;const T=v.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`:v};return a?e.jsx(Vs,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):r?e.jsx(Vs,{title:r.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(_a,{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(qi,{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(be,{className:"lg:sticky lg:top-4",children:e.jsxs(Re,{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((v,k)=>{const C=y(v,k),T=u.has(v.id),M=v.id===o;return e.jsxs("button",{disabled:C,onClick:()=>!C&&c(v.id),className:Et("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",M?"bg-primary/10 text-primary":"hover:bg-muted/50",C&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"shrink-0",children:C?e.jsx(du,{className:"h-4 w-4 text-muted-foreground"}):T?e.jsx(Rr,{className:"h-4 w-4 text-green-500"}):e.jsx(Sx,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Et("font-medium truncate",M&&"text-primary"),children:[k+1,". ",v.title]}),v.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(Vr,{className:"h-3 w-3"})," ",v.duration_minutes," min"]})]})]},v.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:p?e.jsxs(e.Fragment,{children:[p.video_url&&e.jsx(be,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:b(p.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:p.title}),p.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:p.description})]}),u.has(p.id)?e.jsxs(qe,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(B,{size:"sm",onClick:g,disabled:l.isPending,children:[e.jsx(Rr,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),p.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:p.text_content}),p.resources&&p.resources.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Resources"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:p.resources.map(v=>e.jsxs("a",{href:v.url||v.file_url||"#",target:"_blank",rel:"noreferrer",className:"flex items-center gap-2 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-sm",children:[v.resource_type==="pdf"?e.jsx($r,{className:"h-4 w-4 text-red-500 shrink-0"}):v.resource_type==="template"?e.jsx(Uh,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(Rc,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:v.title}),e.jsx(Tr,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},v.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:x===0,onClick:()=>x>0&&c(d[x-1].id),children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),xc(d[x+1].id),children:["Next ",e.jsx(Qa,{className:"h-3.5 w-3.5 ml-1"})]}):m===100&&e.jsx(qe,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(be,{children:e.jsx(Re,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(Vs,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function BAn({headline:s,subtext:t,primaryColor:n,accentColor:r,heroImageUrl:a,logoUrl:i,brokerageName:l}){return e.jsxs("section",{className:"relative min-h-screen flex items-center justify-center overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(160deg, ${r} 0%, ${n} 50%, ${r}ee 100%)`}}),a&&e.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-20",style:{backgroundImage:`url(${a})`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px), radial-gradient(circle at 75% 75%, white 1px, transparent 1px)",backgroundSize:"60px 60px"}}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-white to-transparent"}),e.jsxs("div",{className:"relative z-10 text-center max-w-4xl mx-auto px-6 py-24",children:[i&&e.jsx(br.img,{src:i,alt:l,className:"h-14 md:h-20 w-auto mx-auto mb-10 drop-shadow-2xl",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.8,delay:.2}}),e.jsx(br.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.3},children:e.jsx("span",{className:"inline-block text-white/70 text-sm md:text-base font-medium tracking-[0.2em] uppercase mb-6",children:"Your Next Chapter Starts Here"})}),e.jsx(br.h1,{className:"text-4xl md:text-6xl lg:text-7xl font-bold text-white mb-8 leading-[1.1] tracking-tight",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.9,delay:.5},children:s}),e.jsx(br.p,{className:"text-lg md:text-xl text-white/80 mb-12 max-w-2xl mx-auto leading-relaxed font-light",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.7},children:t}),e.jsxs(br.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.7,delay:.9},className:"flex flex-col sm:flex-row items-center justify-center gap-4",children:[e.jsxs("a",{href:"#apply",className:"group inline-flex items-center gap-3 px-10 py-4 rounded-full text-lg font-semibold shadow-2xl transition-all duration-300 hover:scale-105 hover:shadow-3xl",style:{backgroundColor:"white",color:r},children:["Get In Touch",e.jsx(Xa,{className:"h-5 w-5 transition-transform group-hover:translate-x-1"})]}),e.jsx("a",{href:"#benefits",className:"inline-flex items-center gap-2 px-8 py-4 rounded-full text-base font-medium text-white/90 border border-white/30 backdrop-blur-sm transition-all duration-300 hover:bg-white/10 hover:border-white/50",children:"Learn More"})]})]}),e.jsx(br.div,{className:"absolute bottom-8 left-1/2 -translate-x-1/2 z-10",animate:{y:[0,8,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:e.jsx("div",{className:"w-6 h-10 border-2 border-white/40 rounded-full flex justify-center pt-2",children:e.jsx("div",{className:"w-1.5 h-3 bg-white/60 rounded-full"})})})]})}function aw({children:s,className:t="",delay:n=0,direction:r="up"}){const a=j.useRef(null),i=f_s(a,{once:!0,margin:"-80px"}),l={hidden:{opacity:0,y:r==="up"?40:0,x:r==="left"?-40:r==="right"?40:0},visible:{opacity:1,y:0,x:0}};return e.jsx(br.div,{ref:a,initial:"hidden",animate:i?"visible":"hidden",variants:l,transition:{duration:.7,delay:n,ease:[.25,.46,.45,.94]},className:t,children:s})}function $An({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(aw,{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(aw,{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 UAn({images:s,primaryColor:t,accentColor:n}){const[r,a]=j.useState(null);return s.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"py-24 md:py-32 px-6 bg-gray-50",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(aw,{children:e.jsxs("div",{className:"text-center mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white border border-gray-200 mb-6",children:[e.jsx(Bn,{className:"h-4 w-4",style:{color:t}}),e.jsx("span",{className:"text-sm font-medium text-gray-600",children:"Life at Our Brokerage"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",style:{color:n},children:"Our Team & Culture"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 md:gap-4",children:s.map((i,l)=>e.jsx(aw,{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(dr,{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 qAn({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(aw,{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(aw,{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(yN,{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 VAn({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(aw,{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(aw,{delay:.2,children:e.jsxs("form",{onSubmit:l=>{l.preventDefault(),n()},className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(ye,{required:!0,value:s.first_name,onChange:l=>t(o=>({...o,first_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(ye,{value:s.last_name,onChange:l=>t(o=>({...o,last_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(ye,{type:"email",required:!0,value:s.email,onChange:l=>t(o=>({...o,email:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(ye,{value:s.phone,onChange:l=>t(o=>({...o,phone:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(ye,{value:s.current_brokerage,onChange:l=>t(o=>({...o,current_brokerage:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Your current brokerage name"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(ye,{value:s.license_number,onChange:l=>t(o=>({...o,license_number:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(ye,{type:"number",min:"0",value:s.experience_years,onChange:l=>t(o=>({...o,experience_years:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(ye,{value:s.annual_production,onChange:l=>t(o=>({...o,annual_production:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"e.g. $5M, 20 transactions"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(Ds,{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(Xa,{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(_f,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function HAn({form:s,setForm:t,onSubmit:n,isPending:r,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=j.useState(1),[d,u]=j.useState(""),h=3,m=!!s.first_name&&!!s.email,p=x=>{u(x),t(y=>({...y,why_interested:x})),setTimeout(()=>c(2),200)};return e.jsxs("section",{id:"apply",className:"py-24 md:py-32 px-6 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 top-0 h-1/2",style:{background:`linear-gradient(160deg, ${i}, ${a})`}}),e.jsx("div",{className:"absolute inset-0 top-1/2 bg-gray-50"}),e.jsxs("div",{className:"relative z-10 max-w-xl mx-auto",children:[e.jsx(aw,{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(du,{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(aw,{delay:.15,children:e.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-7",children:[[1,2,3].map(x=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:x<=o?a:"#e5e7eb"}},x)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",h]})]}),e.jsxs(QU,{mode:"wait",children:[o===1&&e.jsxs(br.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-3",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"What's most important to you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-5",children:"Pick the one that resonates most. We'll tailor the conversation."}),[{val:"Better commission split / cap",label:"Better Splits & Caps",icon:"💰"},{val:"Better technology and tools",label:"Better Tech & Tools",icon:"🛠️"},{val:"Better training and mentorship",label:"Better Training",icon:"📚"},{val:"Better culture and team",label:"Better Culture",icon:"🤝"},{val:"Just exploring options confidentially",label:"Just Exploring",icon:"🔍"}].map(x=>e.jsxs("button",{type:"button",onClick:()=>p(x.val),className:"w-full flex items-center gap-3 p-4 rounded-xl border-2 border-gray-100 hover:border-gray-300 transition-all text-left group",children:[e.jsx("span",{className:"text-2xl",children:x.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:x.label}),e.jsx(Xa,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},x.val))]},"step1"),o===2&&e.jsxs(br.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"How can we reach you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"We'll text first, on your schedule."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(ye,{required:!0,value:s.first_name,onChange:x=>t(y=>({...y,first_name:x.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(ye,{value:s.last_name,onChange:x=>t(y=>({...y,last_name:x.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(ye,{type:"email",required:!0,value:s.email,onChange:x=>t(y=>({...y,email:x.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(ye,{value:s.phone,onChange:x=>t(y=>({...y,phone:x.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(_a,{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(Xa,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(br.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"A few quick details (optional)"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"Helps us prepare a more personalized comp comparison."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(ye,{value:s.current_brokerage,onChange:x=>t(y=>({...y,current_brokerage:x.target.value})),className:"h-11",placeholder:"(stays private)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(ye,{type:"number",min:"0",value:s.experience_years,onChange:x=>t(y=>({...y,experience_years:x.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(ye,{value:s.annual_production,onChange:x=>t(y=>({...y,annual_production:x.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(Ds,{value:s.why_interested,onChange:x=>t(y=>({...y,why_interested:x.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(_a,{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(da,{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(_f,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(ro,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(pa,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function GAn({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=pi(),[l,o]=j.useState("250000"),[c,d]=j.useState("12"),[u,h]=j.useState("70"),[m,p]=j.useState("150"),[x,y]=j.useState(""),[g,b]=j.useState(!1),[v,k]=j.useState(!1),C=s.commission_split_pct??80,T=s.cap_amount??16e3,M=s.post_cap_split_pct??100,P=s.monthly_fee??99,L=s.transaction_fee??0,I=j.useMemo(()=>{const q=parseFloat(l)||0,W=Math.max(0,parseInt(c,10)||0),G=parseFloat(u)||0,K=parseFloat(m)||0,ee=q*(G/100)-K*12-L*W,J=1-C/100,le=J>0?T/J:q,ue=Math.min(q,le),oe=Math.max(0,q-le),ie=ue*J+oe*(1-M/100),de=q-ie-P*12-L*W,we=de-ee;return{currentNet:ee,newNet:de,diff:we}},[l,c,u,m,C,T,M,P,L]),O=q=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(q),$=async q=>{if(q.preventDefault(),!!x){k(!0);try{const{error:W}=await U.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:x,source:"calculator"});if(W)throw W;const{error:G}=await U.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:r,brokerage_name:a,email:x,inputs:{gci:parseFloat(l)||0,transactions:parseInt(c,10)||0,current_split_pct:parseFloat(u)||0,current_monthly_fee:parseFloat(m)||0},plan:{commission_split_pct:C,cap_amount:T,post_cap_split_pct:M,monthly_fee:P,transaction_fee:L},result:I,primary_color:t,accent_color:n}});G&&console.error("Breakdown email failed:",G),b(!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(aw,{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(du,{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(aw,{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(P5,{className:"h-5 w-5",style:{color:t}}),e.jsx("h3",{className:"font-semibold",style:{color:n},children:"Your Numbers"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-gray-600 text-sm",children:"Your GCI Last 12 Months"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(ye,{type:"number",value:l,onChange:q=>o(q.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(ye,{type:"number",min:"0",value:c,onChange:q=>d(q.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(ye,{type:"number",value:u,onChange:q=>h(q.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-gray-600 text-sm",children:"Your Current Monthly Fees"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(ye,{type:"number",value:m,onChange:q=>p(q.target.value),className:"pl-7 h-11 text-base",placeholder:"150"})]})]})]})]}),e.jsxs("div",{className:"p-8 md:p-10 text-white",style:{background:`linear-gradient(160deg, ${n}, ${t})`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(kl,{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:O(I.currentNet)})]}),e.jsxs("div",{className:"flex items-baseline justify-between border-b border-white/20 pb-3",children:[e.jsx("span",{className:"text-white/70 text-sm",children:"With us"}),e.jsx("span",{className:"text-xl font-semibold",children:O(I.newNet)})]})]}),e.jsxs(br.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},className:"bg-white/10 backdrop-blur rounded-2xl p-5 text-center",children:[e.jsx("p",{className:"text-white/80 text-xs uppercase tracking-wide mb-1",children:I.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[I.diff>=0?"+":"",O(I.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:I.diff>=0?"more per year":"per year"})]},I.diff),s.show_email_capture&&!g&&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(ye,{type:"email",required:!0,value:x,onChange:q=>y(q.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:v,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),g&&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(da,{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 WAn({config:s,primaryColor:t,accentColor:n,brokerageId:r}){const{toast:a}=pi(),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(!1),p=async x=>{x.preventDefault(),m(!0);try{const{error:y}=await U.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:i,first_name:o||null,source:"lead_magnet",user_agent:navigator.userAgent,referrer:document.referrer||null});if(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(aw,{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(jj,{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(du,{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(da,{className:"h-5 w-5 shrink-0"}),e.jsxs("span",{children:["Sent! ",s.pdf_url?"Your download should open in a new tab.":"Check your email shortly."]})]}):e.jsxs("form",{onSubmit:p,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(ye,{value:o,onChange:x=>c(x.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(ye,{type:"email",required:!0,value:i,onChange:x=>l(x.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(jj,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function KAn(){const{slug:s}=$i(),{toast:t}=pi(),[n,r]=j.useState(!1),[a,i]=j.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});j.useEffect(()=>{document.body.classList.add("recruit-landing-page");const I=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(W=>document.querySelectorAll(W).forEach(G=>G.style.display="none"))};I();const O=[setTimeout(I,500),setTimeout(I,1500),setTimeout(I,3e3)],$=new MutationObserver(I);return $.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),O.forEach(clearTimeout),$.disconnect()}},[]);const{data:l,isLoading:o,error:c}=mt({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:I,error:O}=await U.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(O)throw O;return I},enabled:!!s}),{data:d}=mt({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:I,error:O}=await U.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if(O&&O.code!=="PGRST116")throw O;return I},enabled:!!(l!=null&&l.id)}),u=vt({mutationFn:async()=>{const I={brokerage_id:l.id,first_name:a.first_name,last_name:a.last_name||null,email:a.email,phone:a.phone||null,current_brokerage:a.current_brokerage||null,experience_years:a.experience_years?parseInt(a.experience_years):null,annual_production:a.annual_production||null,license_number:a.license_number||null,why_interested:a.why_interested||null},{error:O}=await U.from("recruit_interest_submissions").insert(I);if(O)throw O;U.functions.invoke("recruit-lead-notify",{body:{lead:I,brokerage_id:l.id}}).catch($=>console.error("Lead notification error:",$))},onSuccess:()=>r(!0),onError:I=>t({title:"Error",description:I.message,variant:"destructive"})});if(o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-3 border-gray-200 border-t-gray-800"}),e.jsx("span",{className:"text-sm text-gray-400 tracking-wide",children:"Loading..."})]})});if(c||!l||!l.recruit_form_enabled)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"max-w-md w-full mx-4 text-center",children:[e.jsx(Ni,{className:"h-10 w-10 mx-auto text-gray-300 mb-4"}),e.jsx("p",{className:"text-gray-400 text-lg",children:"This page is not available."})]})});const h=d,m=(h==null?void 0:h.primary_color)||"#406E71",p=(h==null?void 0:h.accent_color)||"#2a4c64",x=(h==null?void 0:h.benefits)||[],y=(h==null?void 0:h.testimonials)||[],g=(h==null?void 0:h.gallery_images)||[],b=(h==null?void 0:h.hero_headline)||`Join ${l.name}`,v=(h==null?void 0:h.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",k=(h==null?void 0:h.calculator_enabled)===!0,C=(h==null?void 0:h.calculator_config)||{},T=(h==null?void 0:h.lead_magnet_enabled)===!0,M=(h==null?void 0:h.lead_magnet_config)||{},P=(h==null?void 0:h.form_style)||"classic",L=(h==null?void 0:h.confidential_messaging)!==!1;return n?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs(br.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{duration:.6},className:"max-w-md w-full mx-4 text-center",children:[e.jsx("div",{className:"h-20 w-20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg",style:{background:`linear-gradient(135deg, ${m}, ${p})`},children:e.jsx(da,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:p},children:"Thank You!"}),e.jsxs("p",{className:"text-gray-500 text-lg leading-relaxed mb-8",children:["Your interest in joining ",e.jsx("span",{className:"font-semibold",style:{color:p},children:l.name})," has been received. A member of our recruitment team will be in touch shortly."]}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full",style:{backgroundColor:m}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":m,"--recruit-accent":p},children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-40 bg-white/80 backdrop-blur-lg border-b border-gray-100/50",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-6 h-14 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[(h==null?void 0:h.logo_url)&&e.jsx("img",{src:h.logo_url,alt:l.name,className:"h-8 w-auto"}),e.jsx("span",{className:"font-semibold text-sm tracking-tight",style:{color:p},children:l.name})]}),e.jsxs("a",{href:"#apply",className:"inline-flex items-center gap-2 px-5 py-2 rounded-full text-sm font-semibold text-white transition-all duration-300 hover:shadow-md hover:scale-105",style:{background:`linear-gradient(135deg, ${m}, ${p})`},children:["Apply Now ",e.jsx(Xa,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(BAn,{headline:b,subtext:v,primaryColor:m,accentColor:p,heroImageUrl:h==null?void 0:h.hero_image_url,logoUrl:h==null?void 0:h.logo_url,brokerageName:l.name}),e.jsx($An,{benefits:x,accentColor:p,primaryColor:m}),e.jsx(UAn,{images:g,primaryColor:m,accentColor:p}),e.jsx(qAn,{testimonials:y,primaryColor:m,accentColor:p}),k&&e.jsx(GAn,{config:C,primaryColor:m,accentColor:p,brokerageId:l.id,brokerageName:l.name}),T&&e.jsx(WAn,{config:M,primaryColor:m,accentColor:p,brokerageId:l.id}),P==="multi_step"?e.jsx(HAn,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:p,showConfidentialBadges:L}):e.jsx(VAn,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:p}),e.jsx("footer",{className:"py-10 text-center bg-white border-t border-gray-100",children:e.jsxs("p",{className:"text-sm text-gray-400",children:["© ",new Date().getFullYear()," ",l.name,". All rights reserved."]})})]})}function YAn(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 ZAn(){var m,p,x,y;const{shareToken:s}=$i(),t=j.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:g,error:b}=await U.from("recruit_videos").select(` *, prospect:recruit_prospects(first_name, last_name), video:agent_videos(id, title, playback_url, thumbnail_url, duration_seconds, owner_user_id) `).eq("share_token",s).single();if(b)throw b;const{data:v}=await U.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(T=g.video)==null?void 0:T.owner_user_id).single(),{data:k}=await U.from("brokerages").select("name").eq("id",g.brokerage_id).single(),{data:C}=await U.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",g.brokerage_id).maybeSingle();return{rv:g,profile:v,brokerage:k,settings:C}},enabled:!!s});if(j.useEffect(()=>{var g;!((g=n==null?void 0:n.rv)!=null&&g.id)||t.current||(t.current=!0,U.rpc("log_recruit_video_view",{p_recruit_video_id:n.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(m=n==null?void 0:n.rv)==null?void 0:m.id]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=n,d=(c==null?void 0:c.primary_color)||"#3b82f6",u=((p=i.prospect)==null?void 0:p.first_name)||"there",h=(x=i.video)!=null&&x.playback_url?YAn(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(ql,{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:()=>{U.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:e.jsxs("a",{href:l.recruit_cta_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(ra,{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 XAn="relzejiswnotikjgvjhz",Ogt=`https://${XAn}.supabase.co/functions/v1/recruit-unsubscribe`;function QAn(){const[s]=dc(),t=s.get("token")||"",[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState({});j.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const p=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(b=>document.querySelectorAll(b).forEach(v=>v.style.display="none"))};p();const x=[setTimeout(p,500),setTimeout(p,1500),setTimeout(p,3e3)],y=new MutationObserver(p);return y.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),x.forEach(clearTimeout),y.disconnect()}},[]),j.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${Ogt}?token=${encodeURIComponent(t)}`).then(async p=>{const x=await p.json();if(!p.ok)throw new Error(x.error||"Lookup failed");h(x),x.already_unsubscribed&&o(!0)}).catch(p=>h({error:p.message||"Could not load status"})).finally(()=>r(!1))},[t]);const m=async()=>{i(!0);try{const p=await fetch(Ogt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),x=await p.json();if(!p.ok)throw new Error(x.error||"Failed");o(!0)}catch(p){h({...u,error:p.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(Wt,{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(po,{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(Rr,{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(a0,{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(a0,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe",u.first_name?`, ${u.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll be removed from ",u.brokerage_name||"this brokerage","'s recruiting emails immediately. Everything stays confidential."]}),u.email&&e.jsx("p",{className:"text-xs text-slate-400",children:u.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(Ds,{id:"reason",value:c,onChange:p=>d(p.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx(B,{onClick:m,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{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 JAn="relzejiswnotikjgvjhz",Fgt=`https://${JAn}.supabase.co/functions/v1/event-invite-unsubscribe`;function eTn(){const[s]=dc(),t=s.get("token")||"",[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState({});j.useEffect(()=>(document.body.classList.add("event-invite-unsubscribe-page"),()=>{document.body.classList.remove("event-invite-unsubscribe-page")}),[]),j.useEffect(()=>{if(!t){d({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${Fgt}?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(Fgt,{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(Wt,{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(po,{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(Rr,{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(a0,{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(LW,{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(Wt,{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 tTn(){const s=Hn(),t=as(),{isAdmin:n}=Ns(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState(null),{data:d,isLoading:u}=mt({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:C},error:T}=await U.auth.getUser();if(T)throw T;if(!C)return[];const{data:M,error:P}=await U.from("social_accounts").select("*").eq("user_id",C.id).order("created_at",{ascending:!1});if(P)throw P;return M}}),h=vt({mutationFn:async C=>{const{data:{user:T},error:M}=await U.auth.getUser();if(M)throw M;if(!T)throw new Error("Not authenticated");const{error:P}=await U.from("social_accounts").delete().eq("id",C).eq("user_id",T.id);if(P)throw P},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),re.success("Account disconnected successfully")},onError:()=>{re.error("Failed to disconnect account")}}),m=async()=>{a(!0);try{const{data:C,error:T}=await U.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(T)throw T;if(C!=null&&C.authUrl)window.location.href=C.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(C){console.error("LinkedIn OAuth error:",C),re.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},p=async()=>{a(!0);try{const{data:C,error:T}=await U.functions.invoke("google-business-oauth",{body:{action:"get_auth_url"}});if(T)throw T;if(C!=null&&C.authUrl)window.location.href=C.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(C){console.error("Google OAuth error:",C),re.error("Failed to start Google connection. Please try again."),a(!1)}},x=(d==null?void 0:d.filter(C=>C.platform==="facebook"))||[],y=(d==null?void 0:d.filter(C=>C.platform==="instagram"))||[],g=(d==null?void 0:d.filter(C=>C.platform==="linkedin"))||[],b=(d==null?void 0:d.filter(C=>C.platform==="google_business"))||[],v=((d==null?void 0:d.length)||0)>0,k=async(C,T)=>{l(C),c(null);try{const{data:M,error:P}=await U.functions.invoke("meta-api-test",{body:{testType:"all",accountId:C}});if(P)throw P;c(M.results||[]),re.success(M.summary||"API tests completed")}catch(M){console.error("Meta API test error:",M),re.error("Failed to run API tests")}finally{l(null)}};return e.jsx(Vs,{title:"Social Connections",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-pink-500 via-purple-500 to-blue-500 p-6 md:p-8 text-white",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs(qe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(yn,{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(_a,{className:"h-4 w-4"}),"Back to Social Swag"]}),v&&e.jsx(be,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Re,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(To,{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(be,{children:[e.jsx(Ft,{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(sx,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Facebook",e.jsx(qe,{variant:"outline",className:"text-amber-600 border-amber-200 bg-amber-50",children:"Coming Soon"})]}),e.jsx(fr,{children:"Facebook integration is coming soon — stay tuned!"})]})]})}),e.jsxs(Re,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ki,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):x.length>0?e.jsx("div",{className:"space-y-3",children:x.map(C=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:C.profile_picture_url||""}),e.jsx(Da,{children:e.jsx(sx,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.page_name||C.platform_username||"Facebook Page"}),e.jsx(qe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect Facebook?"}),e.jsx(xl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs(B,{disabled:!0,className:"w-full gap-2",variant:"outline",children:[e.jsx(Vr,{className:"h-4 w-4"}),"Coming Soon"]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{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(vm,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(Ut,{className:"text-lg flex items-center gap-2",children:["Instagram",e.jsx(qe,{variant:"outline",className:"text-amber-600 border-amber-200 bg-amber-50",children:"Coming Soon"})]}),e.jsx(fr,{children:"Instagram integration is coming soon — stay tuned!"})]})]})}),e.jsxs(Re,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ki,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):y.length>0?e.jsx("div",{className:"space-y-3",children:y.map(C=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:C.profile_picture_url||""}),e.jsx(Da,{children:e.jsx(vm,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",C.platform_username||"Instagram Account"]}),e.jsx(qe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect Instagram?"}),e.jsx(xl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs(B,{disabled:!0,className:"w-full gap-2",variant:"outline",children:[e.jsx(Vr,{className:"h-4 w-4"}),"Coming Soon"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Use Instagram login for Business or Creator accounts; Facebook Page login is only needed if you want to connect Pages."})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{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(ry,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:"LinkedIn"}),e.jsx(fr,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Re,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ki,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):g.length>0?e.jsx("div",{className:"space-y-3",children:g.map(C=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:C.profile_picture_url||""}),e.jsx(Da,{children:e.jsx(ry,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.platform_username||"LinkedIn Account"}),e.jsx(qe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect LinkedIn?"}),e.jsx(xl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs(B,{onClick:m,disabled:r,className:"w-full gap-2",variant:g.length>0?"outline":"default",children:[r?e.jsx(Ki,{className:"h-4 w-4 animate-spin"}):e.jsx(Js,{className:"h-4 w-4"}),g.length>0?"Reconnect LinkedIn":"Connect LinkedIn"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Share content directly to your LinkedIn profile"})]})]}),e.jsxs(be,{className:`relative overflow-hidden ${n?"":"opacity-75"}`,children:[!n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(qe,{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(qe,{variant:"secondary",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:"Admin Testing"})}),e.jsx(Ft,{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(oi,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:"Google Business"}),e.jsx(fr,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Re,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ki,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(C=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:C.profile_picture_url||""}),e.jsx(Da,{children:e.jsx(oi,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.page_name||C.platform_username||"Google Business"}),e.jsx(qe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Nl,{children:[e.jsx(yf,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})}),e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Disconnect Google Business?"}),e.jsx(xl,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:n?"No Google Business account connected yet":"Google Business Profile integration is coming soon!"}),e.jsxs(B,{onClick:n?p:void 0,disabled:!n||r,className:"w-full gap-2",variant:b.length>0?"outline":"default",children:[r?e.jsx(Ki,{className:"h-4 w-4 animate-spin"}):e.jsx(Js,{className:"h-4 w-4"}),b.length>0?"Reconnect Google Business":"Connect Google Business"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Post updates directly to your Google Business Profile"})]})]})]}),n&&(x.length>0||y.length>0)&&e.jsxs(be,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(Ft,{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(VT,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(fr,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:['Click "Run Tests" on an account to trigger API calls for: ',e.jsx("strong",{children:"public_profile"}),", ",e.jsx("strong",{children:"pages_show_list"}),", ",e.jsx("strong",{children:"pages_read_engagement"}),", ",e.jsx("strong",{children:"instagram_basic"}),", ",e.jsx("strong",{children:"pages_manage_posts"}),", and ",e.jsx("strong",{children:"instagram_content_publish"}),"."]}),e.jsxs("div",{className:"space-y-3",children:[x.map(C=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(sx,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:C.page_name||"Facebook Page"})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>k(C.id),disabled:i===C.id,children:i===C.id?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(VT,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${C.id}`)),y.map(C=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(vm,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",C.platform_username||"Instagram"]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>k(C.id),disabled:i===C.id,children:i===C.id?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(VT,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${C.id}`))]}),o&&o.length>0&&e.jsxs("div",{className:"mt-4 rounded-lg border bg-background p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:"Test Results"}),e.jsx("div",{className:"space-y-2",children:o.map((C,T)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[C.status==="success"?e.jsx(Rr,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):C.status==="pending"?e.jsx(Wt,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(Rd,{className:"h-4 w-4 text-red-600 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-mono text-xs bg-muted px-1 rounded",children:C.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:C.details})]})]},T))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Note: Facebook posts are auto-deleted. Instagram posts will remain and should be manually deleted. Allow up to 24 hours for Meta to register the API calls."})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-lg",children:"How it works"})}),e.jsx(Re,{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 sTn(){const[s]=dc(),t=Hn(),[n,r]=j.useState("loading"),a=j.useRef(!1),[i,l]=j.useState("Processing your connection..."),o=(()=>{const c=sessionStorage.getItem("social-connect-return-to");return c&&c.startsWith("/")&&!c.startsWith("/admin")?c:"/social-connections"})();return j.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var p;const d=s.get("code"),u=s.get("error"),h=s.get("error_description"),m=s.get("state");if(u){r("error"),l(h||"Authorization was denied"),re.error("Connection failed: "+(h||u));return}if(!d){r("error"),l("No authorization code received"),re.error("No authorization code received");return}try{const{data:x,error:y}=await U.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:d,state:m,callbackPath:"/social-connections/callback"}});if(y)throw y;if(x!=null&&x.success)r("success"),l(`Successfully connected ${((p=x.accounts)==null?void 0:p.length)||0} account(s)!`),re.success("Social accounts connected successfully!");else throw new Error((x==null?void 0:x.error)||"Unknown error")}catch(x){console.error("OAuth callback error:",x),r("error"),l(x instanceof Error?x.message:"Failed to connect accounts"),re.error("Failed to connect: "+(x instanceof Error?x.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(Ft,{className:"text-center",children:[n==="loading"&&e.jsx(Wt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(To,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Rd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Ut,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(fr,{children:i})]}),e.jsx(Re,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t(o),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function nTn(){const[s]=dc(),t=Hn(),[n,r]=j.useState("loading"),[a,i]=j.useState("Connecting your Google Business Profile...");return j.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),re.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),re.error("No authorization code received");return}try{const{data:h,error:m}=await U.functions.invoke("google-business-oauth",{body:{action:"exchange_code",code:o,state:u}});if(m)throw m;if(h!=null&&h.success)r("success"),i(h.message||"Successfully connected Google Business Profile!"),re.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"),re.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(Ft,{className:"text-center",children:[n==="loading"&&e.jsx(Wt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(To,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Rd,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Ut,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(fr,{children:a})]}),e.jsx(Re,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/social-connections"),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function rTn(){const[s]=dc(),t=Hn(),[n,r]=j.useState("loading"),[a,i]=j.useState("Connecting your LinkedIn account...");return j.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("state"),d=s.get("error"),u=s.get("error_description");if(d){console.error("LinkedIn OAuth error:",d,u),r("error"),i(u||"Failed to connect LinkedIn account"),re.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),re.error("No authorization code received");return}try{const{data:m,error:p}=await U.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(p)throw p;if(m!=null&&m.success)r("success"),i(`Successfully connected ${((h=m.accounts)==null?void 0:h.length)||1} LinkedIn account`),re.success("LinkedIn connected successfully!");else throw new Error((m==null?void 0:m.error)||"Failed to connect LinkedIn account")}catch(m){console.error("LinkedIn callback error:",m),r("error"),i(m instanceof Error?m.message:"Failed to connect LinkedIn account"),re.error("Failed to connect LinkedIn")}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-background",children:e.jsxs(be,{className:"w-full max-w-md",children:[e.jsxs(Ft,{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(Wt,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(To,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx(Rd,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(Ut,{className:"flex items-center justify-center gap-2",children:[e.jsx(ry,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(fr,{children:a})]}),e.jsx(Re,{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 aTn(){const s=Hn(),[t,n]=j.useState(null),{data:r,isLoading:a}=mBt(t||void 0,!0),{data:i,isLoading:l}=oYe(!0),{cartItems:o}=U3e(),c=o.reduce((u,h)=>u+h.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx(Vs,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(u=>e.jsx(gn,{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(gn,{className:"h-72 w-full"},u))})]})}):e.jsx(Vs,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),e.jsxs(B,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(ib,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(qe,{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(be,{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(Eu,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx(qe,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(Re,{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(Eu,{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 $Bt=j.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));$Bt.displayName="Breadcrumb";const UBt=j.forwardRef(({className:s,...t},n)=>e.jsx("ol",{ref:n,className:Et("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));UBt.displayName="BreadcrumbList";const k2e=j.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Et("inline-flex items-center gap-1.5",s),...t}));k2e.displayName="BreadcrumbItem";const TBe=j.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?dUe:"a";return e.jsx(a,{ref:r,className:Et("transition-colors hover:text-foreground",t),...n})});TBe.displayName="BreadcrumbLink";const qBt=j.forwardRef(({className:s,...t},n)=>e.jsx("span",{ref:n,role:"link","aria-disabled":"true","aria-current":"page",className:Et("font-normal text-foreground",s),...t}));qBt.displayName="BreadcrumbPage";const EBe=({children:s,className:t,...n})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Et("[&>svg]:size-3.5",t),...n,children:s??e.jsx(Qa,{})});EBe.displayName="BreadcrumbSeparator";function iTn(){var W,G;const{productId:s}=$i(),t=Hn(),{data:n,isLoading:r}=W3n(s||""),{addToCart:a,cartItems:i}=U3e(),[l,o]=j.useState(null),[c,d]=j.useState(1),[u,h]=j.useState(0),[m,p]=j.useState(null),[x,y]=j.useState(!1),[g,b]=j.useState(!1),v=(W=n==null?void 0:n.variants)==null?void 0:W.find(K=>K.id===l),k=((G=n==null?void 0:n.variants)==null?void 0:G.filter(K=>K.is_active))||[],C=Number((n==null?void 0:n.base_price)||0),T=v?Number(v.price_adjustment):0,M=C+T,P=Number((n==null?void 0:n.shipping_fee)||0),L=i.reduce((K,ee)=>K+ee.quantity,0),I=async K=>{if(!K.target.files||K.target.files.length===0)return;y(!0);const ee=K.target.files[0],J=ee.name.split(".").pop(),le=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${J}`;try{const{error:ue}=await U.storage.from("marketplace").upload(le,ee);if(ue)throw ue;const{data:{publicUrl:oe}}=U.storage.from("marketplace").getPublicUrl(le);p(oe),re.success("Artwork uploaded successfully")}catch(ue){re.error("Failed to upload artwork: "+ue.message)}finally{y(!1)}},O=()=>{if(n){if(k.length>0&&!l){re.error("Please select an option");return}a(n,v||void 0,c,m||void 0),b(!0),re.success("Added to cart!"),setTimeout(()=>b(!1),2e3)}},$=()=>{n!=null&&n.images&&h(K=>(K+1)%n.images.length)},q=()=>{n!=null&&n.images&&h(K=>(K-1+n.images.length)%n.images.length)};return r?e.jsx(Vs,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(gn,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(gn,{className:"h-8 w-3/4"}),e.jsx(gn,{className:"h-6 w-1/4"}),e.jsx(gn,{className:"h-24 w-full"}),e.jsx(gn,{className:"h-12 w-full"})]})]})}):n?e.jsxs(Vs,{title:n.name,children:[e.jsx($Bt,{className:"mb-6",children:e.jsxs(UBt,{children:[e.jsx(k2e,{children:e.jsx(TBe,{asChild:!0,children:e.jsx(Yn,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(EBe,{}),e.jsx(k2e,{children:e.jsx(TBe,{asChild:!0,children:e.jsx(Yn,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(EBe,{}),e.jsx(k2e,{children:e.jsx(qBt,{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:q,children:e.jsx(Cc,{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(Eu,{className:"h-24 w-24 text-muted-foreground"})})}),n.images&&n.images.length>1&&e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:n.images.map((K,ee)=>e.jsx("button",{onClick:()=>h(ee),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${ee===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:K.image_url,alt:"",className:"w-full h-full object-cover"})},K.id))}),n.video&&e.jsx(be,{children:e.jsxs(Re,{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(qe,{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:["$",M.toFixed(2)]}),P>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",P.toFixed(2)," shipping"]})]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})}),k.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.map(K=>e.jsxs(B,{variant:l===K.id?"default":"outline",onClick:()=>o(K.id),children:[K.name,Number(K.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(K.price_adjustment)>0?"+":"","$",Number(K.price_adjustment).toFixed(2),")"]})]},K.id))})]}),n.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Upload Your Artwork (Optional)"}),m?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:m,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx(B,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>p(null),children:"×"})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6",children:[e.jsx("input",{type:"file",accept:"image/*,.pdf,.ai,.eps",onChange:I,className:"hidden",id:"artwork-upload",disabled:x}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(Ja,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:x?"Uploading...":"Click to upload artwork"}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"Supported: JPG, PNG, PDF, AI, EPS"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(K=>Math.max(1,K-1)),children:"-"}),e.jsx(ye,{type:"number",value:c,onChange:K=>d(Math.max(1,parseInt(K.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(K=>K+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(B,{size:"lg",className:"flex-1",onClick:O,disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(ib,{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(ib,{className:"h-5 w-5"}),L>0&&e.jsx(qe,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:L})]})]}),n.requires_proof_approval&&e.jsx("p",{className:"text-sm text-muted-foreground bg-muted p-3 rounded-lg",children:"📋 This product requires proof approval before production. You'll receive a proof to review after your order is placed."})]})]})]}):e.jsx(Vs,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Eu,{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 oTn(){const s=Hn(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=U3e(),[d,u]=j.useState(!1),[h,m]=j.useState(""),p=async()=>{if(t.length===0){re.error("Your cart is empty");return}u(!0);try{const{data:x,error:y}=await U.functions.invoke("marketplace-checkout",{body:{items:t.map(g=>{var b;return{product_id:g.product.id,variant_id:((b=g.variant)==null?void 0:b.id)||null,quantity:g.quantity,artwork_url:g.artworkUrl||null}}),notes:h.trim()||null}});if(y)throw y;if(x!=null&&x.url)c(),window.open(x.url,"_blank");else throw new Error("No checkout URL received")}catch(x){re.error("Checkout failed: "+x.message)}finally{u(!1)}};return t.length===0?e.jsx(Vs,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(D5,{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(Vs,{title:"Shopping Cart",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[t.map(x=>{var y,g;return e.jsx(be,{children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"w-24 h-24 flex-shrink-0 bg-muted rounded-lg overflow-hidden",children:x.product.images&&x.product.images.length>0?e.jsx("img",{src:((y=x.product.images.find(b=>b.is_primary))==null?void 0:y.image_url)||x.product.images[0].image_url,alt:x.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(D5,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:x.product.name}),x.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:x.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(x).toFixed(2),Number(x.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(x.product.shipping_fee).toFixed(2)," shipping"]})]}),x.artworkUrl&&e.jsx("div",{className:"mt-2",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Artwork uploaded ✓"})})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var b;return n(x.product.id,(b=x.variant)==null?void 0:b.id)},children:e.jsx(Rn,{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 b;return r(x.product.id,(b=x.variant)==null?void 0:b.id,x.quantity-1)},disabled:x.quantity<=1,children:e.jsx(gN,{className:"h-3 w-3"})}),e.jsx(ye,{type:"number",value:x.quantity,onChange:b=>{var v;return r(x.product.id,(v=x.variant)==null?void 0:v.id,parseInt(b.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var b;return r(x.product.id,(b=x.variant)==null?void 0:b.id,x.quantity+1)},children:e.jsx(Js,{className:"h-3 w-3"})})]})]})]})})},`${x.product.id}-${((g=x.variant)==null?void 0:g.id)||"base"}`)}),e.jsx(B,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(be,{className:"sticky top-4",children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Order Summary"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((x,y)=>x+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(Xl,{}),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(Xl,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(Ds,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:h,onChange:x=>m(x.target.value),rows:3,className:"resize-none"})]}),e.jsx(B,{className:"w-full",size:"lg",onClick:p,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(Xa,{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 lTn(){const s=Hn(),{data:t,isLoading:n}=rCn();return n?e.jsx(Vs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(r=>e.jsx(gn,{className:"h-32 w-full"},r))})}):!t||t.length===0?e.jsx(Vs,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Eu,{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(Vs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(r=>{var a,i,l;return e.jsx(be,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${r.id}`),children:e.jsxs(Re,{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:Bs(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx(qe,{className:iYe[r.status],children:Uz[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 zgt=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function cTn({currentStatus:s,statusHistory:t}){const n=zgt.indexOf(s);return e.jsx("div",{className:"space-y-3",children:zgt.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(Rr,{className:"h-4 w-4"}):o?e.jsx(Vr,{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:Uz[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Bs(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function dTn(){var b;const{orderId:s}=$i(),t=Hn(),{data:n,isLoading:r,refetch:a}=aCn(s||""),i=lCn(),l=cCn(),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(""),[p,x]=j.useState(null),y=async v=>{x(v);try{await i.mutateAsync({orderId:s,itemId:v}),re.success("Proof approved!"),a()}catch{re.error("Failed to approve proof")}finally{x(null)}},g=async()=>{if(d){x(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),re.success("Revision requested"),c(!1),m(""),u(null),a()}catch{re.error("Failed to request revision")}finally{x(null)}}};return r?e.jsx(Vs,{title:"Order Details",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsx(gn,{className:"h-64 w-full"}),e.jsx(gn,{className:"h-48 w-full"})]}),e.jsx(gn,{className:"h-96 w-full"})]})}):n?e.jsxs(Vs,{title:`Order ${n.order_number}`,children:[e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsx(Ut,{children:"Order Status"}),e.jsx(qe,{className:iYe[n.status],children:Uz[n.status]})]}),e.jsx(Re,{children:e.jsx(cTn,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Items"})}),e.jsx(Re,{className:"space-y-4",children:(b=n.items)==null?void 0:b.map(v=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:v.product_name}),v.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:v.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",v.quantity," × $",Number(v.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(v.unit_price)*v.quantity).toFixed(2)]})]}),v.artwork_url&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your Artwork:"}),e.jsxs("a",{href:v.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(g3,{className:"h-4 w-4"}),"View Artwork",e.jsx(Tr,{className:"h-3 w-3"})]})]}),v.proof_url&&e.jsxs("div",{className:"bg-muted rounded-lg p-3",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Proof Ready for Review"}),e.jsxs("a",{href:v.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(g3,{className:"h-4 w-4"}),"View Proof",e.jsx(Tr,{className:"h-3 w-3"})]}),v.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",onClick:()=>y(v.id),disabled:p===v.id,children:[p===v.id?e.jsx(Wt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(mg,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{u(v.id),c(!0)},disabled:p===v.id,children:[e.jsx(hK,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),v.proof_status==="approved"&&e.jsxs(qe,{className:"bg-green-100 text-green-800",children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),v.proof_status==="rejected"&&v.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(qe,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.proof_notes})]})]})]},v.id))})]}),n.shipping_name&&e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(pK,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Re,{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(be,{className:"sticky top-4",children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Order Summary"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",Bs(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(Xl,{}),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(Xl,{}),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(Xl,{}),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(Fs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Request Changes"}),e.jsx(kr,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Ds,{placeholder:"Describe the changes needed...",value:h,onChange:v=>m(v.target.value),rows:4}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:g,disabled:!h.trim()||p!==null,children:[p?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(Vs,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Eu,{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 uTn(){const s=Hn(),[t]=dc();return t.get("session_id"),j.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(Vs,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(be,{children:e.jsxs(Re,{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(Rr,{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(Eu,{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(Xa,{className:"h-4 w-4 ml-2"})]}),e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function hTn(){const{user:s}=Ns(),[t,n]=j.useState("store"),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(5),[h,m]=j.useState(""),[p,x]=j.useState(!1),[y,g]=j.useState(!1),[b,v]=j.useState(""),[k,C]=j.useState(null),[T,M]=j.useState(!1),{hasSubmittedReview:P,submitReview:L,markPostedToGoogle:I}=NCt(),{data:O}=fBt(),{data:$,isLoading:q}=pBt(),{data:W,isLoading:G}=xCn(r),{data:K,isLoading:ee}=gCn(s==null?void 0:s.id),{data:J=0}=vCn(s==null?void 0:s.id),le=bCn(),ue=new Set((K==null?void 0:K.map(fe=>fe.item_id))||[]),oe=async()=>{if(i)try{const fe=await le.mutateAsync(i.id);i.item_type==="reelflow_credits"?re.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):re.success(`Successfully purchased "${i.name}"!`),l(null)}catch(fe){re.error(fe.message||"Failed to purchase item")}},ie=async()=>{if(!h.trim()){re.error("Please write a review");return}x(!0);const fe=await L(d,h);x(!1),fe.success?(re.success("Thank you for your review! You earned 25 points!"),v(h),g(!0),m(""),u(5)):re.error(fe.error||"Failed to submit review")},de=()=>{navigator.clipboard.writeText(b),re.success("Review copied to clipboard!")},we=()=>{I(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},je=()=>{g(!1),c(!1),v("")};return q||G||ee?e.jsx(Vs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(gn,{className:"h-24 w-full"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(fe=>e.jsx(gn,{className:"h-64"},fe))})]})}):e.jsxs(Vs,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Reward Store"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Redeem your points for exclusive rewards"})]}),e.jsx(be,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Re,{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:J.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-6 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ll,{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(Fd,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(i0,{open:T,onOpenChange:M,children:e.jsxs(be,{className:"border-primary/20",children:[e.jsx(o0,{asChild:!0,children:e.jsx(Ft,{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(ll,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ut,{className:"text-base",children:"How to Earn Points"}),e.jsx(fr,{children:"See all the ways you can earn spendable points"})]})]}),T?e.jsx(Qy,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(Po,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(l0,{children:e.jsx(Re,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[O==null?void 0:O.filter(fe=>fe.is_active).map(fe=>{const Se=Ee=>{switch(Ee){case"event_attendance":return e.jsx(ra,{className:"h-5 w-5"});case"leave_review":return e.jsx(Wa,{className:"h-5 w-5"});case"add_listing":return e.jsx(ia,{className:"h-5 w-5"});case"first_contact":return e.jsx(Bn,{className:"h-5 w-5"});case"first_video":return e.jsx(Zr,{className:"h-5 w-5"});case"first_community_post":return e.jsx(ro,{className:"h-5 w-5"});default:return e.jsx(zo,{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(fe.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:fe.action_name}),fe.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:fe.description})]}),e.jsxs(qe,{variant:"secondary",className:"font-bold shrink-0",children:["+",fe.points]})]},fe.id)}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-orange-500/10 border border-orange-500/20",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/20 flex items-center justify-center text-orange-500 shrink-0",children:e.jsx(Fd,{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(qe,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!P&&e.jsx(be,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Re,{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(ro,{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(fa,{value:t,onValueChange:n,children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"store",className:"flex items-center gap-2",children:[e.jsx(D5,{className:"h-4 w-4"}),"Store"]}),e.jsxs(ss,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(Eu,{className:"h-4 w-4"}),"My Rewards",K&&K.length>0&&e.jsx(qe,{variant:"secondary",className:"ml-1",children:K.length})]})]}),e.jsxs(ns,{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(fe=>e.jsxs(B,{variant:r===fe.id?"default":"outline",size:"sm",onClick:()=>a(fe.id),children:[fe.icon&&`${fe.icon} `,fe.name]},fe.id))]}),!W||W.length===0?e.jsx(be,{children:e.jsx(Re,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(zo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No items available"}),e.jsx("p",{className:"text-sm",children:"Check back later for new rewards!"})]})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:W.map(fe=>{const Se=fe.item_type==="reelflow_credits",Ee=!Se&&ue.has(fe.id),Le=!Se&&fe.max_quantity!==null&&fe.current_quantity===0,De=J>=fe.points_cost;return e.jsxs(be,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${Ee?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>C(fe),children:[fe.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:fe.preview_image_url,alt:fe.name,className:"w-full h-full object-cover"}),Ee&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(qe,{className:"bg-green-500 text-white",children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Le&&!Ee&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(qe,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(zo,{className:"h-12 w-12 text-muted-foreground/50"}),Ee&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(qe,{className:"bg-green-500 text-white",children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(Ft,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(Ut,{className:"text-lg",children:fe.name}),e.jsxs(qe,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(Wa,{className:"h-3 w-3 mr-1"}),fe.points_cost]})]}),fe.category&&e.jsxs(qe,{variant:"outline",className:"w-fit",children:[fe.category.icon&&`${fe.category.icon} `,fe.category.name]})]}),e.jsxs(Re,{children:[e.jsx(fr,{className:"mb-4 line-clamp-2",children:fe.description||"No description available"}),fe.max_quantity!==null&&!Ee&&!Se&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[fe.current_quantity," of ",fe.max_quantity," remaining"]}),Se&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",fe.max_quantity," ReelFlow credits per purchase"]}),Ee?e.jsx(B,{className:"w-full",onClick:Be=>{Be.stopPropagation(),fe.file_url&&XIe(fe.file_url,fe.name)},disabled:!fe.file_url,children:fe.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(ii,{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(fe)},disabled:Le||!De,children:Le?"Sold Out":De?e.jsxs(e.Fragment,{children:[e.jsx(D5,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${fe.points_cost-J} more pts`})]})]},fe.id)})})]}),e.jsx(ns,{value:"my-rewards",className:"mt-6",children:!K||K.length===0?e.jsx(be,{children:e.jsx(Re,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Eu,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No rewards yet"}),e.jsx("p",{className:"text-sm",children:"Purchase items from the store to see them here!"})]})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:K.map(fe=>{var Se,Ee,Le,De,Be,Ne,Ge;return e.jsxs(be,{className:"overflow-hidden",children:[(Se=fe.item)!=null&&Se.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:fe.item.preview_image_url,alt:((Ee=fe.item)==null?void 0:Ee.name)||"Reward",className:"w-full h-full object-cover"})}):e.jsx("div",{className:"aspect-video bg-muted flex items-center justify-center",children:e.jsx(zo,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(Ft,{className:"pb-2",children:[e.jsx(Ut,{className:"text-lg",children:((Le=fe.item)==null?void 0:Le.name)||"Unknown Item"}),e.jsxs(fr,{className:"text-xs",children:["Purchased for ",fe.points_spent," points • ",new Date(fe.purchased_at).toLocaleDateString()]})]}),e.jsx(Re,{children:((De=fe.item)==null?void 0:De.item_type)==="reelflow_credits"?e.jsxs(B,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(Rr,{className:"h-4 w-4 mr-2 text-green-500"}),(Be=fe.item)==null?void 0:Be.max_quantity," Credits Applied"]}):e.jsx(B,{className:"w-full",onClick:()=>{var _e,Oe;(_e=fe.item)!=null&&_e.file_url&&XIe(fe.item.file_url,(Oe=fe.item)==null?void 0:Oe.name)},disabled:!((Ne=fe.item)!=null&&Ne.file_url),children:((Ge=fe.item)==null?void 0:Ge.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(ii,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},fe.id)})})})]})]}),e.jsx(Nl,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Confirm Purchase"}),e.jsxs(xl,{children:['Are you sure you want to purchase "',i==null?void 0:i.name,'" for ',i==null?void 0:i.points_cost," points?",(i==null?void 0:i.item_type)==="reelflow_credits"&&e.jsxs(e.Fragment,{children:[e.jsx("br",{}),e.jsx("br",{}),"🎬 ",e.jsxs("strong",{children:[i==null?void 0:i.max_quantity," ReelFlow credits"]})," will be added to your balance instantly."]}),e.jsx("br",{}),e.jsx("br",{}),"You currently have ",e.jsxs("strong",{children:[J," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[J-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:oe,disabled:le.isPending,children:le.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(Fs,{open:o,onOpenChange:fe=>{!fe&&y?je():c(fe)},children:e.jsx(Os,{children:y?e.jsxs(e.Fragment,{children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Rr,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(kr,{children:"Would you also share your review on Google? It helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-muted p-4 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your review:"}),e.jsxs("p",{className:"text-sm italic",children:['"',b,'"']})]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:de,children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(Nr,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(B,{variant:"outline",onClick:je,children:"Maybe Later"}),e.jsxs(B,{onClick:we,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($s,{children:[e.jsx(zs,{children:"Leave a Review"}),e.jsx(kr,{children:"Share your experience with LevelUp and earn 25 spendable points!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Rating"}),e.jsx("div",{className:"flex gap-1",children:[1,2,3,4,5].map(fe=>e.jsx("button",{type:"button",onClick:()=>u(fe),className:"focus:outline-none",children:e.jsx(Wa,{className:`h-8 w-8 transition-colors ${d>=fe?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},fe))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(Ds,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:h,onChange:fe=>m(fe.target.value),rows:4})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:ie,disabled:p,className:"bg-yellow-600 hover:bg-yellow-700",children:p?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(Fs,{open:!!k,onOpenChange:()=>C(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[k==null?void 0:k.name,e.jsxs(qe,{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(qe,{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(Nr,{children:k&&k.item_type!=="reelflow_credits"&&ue.has(k.id)?e.jsx(B,{className:"w-full",onClick:()=>{k.file_url&&XIe(k.file_url,k.name)},disabled:!k.file_url,children:k.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(ii,{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:()=>{C(null),l(k)},disabled:k.item_type!=="reelflow_credits"&&k.max_quantity!==null&&k.current_quantity===0||J{s&&ee()},[s==null?void 0:s.id]);const ee=async()=>{if(!s)return;o(!0),b(!1),y(!0);const{data:Be}=await U.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);Be==null||Be.forEach(Oe=>{Oe.action_key==="referral_signup"&&h(Oe.points),Oe.action_key==="referral_paid"&&p(Oe.points)});const{data:Ne}=await U.from("profiles").select("name").eq("id",s.id).maybeSingle();Ne!=null&&Ne.name&&k(Ne.name);let{data:Ge}=await U.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Ge){const{data:Oe}=await U.rpc("generate_agent_referral_code",{_user_id:s.id}),Ae=Oe||`agent${s.id.slice(0,6)}`,{data:Xe,error:Ue}=await U.from("agent_referral_codes").insert({user_id:s.id,code:Ae}).select("code").maybeSingle();!Ue&&Xe&&(Ge=Xe)}i((Ge==null?void 0:Ge.code)??null);const{data:_e}=await U.from("agent_referrals").select("id, referred_user_id, status, signed_up_at, qualified_at, signup_points_awarded, paid_points_awarded").eq("referrer_user_id",s.id).order("signed_up_at",{ascending:!1});if(_e&&_e.length>0){const Oe=_e.map(Ue=>Ue.referred_user_id),{data:Ae}=await U.from("profiles").select("id, name, email").in("id",Oe),Xe=new Map((Ae==null?void 0:Ae.map(Ue=>[Ue.id,Ue]))??[]);d(_e.map(Ue=>({...Ue,referred_profile:Xe.get(Ue.referred_user_id)??null})))}else d([]);o(!1)},J=j.useMemo(()=>a?`${mTn}/trial?ref=${a}`:"",[a]),le=c.length,ue=c.filter(Be=>Be.status==="qualified").length,oe=c.filter(Be=>Be.signup_points_awarded).length*u+c.filter(Be=>Be.paid_points_awarded).length*m,ie=async()=>{J&&(await navigator.clipboard.writeText(J),re.success("Referral link copied!"))},de=()=>{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: ${J} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${Be}&body=${Ne}`},we=()=>{const Be=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${J}`);window.location.href=`sms:?&body=${Be}`},je=async()=>{if(navigator.share&&J)try{await navigator.share({title:"Join me on LevelUp",text:"I use LevelUp to grow my real estate business — try it with my link:",url:J})}catch{}else ie()},xe=Be=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Be.trim()),fe=Be=>{const Ne=(Be??M).trim().replace(/,$/,"");if(!Ne)return;const Ge=Ne.split(/[\s,;]+/).filter(Boolean),_e=[...L];let Oe=0;for(const Ae of Ge){if(!xe(Ae)){re.error(`Invalid email: ${Ae}`);continue}_e.includes(Ae)||(_e.push(Ae),Oe++)}I(_e),Oe>0&&P("")},Se=Be=>I(L.filter(Ne=>Ne!==Be)),Ee=()=>{W(`${v?v.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)},Le=Be=>{const Ne=Be.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Ge=v||"A fellow agent",_e="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",Oe=J;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:
${Oe}

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

`.trim()},De=async()=>{if(L.length===0&&(M.trim()&&fe(),L.length===0)){re.error("Add at least one recipient");return}if(!q.trim()){re.error("Subject is required");return}K(!0);const Be=Le(O);let Ne=0,Ge=0;for(const _e of L)try{const{data:Oe,error:Ae}=await U.functions.invoke("gmail-send",{body:{to:_e,subject:q,body:Be,source:"referral_invite"}});if(Ae||Oe!=null&&Oe.error)throw new Error((Ae==null?void 0:Ae.message)||(Oe==null?void 0:Oe.error));Ne++}catch(Oe){console.error("Gmail send failed for",_e,Oe),Ge++}K(!1),Ne>0?(re.success(`Invite sent to ${Ne} ${Ne===1?"person":"people"}`+(Ge>0?` (${Ge} failed)`:"")),I([]),P(""),T(!1)):re.error("Failed to send invites")};return!g&&!x?e.jsx(Vs,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(ql,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(be,{className:"border-2 border-dashed",children:[e.jsxs(Ft,{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(du,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(Ut,{children:"Refer & Earn is for active members"}),e.jsx(fr,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Re,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(Vs,{title:"Refer & Earn",children:[e.jsxs("div",{className:"container max-w-5xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs(ql,{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(zo,{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(be,{children:e.jsxs(Re,{className:"p-4 flex items-center gap-3",children:[e.jsx(Bn,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:le}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(be,{children:e.jsxs(Re,{className:"p-4 flex items-center gap-3",children:[e.jsx(Rr,{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(be,{children:e.jsxs(Re,{className:"p-4 flex items-center gap-3",children:[e.jsx(ll,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:oe.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(fr,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(ye,{readOnly:!0,value:l?"Loading…":J,className:"font-mono text-sm",onFocus:Be=>Be.currentTarget.select()}),e.jsxs(B,{onClick:ie,disabled:!J,children:[e.jsx(ja,{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:Ee,disabled:!J,className:"bg-primary hover:bg-primary/90",children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:de,disabled:!J,children:[e.jsx(on,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:we,disabled:!J,children:[e.jsx(ro,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:je,disabled:!J,children:[e.jsx(zd,{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(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Your Referrals"}),e.jsx(fr,{children:"Track who joined and when they upgrade."})]}),e.jsx(Re,{children:l?e.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:"Loading…"}):c.length===0?e.jsxs("div",{className:"text-center py-10 space-y-2",children:[e.jsx(Bn,{className:"h-10 w-10 mx-auto text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No referrals yet. Share your link to get started!"})]}):e.jsx("div",{className:"divide-y",children:c.map(Be=>{var _e,Oe;const Ne=((_e=Be.referred_profile)==null?void 0:_e.name)||((Oe=Be.referred_profile)==null?void 0:Oe.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(qe,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(Rr,{className:"h-3 w-3 mr-1"})," Paid · +",u+m," pts"]}):e.jsxs(qe,{variant:"secondary",children:[e.jsx(Vr,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},Be.id)})})})]}),e.jsx(be,{className:"bg-muted/30",children:e.jsxs(Re,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(yn,{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(Xl,{className:"opacity-0"})]}),e.jsx(Fs,{open:C,onOpenChange:T,children:e.jsxs(Os,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(kr,{children:["Sending from ",e.jsx("span",{className:"font-medium text-foreground",children:r}),". We'll deliver a branded LevelUp invite with your personal note."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipients"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-2 border rounded-md min-h-[44px] bg-background",children:[L.map(Be=>e.jsxs(qe,{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(dr,{className:"h-3 w-3"})})]},Be)),e.jsx("input",{type:"email",value:M,onChange:Be=>P(Be.target.value),onKeyDown:Be=>{Be.key==="Enter"||Be.key===","||Be.key===" "?(Be.preventDefault(),fe()):Be.key==="Backspace"&&!M&&L.length>0&&I(L.slice(0,-1))},onBlur:()=>M.trim()&&fe(),onPaste:Be=>{const Ne=Be.clipboardData.getData("text");/[\s,;]/.test(Ne)&&(Be.preventDefault(),fe(Ne))},placeholder:L.length===0?"name@example.com, another@example.com":"Add another…",className:"flex-1 min-w-[160px] bg-transparent outline-none text-sm"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Press Enter, comma, or space to add. You can paste multiple emails at once."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"email-subject",children:"Subject"}),e.jsx(ye,{id:"email-subject",value:q,onChange:Be=>W(Be.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(Ds,{id:"personal-note",value:O,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(se,{children:"Preview"}),e.jsxs("div",{className:"border rounded-md overflow-hidden bg-muted/30",children:[e.jsxs("div",{className:"px-3 py-2 bg-muted/60 border-b text-xs text-muted-foreground flex items-center justify-between",children:[e.jsxs("span",{className:"truncate",children:["From: ",r]}),e.jsxs("span",{className:"truncate ml-2",children:["Subject: ",q||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Le(O),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>T(!1),disabled:G,children:"Cancel"}),e.jsxs(B,{onClick:De,disabled:G,children:[e.jsx(Dr,{className:"h-4 w-4 mr-2"}),G?"Sending…":`Send${L.length>0?` to ${L.length}`:""}`]})]})]})})]})}const VBt=()=>{const{user:s}=Ns(),t=as(),n=mt({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await U.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(u)throw u;return d||[]},enabled:!!s}),r=mt({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await U.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(u)throw u;return d||[]},enabled:!!s}),a=vt({mutationFn:async d=>{const{data:u,error:h}=await U.from("smart_presentations").insert({owner_user_id:s.id,...d}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),i=vt({mutationFn:async({id:d,...u})=>{const{data:h,error:m}=await U.from("smart_presentations").update(u).eq("id",d).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=vt({mutationFn:async d=>{const{data:u,error:h}=await U.from("smart_presentations").update({status:"published",published_at:new Date().toISOString()}).eq("id",d).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),re.success("Presentation published!")}}),o=vt({mutationFn:async d=>{const{error:u}=await U.from("smart_presentations").update({status:"archived"}).eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),re.success("Presentation archived")}}),c=vt({mutationFn:async d=>{const{error:u}=await U.from("smart_presentation_templates").insert({owner_user_id:s.id,name:d.title+" Template",description:"Created from "+d.title,template_type:"custom",icon:"📄",sections:d.sections,cta_config:{type:d.cta_type,label:d.cta_label},is_system:!1});if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),re.success("Saved as template!")}});return{presentations:n.data||[],templates:r.data||[],isLoading:n.isLoading,templatesLoading:r.isLoading,createPresentation:a,updatePresentation:i,publishPresentation:l,archivePresentation:o,saveAsTemplate:c}},fTn=()=>{const s=Hn(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=VBt(),i=o=>o.status==="draft"?e.jsx(qe,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(qe,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(qe,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(qe,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),re.success("Link copied!")};return e.jsx(Vs,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-serif font-bold text-foreground",children:"Smart Presentations"})}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create personalized, video-first presentations for your clients"})]}),e.jsxs(B,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(gn,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(be,{children:e.jsxs(Re,{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(yb,{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(Js,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(be,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Re,{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($r,{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 ",Bs(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ma,{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(ja,{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(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(W0,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(wa,{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(wa,{onClick:()=>a.mutate(o),children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(wa,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(gm,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},Bgt={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."}]},xTn=[{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 gTn(s){const t=Bgt[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(Bgt))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return xTn}function yTn({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=j.useState(!1),[i,l]=j.useState("script"),[o,c]=j.useState(0),[d,u]=j.useState(0),{canRecord:h}=bRt(),m=hS(),[p,x]=j.useState(""),[y,g]=j.useState(!1),[b,v]=j.useState(!0),[k,C]=j.useState(!1),[T,M]=j.useState(null),P=gTn(s),L=()=>{l("script"),c(0),u(0),x(""),g(!1),v(!0),C(!1),M(null)},I=G=>{!G&&(i==="uploading"||i==="processing")||(a(G),G||L())},O=G=>{M(G),x(P[G].text),g(!1)},$=()=>{l("record"),v(p.trim().length>0)},q=()=>{x(""),v(!1),l("record")},W=j.useCallback(async(G,K)=>{l("uploading");try{const ee=s||"Presentation Video",{videoId:J,uploadUrl:le,libraryId:ue}=await w6(ee),{apiKey:oe}=await j6(J),ie=new XMLHttpRequest;ie.upload.onprogress=fe=>{fe.lengthComputable&&c(fe.loaded/fe.total*100)},await new Promise((fe,Se)=>{ie.onload=()=>ie.status>=200&&ie.status<300?fe():Se(new Error("Upload failed")),ie.onerror=()=>Se(new Error("Upload failed")),ie.open("PUT",le),ie.setRequestHeader("AccessKey",oe),ie.send(G)}),l("processing");let de=0;const we=Date.now(),je=9e4;let xe=null;for(;de<4;){if(await new Promise(Se=>setTimeout(Se,3e3)),Date.now()-we>je){const Se=G.size/1048576,Ee=`https://iframe.mediadelivery.net/embed/${ue}/${J}?responsive=true`;await m.mutateAsync({bunny_video_id:J,playback_url:Ee,file_size_mb:Se,title:ee,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(Ee),re.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const fe=await $j(J);if(de=fe.status,u(fe.encodeProgress||0),de===4)xe={playbackUrl:fe.directPlayUrl,thumbnailUrl:fe.thumbnailUrl,previewUrl:fe.previewUrl||null,duration:fe.length||K,fileSizeMb:(fe.storageSize||G.size)/(1024*1024)};else if(de===5||de===6)throw new Error("Video processing failed")}if(!xe)throw new Error("No video data");await m.mutateAsync({bunny_video_id:J,contact_id:t||void 0,playback_url:xe.playbackUrl,thumbnail_url:xe.thumbnailUrl,preview_url:xe.previewUrl,duration_seconds:xe.duration,file_size_mb:xe.fileSizeMb,title:ee,status:"ready",touch_type:"presentation"}),n(xe.playbackUrl),re.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(ee){console.error("Recording upload error:",ee),re.error("Failed to process video. Please try again."),l("record")}},[s,t,n,m]);return e.jsxs(Fs,{open:r,onOpenChange:I,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto !top-[5%] !translate-y-0 sm:!top-[5%] sm:!translate-y-0",children:[e.jsx($s,{children:e.jsxs(zs,{children:[i==="script"&&`Prepare your script for "${s}"`,i==="record"&&`Record video for "${s}"`,i==="uploading"&&"Uploading...",i==="processing"&&"Processing...",i==="done"&&"Done!"]})}),i==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a starter script below, edit it to make it yours, or skip and speak freely."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Starter Scripts"}),e.jsx("div",{className:"grid gap-2",children:P.map((G,K)=>e.jsxs("button",{onClick:()=>O(K),className:Et("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",T===K?"border-primary bg-primary/5 ring-1 ring-primary":"border-border"),children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx($r,{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})]},K))})]}),p&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Your Script"}),!y&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>g(!0),className:"h-7 text-xs gap-1",children:[e.jsx(Za,{className:"h-3 w-3"}),"Edit"]})]}),y?e.jsx(Ds,{value:p,onChange:G=>x(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:p})]}),!p&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Or Write Your Own"}),e.jsx(Ds,{value:p,onChange:G=>{x(G.target.value),M(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:q,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx(B,{onClick:$,disabled:!1,children:p.trim()?"Continue with Script":"Continue Without Script"})]})]}),!h&&i==="record"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx(hd,{className:"h-10 w-10 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You've reached your video storage limit. Delete some videos to free up space."})]}):i==="record"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Record up to 5 minutes. Saved to your library & auto-attached."}),p.trim()&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>v(!b),className:"h-7 text-xs gap-1",children:[b?e.jsx(n0,{className:"h-3 w-3"}):e.jsx(ma,{className:"h-3 w-3"}),b?"Hide Script":"Show Script"]})]}),e.jsx(k6,{maxDurationSeconds:600,onRecordingComplete:W,onRecordingStateChange:C,onError:G=>re.error(G),teleprompterContent:p.trim()?e.jsx(eYe,{text:p,isVisible:b,onToggleVisibility:()=>v(!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(Wt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(qi,{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(Wt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(qi,{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(To,{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 vTn({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState("idle"),[d,u]=j.useState(0),h=j.useRef(null),m=hS(),{data:p}=RAe(),x=(p==null?void 0:p.total_storage_mb)||0,g=((p==null?void 0:p.max_storage_mb)||1024)-x,b=()=>{l(null),c("idle"),u(0)},v=P=>{!P&&o!=="idle"&&o!=="done"||(a(P),P||b())},k=P=>{var O;const L=(O=P.target.files)==null?void 0:O[0];if(!L)return;if(!L.type.startsWith("video/")){re.error("Please select a video file");return}const I=L.size/(1024*1024);if(I>500){re.error("Video file must be less than 500MB");return}if(I>g){re.error(`Not enough storage. You have ${g.toFixed(1)} MB remaining.`);return}l(L)},C=j.useCallback(async()=>{if(i){c("creating"),u(0);try{const P=s||i.name,{data:L,error:I}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:P,isAgentVideo:!0}});if(I)throw new Error(I.message);const{videoId:O,libraryId:$}=L;c("uploading");const{data:q,error:W}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:O,isAgentVideo:!0}});if(W)throw new Error(W.message);await new Promise((ee,J)=>{const le=new XMLHttpRequest;le.upload.addEventListener("progress",ue=>{ue.lengthComputable&&u(Math.round(ue.loaded/ue.total*100))}),le.addEventListener("load",()=>le.status>=200&&le.status<300?ee():J(new Error(`Upload failed (${le.status})`))),le.addEventListener("error",()=>J(new Error("Upload failed"))),le.open("PUT",q.uploadUrl),le.setRequestHeader("AccessKey",q.apiKey),le.send(i)}),c("processing");const G=i.size/(1024*1024),K=`https://iframe.mediadelivery.net/embed/${$}/${O}`;await m.mutateAsync({bunny_video_id:O,playback_url:K,file_size_mb:G,title:P,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(K),c("done"),re.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(P){console.error("Upload error:",P),re.error(P instanceof Error?P.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""}},M=o!=="idle"&&o!=="done";return e.jsxs(Fs,{open:r,onOpenChange:v,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(Ja,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx($s,{children:e.jsxs(zs,{children:['Upload Video for "',s,'"']})}),e.jsxs("div",{className:"space-y-4 py-2",children:[i?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(Zr,{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"]})]}),!M&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(dr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"border-2 border-dashed border-muted-foreground/25 rounded-lg p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",onClick:()=>{var P;return(P=h.current)==null?void 0:P.click()},children:[e.jsx(Ja,{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:M}),M&&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(Wt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:T()})]}),e.jsx(qi,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),disabled:M,children:"Cancel"}),e.jsx(B,{onClick:C,disabled:!i||M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const $gt=[{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"}],Ugt=()=>{const s=Hn(),{id:t}=$i(),{user:n}=Ns(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=VBt(),{isGmailConnected:c,gmailEmail:d}=Tf(),[u,h]=j.useState(!1),[m,p]=j.useState("client"),[x,y]=j.useState(!1),[g,b]=j.useState(""),[v,k]=j.useState([]),[C,T]=j.useState(!1),[M,P]=j.useState(null),[L,I]=j.useState(!1),[O,$]=j.useState(""),[q,W]=j.useState(""),[G,K]=j.useState(""),[ee,J]=j.useState("buyer"),[le,ue]=j.useState(""),[oe,ie]=j.useState(null),[de,we]=j.useState(""),[je,xe]=j.useState([]),[fe,Se]=j.useState("schedule_call"),[Ee,Le]=j.useState("Schedule a Call"),[De,Be]=j.useState(""),[Ne,Ge]=j.useState(""),[_e,Oe]=j.useState(null),[Ae,Xe]=j.useState(t||null),[Ue,Ze]=j.useState(null),[Qe,Ye]=j.useState(!1),nt=async(jt,Qs)=>{if(!n)return;const cn=5*1024*1024;if(jt.size>cn){re.error("Image must be under 5MB");return}if(!jt.type.startsWith("image/")){re.error("Please upload an image file");return}Oe(Qs);try{const qt=jt.name.split(".").pop()||"jpg",Gs=`${n.id}/${Date.now()}.${qt}`,{error:Ls}=await U.storage.from("listing-photos").upload(Gs,jt);if(Ls)throw Ls;const{data:{publicUrl:sn}}=U.storage.from("listing-photos").getPublicUrl(Gs);zt(Qs,{image_url:sn}),re.success("Image uploaded")}catch{re.error("Failed to upload image")}finally{Oe(null)}};j.useEffect(()=>{t&&rt(t)},[t]);const rt=async jt=>{const{data:Qs,error:cn}=await U.from("smart_presentations").select("*").eq("id",jt).single();if(cn||!Qs)return;const qt=Qs;if(y(!0),we(qt.title),$(qt.client_name||""),ue(qt.property_address||""),xe(qt.sections||[]),Se(qt.cta_type||"schedule_call"),Le(qt.cta_label||"Schedule a Call"),Be(qt.cta_url||""),Ge(qt.heading||""),Ze(qt.share_token),Ye(qt.status==="published"),Xe(qt.id),p("builder"),qt.contact_id){const{data:Gs}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",qt.contact_id).maybeSingle();Gs&&(P(Gs),W(Gs.email||""),K(Gs.phone||""))}};j.useEffect(()=>{if(!n||g.length<1){k([]);return}const jt=setTimeout(async()=>{T(!0);const{data:Qs}=await U.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",n.id).or(`first_name.ilike.%${g}%,last_name.ilike.%${g}%,email.ilike.%${g}%`).limit(10);k(Qs||[]),T(!1)},300);return()=>clearTimeout(jt)},[g,n]);const Fe=jt=>{P(jt),$(`${jt.first_name} ${jt.last_name||""}`.trim()),W(jt.email||""),K(jt.phone||""),I(!1)},dt=async()=>{if(!O.trim()){re.error("Client name is required");return}const jt=O.trim().split(" "),Qs=jt[0],cn=jt.slice(1).join(" ")||null,{data:qt,error:Gs}=await U.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:Qs,last_name:cn,email:q||null,phone:G||null,lead_source:"Smart Presentation"}).select().single();if(Gs){re.error("Failed to create client");return}P(qt),re.success("Client created & saved to Agent OS"),p("template")},Dt=jt=>{ie(jt);const Qs=(jt.sections||[]).map(cn=>({...cn,is_visible:!0,video_url:"",text:""}));if(xe(Qs),we(jt.name+(O?` for ${O}`:"")),jt.cta_config){const cn=jt.cta_config;Se(cn.type||"schedule_call"),Le(cn.label||"Schedule a Call")}p("builder")},pt=()=>{xe([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),we(O?`Presentation for ${O}`:"New Presentation"),p("builder")},zt=(jt,Qs)=>{xe(cn=>cn.map((qt,Gs)=>Gs===jt?{...qt,...Qs}:qt))},Gt=jt=>{zt(jt,{is_visible:!je[jt].is_visible})},qs=()=>{xe(jt=>[...jt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},As=jt=>{xe(Qs=>Qs.filter((cn,qt)=>qt!==jt))},Bt=async()=>{if(!de.trim()){re.error("Title is required");return}try{if(Ae){const jt=await l.mutateAsync({id:Ae,title:de,sections:je,client_name:O,property_address:le||null,cta_type:fe,cta_label:Ee,cta_url:De||null,heading:Ne||null});re.success("Saved")}else{const jt=await i.mutateAsync({title:de,contact_id:(M==null?void 0:M.id)||void 0,client_name:O,property_address:le||void 0,template_id:(oe==null?void 0:oe.id)||void 0,sections:je,cta_type:fe,cta_label:Ee,cta_url:De||void 0,heading:Ne||void 0});Xe(jt.id),Ze(jt.share_token),re.success("Presentation created!")}}catch(jt){console.error("Failed to save presentation:",jt);const Qs=(jt==null?void 0:jt.message)||(jt==null?void 0:jt.toString())||"Unknown error";re.error(`Failed to save: ${Qs}`)}},At=async()=>{try{await Bt();const jt=Ae;if(jt){const Qs=await o.mutateAsync(jt);Ze(Qs.share_token),Ye(!0),p("share")}}catch(jt){console.error("Failed to publish presentation:",jt),re.error(`Failed to publish: ${(jt==null?void 0:jt.message)||"Unknown error"}`)}},Is=Ue?`https://presentations.relevelup.com/${Ue}`:"";return e.jsx(Vs,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-serif font-bold text-foreground",children:x?"Edit Presentation":"Create Smart Presentation"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[m==="client"&&"Who is this presentation for?",m==="template"&&"Choose a starting template",m==="builder"&&"Customize your presentation",m==="share"&&"Share with your client"]})]})]}),!x&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((jt,Qs)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Et("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",m===jt?"bg-primary text-primary-foreground":Qs<["client","template","builder","share"].indexOf(m)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:Qs<["client","template","builder","share"].indexOf(m)?e.jsx(da,{className:"h-4 w-4"}):Qs+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:jt}),Qs<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},jt))}),m==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{P(null),$(""),W(""),K(""),I(!1),p("template")},className:"w-full group flex items-center justify-between gap-4 rounded-xl border border-dashed border-primary/30 bg-primary/5 hover:bg-primary/10 transition-all p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Dr,{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(Xa,{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(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Re,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:g,onChange:jt=>b(jt.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[C&&e.jsx(gn,{className:"h-12 w-full"}),v.map(jt=>e.jsxs("button",{onClick:()=>Fe(jt),className:Et("w-full text-left p-3 rounded-lg border transition-colors",(M==null?void 0:M.id)===jt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[jt.first_name," ",jt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:jt.email||jt.phone||"No contact info"})]},jt.id)),!g&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),g&&v.length===0&&!C&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),M&&e.jsxs(B,{onClick:()=>p("template"),className:"w-full gap-2",children:["Continue with ",M.first_name,e.jsx(Xa,{className:"h-4 w-4"})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(Sl,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Re,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{className:"text-xs",children:"Name *"}),e.jsx(ye,{value:O,onChange:jt=>{$(jt.target.value),I(!0),P(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Email"}),e.jsx(ye,{value:q,onChange:jt=>W(jt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Phone"}),e.jsx(ye,{value:G,onChange:jt=>K(jt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Client Type"}),e.jsxs(vs,{value:ee,onValueChange:J,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"buyer",children:"Buyer"}),e.jsx(Je,{value:"seller",children:"Seller"}),e.jsx(Je,{value:"recruit",children:"Recruit"}),e.jsx(Je,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Property Address"}),e.jsx(ye,{value:le,onChange:jt=>ue(jt.target.value),placeholder:"Optional"})]})]}),L&&O&&e.jsxs(B,{onClick:dt,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(Xa,{className:"h-4 w-4"})]})]})]})]})]}),m==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fa,{defaultValue:"system",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"mine",children:"My Core Templates"}),e.jsx(ss,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(ss,{value:"blank",children:"+ Start Blank"})]}),e.jsx(ns,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(jt=>e.jsx(gn,{className:"h-32"},jt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(jt=>!jt.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(jt=>!jt.is_system).map(jt=>e.jsx(qgt,{template:jt,onSelect:Dt},jt.id))})}),e.jsx(ns,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(jt=>jt.is_system).map(jt=>e.jsx(qgt,{template:jt,onSelect:Dt},jt.id))})}),e.jsx(ns,{value:"blank",className:"mt-4",children:e.jsx(be,{children:e.jsxs(Re,{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:pt,children:"Start from Scratch"})]})})})]}),e.jsxs(B,{variant:"outline",onClick:()=>p("client"),className:"gap-2",children:[e.jsx(_a,{className:"h-4 w-4"}),"Back"]})]}),m==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(be,{children:e.jsxs(Re,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Presentation Title"}),e.jsx(ye,{value:de,onChange:jt=>we(jt.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Page Heading"}),e.jsx(ye,{value:Ne,onChange:jt=>Ge(jt.target.value),placeholder:O?`Welcome, ${O}!`:"e.g. Welcome! or Your Custom Listing Plan"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:['The main heading visitors see. Leave blank for "Welcome, ',"",'!"']})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Client Name"}),e.jsx(ye,{value:O,onChange:jt=>$(jt.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Property Address"}),e.jsx(ye,{value:le,onChange:jt=>ue(jt.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:qs,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:je.map((jt,Qs)=>e.jsx(be,{className:Et(!jt.is_visible&&"opacity-50"),children:e.jsx(Re,{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(Fp,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:jt.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ye,{value:jt.title,onChange:cn=>zt(Qs,{title:cn.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:()=>Gt(Qs),children:jt.is_visible?e.jsx(ma,{className:"h-4 w-4"}):e.jsx(n0,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>As(Qs),className:"text-destructive hover:text-destructive",children:e.jsx(Rn,{className:"h-4 w-4"})})]})]}),e.jsx(ye,{value:jt.description||"",onChange:cn=>zt(Qs,{description:cn.target.value}),placeholder:"Section description...",className:"text-sm"}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{className:"text-xs",children:"Video URL"}),e.jsx(ye,{value:jt.video_url||"",onChange:cn=>zt(Qs,{video_url:cn.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(yTn,{sectionTitle:jt.title,contactId:M==null?void 0:M.id,onVideoReady:cn=>zt(Qs,{video_url:cn})}),e.jsx(vTn,{sectionTitle:jt.title,contactId:M==null?void 0:M.id,onVideoReady:cn=>zt(Qs,{video_url:cn})}),e.jsx(LO,{userId:n==null?void 0:n.id,onSelect:cn=>zt(Qs,{video_url:cn})})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),jt.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:jt.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:()=>zt(Qs,{image_url:""}),children:e.jsx(dr,{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:[_e===Qs?e.jsx(Wt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(a1,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:_e===Qs?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:_e===Qs,onChange:cn=>{var Gs;const qt=(Gs=cn.target.files)==null?void 0:Gs[0];qt&&nt(qt,Qs),cn.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Text (optional)"}),e.jsx(Kj,{content:jt.text||"",onChange:cn=>zt(Qs,{text:cn}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},Qs))})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Call to Action"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"CTA Type"}),e.jsxs(vs,{value:fe,onValueChange:jt=>{Se(jt);const Qs=$gt.find(cn=>cn.value===jt);Qs&&Le(Qs.label)},children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:$gt.map(jt=>e.jsx(Je,{value:jt.value,children:jt.label},jt.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Button Label"}),e.jsx(ye,{value:Ee,onChange:jt=>Le(jt.target.value)})]}),e.jsxs("div",{children:[e.jsxs(se,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(ye,{value:De,onChange:jt=>Be(jt.target.value),placeholder:"https://calendly.com/..."}),!De&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Without a URL, clients will see a contact form — their info gets added to your contacts and you'll receive an email notification."})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[!x&&e.jsxs(B,{variant:"outline",onClick:()=>p("template"),className:"gap-2",children:[e.jsx(_a,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx(B,{variant:"outline",onClick:Bt,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(B,{onClick:At,disabled:o.isPending,className:"gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),Qe?"Update & Reshare":"Publish & Share"]})]})]})]}),m==="share"&&Ue&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(be,{children:e.jsxs(Re,{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(da,{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 ",O||"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(ye,{value:Is,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(B,{onClick:()=>{navigator.clipboard.writeText(Is),re.success("Link copied!")},children:e.jsx(ja,{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 jt=`Hi ${O||""}! I put together something for you — check it out: ${Is}`;navigator.clipboard.writeText(jt),re.success("Message copied!")},children:[e.jsx(ro,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs(B,{variant:"outline",className:"gap-2",onClick:()=>{c?h(!0):window.open(`mailto:${q||""}?subject=${encodeURIComponent(de)}&body=${encodeURIComponent(`Hi ${(M==null?void 0:M.first_name)||(O==null?void 0:O.split(" ")[0])||""}, I put together a personalized presentation for you: ${Is} Looking forward to connecting!`)}`)},children:[e.jsx(on,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(cw,{open:u,onOpenChange:h,contact:M?{id:M.id,first_name:M.first_name,last_name:M.last_name,email:q||M.email||""}:q?{id:"",first_name:(O==null?void 0:O.split(" ")[0])||"",last_name:(O==null?void 0:O.split(" ").slice(1).join(" "))||"",email:q}:void 0,defaultSubject:de,defaultBody:`Hi ${(M==null?void 0:M.first_name)||(O==null?void 0:O.split(" ")[0])||""}, I put together a personalized presentation for you: ${Is} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(B,{variant:"outline",onClick:()=>p("builder"),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(B,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},qgt=({template:s,onSelect:t})=>e.jsx(be,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Re,{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(qe,{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"})]})}),bTn=()=>{var y;const{shareToken:s}=$i(),[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(0),[o,c]=j.useState(!1);j.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),j.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:g,error:b}=await U.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(b||!g){c(!0),a(!1);return}const{data:v}=await U.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",g.owner_user_id).single();let k;if(v!=null&&v.brokerage_id){const{data:T}=await U.from("brokerages").select("name").eq("id",v.brokerage_id).single();k=(T==null?void 0:T.name)||void 0}let C=null;if(g.contact_id){const{data:T}=await U.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",g.contact_id).single();C=T}n({...g,owner_name:v==null?void 0:v.name,owner_email:v==null?void 0:v.email,owner_phone:v==null?void 0:v.phone,owner_avatar:v==null?void 0:v.avatar_url,owner_title:(v==null?void 0:v.title)||void 0,brokerage_name:k,contact_name:C?[C.first_name,C.last_name].filter(Boolean).join(" "):void 0,contact_email:(C==null?void 0:C.email)||void 0,contact_phone:(C==null?void 0:C.phone)||void 0}),a(!1);try{await U.rpc("log_presentation_view",{p_presentation_id:g.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await U.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}};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(gn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(gn,{className:"h-64 w-full"}),e.jsx(gn,{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(g=>g.is_visible!==!1),m=h[i],p=g=>{const b=g.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(b)return`https://www.youtube.com/embed/${b[1]}?rel=0`;if(g.includes("iframe.mediadelivery.net/play/")){const C=g.replace("/play/","/embed/"),T=C.includes("?")?"&":"?";return`${C}${T}responsive=true`}if(g.includes("iframe.mediadelivery.net")){if(g.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const T=g.includes("?")?"&":"?";return`${g}${T}responsive=true`}return""}const v=g.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(v)return`https://www.loom.com/embed/${v[1]}`;const k=g.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return k?`https://iframe.mediadelivery.net/embed/${k[1]}/${k[2]}?responsive=true`:g},x=!!((y=t.cta_url)!=null&&y.trim());return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})]})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[m!=null&&m.video_url&&p(m.video_url)?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:p(m.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):m!=null&&m.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:m.image_url,alt:m.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:m==null?void 0:m.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:m==null?void 0:m.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:m==null?void 0:m.description})]}),(m==null?void 0:m.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:m.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:h.map((g,b)=>e.jsx("button",{onClick:()=>l(b),className:Et("w-full text-left p-4 rounded-xl border transition-all",i===b?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(b+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:g.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:g.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:g.description})]})]})},b))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),x?e.jsxs(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(o5t,{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"})]})},JIe="__none__";function _Tn({value:s,onChange:t}){const{data:n=[],isLoading:r}=QJ(),a=wWe(),[i,l]=j.useState(!1),o=j.useMemo(()=>n.filter(h=>!h.is_starter),[n]),c=j.useMemo(()=>n.find(h=>h.is_starter&&/open house/i.test(h.name||"")),[n]),d=j.useMemo(()=>o.some(h=>/open house/i.test(h.name||"")),[o]),u=async()=>{if(c){l(!0);try{const h=await a.mutateAsync(c.id);h!=null&&h.id&&t(h.id),ba({title:"Open House Follow-Up added",description:"The 6-email sequence is now in your library and selected here."})}catch(h){ba({title:"Could not add campaign",description:(h==null?void 0:h.message)??"Please try again.",variant:"destructive"})}finally{l(!1)}}};return e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/20 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(nE,{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(qe,{variant:"outline",className:"text-[10px] border-emerald-300 bg-emerald-500/10 text-emerald-700",children:"On"})]}),e.jsxs(vs,{value:s??JIe,onValueChange:h=>t(h===JIe?null:h),disabled:r,children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"No follow-up campaign"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:JIe,children:"No follow-up campaign"}),o.map(h=>e.jsxs(Je,{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(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(yn,{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 wTn({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=rds(s),i=lds(),l=cds(),o=dds(),c=uds(),[d,u]=j.useState(""),[h,m]=j.useState("rating"),p=async b=>{n(b),b&&(!r||r.length===0)&&await c.mutateAsync(s)},x=async()=>{if(!d.trim())return;const b=(r==null?void 0:r.reduce((v,k)=>Math.max(v,k.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:h,question_text:d.trim(),sort_order:b+1}),u("")},y=async b=>{await l.mutateAsync({id:b.id,open_house_id:s,is_active:!b.is_active})},g=async b=>{await o.mutateAsync({id:b.id,open_house_id:s})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(r1,{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(Mn,{checked:t,onCheckedChange:p})]}),t&&e.jsx("div",{className:"space-y-3 pt-2 border-t border-border",children:a?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Wt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:r==null?void 0:r.map(b=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Fp,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm truncate",children:b.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:b.question_type.replace("_"," ")})]}),e.jsx(Mn,{checked:b.is_active,onCheckedChange:()=>y(b),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>g(b),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]},b.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(ye,{value:d,onChange:b=>u(b.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:b=>b.key==="Enter"&&x()})]}),e.jsxs(vs,{value:h,onValueChange:m,children:[e.jsx(gs,{className:"w-28 h-9 text-xs",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"rating",children:"Rating"}),e.jsx(Je,{value:"open_text",children:"Text"})]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:x,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(Js,{className:"h-3.5 w-3.5"})})]})]})})]})}function jTn({openHouseId:s}){const{user:t}=Ns(),{data:n=[],isLoading:r}=fds(s),a=gds(),[i,l]=j.useState(""),[o,c]=j.useState(!1),d=async()=>{const u=i.trim();if(u){c(!0);try{await a.mutateAsync({open_house_id:s,name:u,sort_order:n.length}),l("")}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos. Visitors swipe through them on mobile and tab through them on desktop."})]}),r?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(Wt,{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(NTn,{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(ye,{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(Wt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function NTn({room:s,index:t,total:n,userId:r,openHouseId:a}){const i=yds(),l=vds(),o=bds(),c=_ds(),d=j.useRef(null),[u,h]=j.useState(!0),[m,p]=j.useState(s.name),[x,y]=j.useState(s.description||""),[g,b]=j.useState(!1),v=j.useMemo(()=>s.media.filter(I=>I.kind==="video"&&I.agent_video_id).map(I=>I.agent_video_id),[s.media]),{data:k={}}=mt({queryKey:["room-video-statuses",s.id,v.join(",")],enabled:v.length>0,queryFn:async()=>{const{data:I,error:O}=await U.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",v);if(O)throw O;const $=I||[],q=$.filter(G=>G.status==="processing"&&G.bunny_video_id);await Promise.all(q.map(async G=>{try{const{data:K}=await U.functions.invoke("bunny-upload",{body:{action:"status",videoId:G.bunny_video_id,isAgentVideo:!0}});K&&K.status===4&&(await U.from("agent_videos").update({status:"ready",playback_url:K.directPlayUrl,thumbnail_url:K.thumbnailUrl,preview_url:K.previewUrl,duration_seconds:K.length||void 0,updated_at:new Date().toISOString()}).eq("id",G.id),G.status="ready",G.thumbnail_url=K.thumbnailUrl,G.preview_url=K.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:I=>{const O=I.state.data;return O?Object.values(O).some($=>$.status!=="ready"&&$.status!=="failed")?5e3:!1:5e3}}),C=()=>{m.trim()&&m!==s.name&&i.mutate({id:s.id,open_house_id:a,name:m.trim()})},T=()=>{x!==(s.description||"")&&i.mutate({id:s.id,open_house_id:a,description:x.trim()||null})},M=async()=>{await Bi(`Delete "${s.name}" and all its media?`)&&l.mutate({id:s.id,open_house_id:a})},P=I=>{i.mutate({id:s.id,open_house_id:a,sort_order:t+I})},L=async I=>{const O=Array.from(I.target.files||[]);if(!(!O.length||!r)){b(!0);try{for(const $ of O){const q=$.type.startsWith("video/"),W=q?500*1024*1024:15*1024*1024;if($.size>W){ba({title:`${$.name} is too large`,description:q?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(q){try{const le=`${s.name} – ${$.name.replace(/\.[^/.]+$/,"")}`,{data:ue,error:oe}=await U.functions.invoke("bunny-upload",{body:{action:"create",title:le,isAgentVideo:!0}});if(oe||!ue)throw new Error((oe==null?void 0:oe.message)||"Could not start upload");const{videoId:ie,libraryId:de}=ue,{data:we,error:je}=await U.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ie,isAgentVideo:!0}});if(je||!we)throw new Error((je==null?void 0:je.message)||"Could not get upload URL");await new Promise((Le,De)=>{const Be=new XMLHttpRequest;Be.addEventListener("load",()=>{Be.status>=200&&Be.status<300?Le():De(new Error(`Upload failed (${Be.status})`))}),Be.addEventListener("error",()=>De(new Error("Upload failed"))),Be.open("PUT",we.uploadUrl),Be.setRequestHeader("AccessKey",we.apiKey),Be.send($)});const xe=`https://iframe.mediadelivery.net/embed/${de}/${ie}`,fe=$.size/(1024*1024),{data:Se,error:Ee}=await U.from("agent_videos").insert({owner_user_id:r,bunny_video_id:ie,playback_url:xe,file_size_mb:fe,title:le,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(Ee)throw Ee;await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:xe,sort_order:s.media.length,agent_video_id:Se.id}),ba({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(le){ba({title:"Video upload failed",description:(le==null?void 0:le.message)||"Try again",variant:"destructive"})}continue}const G=$.name.split(".").pop()||"jpg",K=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${G}`,{error:ee}=await U.storage.from("open-house-tour-media").upload(K,$,{upsert:!1,contentType:$.type});if(ee){ba({title:"Upload failed",description:ee.message,variant:"destructive"});continue}const{data:J}=U.storage.from("open-house-tour-media").getPublicUrl(K);await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:J.publicUrl,sort_order:s.media.length})}}finally{b(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:"rounded-lg border border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[e.jsx(Fp,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>h(I=>!I),className:"flex-1 text-left text-sm font-medium truncate",children:[s.name," ",e.jsxs("span",{className:"text-muted-foreground font-normal text-xs",children:["· ",s.media.length," ",s.media.length===1?"item":"items"]})]}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>P(-1),disabled:t===0,children:e.jsx(Qy,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>P(1),disabled:t===n-1,children:e.jsx(Po,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:M,children:e.jsx(Rn,{className:"h-4 w-4"})})]}),u&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(ye,{value:m,onChange:I=>p(I.target.value),onBlur:C,placeholder:"Room name",className:"h-9"}),e.jsx(Ds,{value:x,onChange:I=>y(I.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(I=>{const O=I.agent_video_id?k[I.agent_video_id]:void 0,$=O==null?void 0:O.status,q=I.kind==="video"&&$&&$!=="ready"&&$!=="failed",W=I.kind==="video"&&$==="failed",G=(O==null?void 0:O.thumbnail_url)||(O==null?void 0:O.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[I.kind==="video"?e.jsxs(e.Fragment,{children:[G?e.jsx("img",{src:G,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(I.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:I.url,className:"w-full h-full object-cover"}),!q&&!W&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(Zr,{className:"h-6 w-6 text-white"})}),q&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-black/70 text-white gap-1 pointer-events-none",children:[e.jsx(Wt,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),W&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-destructive/80 text-white text-[10px] font-medium uppercase tracking-wide pointer-events-none px-2 text-center",children:"Failed"})]}):e.jsx("img",{src:I.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>c.mutate({id:I.id,open_house_id:a}),className:"absolute top-1 right-1 w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition",children:e.jsx(dr,{className:"h-3.5 w-3.5"})})]},I.id)})}),e.jsx("input",{ref:d,type:"file",accept:"image/*,video/*",multiple:!0,onChange:L,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{var I;return(I=d.current)==null?void 0:I.click()},disabled:g,className:"flex-1",children:g?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(LO,{userId:r,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async I=>{try{await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:I.playback_url||"",sort_order:s.media.length,agent_video_id:I.id}),ba({title:"Video added to room"})}catch(O){ba({title:"Failed to add video",description:O==null?void 0:O.message,variant:"destructive"})}}})]})]})]})}function kTn({open:s,onOpenChange:t,openHouse:n}){const r=c5t(),{user:a}=Ns(),i=j.useRef(null),l=j.useRef(null),o=j.useRef(null),c=n.kind==="virtual",[d,u]=j.useState(n.auto_forward_to_card??!1),[h,m]=j.useState(n.disclosure_pdf_url??""),[p,x]=j.useState(n.enable_survey??!1),[y,g]=j.useState(n.ask_visitor_intent??!0),[b,v]=j.useState(n.ask_visitor_address??!1),[k,C]=j.useState(n.photo_url??""),[T,M]=j.useState(!1),[P,L]=j.useState(!1),[I,O]=j.useState(!1),[$,q]=j.useState(n.hero_video_url??""),[W,G]=j.useState(!1),[K,ee]=j.useState(n.price!=null?String(n.price):""),[J,le]=j.useState(n.beds!=null?String(n.beds):""),[ue,oe]=j.useState(n.baths!=null?String(n.baths):""),[ie,de]=j.useState(n.sqft!=null?String(n.sqft):""),[we,je]=j.useState(n.enable_question??!0),[xe,fe]=j.useState(n.enable_showing??!0),[Se,Ee]=j.useState(n.enable_disclosures??!0),[Le,De]=j.useState(n.enable_offer??!0),[Be,Ne]=j.useState(n.brand_color_override??""),[Ge,_e]=j.useState(n.property_description??""),[Oe,Ae]=j.useState(n.drip_campaign_id??null),Xe=async rt=>{var Gt;const Fe=(Gt=rt.target.files)==null?void 0:Gt[0];if(!Fe||!a)return;if(Fe.size>200*1024*1024){ba({title:"Video must be under 200MB",variant:"destructive"});return}if(!Fe.type.startsWith("video/")){ba({title:"Please upload a video file",variant:"destructive"});return}G(!0);const dt=Fe.name.split(".").pop()||"mp4",Dt=`${a.id}/${n.id}/hero-${Date.now()}.${dt}`,{error:pt}=await U.storage.from("open-house-tour-media").upload(Dt,Fe,{upsert:!0,contentType:Fe.type});if(pt){ba({title:"Upload failed",description:pt.message,variant:"destructive"}),G(!1);return}const{data:zt}=U.storage.from("open-house-tour-media").getPublicUrl(Dt);q(zt.publicUrl),G(!1),ba({title:"Video uploaded!"})},Ue=async rt=>{var Gt;const Fe=(Gt=rt.target.files)==null?void 0:Gt[0];if(!Fe||!a)return;if(Fe.size>10*1024*1024){ba({title:"Image must be under 10MB",variant:"destructive"});return}if(!Fe.type.startsWith("image/")){ba({title:"Please upload an image file",variant:"destructive"});return}L(!0);const dt=Fe.name.split(".").pop()||"jpg",Dt=`${a.id}/${n.id}-${Date.now()}.${dt}`,{error:pt}=await U.storage.from("open-house-photos").upload(Dt,Fe,{upsert:!0});if(pt){ba({title:"Upload failed",description:pt.message,variant:"destructive"}),L(!1);return}const{data:zt}=U.storage.from("open-house-photos").getPublicUrl(Dt);C(zt.publicUrl),L(!1),ba({title:"Photo updated!"})},Ze=()=>{C(""),l.current&&(l.current.value="")},Qe=async rt=>{var zt;const Fe=(zt=rt.target.files)==null?void 0:zt[0];if(!Fe||!a)return;if(Fe.size>20*1024*1024){ba({title:"File must be under 20MB",variant:"destructive"});return}if(Fe.type!=="application/pdf"){ba({title:"Only PDF files are accepted",variant:"destructive"});return}M(!0);const dt=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:Dt}=await U.storage.from("open-house-photos").upload(dt,Fe,{upsert:!0});if(Dt){ba({title:"Upload failed",description:Dt.message,variant:"destructive"}),M(!1);return}const{data:pt}=U.storage.from("open-house-photos").getPublicUrl(dt);m(pt.publicUrl),M(!1),ba({title:"PDF uploaded!"})},Ye=()=>{m(""),i.current&&(i.current.value="")},nt=async()=>{O(!0);try{const rt={id:n.id,auto_forward_to_card:d,disclosure_pdf_url:h||null,enable_survey:p,ask_visitor_intent:y,ask_visitor_address:b,photo_url:k||null,drip_campaign_id:Oe};c&&(rt.hero_video_url=$||null,rt.price=K.trim()?Number(K):null,rt.beds=J.trim()?parseInt(J,10):null,rt.baths=ue.trim()?Number(ue):null,rt.sqft=ie.trim()?parseInt(ie,10):null,rt.enable_question=we,rt.enable_showing=xe,rt.enable_disclosures=Se,rt.enable_offer=Le,rt.brand_color_override=Be.trim()||null,rt.property_description=Ge.trim()||null),await r.mutateAsync(rt),ba({title:"Settings saved!"}),t(!1)}catch{ba({title:"Failed to save",variant:"destructive"})}finally{O(!1)}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(kr,{className:"truncate",children:n.property_address})]}),e.jsxs("div",{className:"space-y-6 pt-2",children:[c&&e.jsxs(e.Fragment,{children:[n.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Zr,{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(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>q(""),children:e.jsx(dr,{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(Wt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(jTn,{openHouseId:n.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Property Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(ye,{type:"number",value:K,onChange:rt=>ee(rt.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(ye,{type:"number",value:ie,onChange:rt=>de(rt.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(ye,{type:"number",value:J,onChange:rt=>le(rt.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(ye,{type:"number",step:"0.5",value:ue,onChange:rt=>oe(rt.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Property Description"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Showcase the home — features, finishes, location highlights. Shown on the virtual tour page below the headline."}),e.jsx(Ds,{value:Ge,onChange:rt=>_e(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(se,{className:"text-sm font-medium",children:"Visitor Actions"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Choose what visitors can do during the tour."}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Ask a question"}),e.jsx(Mn,{checked:we,onCheckedChange:je})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(Mn,{checked:xe,onCheckedChange:fe})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(Mn,{checked:Se,onCheckedChange:Ee})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(Mn,{checked:Le,onCheckedChange:De})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Brand Accent Color"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Used for highlights and CTA buttons on your virtual tour page. Leave blank to use the default."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:Be||"#0f172a",onChange:rt=>Ne(rt.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(ye,{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(se,{className:"text-sm font-medium",children:"Property Photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown on the sign-in screen and printable QR sheet"}),e.jsx("input",{ref:l,type:"file",accept:"image/*",onChange:Ue,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:P,children:[P?e.jsx(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ja,{className:"h-3.5 w-3.5 mr-1"}),P?"":"Replace"]}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:Ze,children:e.jsx(dr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=l.current)==null?void 0:rt.click()},disabled:P,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:P?e.jsx(Wt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ac,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx(_Tn,{value:Oe,onChange:Ae}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Auto-forward to Digital Card"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"After check-in, redirect visitors to your digital business card"})]}),e.jsx(Mn,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-sm font-medium",children:"Seller's Disclosures (PDF)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visitors can view or download this on the thank you screen after check-in"}),e.jsx("input",{ref:i,type:"file",accept:"application/pdf",onChange:Qe,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($r,{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:Ye,children:e.jsx(dr,{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(Wt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload PDF (max 20MB)"})]})})]}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(se,{className:"text-sm font-medium",children:'Ask "What brings you here?"'}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show the buying / selling / browsing question after sign-in. Turn off to let visitors check in without picking an option."})]}),e.jsx(Mn,{checked:y,onCheckedChange:g})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(se,{className:"text-sm font-medium",children:"Ask for visitor's home address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds an optional address field to the sign-in form — helpful for follow-up and market reports."})]}),e.jsx(Mn,{checked:b,onCheckedChange:v})]})}),e.jsx(wTn,{openHouseId:n.id,enableSurvey:p,onToggleSurvey:x}),e.jsx(B,{onClick:nt,disabled:I,className:"w-full",children:I?"Saving...":"Save Settings"})]})]})})}const HBt={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function STn({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:HBt[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 CTn({openHouseId:s}){const{data:t,isLoading:n}=ods(s),{data:r}=l5t(s),a=j.useMemo(()=>{const h={};return r==null||r.forEach(m=>{h[m.id]=m}),h},[r]);if(n||!t)return null;const{questions:i,responses:l}=t;if(i.length===0)return null;const o=i.filter(h=>h.question_type==="rating"),c=i.filter(h=>h.question_type!=="rating"),d=[...new Set(l.map(h=>h.visitor_id))],u=d.length;return u===0?e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(r1,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Re,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(be,{children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(r1,{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(Re,{children:e.jsxs(fa,{defaultValue:"summary",children:[e.jsxs(xa,{className:"mb-4",children:[e.jsxs(ss,{value:"summary",className:"text-xs gap-1",children:[e.jsx(ol,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(ss,{value:"individual",className:"text-xs gap-1",children:[e.jsx(Eo,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(ns,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(STn,{question:h,responses:l},h.id)),c.map(h=>{const m=l.filter(p=>p.question_id===h.id&&p.text_value);return m.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:h.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:m.map(p=>{const x=a[p.visitor_id];return e.jsxs("div",{className:"text-sm p-2 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-muted-foreground text-xs",children:[x?`${x.first_name} ${x.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:p.text_value})]},p.id)})})]},h.id)})]}),e.jsx(ns,{value:"individual",className:"space-y-4",children:d.map(h=>{const m=a[h],p=l.filter(x=>x.visitor_id===h);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[m?`${m.first_name} ${m.last_name||""}`.trim():"Unknown Visitor",(m==null?void 0:m.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:m.email})]}),e.jsx("div",{className:"space-y-1",children:p.map(x=>{const y=i.find(g=>g.id===x.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:x.rating_value!=null?HBt[x.rating_value]||x.rating_value:x.text_value})]},x.id):null})})]},h)})})]})})]})}const ATn={question:{label:"Question",icon:ro,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:ra,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:$r,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:Od,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},Vgt={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 TTn({openHouseId:s}){const{data:t=[],isLoading:n}=wds(s),r=jds(),[a,i]=j.useState(null),[l,o]=j.useState("all"),c=t.filter(h=>l==="all"?!0:l==="new"?h.status==="new":h.action_type===l),d={all:t.length,new:t.filter(h=>h.status==="new").length,question:t.filter(h=>h.action_type==="question").length,showing:t.filter(h=>h.action_type==="showing").length,disclosure:t.filter(h=>h.action_type==="disclosure").length,offer:t.filter(h=>h.action_type==="offer").length},u=(h,m)=>{r.mutate({id:h,status:m,open_house_id:s})};return n?e.jsx("div",{className:"text-sm text-muted-foreground py-4",children:"Loading leads…"}):e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 bg-muted/40 border-b flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(WT,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(qe,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(qe,{className:"bg-emerald-600 hover:bg-emerald-600",children:[d.new," new"]})]}),e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:[["all","All",d.all],["new","New",d.new],["offer","Hot",d.offer],["showing","Showings",d.showing],["question","Questions",d.question],["disclosure","Docs",d.disclosure]].map(([h,m,p])=>e.jsxs("button",{onClick:()=>o(h),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===h?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[m," ",e.jsx("span",{className:"opacity-60",children:p})]},h))})]}),c.length===0?e.jsx("div",{className:"px-4 py-10 text-center text-sm text-muted-foreground",children:t.length===0?"No leads yet. Share your virtual open house link to start capturing leads.":"No leads match this filter."}):e.jsx("ul",{className:"divide-y",children:c.map(h=>{const m=ATn[h.action_type],p=m.icon,x=h.payload||{},y=a===h.id,g=h.status==="contacted",b=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${b?"opacity-60":""} ${h.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(y?null:h.id),className:"w-full text-left px-4 py-3 flex items-start gap-3 hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${m.bg}`,children:e.jsx(p,{className:`h-4 w-4 ${m.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:x.visitor_name||"Visitor"}),e.jsx(qe,{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"}),g&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(Rr,{className:"h-3 w-3"}),"Contacted"]})]}),x.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',x.message,'"']}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),Bs(new Date(h.created_at),"MMM d, h:mm a")]}),x.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(on,{className:"h-3 w-3"}),x.email]}),x.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pa,{className:"h-3 w-3"}),x.phone]})]})]}),y?e.jsx(Po,{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:[x.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',x.message,'"']}),Object.keys(Vgt).some(v=>x[v]!=null&&x[v]!==""&&!(Array.isArray(x[v])&&x[v].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(Vgt).map(([v,k])=>{const C=x[v];return C==null||C===""||Array.isArray(C)&&C.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:k}),e.jsx("div",{className:"font-medium",children:Array.isArray(C)?C.join(", "):String(C)})]},v)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[x.email&&e.jsx("a",{href:`mailto:${x.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs(B,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(on,{className:"h-3.5 w-3.5"}),"Reply"]})}),x.phone&&e.jsx("a",{href:`tel:${String(x.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(pa,{className:"h-3.5 w-3.5"}),"Call"]})}),!g&&e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(Rr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),b?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(gm,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}function ETn({open:s,onOpenChange:t,openHouse:n}){const{isGmailConnected:r,gmailEmail:a}=Tf(),i=ei(),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[x,y]=j.useState(""),[g,b]=j.useState(""),[v,k]=j.useState(""),[C,T]=j.useState(!1),[M,P]=j.useState(!1),[L,I]=j.useState(!1),O=`https://guestbook.relevelup.com/${n.slug}`;j.useEffect(()=>{s&&(b(`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){p(!0);try{const{data:ue,error:oe}=await U.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(oe)throw oe;o(ue||[])}catch{re.error("Failed to load contacts")}finally{p(!1)}}},q=ue=>`${ue.first_name} ${ue.last_name||""}`.trim(),W=ue=>{d(oe=>oe.find(ie=>ie.id===ue.id)?oe.filter(ie=>ie.id!==ue.id):[...oe,ue])},G=()=>{const ue=x.trim();if(!ue)return;if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ue)){re.error("Invalid email");return}d(ie=>[...ie,{id:`manual-${ue}`,first_name:ue.split("@")[0],last_name:null,email:ue}]),y("")},K=j.useMemo(()=>c.filter(ue=>!!ue.email).map(ue=>({email:ue.email,name:q(ue)})),[c]),ee=ue=>{const oe=ue?`Hi ${ue},`:"Hi there,",ie=v.split(/\n\n+/).map(de=>`

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

`).join("");return`

${oe}

${ie}

▶ Start Virtual Tour

Or copy this link: ${O}

`},J=async()=>{var ue;if(K.length===0){re.error("Add at least one recipient");return}P(!0);try{if(C&&r){let oe=0;for(const ie of K){const{data:de,error:we}=await U.functions.invoke("gmail-send",{body:{to:ie.email,subject:g,body:ee((ue=ie.name)==null?void 0:ue.split(" ")[0])}});!we&&(de!=null&&de.success)?oe+=1:console.warn("gmail-send error",we,de)}if(oe===0)throw new Error("Gmail send failed");re.success(`Sent to ${oe} of ${K.length} via Gmail`)}else{const{data:oe,error:ie}=await U.functions.invoke("send-virtual-tour-invite",{body:{openHouseId:n.id,recipients:K,subject:g,personalMessage:v}});if(ie)throw ie;if(!(oe!=null&&oe.success))throw new Error((oe==null?void 0:oe.error)||"Send failed");re.success(`Sent to ${oe.sent} of ${oe.total} recipient${oe.total===1?"":"s"}`)}t(!1)}catch(oe){re.error((oe==null?void 0:oe.message)||"Failed to send")}finally{P(!1)}},le=async()=>{await navigator.clipboard.writeText(O),I(!0),setTimeout(()=>I(!1),1500)};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[560px] w-[calc(100vw-2rem)] max-h-[90vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs($s,{className:"min-w-0",children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5 text-primary"}),"Share Virtual Tour"]}),e.jsx(kr,{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(vc,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:O}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:le,className:"shrink-0 h-7 gap-1",children:[L?e.jsx(da,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(ja,{className:"h-3.5 w-3.5"}),L?"Copied":"Copy"]})]}),r&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{type:"button",variant:C?"default":"outline",size:"sm",onClick:()=>T(!0),className:"gap-1.5",children:[e.jsx(on,{className:"h-3.5 w-3.5"}),"Send from Gmail"]}),e.jsx(B,{type:"button",variant:C?"outline":"default",size:"sm",onClick:()=>T(!1),className:"gap-1.5",children:"Send from LevelUp"})]}),C&&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(se,{className:"flex items-center gap-1.5",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),"Recipients"]}),e.jsxs(lc,{open:u,onOpenChange:h,modal:!0,children:[e.jsx(cc,{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(fb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Jl,{className:"w-[440px] max-w-[calc(100vw-2rem)] p-0",align:"start",children:e.jsxs(Sb,{children:[e.jsx(Cb,{placeholder:"Search contacts..."}),e.jsxs(Ab,{className:"max-h-[300px] overflow-y-auto",children:[e.jsx(Tb,{children:m?"Loading...":"No contacts found."}),e.jsx(Eb,{children:l.map(ue=>{const oe=!!c.find(we=>we.id===ue.id),ie=q(ue).slice(0,80),de=(ue.email||"").slice(0,80);return e.jsxs(Yy,{value:`${ie} ${de}`,onSelect:()=>W(ue),className:"py-2",children:[e.jsx(da,{className:Et("mr-2 h-4 w-4 shrink-0",oe?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:ie||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:de})]})]},ue.id)})})]})]})})]}),c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:c.map(ue=>e.jsxs(qe,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:q(ue)}),e.jsx("button",{onClick:()=>W(ue),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(dr,{className:"h-3 w-3"})})]},ue.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(ye,{value:x,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(Xl,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(ye,{id:"vt-subject",value:g,onChange:ue=>b(ue.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{htmlFor:"vt-message",children:"Personal Message"}),e.jsx(Ds,{id:"vt-message",value:v,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:M,children:"Cancel"}),e.jsxs(B,{onClick:J,disabled:M||K.length===0||!g.trim(),className:"gap-2",children:[M?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4"}),M?"Sending...":`Send${K.length?` to ${K.length}`:""}`]})]})]})]})})}const MBe="guestbook.relevelup.com";function MTn(){const{data:s,isLoading:t}=eds(),n=tds(),r=c5t(),a=sds(),[i,l]=j.useState(!1),[o,c]=j.useState(null),{user:d}=Ns(),u=ei(),[h,m]=j.useState(null),[p,x]=j.useState(null),[y,g]=j.useState(!1),b=j.useRef(null),[v,k]=j.useState({property_address:"",city:"",state:"",zip:"",event_date:Bs(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"}),C=L=>{var O;const I=(O=L.target.files)==null?void 0:O[0];if(I){if(I.size>5*1024*1024){ba({title:"Photo must be under 5MB",variant:"destructive"});return}m(I),x(URL.createObjectURL(I))}},T=()=>{m(null),x(null),b.current&&(b.current.value="")},M=async()=>{if(!v.property_address){ba({title:v.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let L;if(h&&d){g(!0);const O=h.name.split(".").pop(),$=`${u}/${Date.now()}.${O}`,{error:q}=await U.storage.from("open-house-photos").upload($,h,{upsert:!0});if(q){ba({title:"Photo upload failed",description:q.message,variant:"destructive"}),g(!1);return}const{data:W}=U.storage.from("open-house-photos").getPublicUrl($);L=W.publicUrl,g(!1)}const I=v.kind==="virtual"?{...v,start_time:void 0,end_time:void 0,photo_url:L}:{...v,photo_url:L};await n.mutateAsync(I),l(!1),k({property_address:"",city:"",state:"",zip:"",event_date:Bs(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()},P=L=>{navigator.clipboard.writeText(`https://${MBe}/${L}`),ba({title:"Link copied!"})};return e.jsxs(Vs,{title:"Guest Book",children:[e.jsx(ql,{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(Fs,{open:i,onOpenChange:l,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"New Open House"]})}),e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Create Open House"}),e.jsx(kr,{children:"Set up a new open house sign-in page"})]}),e.jsxs("div",{className:"space-y-4 pt-2 overflow-y-auto flex-1 pr-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Open House Type"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>k(L=>({...L,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${v.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(L=>({...L,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${v.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"})]})]})]}),v.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(L=>({...L,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${v.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(L=>({...L,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${v.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),v.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tour Format"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>k(L=>({...L,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${v.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(L=>({...L,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${v.tour_mode==="single_video"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Single video"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"One walkthrough video"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can add the video or room media in settings after creating."})]}),e.jsxs("div",{children:[e.jsx(se,{children:v.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(ye,{value:v.property_address,onChange:L=>k(I=>({...I,property_address:L.target.value})),placeholder:v.event_type==="community"?"Spring Festival at Riverside Estates":"123 Main Street"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"City"}),e.jsx(ye,{value:v.city,onChange:L=>k(I=>({...I,city:L.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(ye,{value:v.state,onChange:L=>k(I=>({...I,state:L.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"ZIP"}),e.jsx(ye,{value:v.zip,onChange:L=>k(I=>({...I,zip:L.target.value})),placeholder:"78701"})]})]}),v.kind==="virtual"?e.jsxs("div",{className:"rounded-lg border border-dashed border-muted-foreground/30 bg-muted/20 p-3 text-xs text-muted-foreground",children:["🕒 Virtual open houses are ",e.jsx("span",{className:"font-medium text-foreground",children:"always on"})," — no date or time needed. Visitors can tour any time via your link or QR code."]}):e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Date"}),e.jsx(ye,{type:"date",value:v.event_date,onChange:L=>k(I=>({...I,event_date:L.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Start Time"}),e.jsx(ye,{type:"time",value:v.start_time,onChange:L=>k(I=>({...I,start_time:L.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"End Time"}),e.jsx(ye,{type:"time",value:v.end_time,onChange:L=>k(I=>({...I,end_time:L.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Welcome Message"}),e.jsx(Ds,{value:v.agent_greeting,onChange:L=>k(I=>({...I,agent_greeting:L.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(se,{children:v.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:b,type:"file",accept:"image/*",onChange:C,className:"hidden"}),p?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:p,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(dr,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var L;return(L=b.current)==null?void 0:L.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(a1,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",v.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx(B,{onClick:M,disabled:n.isPending||y,className:"w-full",children:y?"Uploading photo...":n.isPending?"Creating...":v.kind==="virtual"?"Create Virtual Open House":v.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})]}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(L=>e.jsx(be,{className:"animate-pulse",children:e.jsxs(Ft,{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"})]})},L))}):s!=null&&s.length?e.jsx("div",{className:"space-y-4",children:s.map(L=>e.jsx(LTn,{openHouse:L,isExpanded:o===L.id,onToggle:()=>c(o===L.id?null:L.id),onCopyLink:()=>P(L.slug||""),onToggleActive:()=>r.mutate({id:L.id,is_active:!L.is_active}),onDelete:()=>a.mutate(L.id)},L.id))}):e.jsx(be,{className:"border-dashed",children:e.jsxs(Re,{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(hg,{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(Js,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function LTn({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i}){const{data:l}=l5t(t?s.id:void 0),{data:o}=mt({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:P,error:L}=await U.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(L)throw L;const I=P.brokerages;return{...P,brokerage_name:(I==null?void 0:I.name)||null}},enabled:!!s.agent_id}),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[x,y]=j.useState(!1),g=j.useRef(null),b=`https://${MBe}/${s.slug}`,v=P=>{if(!P)return"";const[L,I]=P.split(":"),O=parseInt(L),$=O>=12?"PM":"AM";return`${O>12?O-12:O||12}:${I} ${$}`},k=()=>{if(!(l!=null&&l.length))return;const P=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],L=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,'""'),Bs(new Date(W.created_at),"MM/dd/yyyy h:mm a")]),I=[P,...L].map(W=>W.map(G=>`"${G}"`).join(",")).join(` `),O=new Blob([I],{type:"text/csv"}),$=URL.createObjectURL(O),q=document.createElement("a");q.href=$,q.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,q.click(),URL.revokeObjectURL($)},C=j.useCallback(()=>{if(!g.current)return;const P=g.current.querySelector("svg");if(!P)return;const L=new XMLSerializer().serializeToString(P),I=document.createElement("canvas");I.width=1024,I.height=1024;const O=I.getContext("2d"),$=new Image;$.onload=()=>{O==null||O.drawImage($,0,0,1024,1024);const q=document.createElement("a");q.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,q.href=I.toDataURL("image/png"),q.click()},$.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(L)))},[s.property_address]),T=j.useCallback(()=>{var _e;if(!g.current)return;const P=g.current.querySelector("svg");if(!P)return;const L=new XMLSerializer().serializeToString(P),I="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(L))),O=Bs(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),$=s.start_time?`${v(s.start_time)}${s.end_time?" – "+v(s.end_time):""}`:"",q=[s.city,s.state].filter(Boolean).join(", "),W=s.agent_greeting||"Welcome! Please sign in below.",G=!!s.photo_url,K=!!o,ee=G||K,J=G&&K,le=J?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ue=J?"28px":"34px",oe=J?"0.2in 0.75in":ee?"0.3in 0.75in":"0.4in 0.75in",ie=ee?"0.15in":"0.3in",de=ee?"0.15in":"0.3in",we=J?"14px 36px":"22px 44px",je=J?"20px":"24px",xe=ee?"0.2in":"0.35in",fe=J?"1.8in":"2.4in",Se=ee?"0.15in":"0.3in",Ee=J?"140px":ee?"160px":"200px",Le=J?"16px":"24px",De=J?"10px 20px":"16px 28px",Be=J?"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}
${q?`
${q}${s.zip?" "+s.zip:""}
`:""}
Date
${O}
${$?`
Time
${$}
`:""}
${W}
${o?`
${o.avatar_url?`${o.name}`:`
${((_e=o.name)==null?void 0:_e.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,b,o]),M=async()=>{y(!0);try{const{error:P}=await U.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(P)throw P;ba({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(P){ba({title:"Failed to send",description:P.message,variant:"destructive"})}finally{y(!1)}};return e.jsxs(be,{className:`transition-all ${s.is_active?"border-primary/30":"opacity-75"}`,children:[e.jsx(Ft,{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(Ut,{className:"text-base leading-snug break-words",children:s.property_address}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1.5 flex-wrap",children:[e.jsx(qe,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(qe,{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(ma,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(qe,{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(oi,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(qe,{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(Eo,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(qe,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(Ni,{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(Qy,{className:"h-4 w-4"}):e.jsx(Po,{className:"h-4 w-4"})})]}),e.jsxs(fr,{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(oi,{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(Vr,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ra,{className:"h-3 w-3"}),Bs(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(Vr,{className:"h-3 w-3"}),v(s.start_time),s.end_time?` – ${v(s.end_time)}`:""]})]}),e.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[e.jsx(Bn,{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(hg,{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(iy,{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(ja,{className:"h-3.5 w-3.5"}),"Copy"]}),s.kind==="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>p(!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(zd,{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(ma,{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(hg,{className:"h-3.5 w-3.5"}),"QR"]}),s.kind!=="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(`${b}?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(cz,{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(ic,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>window.open(b,"_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(n0,{className:"h-3.5 w-3.5"}):e.jsx(ma,{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(Rn,{className:"h-3.5 w-3.5"})})]})]})}),t&&e.jsxs(Re,{className:"pt-0",children:[e.jsx(Xl,{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://",MBe,"/",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(ii,{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(P=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"p-2 font-medium",children:[P.first_name,P.last_name?` ${P.last_name}`:""]}),e.jsxs("td",{className:"p-2 text-muted-foreground hidden sm:table-cell",children:[P.email&&e.jsx("div",{className:"truncate max-w-[180px]",children:P.email}),P.phone&&e.jsx("div",{className:"text-xs",children:P.phone}),P.visitor_address&&e.jsx("div",{className:"text-xs truncate max-w-[180px]",children:P.visitor_address})]}),e.jsx("td",{className:"p-2 hidden md:table-cell",children:P.visitor_intent?e.jsx(qe,{variant:"outline",className:"text-xs capitalize",children:P.visitor_intent}):P.partial_signin?e.jsx(qe,{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:Bs(new Date(P.created_at),"h:mm a")})]},P.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(TTn,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(CTn,{openHouseId:s.id})})]}),e.jsx(Fs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"sm:max-w-sm",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"QR Code"}),e.jsx(kr,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:g,className:"bg-white p-4 rounded-xl",children:e.jsx(PN,{value:b,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:b}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:C,children:[e.jsx(ii,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:T,children:[e.jsx(GR,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(B,{variant:"default",className:"w-full",onClick:M,disabled:x,children:[e.jsx(on,{className:"h-4 w-4 mr-2"}),x?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(kTn,{open:u,onOpenChange:h,openHouse:s}),s.kind==="virtual"&&e.jsx(ETn,{open:m,onOpenChange:p,openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state}})]})}function PTn(){const{slug:s}=$i();return s?e.jsx(T3t,{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 GBt({photoUrl:s,videoUrl:t,onPhotoChange:n,onVideoChange:r,contactId:a}){const{user:i}=Ns(),l=hS(),o=j.useRef(null),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[p,x]=j.useState(0),y=async b=>{if(i){u(!0);try{const v=b.name.split(".").pop()||"jpg",k=`${i.id}/card-${Date.now()}.${v}`,{error:C}=await U.storage.from("listing-photos").upload(k,b);if(C)throw C;const{data:{publicUrl:T}}=U.storage.from("listing-photos").getPublicUrl(k);n(T),re.success("Photo uploaded")}catch(v){re.error(v.message||"Failed to upload photo")}finally{u(!1)}}},g=async b=>{if(i){if(b.size>500*1024*1024){re.error("Video must be under 500MB");return}m(!0),x(0);try{const{videoId:v,libraryId:k}=await w6(`Card Video - ${Date.now()}`),{uploadUrl:C,apiKey:T}=await j6(v);await new Promise((L,I)=>{const O=new XMLHttpRequest;O.upload.addEventListener("progress",$=>{$.lengthComputable&&x(Math.round($.loaded/$.total*100))}),O.addEventListener("load",()=>{O.status>=200&&O.status<300?L():I(new Error("Upload failed"))}),O.addEventListener("error",()=>I(new Error("Upload failed"))),O.open("PUT",C),O.setRequestHeader("AccessKey",T),O.send(b)});const M=`https://iframe.mediadelivery.net/embed/${k}/${v}`;r(M);const P=parseFloat((b.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:v,playback_url:`https://iframe.mediadelivery.net/play/${k}/${v}`,file_size_mb:P,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),re.success("Video uploaded & added to your library")}catch(v){re.error(v.message||"Failed to upload video")}finally{m(!1),x(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(se,{children:"Media (optional)"}),e.jsxs(fa,{defaultValue:"photo",className:"w-full",children:[e.jsxs(xa,{className:"grid w-full grid-cols-2",children:[e.jsxs(ss,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(ac,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(ss,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(ns,{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(dr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},disabled:d,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:d?e.jsx(Wt,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(s0,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a photo"})]})}),e.jsx("input",{ref:o,type:"file",accept:"image/*",className:"hidden",onChange:b=>{var k;const v=(k=b.target.files)==null?void 0:k[0];v&&y(v),b.target.value=""}})]}),e.jsxs(ns,{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(dr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var b;return(b=c.current)==null?void 0:b.click()},disabled:h,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:h?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Wt,{className:"h-6 w-6 animate-spin"}),e.jsxs("span",{className:"text-xs",children:["Uploading... ",p,"%"]}),e.jsx("div",{className:"w-32 h-1.5 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${p}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ja,{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(tYe,{contactId:a,onVideoReady:b=>r(b)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:b=>{var k;const v=(k=b.target.files)==null?void 0:k[0];v&&g(v),b.target.value=""}}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1.5 text-center",children:"Videos are also saved to your Video Library"})]})]})]})}const ITn=[{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 RTn({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:ITn.map((t,n)=>e.jsxs(br.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 Kq={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 Hgt({initialOpen:s,initialCardType:t,initialContactId:n,initialRecipientName:r,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=Ns(),c=as(),[d,u]=j.useState(!1),[h,m]=j.useState("type"),[p,x]=j.useState(""),[y,g]=j.useState(null),[b,v]=j.useState(!1),[k,C]=j.useState("home_anniversary"),[T,M]=j.useState(""),[P,L]=j.useState(""),[I,O]=j.useState(""),[$,q]=j.useState(""),[W,G]=j.useState("elegant"),[K,ee]=j.useState(null),[J,le]=j.useState(null),ue=j.useState(!1);!ue[0]&&s&&t&&(ue[1](!0),u(!0),C(t),n&&g(n),r&&M(r),a&&L(a),i&&O(i),m(r?"details":"contact"));const{data:oe}=mt({queryKey:["contacts-for-card",o==null?void 0:o.id,p],queryFn:async()=>{let Be=U.from("innercircle_contacts").select("id, first_name, last_name, address, city, state, home_anniversary, wedding_anniversary, email, phone").eq("owner_user_id",o.id).order("first_name").limit(20);p&&(Be=Be.or(`first_name.ilike.%${p}%,last_name.ilike.%${p}%`));const{data:Ne,error:Ge}=await Be;if(Ge)throw Ge;return Ne},enabled:!!(o!=null&&o.id)&&d}),{data:ie}=mt({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:Be,error:Ne}=await U.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)}),de=Be=>{g(Be.id),M(`${Be.first_name}${Be.last_name?" "+Be.last_name:""}`),L([Be.address,Be.city,Be.state].filter(Boolean).join(", "));const Ne=k==="wedding_anniversary"?Be.wedding_anniversary:k==="home_anniversary"?Be.home_anniversary:"";O(Ne||""),m("details")},we=Be=>{C(Be),m("contact")},je=async()=>{var Be;if(!(!o||!ie)){v(!0);try{const Ne={owner_user_id:o.id,contact_id:y,card_type:k,template:W,recipient_name:T,property_address:P||null,home_anniversary_date:I||null,custom_message:$||null,property_photo_url:K||null,video_url:J||null,agent_name:ie.name||"Agent",agent_photo_url:ie.avatar_url,agent_phone:ie.phone,agent_email:ie.email,agent_brokerage:((Be=ie.brokerage)==null?void 0:Be.name)||null},{error:Ge}=await U.from("sendable_cards").insert(Ne);if(Ge)throw Ge;re.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),xe()}catch(Ne){re.error(Ne.message||"Failed to create card")}finally{v(!1)}}},xe=()=>{u(!1),m("type"),C("home_anniversary"),x(""),g(null),M(""),L(""),O(""),q(""),G("elegant"),ee(null),le(null)},fe={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"},Se=Kq[k],Ee=k==="home_anniversary"||k==="wedding_anniversary",Le=k==="wedding_anniversary"?"Wedding Anniversary Date":"Home Anniversary Date",De=["home_anniversary","just_listed","just_sold"].includes(k);return e.jsxs(Fs,{open:d,onOpenChange:Be=>{Be?u(!0):(xe(),l==null||l(!1))},children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Js,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:h==="type"?"What type of card?":h==="contact"?`${fe[k]} — Choose a Contact`:`${fe[k]} — Customize`})}),h==="type"&&e.jsx(RTn,{onSelect:we}),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(_a,{className:"h-3.5 w-3.5"})," Back to card types"]}),e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search contacts...",value:p,onChange:Be=>x(Be.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[oe==null?void 0:oe.map(Be=>e.jsxs("button",{onClick:()=>de(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(Eo,{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(ia,{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)),(oe==null?void 0:oe.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(_a,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipient Name"}),e.jsx(ye,{value:T,onChange:Be=>M(Be.target.value),placeholder:"John & Jane Smith"})]}),De&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Address"}),e.jsx(ye,{value:P,onChange:Be=>L(Be.target.value),placeholder:"123 Main St, Austin, TX"})]}),Ee&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:Le}),e.jsx(ye,{type:"date",value:I,onChange:Be=>O(Be.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Message (optional)"}),e.jsx(Ds,{value:$,onChange:Be=>q(Be.target.value),placeholder:Se.defaultMessage,rows:3})]}),e.jsx(GBt,{photoUrl:K,videoUrl:J,onPhotoChange:ee,onVideoChange:le,contactId:y}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-5 gap-2",children:[{key:"elegant",label:"Elegant",gradient:"bg-gradient-to-br from-slate-100 to-blue-100 dark:from-slate-800 dark:to-slate-700"},{key:"bold",label:"Bold",gradient:"bg-gradient-to-br from-violet-500 to-fuchsia-500"},{key:"warm",label:"Warm",gradient:"bg-gradient-to-br from-amber-200 to-orange-300"},{key:"glass",label:"Glass",gradient:"bg-gradient-to-br from-slate-900 via-blue-900/50 to-slate-900 border border-white/10"},{key:"cinematic",label:"Cinema",gradient:"bg-gradient-to-br from-slate-950 via-blue-950 to-slate-950"}].map(({key: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:je,disabled:!T||b,className:"flex-1 gap-2",children:b?"Creating...":"Create Card"})]})]})]})]})}const DTn={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 OTn({card:s}){const{user:t}=Ns(),{isGmailConnected:n,hasVerifiedSes:r,canSendEmail:a,sendMethod:i}=Tf(),l=as(),[o,c]=j.useState(!1);j.useState(!1);const[d,u]=j.useState("");j.useEffect(()=>{o&&s.contact_id&&!d&&U.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:k})=>{k!=null&&k.email&&u(k.email)})},[o,s.contact_id]);const h={home_anniversary:`🏡 Happy Home Anniversary, ${s.recipient_name}!`,wedding_anniversary:`💍 Happy Anniversary, ${s.recipient_name}!`,just_listed:`🏠 Just Listed — Check This Out, ${s.recipient_name}!`,just_sold:`🎉 Just Sold! Congrats, ${s.recipient_name}!`,congratulations:`🏆 Congratulations, ${s.recipient_name}!`,birthday:`🎂 Happy Birthday, ${s.recipient_name}!`,holiday:`🎄 Happy Holidays, ${s.recipient_name}!`,thank_you:`💐 Thank You, ${s.recipient_name}!`,thinking_of_you:`💭 Thinking of You, ${s.recipient_name}!`},[m,p]=j.useState(h[s.card_type]||`A Special Card for ${s.recipient_name}!`),[x,y]=j.useState(""),g=`https://cardstudio.relevelup.com/c/${s.share_token}`,b=vt({mutationFn:async()=>{if(!d)throw new Error("Recipient email is required");const k=`
${x?`

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


`:""}

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

${s.property_address?`

${s.property_address}

`:""}
`,C=async()=>{const{data:L,error:I}=await U.functions.invoke("send-connect-invite",{body:{contactEmail:d,subject:m,htmlBody:k}});if(I)throw I;if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Failed to send");return"system"};if(!a)return await C();const{data:T,error:M}=await U.functions.invoke("gmail-send",{body:{to:d,subject:m,body:k,contactId:s.contact_id||void 0}});let P=T&&T.error?T:null;if(M){P={error:"send_failed",message:M.message};const L=M.context;if(L&&typeof L.json=="function")try{P=await L.clone().json()}catch{}}if(P){if(P.error==="insufficient_scope"||P.error==="no_integration")return await C(),re.warning("Sent using system email — reconnect Gmail in Integrations to send from your own inbox.",{duration:8e3}),"system";throw new Error(P.message||P.error||"Failed to send")}if(!(T!=null&&T.success))throw new Error("Failed to send");return"gmail"},onSuccess:async k=>{await U.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:k==="gmail"?"gmail":"system"}).eq("id",s.id),l.invalidateQueries({queryKey:["sendable-cards"]}),re.success(`Card sent to ${d}!`),c(!1)},onError:k=>{re.error(k.message||"Failed to send email")}}),v=i==="mass_email"?"Mass Email":i==="gmail"?"Gmail":"Email";return e.jsxs(Fs,{open:o,onOpenChange:c,children:[e.jsx(Io,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Dr,{className:"h-3 w-3"})})}),e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx($s,{children:e.jsxs(zs,{children:["Send Card via ",v]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"gmail-to",children:"To"}),e.jsx(dRt,{value:d,onChange:u,userId:t==null?void 0:t.id,placeholder:"Search contacts or type an email..."}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Pick from your Agent OS contacts, or type any email address."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subject"}),e.jsx(ye,{value:m,onChange:k=>p(k.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Note (optional)"}),e.jsx(Ds,{value:x,onChange:k=>y(k.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:g})]}),e.jsx(B,{onClick:()=>b.mutate(),disabled:!d||b.isPending,className:"w-full gap-2",children:b.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{className:"h-4 w-4"})," Send Card"]})})]})]})]})}function FTn({card:s}){const t=as(),[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(s.recipient_name),[c,d]=j.useState(s.property_address||""),[u,h]=j.useState(s.home_anniversary_date||""),[m,p]=j.useState(s.custom_message||""),[x,y]=j.useState(s.template),[g,b]=j.useState(s.property_photo_url),[v,k]=j.useState(s.video_url||null),C=M=>{M&&(o(s.recipient_name),d(s.property_address||""),h(s.home_anniversary_date||""),p(s.custom_message||""),y(s.template),b(s.property_photo_url),k(s.video_url||null)),r(M)},T=async()=>{if(!l.trim()){re.error("Recipient name is required");return}i(!0);try{const{error:M}=await U.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:u||null,custom_message:m.trim()||null,template:x,property_photo_url:g||null,video_url:v||null}).eq("id",s.id);if(M)throw M;t.invalidateQueries({queryKey:["sendable-cards"]}),re.success("Card updated"),r(!1)}catch(M){re.error(M.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(Fs,{open:n,onOpenChange:C,children:[e.jsx(Io,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Za,{className:"h-3 w-3"})})}),e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Edit Card"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipient Name"}),e.jsx(ye,{value:l,onChange:M=>o(M.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Property Address"}),e.jsx(ye,{value:c,onChange:M=>d(M.target.value),placeholder:"123 Main St, Austin, TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Home Anniversary Date"}),e.jsx(ye,{type:"date",value:u,onChange:M=>h(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Personal Message (optional)"}),e.jsx(Ds,{value:m,onChange:M=>p(M.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(GBt,{photoUrl:g,videoUrl:v,onPhotoChange:b,onVideoChange:k,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["elegant","bold","warm"].map(M=>e.jsxs("button",{onClick:()=>y(M),className:`p-3 rounded-lg border-2 transition-all text-center ${x===M?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-12 rounded-md mb-2 ${M==="elegant"?"bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-700":M==="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:M})]},M))})]}),e.jsx(B,{onClick:T,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function zTn(){const{user:s}=Ns(),t=as(),[n,r]=j.useState(""),[a,i]=dc(),l=a.get("cardType"),o=a.get("contactId"),c=a.get("name"),d=a.get("address"),u=a.get("date"),h=!!l,{data:m,isLoading:p}=mt({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:k,error:C}=await U.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(C)throw C;return k},enabled:!!(s!=null&&s.id)}),x=vt({mutationFn:async k=>{const{error:C}=await U.from("sendable_cards").delete().eq("id",k);if(C)throw C},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),re.success("Card deleted")}}),y=k=>{const C=`https://cardstudio.relevelup.com/c/${k}`;navigator.clipboard.writeText(C),re.success("Share link copied!")},g=m==null?void 0:m.filter(k=>{var C;return!n||k.recipient_name.toLowerCase().includes(n.toLowerCase())||((C=k.property_address)==null?void 0:C.toLowerCase().includes(n.toLowerCase()))}),b={elegant:"Elegant",bold:"Bold",warm:"Warm"},v={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};return e.jsx(Vs,{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(Hgt,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search cards...",value:n,onChange:k=>r(k.target.value),className:"pl-9"})]}),p?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(k=>e.jsx(be,{className:"animate-pulse",children:e.jsxs(Re,{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))}):g!=null&&g.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:g.map(k=>e.jsxs(be,{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:v[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(qe,{variant:k.template==="bold"?"outline":"secondary",className:`text-[10px] ${k.template==="bold"?"border-white/30 text-white/80":""}`,children:b[k.template]||k.template})})]}),e.jsxs(Re,{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(ma,{className:"h-3 w-3"}),k.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:oc(new Date(k.created_at),{addSuffix:!0})})]}),k.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",Bs(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(ja,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(FTn,{card:k}),e.jsx(OTn,{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:()=>x.mutate(k.id),children:e.jsx(Rn,{className:"h-3 w-3"})})]})]})]},k.id))}):e.jsx(be,{className:"border-dashed",children:e.jsxs(Re,{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(on,{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(Hgt,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]})})]})})}const fre=[{id:"mls",label:"MLS Description",tag:"Standard",icon:ia,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:sy,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:jf,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:wj,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:BW,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:kl,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:sx,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:vm,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:ry,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:jh,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:Vr,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:vN,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:Vc,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:DW,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:bf,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:Zr,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:wh,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:Sj,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:sy,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:eK,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:oi,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:on,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:G9,accent:"from-teal-500 to-cyan-500",desc:"Public OH invitation",category:"email",extras:["openHouse","signoff"]},{id:"brokerOpenEmail",label:"Broker Open Invite",tag:"Agents",icon:Bn,accent:"from-indigo-500 to-blue-500",desc:"Invite to fellow agents",category:"email",extras:["openHouse","brokerOpen","signoff"]},{id:"priceReductionEmail",label:"Price Reduction",tag:"Update",icon:vN,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:f3,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:oi,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function BTn(){var aa,zr,Na,oa,ur,ao,fo,Va,So,$a,Gr;const{user:s}=Ns(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState([]),[o,c]=j.useState(""),[d,u]=j.useState([]),[h,m]=j.useState(""),[p,x]=j.useState(""),[y,g]=j.useState(""),[b,v]=j.useState(""),[k,C]=j.useState(""),[T,M]=j.useState(""),[P,L]=j.useState(""),[I,O]=j.useState(null),[$,q]=j.useState(""),[W,G]=j.useState(""),[K,ee]=j.useState(""),[J,le]=j.useState(""),[ue,oe]=j.useState(""),[ie,de]=j.useState(""),[we,je]=j.useState(""),[xe,fe]=j.useState(""),[Se,Ee]=j.useState(""),[Le,De]=j.useState(""),[Be,Ne]=j.useState(""),[Ge,_e]=j.useState(""),[Oe,Ae]=j.useState(""),[Xe,Ue]=j.useState(""),[Ze,Qe]=j.useState(""),[Ye,nt]=j.useState(""),[rt,Fe]=j.useState(""),[dt,Dt]=j.useState(""),[pt,zt]=j.useState(""),[Gt,qs]=j.useState(""),[As,Bt]=j.useState(""),[At,Is]=j.useState(""),[jt,Qs]=j.useState(""),[cn,qt]=j.useState(""),[Gs,Ls]=j.useState(""),[sn,Hs]=j.useState("listing"),[nn,tn]=j.useState("mls"),[_n,Cn]=j.useState({}),[Un,Kr]=j.useState({}),[jr,Xs]=j.useState(!1),[Ba,Hr]=j.useState(!1),mr=Qn=>{Hs(Qn);const qa=fre.find(xo=>xo.category===Qn);qa&&tn(qa.id)},{data:pr}=mt({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&jr,queryFn:async()=>{const{data:Qn,error:qa}=await U.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, property_type, description").eq("agent_id",s.id).order("created_at",{ascending:!1}).limit(50);if(qa)throw qa;return Qn||[]}}),rn=()=>{const Qn=o.trim();Qn&&(l(qa=>[...qa,Qn]),c(""))},Jn=Qn=>l(qa=>qa.filter((xo,Wo)=>Wo!==Qn)),ea=Qn=>{var qa,xo,Wo,Co;O(Qn.id),n(Qn.property_address||""),M(Qn.city||""),L(Qn.state||""),v(((qa=Qn.price)==null?void 0:qa.toString())||""),m(((xo=Qn.bedrooms)==null?void 0:xo.toString())||""),x(((Wo=Qn.bathrooms)==null?void 0:Wo.toString())||""),g(((Co=Qn.square_footage)==null?void 0:Co.toString())||""),C(Qn.property_type||""),a(Qn.description||""),Xs(!1),re.success("Listing imported")},_s=async Qn=>{if(!(!Qn.target.files||!(s!=null&&s.id))){Hr(!0);try{const qa=[];for(const xo of Array.from(Qn.target.files).slice(0,10)){const Wo=`${s.id}/${Date.now()}-${xo.name.replace(/[^\w.-]/g,"_")}`,{error:Co}=await U.storage.from("listing-photos").upload(Wo,xo,{upsert:!1});if(Co){console.error(Co);continue}const{data:Ko}=U.storage.from("listing-photos").getPublicUrl(Wo);qa.push(Ko.publicUrl)}u(xo=>[...xo,...qa]),qa.length&&re.success(`${qa.length} photo(s) uploaded`)}catch(qa){re.error(qa.message||"Photo upload failed")}finally{Hr(!1)}}},We=fre.find(Qn=>Qn.id===nn),it=async Qn=>{var xo,Wo,Co;const qa=fre.find(Ko=>Ko.id===Qn);if(!t.trim()&&!r.trim()&&i.length===0){re.error("Add a property address, MLS remarks, or features first");return}if((xo=qa.extras)!=null&&xo.includes("openHouse")&&(!$||!W||!K)){re.error("Add the open house date, start and end time");return}if((Wo=qa.extras)!=null&&Wo.includes("priceImprovement")&&(!J||!ue)){re.error("Add previous and new price");return}if((Co=qa.extras)!=null&&Co.includes("sold")&&!ie){re.error("Add the sold price");return}tn(Qn),Kr(Ko=>({...Ko,[Qn]:!0}));try{const{data:Ko,error:Ud}=await U.functions.invoke("listing-studio-generate",{body:{copyType:Qn,propertyAddress:t,mlsRemarks:r,features:i,photoUrls:d,listingId:I,bedrooms:h?Number(h):null,bathrooms:p?Number(p):null,squareFootage:y?Number(y):null,price:b?Number(b):null,propertyType:k||null,city:T||null,state:P||null,openHouseDate:$||null,openHouseStart:W||null,openHouseEnd:K||null,previousPrice:J?Number(J):null,newPrice:ue?Number(ue):null,soldPrice:ie?Number(ie):null,soldDate:we||null,comingSoonDate:xe||null,builderName:Se||null,yearBuilt:Le?Number(Le):null,warrantyInfo:Be||null,monthlyRent:Ge?Number(Ge):null,capRate:Oe||null,occupancy:Xe||null,daysOnMarket:Ze?Number(Ze):null,offerCount:Ye?Number(Ye):null,originalListPrice:rt?Number(rt):null,soldDaysOnMarket:dt?Number(dt):null,commissionOffered:pt||null,refreshments:Gt||null,vibe:As||null,neighborhoodHighlights:At||null,agentName:jt||null,agentBrokerage:cn||null,agentContact:Gs||null}});if(Ud)throw Ud;if(Ko!=null&&Ko.error)throw new Error(Ko.error);Cn(Mu=>({...Mu,[Qn]:Ko.content}))}catch(Ko){re.error(Ko.message||"Generation failed")}finally{Kr(Ko=>({...Ko,[Qn]:!1}))}},gt=Qn=>{navigator.clipboard.writeText(Qn),re.success("Copied to clipboard")},St=We.icon,Ht=_n[nn]?_n[nn].trim().split(/\s+/).length:0,ts=Qn=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:fre.filter(qa=>qa.category===Qn).map(qa=>{const xo=qa.icon,Wo=nn===qa.id,Co=!!_n[qa.id];return e.jsxs("button",{onClick:()=>tn(qa.id),className:Et("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",Wo?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[Wo&&e.jsx("div",{className:Et("absolute inset-0 opacity-[0.07] bg-gradient-to-br",qa.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:Et("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",qa.accent),children:e.jsx(xo,{className:"h-4 w-4"})}),Co&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(da,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:qa.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:qa.desc})]})]})]},qa.id)})}),Ms=(aa=We.extras)==null?void 0:aa.includes("openHouse"),js=(zr=We.extras)==null?void 0:zr.includes("priceImprovement"),Zs=(Na=We.extras)==null?void 0:Na.includes("sold"),Tn=(oa=We.extras)==null?void 0:oa.includes("comingSoon"),vn=(ur=We.extras)==null?void 0:ur.includes("newConstruction"),_r=(ao=We.extras)==null?void 0:ao.includes("investment"),Jr=(fo=We.extras)==null?void 0:fo.includes("underContract"),ha=(Va=We.extras)==null?void 0:Va.includes("brokerOpen"),Mr=(So=We.extras)==null?void 0:So.includes("vibe"),Xr=($a=We.extras)==null?void 0:$a.includes("neighborhood"),Qt=(Gr=We.extras)==null?void 0:Gr.includes("signoff"),Zn=Ms||js||Zs||Tn||vn||_r||Jr||ha||Mr||Xr||Qt;return e.jsx(Vs,{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(yn,{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(Fs,{open:jr,onOpenChange:Xs,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx($r,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(pr!=null&&pr.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),pr==null?void 0:pr.map(Qn=>e.jsxs("button",{onClick:()=>ea(Qn),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:Qn.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[Qn.city,Qn.state].filter(Boolean).join(", "),Qn.price?` · $${Number(Qn.price).toLocaleString()}`:"",Qn.bedrooms?` · ${Qn.bedrooms}bd`:"",Qn.bathrooms?` · ${Qn.bathrooms}ba`:""]})]},Qn.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(be,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(Re,{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(ia,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Property Details"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Fill in what you have — AI handles the rest"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(ye,{value:t,onChange:Qn=>n(Qn.target.value),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(ye,{value:T,onChange:Qn=>M(Qn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(ye,{value:P,onChange:Qn=>L(Qn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(ye,{type:"number",value:b,onChange:Qn=>v(Qn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(ye,{value:k,onChange:Qn=>C(Qn.target.value),placeholder:"Single Family"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(ye,{type:"number",value:h,onChange:Qn=>m(Qn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(ye,{type:"number",step:"0.5",value:p,onChange:Qn=>x(Qn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(ye,{type:"number",value:y,onChange:Qn=>g(Qn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(Ds,{value:r,onChange:Qn=>a(Qn.target.value),placeholder:"Paste existing MLS remarks or rough notes...",rows:4,className:"resize-none"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:o,onChange:Qn=>c(Qn.target.value),onKeyDown:Qn=>Qn.key==="Enter"&&(Qn.preventDefault(),rn()),placeholder:"e.g. Quartz countertops"}),e.jsx(B,{type:"button",size:"icon",variant:"secondary",onClick:rn,children:e.jsx(Js,{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((Qn,qa)=>e.jsxs(qe,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[Qn,e.jsx("button",{onClick:()=>Jn(qa),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx(dr,{className:"h-3 w-3"})})]},qa))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Photos (optional)"}),e.jsxs("label",{className:"flex items-center justify-center gap-2 p-4 border-2 border-dashed rounded-xl cursor-pointer hover:border-primary hover:bg-accent/30 transition-colors text-sm text-muted-foreground",children:[e.jsx(a1,{className:"h-4 w-4"}),Ba?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:_s,disabled:Ba,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((Qn,qa)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:Qn,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>u(xo=>xo.filter((Wo,Co)=>Co!==qa)),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(dr,{className:"h-3 w-3"})})]},qa))})]}),Zn&&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(yn,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",We.label]})]}),Ms&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(ye,{type:"date",value:$,onChange:Qn=>q(Qn.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(ye,{type:"time",value:W,onChange:Qn=>G(Qn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(ye,{type:"time",value:K,onChange:Qn=>ee(Qn.target.value)})]})]})]}),js&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(ye,{type:"number",value:J,onChange:Qn=>le(Qn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(ye,{type:"number",value:ue,onChange:Qn=>oe(Qn.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(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(ye,{type:"number",value:ie,onChange:Qn=>de(Qn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(ye,{type:"date",value:we,onChange:Qn=>je(Qn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(ye,{type:"number",value:rt,onChange:Qn=>Fe(Qn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(ye,{type:"number",value:dt,onChange:Qn=>Dt(Qn.target.value)})]})]})]}),Tn&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(ye,{type:"date",value:xe,onChange:Qn=>fe(Qn.target.value)})]}),vn&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(ye,{value:Se,onChange:Qn=>Ee(Qn.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(ye,{type:"number",value:Le,onChange:Qn=>De(Qn.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(ye,{value:Be,onChange:Qn=>Ne(Qn.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),_r&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(ye,{type:"number",value:Ge,onChange:Qn=>_e(Qn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(ye,{value:Oe,onChange:Qn=>Ae(Qn.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:Xe,onChange:Qn=>Ue(Qn.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"})]})]})]}),Jr&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(ye,{type:"number",value:Ze,onChange:Qn=>Qe(Qn.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(ye,{type:"number",value:Ye,onChange:Qn=>nt(Qn.target.value),placeholder:"e.g. 5"})]})]}),ha&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(ye,{value:pt,onChange:Qn=>zt(Qn.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(ye,{value:Gt,onChange:Qn=>qs(Qn.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),Mr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:As,onChange:Qn=>Bt(Qn.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"})]})]}),Xr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(Ds,{value:At,onChange:Qn=>Is(Qn.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),Qt&&e.jsxs("div",{className:"space-y-3 pt-2 border-t border-border/40",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Sign-off (optional)"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(ye,{value:jt,onChange:Qn=>Qs(Qn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(ye,{value:cn,onChange:Qn=>qt(Qn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(ye,{value:Gs,onChange:Qn=>Ls(Qn.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:$r},{key:"social",label:"Social Media",icon:vm},{key:"video",label:"Video Scripts",icon:Zr},{key:"email",label:"Email Marketing",icon:on}].map(Qn=>{const qa=Qn.icon,xo=sn===Qn.key;return e.jsxs("button",{onClick:()=>mr(Qn.key),className:Et("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",xo?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(qa,{className:"h-4 w-4"}),Qn.label]},Qn.key)})}),ts(sn),e.jsxs(be,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:Et("h-1 bg-gradient-to-r",We.accent)}),e.jsxs(Re,{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:Et("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",We.accent),children:e.jsx(St,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[We.label,e.jsx(qe,{variant:"outline",className:"text-[10px] font-normal",children:We.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:_n[nn]?`${Ht} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[_n[nn]&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>gt(_n[nn]),children:[e.jsx(ja,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx(B,{onClick:()=>it(nn),disabled:Un[nn],className:Et("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",We.accent),size:"sm",children:Un[nn]?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):_n[nn]?e.jsxs(e.Fragment,{children:[e.jsx(Ki,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(um,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),_n[nn]?e.jsx(Ds,{value:_n[nn],onChange:Qn=>Cn(qa=>({...qa,[nn]:Qn.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:Et("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",We.accent),children:e.jsx(um,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",We.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 nG({delay:s,x:t,y:n,size:r}){return e.jsx(br.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 $Tn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=Kq[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(br.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(br.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(nG,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(nG,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(nG,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(nG,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(nG,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(br.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(br.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(br.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(br.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(br.div,{className:"absolute inset-0 rounded-2xl border-2 border-slate-200/50 dark:border-slate-600/50",animate:{scale:[1,1.15,1],opacity:[.5,0,.5]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl",children:p.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(br.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(br.h1,{className:"text-4xl font-light text-slate-800 dark:text-slate-100 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:p.title[0]}),p.title[1]&&e.jsx(br.h2,{className:"text-4xl font-bold text-slate-800 dark:text-slate-100 mb-8 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:p.title[1]}),e.jsxs(br.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(br.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(br.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(br.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(br.p,{className:"text-sm text-slate-500 dark:text-slate-400 leading-relaxed max-w-xs mx-auto mb-8 italic",initial:{opacity:0},animate:{opacity:1},transition:{duration:.6,delay:1.3},children:i||p.defaultMessage}),e.jsxs(br.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(br.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(br.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(pa,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(br.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(on,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(br.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 e8e({delay:s,x:t,y:n,color:r,size:a}){return e.jsx(br.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 rG({delay:s,x:t,y:n}){return e.jsx(br.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 Ggt={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 UTn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=Kq[t],x=Ggt[t]||Ggt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${x.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx(e8e,{delay:0,x:"10%",y:"10%",color:x.orbs[0],size:200}),e.jsx(e8e,{delay:1,x:"70%",y:"60%",color:x.orbs[1],size:180}),e.jsx(e8e,{delay:2,x:"50%",y:"20%",color:x.orbs[2],size:150}),e.jsx(rG,{delay:0,x:"20%",y:"25%"}),e.jsx(rG,{delay:.8,x:"75%",y:"15%"}),e.jsx(rG,{delay:1.6,x:"85%",y:"65%"}),e.jsx(rG,{delay:2.4,x:"10%",y:"75%"}),e.jsx(rG,{delay:.4,x:"45%",y:"85%"}),e.jsxs(br.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(br.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(br.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(br.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(br.div,{className:"absolute inset-0 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500",animate:{scale:[1,1.3,1],opacity:[.6,0,.6]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl relative z-10",children:p.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(br.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(br.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(br.h1,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-violet-200 via-white to-fuchsia-200 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:p.title[0]}),p.title[1]&&e.jsx(br.h2,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-fuchsia-300 via-violet-200 to-purple-300 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:p.title[1]}),e.jsx(br.div,{className:"text-3xl mb-4",initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},transition:{duration:.4,delay:1,type:"spring",stiffness:300},children:p.emojis.slice(0,3).join("")}),e.jsxs(br.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(ia,{className:"h-3.5 w-3.5"}),r]})]}),h&&e.jsx(br.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(br.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(br.div,{className:"bg-white/5 rounded-2xl p-5 border border-white/10 mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsx("p",{className:"text-sm text-violet-100/80 leading-relaxed",children:i||p.defaultMessage})}),e.jsxs(br.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(br.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(br.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(pa,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(br.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(on,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(br.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 qTn({emoji:s,delay:t,x:n,duration:r}){return e.jsx(br.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 Wgt={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 VTn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=Kq[t],x=Wgt[t]||Wgt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${x.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[p.emojis.map((y,g)=>e.jsx(qTn,{emoji:y,delay:g*1.2,x:`${15+g*14}%`,duration:5+g%3},g)),e.jsx(br.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(br.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(br.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(br.div,{className:`h-28 bg-gradient-to-r ${x.header} relative overflow-hidden`,children:[e.jsx(br.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(br.div,{className:"absolute top-3 left-10 text-5xl",animate:{rotate:[0,10,-5,0],y:[0,-3,0]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:p.emojis[0]}),e.jsx(br.div,{className:"absolute top-2 right-14 text-3xl",animate:{scale:[1,1.3,1],rotate:[0,15,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut",delay:.5},children:p.emojis[1]}),e.jsx(br.div,{className:"absolute bottom-2 left-1/2 -translate-x-1/2 text-3xl",animate:{y:[0,-5,0],scale:[1,1.1,1]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut",delay:1},children:p.emojis[2]})]}),e.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[e.jsx(br.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(br.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-3xl",children:p.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(br.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:e.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${x.accent}`,children:[e.jsx(br.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(br.h1,{className:`text-3xl font-bold ${x.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[p.title.join(" ")," ",p.emojis[4]]}),e.jsxs(br.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:`text-lg font-semibold ${x.text} mb-1`,children:n}),r&&e.jsxs("p",{className:`text-sm ${x.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(oi,{className:"h-3 w-3"}),r]})]}),h&&e.jsx(br.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(br.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(br.div,{className:"bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-5 mb-6 border border-amber-100 shadow-inner",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:`text-sm ${x.text} leading-relaxed italic`,children:['"',i||p.defaultMessage,'"']})}),e.jsxs(br.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(br.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${x.header} flex items-center justify-center shadow-md`,children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:`text-sm font-bold ${x.accent}`,children:l}),u&&e.jsx("p",{className:`text-xs ${x.text} opacity-60`,children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(br.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${x.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(pa,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(br.a,{href:`mailto:${d}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${x.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(on,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(br.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 xre({delay:s,x:t,y:n,size:r,color:a}){return e.jsx(br.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 t8e({delay:s,x:t,y:n,size:r}){return e.jsx(br.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 Kgt={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 HTn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=Kq[t],x=Kgt[t]||Kgt.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(xre,{delay:0,x:"5%",y:"10%",size:300,color:x.mesh[0]}),e.jsx(xre,{delay:2,x:"60%",y:"50%",size:250,color:x.mesh[1]}),e.jsx(xre,{delay:4,x:"30%",y:"70%",size:200,color:x.mesh[2]}),e.jsx(xre,{delay:1,x:"80%",y:"15%",size:180,color:x.mesh[0]}),e.jsx(t8e,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(t8e,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(t8e,{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(br.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(br.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${x.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[e.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:e.jsx(br.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(br.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(br.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(br.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:p.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(br.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(br.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:a}),e.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${x.accent}`,children:a===1?"Year":"Years"})]}),e.jsx(br.h1,{className:"text-4xl font-extralight text-white/90 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.7},children:p.title[0]}),p.title[1]&&e.jsx(br.h2,{className:"text-4xl font-bold text-white mb-6 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.85},children:p.title[1]}),e.jsxs(br.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(oi,{className:"h-3 w-3"})," ",r]})]}),e.jsx(br.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(br.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(br.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(br.div,{className:"bg-white/[0.04] rounded-2xl p-5 border border-white/[0.08] mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:"text-sm text-white/60 leading-relaxed italic",children:['"',i||p.defaultMessage,'"']})}),e.jsxs(br.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(br.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(br.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(pa,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(br.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(on,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(br.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 s8e({delay:s,x:t,angle:n,color:r}){return e.jsx(br.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 gre({delay:s,x:t}){return e.jsx(br.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 Ygt={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 GTn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=Kq[t],x=Ygt[t]||Ygt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${x.gradient} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.04)_0%,transparent_60%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom,rgba(0,0,0,0.6)_0%,transparent_60%)]"}),e.jsx(s8e,{delay:0,x:"20%",angle:15,color:x.stripe}),e.jsx(s8e,{delay:2,x:"75%",angle:-12,color:x.stripe}),e.jsx(s8e,{delay:4,x:"50%",angle:5,color:x.stripe}),e.jsx(gre,{delay:0,x:"30%"}),e.jsx(gre,{delay:1.5,x:"60%"}),e.jsx(gre,{delay:3,x:"45%"}),e.jsx(gre,{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(br.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(br.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(br.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(br.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${x.accent} flex items-center justify-center shadow-2xl`,animate:{boxShadow:["0 0 40px rgba(255,255,255,0.05)","0 0 80px rgba(255,255,255,0.1)","0 0 40px rgba(255,255,255,0.05)"]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-4xl",children:p.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(br.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(br.span,{className:`text-6xl font-black bg-gradient-to-r ${x.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:a}),e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:a===1?"Year":"Years"})]}),e.jsx("div",{className:"overflow-hidden mb-2",children:e.jsx(br.h1,{className:"text-5xl font-thin text-white/90 tracking-wide",initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.8,ease:[.16,1,.3,1]},children:p.title[0]})}),p.title[1]&&e.jsx("div",{className:"overflow-hidden mb-8",children:e.jsx(br.h2,{className:`text-5xl font-black bg-gradient-to-r ${x.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:p.title[1]})}),e.jsxs(br.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(oi,{className:"h-3 w-3"})," ",r]})]}),e.jsxs(br.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(br.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(br.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(br.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(br.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(br.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(br.p,{className:"text-sm text-white/40 leading-relaxed max-w-xs mx-auto mb-10 font-light",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.4,duration:.8},children:i||p.defaultMessage}),e.jsxs(br.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(br.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${x.accent} flex items-center justify-center shadow-xl`,children:e.jsx("span",{className:"text-sm font-bold text-slate-900",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium text-white/70",children:l}),u&&e.jsx("p",{className:"text-[11px] text-white/25",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c&&e.jsxs(br.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${x.accent} text-xs font-semibold text-slate-900 shadow-lg`,whileHover:{scale:1.05,boxShadow:"0 10px 40px rgba(255,255,255,0.15)"},whileTap:{scale:.95},children:[e.jsx(pa,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(br.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(on,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(br.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 WBt(){const{shareToken:s}=$i(),{data:t,isLoading:n,error:r}=mt({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await U.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(j.useEffect(()=>{s&&U.rpc("log_sendable_card_view",{p_share_token:s}).then(({error:l})=>{l&&console.error("Error tracking view:",l)})},[s]),n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[e.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),e.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This card may have been removed or the link is invalid."})]})});const a=t.home_anniversary_date?Math.floor((Date.now()-Ic(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(UTn,{...i});case"warm":return e.jsx(VTn,{...i});case"glass":return e.jsx(HTn,{...i});case"cinematic":return e.jsx(GTn,{...i});case"elegant":default:return e.jsx($Tn,{...i})}}function WTn(){const s=ei();return mt({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function KTn(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r}=await U.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(r){const{data:a,error:i}=await U.from("drip_settings").update(n).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await U.from("drip_settings").insert({user_id:s,is_globally_enabled:n.is_globally_enabled??!1,append_signature:n.append_signature??!0}).select().single();if(i)throw i;return a}},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-settings"]})}})}function YTn(){const s=Hn(),{isGmailConnected:t,gmailEmail:n}=Tf(),{data:r,isLoading:a}=WTn(),i=KTn(),[l,o]=j.useState(!1),[c,d]=j.useState(!0),[u,h]=j.useState(!1);j.useEffect(()=>{r&&(o(r.is_globally_enabled),d(r.append_signature))},[r]);const m=async x=>{if(x&&!t){re.error("Connect your Gmail account first before enabling Smart Drips");return}o(x);try{await i.mutateAsync({is_globally_enabled:x}),re.success(x?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!x),re.error("Failed to update settings")}},p=async x=>{d(x);try{await i.mutateAsync({append_signature:x}),re.success(x?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!x),re.error("Failed to update settings")}};return e.jsxs(Fs,{open:u,onOpenChange:h,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(ic,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(ic,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(kr,{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(on,{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(qe,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(Rr,{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(Xl,{}),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(tK,{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(Mn,{checked:l,onCheckedChange:m,disabled:a||i.isPending})]}),e.jsx(Xl,{}),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(oj,{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(Mn,{checked:c,onCheckedChange:p,disabled:a||i.isPending})]}),c&&e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{h(!1),s("/profile")},children:[e.jsx(oj,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function ZTn(){const s=ei();return mt({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("drip_templates").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function XTn(){const s=ei();return mt({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function QTn(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("drip_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title||"",subject:n.subject||"",body:n.body||"",video_url:n.video_url||null,channel:n.channel||"email",delay_type:n.delay_type||"instant",delay_minutes:n.delay_minutes||0,is_enabled:!1,deal_type:n.deal_type||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}function JTn(){const s=as();return vt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await U.from("drip_templates").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function eEn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("drip_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function tEn(){const s=ei(),t=as();return vt({mutationFn:async({templateId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await U.from("drip_templates").select("*").eq("id",n).single();if(i)throw i;const{data:l,error:o}=await U.from("drip_templates").insert({owner_user_id:s,stage_id:r,title:a.title,subject:a.subject,body:a.body,video_url:a.video_url,channel:a.channel,delay_type:a.delay_type,delay_minutes:a.delay_minutes,is_enabled:!1,is_starter:!1,deal_type:a.deal_type}).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}const sEn=[{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 nEn({open:s,onOpenChange:t,campaignId:n,campaignName:r}){const{data:a,isLoading:i}=xgn(n||void 0),l=ygn(),o=vRt(),c=async(h,m)=>{try{await l.mutateAsync({id:h,status:m}),re.success(`Enrollment ${m}`)}catch{re.error("Failed to update")}},d=async h=>{if(n)try{const m=await o.mutateAsync({campaignId:n,contactIds:[h]});m.enrolled>0?re.success("Contact re-enrolled — first email queued"):m.skipped>0?re.message("Already active in this campaign"):re.error("Could not re-enroll")}catch{re.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(qe,{variant:"outline",className:`text-[10px] capitalize ${m[h]||""}`,children:h})};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs("div",{className:"p-5 border-b shrink-0",children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(Bn,{className:"h-4 w-4 text-primary"}),"Enrollments — ",r||"Campaign"]}),e.jsx(kr,{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(gn,{className:"h-14"},h))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Bn,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No contacts enrolled yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",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,p,x,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," ",(p=h.contact)==null?void 0:p.last_name]}),u(h.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((x=h.contact)==null?void 0:x.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(on,{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: ",Bs(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(ay,{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(fd,{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(dr,{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(bm,{className:"h-3 w-3"}),"Re-enroll"]})]},h.id)})})})})]})})}function rEn(){var k;const{data:s,isLoading:t}=QJ(),{hasLeadSite:n}=h0(),r=wWe(),a=hgn(),i=gRt(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(null),x=(s||[]).filter(C=>!C.is_starter),y=(s||[]).filter(C=>C.is_starter).filter(C=>!C.requires_lead_site||n),g=async C=>{try{await r.mutateAsync(C),re.success("Campaign added to your library — customize and activate it!"),o(null)}catch(T){re.error(T.message||"Failed to copy campaign")}},b=async C=>{try{await i.mutateAsync({id:C.id,is_active:!C.is_active}),re.success(C.is_active?"Campaign paused":"Campaign activated")}catch{re.error("Failed to update")}},v=async C=>{if(await Bi("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(C),re.success("Campaign deleted")}catch{re.error("Failed to delete")}};return t?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(C=>e.jsx(gn,{className:"h-44 rounded-xl"},C))}):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(I5,{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(uu,{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(Dr,{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(Bn,{className:"h-4 w-4 text-primary"}),"My Campaigns"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Custom drip campaigns you've created or copied"})]}),e.jsxs(B,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1.5"})," New Campaign"]})]}),x.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl bg-muted/20",children:[e.jsx(yn,{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(Js,{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:x.map(C=>e.jsx(aEn,{campaign:C,onPreview:()=>o(C.id),onToggleActive:()=>b(C),onDelete:()=>v(C.id),onEdit:()=>{h(C.id),d(!0)},onViewEnrollments:()=>p(C.id)},C.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(yn,{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(qe,{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(C=>e.jsx(iEn,{campaign:C,onPreview:()=>o(C.id)},C.id))})]}),e.jsx(oEn,{campaignId:l,open:!!l,onOpenChange:C=>!C&&o(null),onClone:g,isCloning:r.isPending,onEdit:C=>{o(null),h(C),d(!0)}}),e.jsx(wRt,{open:c,onOpenChange:d,campaignId:u}),e.jsx(nEn,{open:!!m,onOpenChange:C=>!C&&p(null),campaignId:m,campaignName:(k=x.find(C=>C.id===m))==null?void 0:k.name})]})}function aEn({campaign:s,onPreview:t,onToggleActive:n,onDelete:r,onEdit:a,onViewEnrollments:i}){const o=ggn(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(qe,{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(qe,{variant:"outline",className:"text-[9px] mt-2",children:IAe[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(hd,{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(Za,{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 iEn({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(qe,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(yn,{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(qe,{variant:"outline",className:"text-[9px] mt-2",children:IAe[s.category]})]})]})}function oEn({campaignId:s,open:t,onOpenChange:n,onClone:r,isCloning:a,onEdit:i}){const{data:l}=QJ(),{data:o}=yRt(s||void 0),[c,d]=j.useState(new Set),u=l==null?void 0:l.find(p=>p.id===s);if(!u)return null;const h=p=>{d(x=>{const y=new Set(x);return y.has(p)?y.delete(p):y.add(p),y})},m=(p,x)=>{if(p.delay_type==="calendar_anchor"){const g=p.anchor_field==="birthday"?"birthday":"home anniversary",b=p.anchor_offset_days||0;return b===0?`On their ${g}`:b<0?`${Math.abs(b)} days before ${g}`:`${b} days after ${g}`}if(x===0&&p.delay_days===0&&p.delay_hours===0)return"Sends immediately";const y=[];return p.delay_days&&y.push(`${p.delay_days}d`),p.delay_hours&&y.push(`${p.delay_hours}h`),x===0?`After ${y.join(" ")}`:`+${y.join(" ")}`};return e.jsx(Fs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${u.cover_color} p-6 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("span",{className:"text-5xl drop-shadow-sm",children:u.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx(zs,{className:"text-xl font-bold text-white",children:u.name}),e.jsx(kr,{className:"text-white/90 mt-1",children:u.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(qe,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:IAe[u.category]}),e.jsxs(qe,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:[(o==null?void 0:o.length)||0," step",(o==null?void 0:o.length)!==1?"s":""]})]})]})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"The sequence"}),u.is_starter?e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Copy to your library to edit"}):e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Tap a step to expand · Edit to customize"})]}),o==null?void 0:o.map((p,x)=>{const y=c.has(p.id);return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"shrink-0 flex flex-col items-center",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:x+1}),xh(p.id),className:"flex-1 pb-4 text-left",children:e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/20 hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 text-xs text-muted-foreground",children:[p.delay_type==="calendar_anchor"?e.jsx(ra,{className:"h-3 w-3"}):e.jsx(Vr,{className:"h-3 w-3"}),e.jsx("span",{children:m(p,x)}),e.jsx("span",{children:"·"}),e.jsx(on,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:p.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:p.subject}),(()=>{const g=p.body||"",b=/<\/?[a-z][\s\S]*>/i.test(g),v=b?g.replace(//gi,"").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim():g;return y?b?e.jsx("div",{className:"text-xs text-foreground mt-2 prose prose-sm max-w-none [&_a]:text-primary",dangerouslySetInnerHTML:{__html:g}}):e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:g}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:v})})(),p.body&&p.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:y?"Show less":"Show full email"})]})})]},p.id)})]})}),e.jsxs(Nr,{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(Za,{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(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(ja,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}const S2e=[{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 lEn(){const s=ei();return mt({queryKey:["drip-auto-rules",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await U.from("drip_auto_enroll_rules").select("*, campaign:drip_campaigns(id, name, category, cover_color)").eq("owner_user_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function cEn(){const s=ei(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={owner_user_id:s,campaign_id:n.campaign_id,trigger_type:n.trigger_type,lead_days:n.lead_days??14,filter_tags:n.filter_tags??[],filter_relationship_types:n.filter_relationship_types??[],require_email:n.require_email??!0,is_active:n.is_active??!0};n.id&&(r.id=n.id);const{data:a,error:i}=await U.from("drip_auto_enroll_rules").upsert(r).select().single();if(i)throw i;return a},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-auto-rules"]})}})}function dEn(){const s=as();return vt({mutationFn:async({id:t,is_active:n})=>{const{error:r}=await U.from("drip_auto_enroll_rules").update({is_active:n}).eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function uEn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("drip_auto_enroll_rules").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function hEn(s=25){const t=ei();return mt({queryKey:["drip-auto-log",t,s],queryFn:async()=>{if(!t)return[];const{data:n,error:r}=await U.from("drip_auto_enroll_log").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("owner_user_id",t).order("created_at",{ascending:!1}).limit(s);if(r)throw r;return n||[]},enabled:!!t})}function mEn(){const s=ei();return mt({queryKey:["life-event-coverage",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await U.from("innercircle_contacts").select("birthday, home_anniversary, spouse_birthday, wedding_anniversary, email").eq("owner_user_id",s).limit(1e4);if(n)throw n;const r=t||[],a=(l,o)=>{if(!l)return!1;const[,c,d]=String(l).split("-").map(Number),u=new Date;let h=new Date(u.getFullYear(),c-1,d);return h{const o=r.filter(c=>!!c[l.column]);i[l.value]={total:o.length,upcoming30:o.filter(c=>a(c[l.column],30)).length}}),{totalContacts:r.length,counts:i}},enabled:!!s})}function pEn(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.functions.invoke("process-life-event-drips",{body:t?{rule_id:t}:{}});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-auto-rules"]}),s.invalidateQueries({queryKey:["drip-auto-log"]}),s.invalidateQueries({queryKey:["drip-campaign-enrollments"]})}})}const fEn={birthday:Wm,home_anniversary:hN,spouse_birthday:zo,wedding_anniversary:mo};function xEn(){var C;const{data:s,isLoading:t}=lEn(),{data:n}=QJ(),{data:r}=mEn(),{data:a}=hEn(10),i=cEn(),l=dEn(),o=uEn(),c=pEn(),d=wWe(),[u,h]=j.useState(null),m=j.useMemo(()=>(n||[]).filter(T=>!T.is_starter),[n]),p={birthday:"Birthday",home_anniversary:"Home Anniversary",spouse_birthday:"Spouse Birthday",wedding_anniversary:"Wedding Anniversary"},x=j.useMemo(()=>{if(!(u!=null&&u.trigger_type))return null;const T=p[u.trigger_type];return!T||m.some(P=>String(P.name||"").toLowerCase().includes(T.toLowerCase()))?null:(n||[]).find(P=>P.is_starter&&String(P.name||"").toLowerCase()===T.toLowerCase())??null},[n,m,u==null?void 0:u.trigger_type]),y=async()=>{if(x)try{const T=await d.mutateAsync(x.id);h(M=>({...M,campaign_id:T.id})),re.success(`“${x.name}” template added to your campaigns`)}catch(T){re.error((T==null?void 0:T.message)||"Could not copy the template")}},g=T=>(s||[]).find(M=>M.trigger_type===T),b=async()=>{if(!(u!=null&&u.campaign_id)||!(u!=null&&u.trigger_type)){re.error("Pick a campaign first");return}try{await i.mutateAsync(u),re.success("Autopilot rule saved"),h(null)}catch(T){re.error((T==null?void 0:T.message)||"Could not save rule")}},v=async()=>{try{const T=await c.mutateAsync(void 0);re.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){re.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(yn,{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:v,disabled:c.isPending||k===0,className:"gap-2 shrink-0",children:[c.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ki,{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:S2e.map(T=>{const M=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:(M==null?void 0:M.total)??0}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[(M==null?void 0:M.upcoming30)??0," in next 30 days"]})]},T.value)})})]}),t?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Wt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:S2e.map(T=>{var I;const M=g(T.value),P=fEn[T.value]||Wm,L=r==null?void 0:r.counts[T.value];return e.jsxs("div",{className:Et("rounded-xl border bg-card p-4 transition-colors",(M==null?void 0:M.is_active)&&"border-primary/40 bg-primary/[0.03]"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Et("h-10 w-10 rounded-lg flex items-center justify-center shrink-0",M!=null&&M.is_active?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(P,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm",children:T.label}),(M==null?void 0:M.is_active)&&e.jsx(qe,{className:"text-[10px] bg-primary/10 text-primary hover:bg-primary/10",children:"On"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:M?`${((I=M.campaign)==null?void 0:I.name)??"Campaign"} · starts ${M.lead_days} days before`:T.description}),M&&M.total_enrolled>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:[M.total_enrolled," contact",M.total_enrolled===1?"":"s"," enrolled so far"]}),!M&&((L==null?void 0:L.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."})]}),M?e.jsx(Mn,{checked:M.is_active,onCheckedChange:O=>l.mutate({id:M.id,is_active:O})}):null]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",variant:M?"outline":"default",className:"flex-1 gap-1.5",onClick:()=>h(M??{trigger_type:T.value,lead_days:T.value==="birthday"?7:14,require_email:!0,is_active:!0,filter_tags:[],filter_relationship_types:[]}),children:[M?e.jsx(jf,{className:"h-3.5 w-3.5"}):e.jsx(Js,{className:"h-3.5 w-3.5"}),M?"Edit rule":"Turn on autopilot"]}),M&&e.jsx(B,{size:"sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive",onClick:()=>o.mutate(M.id),children:e.jsx(Rn,{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 M,P;return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[e.jsx(da,{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:[(M=T.contact)==null?void 0:M.first_name," ",(P=T.contact)==null?void 0:P.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(Fs,{open:!!u,onOpenChange:T=>!T&&h(null),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs($s,{children:[e.jsxs(zs,{children:[(C=S2e.find(T=>T.value===(u==null?void 0:u.trigger_type)))==null?void 0:C.label," autopilot"]}),e.jsx(kr,{children:"Choose the campaign to run and how far ahead it should start."})]}),e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Campaign to enroll into"}),e.jsxs(vs,{value:(u==null?void 0:u.campaign_id)??"",onValueChange:T=>h(M=>({...M,campaign_id:T})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one of your campaigns"})}),e.jsx(ys,{children:m.map(T=>e.jsx(Je,{value:T.id,children:T.name},T.id))})]}),x&&e.jsx("div",{className:"rounded-lg border border-primary/25 bg-primary/5 p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(yn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium leading-tight",children:["Use the LevelUp “",x.name,"” template"]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Beautifully designed, personalized emails written for this moment. We'll copy it into your campaigns so you can edit anything you like."}),e.jsxs(B,{size:"sm",variant:"outline",className:"mt-2 gap-1.5",disabled:d.isPending,onClick:y,children:[d.isPending?e.jsx(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Js,{className:"h-3.5 w-3.5"}),"Use this template"]})]})]})}),m.length===0&&!x&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"You need one of your own campaigns first — clone a starter from the Campaigns tab."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Start this many days before the event"}),e.jsxs("span",{className:"text-sm font-semibold tabular-nums",children:[(u==null?void 0:u.lead_days)??14,"d"]})]}),e.jsx(Qf,{min:0,max:45,step:1,value:[(u==null?void 0:u.lead_days)??14],onValueChange:([T])=>h(M=>({...M,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(se,{className:"text-sm",children:"Only contacts with an email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip records that can't be reached."})]}),e.jsx(Mn,{checked:(u==null?void 0:u.require_email)??!0,onCheckedChange:T=>h(M=>({...M,require_email:T}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-sm",children:"Autopilot active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Runs every morning automatically."})]}),e.jsx(Mn,{checked:(u==null?void 0:u.is_active)??!0,onCheckedChange:T=>h(M=>({...M,is_active:T}))})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>h(null),children:"Cancel"}),e.jsxs(B,{onClick:b,disabled:i.isPending||!(u!=null&&u.campaign_id),children:[i.isPending&&e.jsx(Wt,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save rule"]})]})]})})]})}function gEn(){const s=ei(),t=Hn(),{isGmailConnected:n,gmailEmail:r,isLoading:a}=Tf(),{data:i,isLoading:l}=ZTn(),{data:o,isLoading:c}=XTn(),d=QTn(),u=JTn(),h=eEn(),m=tEn(),[p,x]=j.useState(null),[y,g]=j.useState(null),b=(i==null?void 0:i.filter(I=>!I.is_starter&&I.owner_user_id===s))||[],v=(i==null?void 0:i.filter(I=>I.is_starter))||[],k=I=>b.filter(O=>O.stage_id===I),C=async I=>{try{await u.mutateAsync({id:I.id,is_enabled:!I.is_enabled}),re.success(I.is_enabled?"Drip disabled":"Drip enabled")}catch{re.error("Failed to update")}},T=async I=>{try{const O=o==null?void 0:o.find($=>$.id===I);await d.mutateAsync({stage_id:I,title:`${(O==null?void 0:O.name)||"Stage"} follow-up`,subject:"",body:"",channel:"email",delay_type:"instant",delay_minutes:0}),x(I),re.success("Drip template created")}catch{re.error("Failed to create template")}},M=async I=>{try{await h.mutateAsync(I),re.success("Template deleted")}catch{re.error("Failed to delete")}},P=async I=>{if(!o||o.length===0){re.error("No pipeline stages found");return}const O=o[0].id;try{await m.mutateAsync({templateId:I,stageId:O}),re.success("Template copied to your drips!")}catch{re.error("Failed to copy template")}},L=l||c;return e.jsx(Vs,{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(jf,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(qe,{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(YTn,{})]}),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(I5,{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(on,{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(I5,{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(on,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs(fa,{defaultValue:"my-drips",children:[e.jsxs(xa,{className:"grid grid-cols-4 w-full max-w-2xl mb-6",children:[e.jsx(ss,{value:"my-drips",children:"Stage Drips"}),e.jsxs(ss,{value:"campaigns",children:["Campaigns",e.jsx(qe,{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(ss,{value:"autopilot",children:["Life Events",e.jsx(qe,{variant:"outline",className:"ml-1.5 text-[9px] bg-primary/10 text-primary border-primary/20 px-1 py-0",children:"Auto"})]}),e.jsxs(ss,{value:"starters",children:["Stage Starters",v.length>0&&e.jsx(qe,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:v.length})]})]}),e.jsx(ns,{value:"campaigns",children:e.jsx(rEn,{})}),e.jsx(ns,{value:"autopilot",children:e.jsx(xEn,{})}),e.jsx(ns,{value:"my-drips",children:L?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(I=>e.jsx(gn,{className:"h-16 w-full rounded-xl"},I))}):!o||o.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(jf,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create pipeline stages first to set up drip automations."})]}):e.jsxs("div",{className:"space-y-2",children:[o.filter(I=>!I.is_won_stage&&!I.is_lost_stage).map(I=>{const O=k(I.id),$=p===I.id,q=O.some(W=>W.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>x($?null:I.id),className:"w-full flex items-center gap-3 p-4 hover:bg-muted/30 transition-colors text-left",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:I.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:I.name}),O.length>0&&e.jsxs(qe,{variant:"outline",className:`text-[10px] ${q?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[O.length," drip",O.length!==1?"s":"",q&&" · Active"]}),$?e.jsx(Po,{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:O.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(I.id),disabled:d.isPending,children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[O.map(W=>e.jsx(Zgt,{template:W,isEditing:y===W.id,onToggleEdit:()=>g(y===W.id?null:W.id),onToggleEnabled:()=>C(W),onUpdate:G=>u.mutateAsync({id:W.id,...G}),onDelete:()=>M(W.id),userId:s||""},W.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>T(I.id),children:[e.jsx(Js,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},I.id)}),o.filter(I=>I.is_won_stage||I.is_lost_stage).length>0&&e.jsxs("div",{className:"pt-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground font-medium mb-2 px-1",children:"Closing Stages"}),o.filter(I=>I.is_won_stage||I.is_lost_stage).map(I=>{const O=k(I.id),$=p===I.id,q=O.some(W=>W.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>x($?null:I.id),className:"w-full flex items-center gap-3 p-4 hover:bg-muted/30 transition-colors text-left",children:[e.jsx("div",{className:"w-3 h-3 rounded-full shrink-0",style:{backgroundColor:I.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:I.name}),O.length>0&&e.jsxs(qe,{variant:"outline",className:`text-[10px] ${q?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[O.length," drip",O.length!==1?"s":"",q&&" · Active"]}),$?e.jsx(Po,{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:O.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(I.id),disabled:d.isPending,children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[O.map(W=>e.jsx(Zgt,{template:W,isEditing:y===W.id,onToggleEdit:()=>g(y===W.id?null:W.id),onToggleEnabled:()=>C(W),onUpdate:G=>u.mutateAsync({id:W.id,...G}),onDelete:()=>M(W.id),userId:s||""},W.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>T(I.id),children:[e.jsx(Js,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},I.id)})]})]})}),e.jsx(ns,{value:"starters",children:v.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(yn,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Starter Templates Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"Admin-created starter templates will appear here. You'll be able to copy them into your own drips."})]}):e.jsx("div",{className:"space-y-3",children:v.map(I=>e.jsx(yEn,{template:I,onCopy:()=>P(I.id),isCopying:m.isPending},I.id))})})]})]})})}function Zgt({template:s,isEditing:t,onToggleEdit:n,onToggleEnabled:r,onUpdate:a,onDelete:i,userId:l}){const[o,c]=j.useState(s.title),[d,u]=j.useState(s.subject),[h,m]=j.useState(s.body),[p,x]=j.useState(s.video_url||""),[y,g]=j.useState(s.channel),[b,v]=j.useState(s.delay_type),[k,C]=j.useState(s.delay_minutes),[T,M]=j.useState(!1),P=async()=>{M(!0);try{await a({title:o,subject:d,body:h,video_url:p||null,channel:y,delay_type:b,delay_minutes:k}),re.success("Drip saved"),n()}catch{re.error("Failed to save")}finally{M(!1)}},L=I=>{m(O=>O+I)};return e.jsxs("div",{className:"border rounded-lg bg-background overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",role:"button",onClick:n,children:[e.jsx("p",{className:"text-sm font-medium truncate",children:s.title||"Untitled drip"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.channel==="sms"?e.jsx(ro,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(on,{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(Zr,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(Mn,{checked:s.is_enabled,onCheckedChange:r})]}),t&&e.jsxs("div",{className:"border-t p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(ye,{value:o,onChange:I=>c(I.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Buyer intro video"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{className:"text-xs font-medium",children:"Channel"}),e.jsx("div",{className:"flex gap-1 mt-1",children:["email","sms"].map(I=>e.jsxs("button",{onClick:()=>g(I),className:`flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${y===I?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[I==="sms"?e.jsx(ro,{className:"h-3 w-3"}):e.jsx(on,{className:"h-3 w-3"}),I==="sms"?"SMS":"Email"]},I))})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(se,{className:"text-xs font-medium",children:"Timing"}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx("button",{onClick:()=>v("instant"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${b==="instant"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:"Instant"}),e.jsxs("button",{onClick:()=>v("scheduled"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${b==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(Vr,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),b==="scheduled"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ye,{type:"number",min:1,value:k>=60?Math.round(k/60):k,onChange:I=>{const O=parseInt(I.target.value)||0;C(k>=60?O*60:O)},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(I=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${I.label==="Minutes"&&k<60||I.label==="Hours"&&k>=60&&k<1440||I.label==="Days"&&k>=1440?"bg-primary/10 text-primary border-primary/30":"text-muted-foreground border-input"}`,onClick:()=>{I.label==="Minutes"?C(30):I.label==="Hours"?C(60):C(1440)},children:I.label},I.label))})]})]}),y==="email"&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(ye,{value:d,onChange:I=>u(I.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Next steps for your home purchase"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(se,{className:"text-xs font-medium",children:y==="sms"?"Message":"Email Body"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Insert:"}),e.jsxs("select",{className:"text-[10px] border rounded px-1 py-0.5 bg-background text-muted-foreground",value:"",onChange:I=>{I.target.value&&L(I.target.value),I.target.value=""},children:[e.jsx("option",{value:"",children:"Merge variable..."}),sEn.map(I=>e.jsx("option",{value:I.key,children:I.label},I.key))]})]})]}),e.jsx("textarea",{value:h,onChange:I=>m(I.target.value),placeholder:y==="sms"?"Hey {{client_first_name}}, great talking with you today! Here's a quick video about what's next...":`Hi {{client_first_name}}, It was great meeting with you! Here's a video about what to expect next...`,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[100px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs font-medium",children:"Attached Video"}),p?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:[e.jsx(Zr,{className:"h-3 w-3 inline mr-1 text-primary"}),p.length>50?p.slice(0,50)+"...":p]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>x(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(tYe,{onVideoReady:I=>x(I)}),e.jsx(LO,{userId:l,onSelect:I=>x(I),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1"}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const I=prompt("Paste a YouTube or Loom URL:");I&&x(I)},children:[e.jsx(vc,{className:"h-3 w-3"})," Paste URL"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:i,children:[e.jsx(Rn,{className:"h-3 w-3 mr-1"})," Delete"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",className:"text-xs",onClick:n,children:"Cancel"}),e.jsx(B,{size:"sm",className:"text-xs",onClick:P,disabled:T,children:T?"Saving...":"Save Drip"})]})]})]})]})}function yEn({template:s,onCopy:t,isCopying:n}){const[r,a]=j.useState(!1),i=s.body.replace(/<[^>]+>/g,""),l=s.deal_type==="buyer"?"Buyer":s.deal_type==="seller"?"Seller":null,o=s.delay_type==="instant"?"Sends instantly":s.delay_minutes>=1440?`Sends after ${Math.round(s.delay_minutes/1440)} day${Math.round(s.delay_minutes/1440)!==1?"s":""}`:s.delay_minutes>=60?`Sends after ${Math.round(s.delay_minutes/60)} hour${Math.round(s.delay_minutes/60)!==1?"s":""}`:`Sends after ${s.delay_minutes} min`;return e.jsxs("div",{className:"border rounded-xl overflow-hidden transition-all hover:shadow-sm",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-start gap-3 p-4 text-left hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:s.subject}),!r&&e.jsx("p",{className:"text-xs text-muted-foreground/70 line-clamp-1 mt-1",children:i})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",children:[l&&e.jsx(qe,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(ro,{className:"h-3 w-3"}):e.jsx(on,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),r?e.jsx(Po,{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(Vr,{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(ja,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const KBt=()=>{const s=$d();return j.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",s.pathname)},[s.pathname]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),e.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),e.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})};function vEn(){return j.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(GY,{children:[e.jsx(fs,{path:"/c/:shareToken",element:e.jsx(WBt,{})}),e.jsx(fs,{path:"*",element:e.jsx(KBt,{})})]})}const n8e={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"},bEn=["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","America/Anchorage","Pacific/Honolulu","Europe/London","Europe/Paris","Asia/Dubai","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];function _En(s,t,n){const[r,a,i]=s.split("-").map(Number),[l,o]=t.split(":").map(Number),c=Date.UTC(r,a-1,i,l,o),d=new Intl.DateTimeFormat("en-US",{timeZone:n,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),u=Object.fromEntries(d.formatToParts(new Date(c)).filter(m=>m.type!=="literal").map(m=>[m.type,m.value])),h=Date.UTC(Number(u.year),Number(u.month)-1,Number(u.day),Number(u.hour)%24,Number(u.minute));return c+(c-h)}function r8e(s){var t;try{return((t=new Intl.DateTimeFormat("en-US",{timeZone:s,timeZoneName:"short"}).formatToParts(new Date).find(r=>r.type==="timeZoneName"))==null?void 0:t.value)||s}catch{return s}}function YBt({slugOverride:s}){const t=$i(),n=s||t.slug,[r,a]=j.useState("types"),[i,l]=j.useState(null),[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState(new Date),[p,x]=j.useState({name:"",email:"",phone:"",message:""}),[y,g]=j.useState(!1),[b,v]=j.useState(null),[k,C]=j.useState(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"America/New_York"}catch{return"America/New_York"}}),{data:T,isLoading:M}=mt({queryKey:["public-booking-settings",n],queryFn:async()=>{const{data:oe,error:ie}=await U.from("agent_booking_settings").select("*").eq("slug",n).eq("is_active",!0).single();if(ie)throw ie;return oe},enabled:!!n}),{data:P}=mt({queryKey:["public-booking-profile",T==null?void 0:T.user_id],queryFn:async()=>{const{data:oe,error:ie}=await U.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",T.user_id).single();if(ie)throw ie;return oe},enabled:!!(T!=null&&T.user_id)}),{data:L=[]}=mt({queryKey:["public-booking-types",T==null?void 0:T.user_id],queryFn:async()=>{const{data:oe,error:ie}=await U.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",T.user_id).eq("is_active",!0).eq("is_coaching_only",!1).order("sort_order");if(ie)throw ie;return oe},enabled:!!(T!=null&&T.user_id)}),I=Bs(h,"yyyy-MM"),{data:O={},isFetching:$}=mt({queryKey:["public-availability-map",n,i==null?void 0:i.id,I],enabled:!!n&&!!i,staleTime:6e4,queryFn:async()=>{const oe=new Date(h.getFullYear(),h.getMonth(),1),ie=xm(new Date),de=vb(ie,oe)?ie:oe,we=new Date(h.getFullYear(),h.getMonth()+1,0),je=Math.max(1,Math.round((we.getTime()-de.getTime())/864e5)+1),{data:xe,error:fe}=await U.functions.invoke("agent-booking",{body:{action:"availability",slug:n,booking_type_id:i.id,start:Bs(de,"yyyy-MM-dd"),days:Math.min(je,90)}});if(fe)throw fe;if(xe!=null&&xe.error)throw new Error(xe.error);return(xe==null?void 0:xe.availability)||{}}}),q=oe=>{const ie=xm(new Date),de=jd(ie,(T==null?void 0:T.max_advance_days)||30);return W_(oe,ie)||vb(oe,de)?!1:(O[Bs(oe,"yyyy-MM-dd")]||[]).length>0},W=j.useMemo(()=>o?O[Bs(o,"yyyy-MM-dd")]||[]:[],[o,O]),G=j.useMemo(()=>{const oe=h.getFullYear(),ie=h.getMonth(),de=new Date(oe,ie,1),we=new Date(oe,ie+1,0),je=de.getDay(),xe=[];for(let fe=0;fe{var oe,ie;if(!(!i||!o||!d||!p.name||!T)){g(!0);try{const de=Bs(o,"yyyy-MM-dd"),{data:we,error:je}=await U.functions.invoke("agent-booking",{body:{action:"create",slug:n,booking_type_id:i.id,date:de,time:d,guest_name:p.name,guest_email:p.email||null,guest_phone:p.phone||null,guest_message:p.message||null,guest_timezone:k}});if(je){let Se=je.message;try{const Ee=await((ie=(oe=je.context)==null?void 0:oe.json)==null?void 0:ie.call(oe));Ee!=null&&Ee.error&&(Se=Ee.error)}catch{}throw new Error(Se)}if(we!=null&&we.error)throw new Error(we.error);const xe=(we==null?void 0:we.end_time)||d,fe=we!=null&&we.manage_token?`${window.location.origin}/booking/manage/${we.manage_token}`:null;v(fe),U.functions.invoke("booking-notify",{body:{agentUserId:T.user_id,guestName:p.name,guestEmail:p.email||null,guestPhone:p.phone||null,guestMessage:p.message||null,bookingTypeName:i.name,bookingDate:de,startTime:d,endTime:xe,durationMinutes:i.duration_minutes,meetingLink:T.meeting_link||null,manageUrl:fe}}).catch(Se=>console.error("Booking notify error:",Se)),a("confirmed")}catch(de){re.error("Failed to book: "+de.message)}finally{g(!1)}}},ee=oe=>{const[ie,de]=oe.split(":").map(Number),we=ie>=12?"PM":"AM";return`${ie%12||12}:${de.toString().padStart(2,"0")} ${we}`},J=(T==null?void 0:T.timezone)||"America/New_York",le=k!==J,ue=(oe,ie)=>{if(!le)return ee(ie);try{return new Intl.DateTimeFormat("en-US",{timeZone:k,hour:"numeric",minute:"2-digit"}).format(new Date(_En(oe,ie,J)))}catch{return ee(ie)}};return M?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..."})]})}):T?e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8]",children:[e.jsx("div",{className:"h-1.5 bg-gradient-to-r from-[#406E71] via-[#5a9a9d] to-[#2a4c64]"}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 py-6 sm:py-10",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden mb-6",children:[e.jsx("div",{className:"relative bg-gradient-to-r from-[#406E71] to-[#2a4c64] px-6 pt-6 pb-12",children:e.jsxs("div",{className:"absolute inset-0 opacity-10",children:[e.jsx("div",{className:"absolute top-2 right-8 w-20 h-20 rounded-full border-2 border-white/30"}),e.jsx("div",{className:"absolute bottom-4 left-12 w-10 h-10 rounded-full border border-white/20"})]})}),e.jsx("div",{className:"relative -mt-10 px-6",children:e.jsxs("div",{className:"flex items-end gap-4",children:[P!=null&&P.avatar_url?e.jsx("img",{src:P.avatar_url,alt:(P==null?void 0:P.name)||"Agent",className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl object-cover border-4 border-white shadow-md"}):e.jsx("div",{className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl bg-gradient-to-br from-[#406E71] to-[#2a4c64] border-4 border-white shadow-md flex items-center justify-center",children:e.jsx(Eo,{className:"h-10 w-10 text-white"})}),e.jsxs("div",{className:"pb-1.5",children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-slate-800 leading-tight",children:(P==null?void 0:P.name)||"Agent"}),(P==null?void 0:P.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:P.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(P==null?void 0:P.phone)&&e.jsxs("a",{href:`tel:${P.phone}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#406E71]/8 hover:bg-[#406E71]/15 text-[#406E71] text-xs font-medium transition-colors",children:[e.jsx(pa,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:P.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(P==null?void 0:P.email)&&e.jsxs("a",{href:`mailto:${P.email}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#2a4c64]/8 hover:bg-[#2a4c64]/15 text-[#2a4c64] text-xs font-medium transition-colors",children:[e.jsx(on,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:P.email}),e.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),e.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",children:[r==="types"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),e.jsx("div",{className:"space-y-2.5",children:L.map(oe=>e.jsx("button",{onClick:()=>{l(oe),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:oe.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:n8e[oe.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:oe.name}),oe.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:oe.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(Vr,{className:"h-3 w-3"}),oe.duration_minutes,"m"]})]})})},oe.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(_a,{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:n8e[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(Vr,{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:Bs(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(Cc,{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(oe=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:oe},oe)),G.map((oe,ie)=>{if(!oe)return e.jsx("div",{},`pad-${ie}`);const de=q(oe),we=o&&pd(oe,o),je=pd(oe,new Date);return e.jsx("button",{disabled:!de,onClick:()=>{c(oe),u(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${we?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":de?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${je&&!we?"ring-1 ring-[#406E71]/40":""}`,children:oe.getDate()},oe.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vc,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Bs(o,"EEEE, MMMM d")})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl bg-slate-50 border border-slate-100 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] text-slate-500",children:"Times shown in your timezone"}),e.jsx("select",{value:k,onChange:oe=>C(oe.target.value),className:"text-[11px] font-medium text-slate-700 bg-transparent focus:outline-none cursor-pointer",children:Array.from(new Set([k,J,...bEn])).map(oe=>e.jsxs("option",{value:oe,children:[oe.replace(/_/g," ")," (",r8e(oe),")"]},oe))})]}),$&&W.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(Wt,{className:"h-6 w-6 text-slate-300 mx-auto animate-spin"}),e.jsx("p",{className:"text-sm text-slate-400",children:"Checking live availability…"})]}):W.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(Vr,{className:"h-8 w-8 text-slate-300 mx-auto"}),e.jsx("p",{className:"text-sm text-slate-400",children:"No available times on this day"}),e.jsx("p",{className:"text-xs text-slate-400",children:"Try selecting a different date"})]}):e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-52 overflow-y-auto pr-1 custom-scrollbar",children:W.map(oe=>{const ie=d===oe;return e.jsx("button",{onClick:()=>u(oe),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${ie?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-[1.02]":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10 hover:text-[#406E71] border border-slate-150"}`,children:ue(Bs(o,"yyyy-MM-dd"),oe)},oe)})}),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(_a,{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:n8e[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(Vc,{className:"h-3.5 w-3.5 text-[#406E71]"}),Bs(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3.5 w-3.5 text-[#406E71]"}),ue(Bs(o,"yyyy-MM-dd"),d)," (",r8e(k),") · ",i.duration_minutes," min"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(ye,{value:p.name,onChange:oe=>x({...p,name:oe.target.value}),placeholder:"Jane Smith",className:"h-11 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold text-slate-700",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(on,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{type:"email",value:p.email,onChange:oe=>x({...p,email:oe.target.value}),placeholder:"jane@email.com",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(pa,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{type:"tel",value:p.phone,onChange:oe=>x({...p,phone:oe.target.value}),placeholder:"(555) 123-4567",className:"h-11 pl-9 rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(Ds,{value:p.message,onChange:oe=>x({...p,message:oe.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:K,disabled:!p.name||y,children:y?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"}),"Booking..."]}):"Confirm Booking"})]}),r==="confirmed"&&e.jsxs("div",{className:"text-center space-y-5 py-6",children:[e.jsxs("div",{className:"relative mx-auto w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping opacity-30"}),e.jsx("div",{className:"relative w-20 h-20 rounded-full bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-200",children:e.jsx(Rr,{className:"h-10 w-10 text-white"})})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-slate-800",children:"You're booked!"}),e.jsxs("p",{className:"text-slate-500 mt-1.5",children:[i==null?void 0:i.name," with ",(P==null?void 0:P.name)||"your agent"]})]}),e.jsx("div",{className:"inline-flex items-center gap-3 px-5 py-3 rounded-xl bg-slate-50 border border-slate-100",children:e.jsxs("div",{className:"text-left text-sm",children:[e.jsx("p",{className:"font-semibold text-slate-800",children:o&&Bs(o,"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-slate-500",children:[o&&d?`${ue(Bs(o,"yyyy-MM-dd"),d)} (${r8e(k)})`:""," · ",i==null?void 0:i.duration_minutes," min"]})]})}),e.jsx("p",{className:"text-sm text-slate-400 max-w-xs mx-auto",children:"A confirmation with meeting details will be sent to you shortly."}),b&&e.jsx("div",{className:"pt-1",children:e.jsx("a",{href:b,className:"inline-flex items-center gap-1.5 text-xs font-semibold text-[#406E71] underline underline-offset-4",children:"Reschedule or cancel this meeting"})}),((P==null?void 0:P.phone)||(P==null?void 0:P.email))&&e.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wider font-semibold",children:"Contact"}),e.jsxs("div",{className:"flex gap-3",children:[(P==null?void 0:P.phone)&&e.jsxs("a",{href:`tel:${P.phone}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#406E71]/10 text-[#406E71] text-xs font-medium hover:bg-[#406E71]/20 transition-colors",children:[e.jsx(pa,{className:"h-3.5 w-3.5"})," Call"]}),(P==null?void 0:P.email)&&e.jsxs("a",{href:`mailto:${P.email}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#2a4c64]/10 text-[#2a4c64] text-xs font-medium hover:bg-[#2a4c64]/20 transition-colors",children:[e.jsx(on,{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(Vc,{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 wEn(){const t=$d().pathname.slice(1).split("/")[0];return j.useEffect(()=>{document.body.classList.add("booking-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("booking-page"),r.forEach(clearTimeout)}},[]),t?e.jsx(YBt,{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 jEn(){const t=$d().pathname.slice(1);return j.useEffect(()=>{document.body.classList.add("connect-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("connect-page"),r.forEach(clearTimeout)}},[]),!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),e.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),e.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):e.jsx(UCt,{slugOverride:t})}function NEn(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 kEn={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function SEn({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=kEn[s.heading_font||"playfair"],u=s.eyebrow||null,h=s.headline_accent||null,m=Array.isArray(s.trust_pills)?s.trust_pills:[],p=t.slice(0,5);return e.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:c},children:[s.hero_image_url?e.jsx("img",{src:s.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${c}, #000)`}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),e.jsx("div",{className:"relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-screen md:min-h-[760px] flex items-center",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[e.jsxs("div",{className:"lg:col-span-3 text-white",children:[s.logo_url&&e.jsx(CEn,{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(pa,{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(on,{className:"h-3 w-3"})," ",s.agent_email]})]})]})]})]}),e.jsx("div",{className:"lg:col-span-2",children:e.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6",children:[e.jsxs("form",{className:"space-y-3",onSubmit:a,children:[p.map(x=>e.jsxs("div",{children:[e.jsxs(se,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[x.label,x.is_required&&e.jsx("span",{className:"ml-1",style:{color:o},children:"*"})]}),e.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900",children:l(x,n,r,c)})]},x.id)),e.jsx("button",{type:"submit",disabled:i,className:"w-full px-6 py-3.5 rounded-lg font-bold text-neutral-900 text-base md:text-lg shadow-lg hover:brightness-110 active:brightness-95 transition-all disabled:opacity-60 mt-2",style:{backgroundColor:o},children:i?"Submitting...":s.cta_text||"Get Started"})]}),m.length>0&&e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:m.map((x,y)=>e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[e.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:o}}),x]},y))})]})})]})})]})}function CEn({src:s}){const[t,n]=j.useState(null),r=e.jsx("img",{src:s,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:a=>n(NEn(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 AEn(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 TEn(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 EEn(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 MEn({startsAt:s,locationName:t,address:n,title:r,accent:a}){const[i,l]=j.useState(Date.now());j.useEffect(()=>{const p=setInterval(()=>l(Date.now()),1e3);return()=>clearInterval(p)},[]);const o=new Date(s).getTime();if(!Number.isFinite(o))return null;const c=AEn(o-i),d=o-i<=0,u=new Date(s).toLocaleString("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"}),h=[t,n].filter(Boolean).join(" · "),m=n?`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(n)}`:null;return e.jsx("section",{className:"max-w-5xl mx-auto px-4 py-10",children:e.jsx("div",{className:"rounded-2xl border bg-white/80 backdrop-blur p-6 md:p-8 shadow-sm",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider font-medium",style:{color:a},children:d?"Just happened":"Event starts in"}),d?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Missed this one? Submit the form and we'll let you know about the next one."}):e.jsx("div",{className:"flex items-baseline gap-3",children:[{v:c.d,l:"days"},{v:c.h,l:"hrs"},{v:c.m,l:"min"},{v:c.s,l:"sec"}].map(p=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl md:text-4xl font-bold tabular-nums",style:{color:a},children:String(p.v).padStart(2,"0")}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:p.l})]},p.l))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 pt-2 text-sm text-neutral-700",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Vr,{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(oi,{className:"h-3.5 w-3.5"})," ",h]})]})]}),!d&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:TEn(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(ra,{className:"h-4 w-4"})," Add to Google"]}),e.jsxs("a",{href:EEn(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(ra,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function LEn(){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 ZBt({slugOverride:s}){var $;const{slug:t}=$i(),n=s||t,[r,a]=j.useState(!1),[i,l]=j.useState({}),[o,c]=j.useState(0),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p]=j.useState(()=>Date.now()),x=j.useState(()=>LEn())[0],{data:y,isLoading:g}=mt({queryKey:["public-landing-page",n],queryFn:async()=>{const{data:q,error:W}=await U.from("landing_pages").select("*").eq("slug",n).eq("is_published",!0).single();if(W)throw W;return q},enabled:!!n}),{data:b=[]}=mt({queryKey:["public-landing-page-fields",y==null?void 0:y.id],queryFn:async()=>{const{data:q,error:W}=await U.from("landing_page_fields").select("*").eq("page_id",y.id).order("sort_order");if(W)throw W;return q},enabled:!!(y!=null&&y.id)});j.useEffect(()=>{y!=null&&y.id&&U.from("landing_pages").update({view_count:(y.view_count||0)+1}).eq("id",y.id).then(()=>{})},[y==null?void 0:y.id]),j.useEffect(()=>{if(!(y!=null&&y.id))return;const q=new URLSearchParams(window.location.search);U.functions.invoke("landing-page-track",{body:{page_id:y.id,event_type:"view",session_id:x,utm_source:q.get("utm_source"),utm_medium:q.get("utm_medium"),utm_campaign:q.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[y==null?void 0:y.id,x]);const v=vt({mutationFn:async()=>{const q=b.find(ie=>ie.field_type==="text"&&ie.label.toLowerCase().includes("name")),W=b.find(ie=>ie.field_type==="email"),G=b.find(ie=>ie.field_type==="phone"),K=q?String(i[q.label]||""):null,ee=W?String(i[W.label]||""):null,J=G?String(i[G.label]||""):null,le=new URLSearchParams(window.location.search),{data:ue,error:oe}=await U.functions.invoke("landing-page-submit",{body:{page_id:y.id,answers:JSON.parse(JSON.stringify(i)),contact_name:K,contact_email:ee,contact_phone:J,session_id:x,honeypot:h,rendered_at:p,utm_source:le.get("utm_source"),utm_medium:le.get("utm_medium"),utm_campaign:le.get("utm_campaign"),referrer:document.referrer||null}});if(oe)throw oe;return ue},onSuccess:q=>{a(!0),q!=null&&q.redirect_url&&setTimeout(()=>{window.location.href=q.redirect_url},1500)}}),k=q=>{q.preventDefault(),!(b.filter(G=>G.is_required&&!i[G.label]).length>0)&&v.mutate()};if(g)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 C=y.primary_color||"#406E71",T=y.accent_color||"#2a4c64",M=y,P=y.page_type==="lead_magnet",L=y.page_type==="just_listed"||y.page_type==="just_sold",I=Array.isArray(M.property_photos)?M.property_photos:[],O=M.lead_magnet_file_url||M.lead_magnet_external_url;if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${C}, ${T})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(Rr,{className:"h-16 w-16 mx-auto mb-4",style:{color:C}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:P?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:y.success_message}),P&&O&&e.jsxs("a",{href:O,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 mt-6 px-6 py-3 rounded-lg text-white font-semibold transition-transform hover:scale-105",style:{backgroundColor:C},children:[e.jsx(ii,{className:"h-5 w-5"}),"Download ",M.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:C},children:[e.jsx(pa,{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:C},children:[e.jsx(on,{className:"h-3 w-3"})," ",y.agent_email]})]})]})});if(L){const q=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&&I.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>u(!1),children:[e.jsx("button",{onClick:()=>u(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:e.jsx(dr,{className:"h-8 w-8"})}),e.jsx("button",{onClick:W=>{W.stopPropagation(),c(G=>G===0?I.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(Cc,{className:"h-6 w-6"})}),e.jsx("img",{src:I[o],alt:`Property photo ${o+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:W=>W.stopPropagation()}),e.jsx("button",{onClick:W=>{W.stopPropagation(),c(G=>G===I.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," / ",I.length]})]}),I.length>0&&e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 pt-6",children:[e.jsx("div",{className:"absolute top-10 left-8 z-10 px-4 py-1.5 rounded-full text-white font-bold text-sm uppercase tracking-wider shadow-lg",style:{backgroundColor:M.property_status==="just_sold"?"#e74c3c":C},children:M.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),I.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{c(0),u(!0)},children:[e.jsx("img",{src:I[0],alt:"Property",className:"w-full h-[50vh] object-cover group-hover:scale-105 transition-transform duration-500"}),e.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white px-3 py-1.5 rounded-lg text-sm flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(iE,{className:"h-4 w-4"})," View"]})]}):I.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:I.slice(0,2).map((W,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:I[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),I.slice(1,5).map((W,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&&I.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",I.length-5," more"]})]},G))]}),I.length>2&&e.jsxs("button",{onClick:()=>{c(0),u(!0)},className:"absolute bottom-4 right-8 bg-white shadow-lg hover:shadow-xl text-gray-800 px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-shadow",children:[e.jsx(iE,{className:"h-4 w-4"})," View all ",I.length," photos"]})]}),I.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, ${C}, ${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:[M.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:C},children:q(M.property_price)}),M.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(oi,{className:"h-5 w-5 shrink-0"})," ",M.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[M.property_beds&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(U_,{className:"h-5 w-5",style:{color:C}})," ",M.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),M.property_baths&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(t0,{className:"h-5 w-5",style:{color:C}})," ",M.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),M.property_sqft&&e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-lg font-semibold",children:[e.jsx(j3,{className:"h-5 w-5",style:{color:C}})," ",Number(M.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),M.property_description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-gray-800 mb-2",children:"About This Property"}),e.jsx("p",{className:"text-gray-600 leading-relaxed whitespace-pre-line",children:M.property_description})]})]})}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 sticky top-6",children:[e.jsx("h2",{className:"text-lg font-bold mb-1",style:{color:C},children:M.property_status==="just_sold"?"Want results like this?":"Interested in this property?"}),e.jsx("p",{className:"text-gray-500 text-sm mb-4",children:"Fill out the form and I'll be in touch!"}),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(pa,{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(on,{className:"h-3 w-3"})," ",y.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:k,className:"space-y-3",children:[b.map(W=>e.jsxs("div",{children:[e.jsxs(se,{className:"text-xs font-medium",children:[W.label,W.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),a8e(W,i,l)]},W.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:C},disabled:v.isPending,children:v.isPending?"Submitting...":"Submit"}),v.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return y.theme_style!=="classic"&&!P?e.jsxs("div",{className:"min-h-screen bg-neutral-50",children:[e.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:h,onChange:q=>m(q.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),e.jsx(SEn,{page:y,fields:b,answers:i,setAnswers:l,onSubmit:k,isSubmitting:v.isPending,renderField:a8e}),y.page_type==="event_registration"&&(($=y.settings)==null?void 0:$.event_starts_at)&&e.jsx(MEn,{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"}),v.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("div",{className:"relative py-16 px-4",style:{background: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, ${C}, ${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}),P&&M.lead_magnet_file_name&&e.jsxs("div",{className:"mt-6 inline-flex items-center gap-2 bg-white/20 backdrop-blur px-4 py-2 rounded-full text-sm",children:[e.jsx(ii,{className:"h-4 w-4"}),"Free Download: ",M.lead_magnet_file_name]})]})}),e.jsx("div",{className:"max-w-2xl mx-auto px-4 -mt-8",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[P&&e.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),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(pa,{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(on,{className:"h-3 w-3"})," ",y.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:k,className:"space-y-4",children:[b.map(q=>e.jsxs("div",{children:[e.jsxs(se,{className:"text-sm font-medium",children:[q.label,q.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),a8e(q,i,l)]},q.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:C},disabled:v.isPending,children:v.isPending?"Submitting...":P?"Get My Free Download":"Submit"}),v.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}function a8e(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(ye,{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(Ds,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",rows:3,className:"mt-1"});case"select":return e.jsxs(vs,{value:String(a),onValueChange:l=>n(o=>({...o,[s.label]:l})),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{placeholder:"Select..."})}),e.jsx(ys,{children:i.map(l=>e.jsx(Je,{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(wi,{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(Mn,{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(ye,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function PEn(){const t=$d().pathname.slice(1).split("/")[0];return j.useEffect(()=>{document.body.classList.add("landing-page-public");const n=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("landing-page-public"),r.forEach(clearTimeout)}},[]),t?e.jsx(ZBt,{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 IEn=[{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}],u$n={hero:"Hero Section",featured_listings:"Featured Listings",featured_areas:"Featured Areas",about:"About Me",testimonials:"Testimonials",cta_banner:"Call To Action",new_listings:"New Listings Carousel",open_houses:"Open Houses Carousel",my_listings:"My Listings Carousel",city_pages:"City Pages Grid",property_types:"Property Types Gallery",advantages:"Advantages / Why Choose Us",rate_my_agent:"RateMyAgent Reviews",lifestyle_gallery:"Lifestyle Gallery",market_pulse:"Market Pulse",concierge_services:"Concierge Services",credentials:"Credentials & Clientele",land_use_guide:"Land Use Guide",land_valuation_cta:"Land Valuation CTA",acreage_showcase:"Acreage Showcase",featured_video:"Featured Video",schedule_cta:"Schedule a Consultation"},h$n={hero:"Full-screen background image with headline, subtitle, and search bar",featured_listings:"Grid of highlighted properties from the MLS",featured_areas:"Spotlight regions or neighborhoods that link to property search",about:"Agent photo, bio, and credentials section",testimonials:"Client reviews carousel with quotes",cta_banner:"Call-to-action block to drive contact and search engagement",new_listings:"Horizontal carousel of newest listings, filterable by city",open_houses:"Horizontal carousel of open house listings, filterable by city",my_listings:"Showcase the agent's own active listings in a carousel",city_pages:"Grid of your city landing pages with photos and links",property_types:"Visual gallery of property categories (Ranch, Farm, Land, etc.)",advantages:"Feature cards highlighting your expertise and unique value",rate_my_agent:"Verified client reviews carousel powered by RateMyAgent",lifestyle_gallery:"Cinematic photo grid showcasing luxury living — pools, views, interiors",market_pulse:"Sleek market stats dashboard with avg price, days on market, inventory",concierge_services:"White-glove services showcase — staging, design, moving coordination",credentials:"Affiliation logos and specialty positioning (e.g. luxury and sports & entertainment divisions)",land_use_guide:"Interactive land use cards — Agriculture, Hunting, Equestrian, Recreational",land_valuation_cta:`"What's Your Land Worth?" — bold call-to-action for landowners`,acreage_showcase:"Large visual cards emphasizing lot size with aerial imagery",featured_video:"Embedded YouTube or Bunny video section for cinematic storytelling",schedule_cta:"Prominent booking section that sends visitors to your online scheduling calendar"},Xgt={basic:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","featured_video","schedule_cta","cta_banner"],luxury:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","cta_banner","lifestyle_gallery","market_pulse","concierge_services","credentials","featured_video","schedule_cta"],"land-ranch":["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","cta_banner","property_types","advantages","land_use_guide","land_valuation_cta","acreage_showcase","featured_video","schedule_cta"]};function m$n(s){return Xgt[s]||Xgt.basic}function REn(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}):IEn,testimonials:Array.isArray(s.testimonials)?s.testimonials:[],featuredListingIds:s.featured_listing_ids||[],searchCities:Array.isArray(t.searchCities)?t.searchCities:[],searchZipCodes:Array.isArray(t.searchZipCodes)?t.searchZipCodes:[],searchCounties:Array.isArray(t.searchCounties)?t.searchCounties:[],searchSubdivisions:Array.isArray(t.searchSubdivisions)?t.searchSubdivisions:[],referralMode:t.referralMode===!0,referralPrimaryLabel:t.referralPrimaryLabel||void 0,referralPrimaryUrl:t.referralPrimaryUrl||void 0,referralSecondaryLabel:t.referralSecondaryLabel||void 0,referralSecondaryUrl:t.referralSecondaryUrl||void 0,divisionLogos:Array.isArray(t.divisionLogos)?t.divisionLogos:[],focusPages:Array.isArray(t.focusPages)?t.focusPages:[]}}function DEn(){const s=new URLSearchParams(window.location.search).get("previewSlug");if(s)return s;const n=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return n?n[1]:null}function OEn(){const s=DEn(),t=s?null:PZt(window.location.hostname),n=s||t,{data:r,isLoading:a,error:i}=mt({queryKey:["lead-site",n],queryFn:async()=>{var p;if(!n)return null;const l=U.from("lead_sites").select("*").eq("is_active",!0),{data:o,error:c}=await(s?l.eq("subdomain_slug",s):l.ilike("custom_domain",t)).maybeSingle();if(c)throw c;if(!o)return null;const{data:d}=await U.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("id",o.agent_id).single();let u=null;if(o.show_team_logo)if(o.team_logo_url)u=o.team_logo_url;else{const{data:x}=await U.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",o.agent_id).limit(1).maybeSingle();x&&((p=x.teams)!=null&&p.avatar_url)&&(u=x.teams.avatar_url)}const h={id:o.id,agentId:o.agent_id,subdomainSlug:o.subdomain_slug,customDomain:o.custom_domain||null,mlsProviderId:o.mls_provider_id,siteTitle:o.site_title,siteTagline:o.site_tagline,leadRegistrationMode:o.lead_registration_mode||"disabled",registrationTriggerCount:o.registration_trigger_count??1,themeConfig:o.theme_config||{},themeTier:o.theme_tier||"basic",brandColor:o.brand_color||void 0,accentColor:o.accent_color||void 0,mlsServiceCities:Array.isArray(o.mls_service_cities)?o.mls_service_cities:[],isActive:o.is_active,brokerageLegalName:o.brokerage_legal_name||null,brokerageLicenseNumber:o.brokerage_license_number||null,agentLicenseNumber:o.agent_license_number||null,licenseState:o.license_state||null,mlsDisclaimerText:o.mls_disclaimer_text||null,mlsLogoUrl:o.mls_logo_url||null,equalHousingEnabled:o.equal_housing_enabled??!0,faviconUrl:o.favicon_url||null,ogImageUrl:o.og_image_url||null,showTeamLogo:o.show_team_logo??!1,teamLogoUrl:u,noMlsMode:o.no_mls_mode===!0,bookingUrl:o.booking_url||null,pageSubtitles:o.page_subtitles||{},agent:d?{id:d.id,full_name:d.name||"",avatar_url:d.avatar_url,email:d.email,phone:d.phone,title:d.title,bio:d.bio,areas_served:d.areas_served||null,years_experience:d.years_experience??null,instagram_url:d.instagram_url||null,facebook_url:d.facebook_url||null,linkedin_url:d.linkedin_url||null}:void 0,testimonials:Array.isArray(o.testimonials)?o.testimonials.filter(x=>x&&typeof x=="object"&&x.text).map(x=>({name:String(x.name||"Client"),text:String(x.text),rating:typeof x.rating=="number"?x.rating:5,location:x.location?String(x.location):void 0})):[],seoMetaTitle:o.seo_meta_title||null,seoMetaDescription:o.seo_meta_description||null},m=REn(o);return{siteConfig:h,themeConfig:m}},enabled:!!n,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1});return{siteConfig:(r==null?void 0:r.siteConfig)??null,themeConfig:(r==null?void 0:r.themeConfig)??null,isLoading:a,error:i,slug:s??(r==null?void 0:r.siteConfig.subdomainSlug)??null,customDomain:t}}async function FEn(s,t){try{await U.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(n){console.warn("Lead notification failed:",n)}}const XBt=j.createContext(null);function bTe(){const s=j.useContext(XBt);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function zEn({siteConfig:s,children:t}){const[n,r]=j.useState(null),[a,i]=j.useState(null),[l,o]=j.useState(!0);j.useEffect(()=>{const{data:{subscription:h}}=U.auth.onAuthStateChange(async(m,p)=>{const x=(p==null?void 0:p.user)??null;if(r(x),x){const{data:y}=await U.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",x.id).eq("lead_site_id",s.id).maybeSingle();y&&i({...y,email:x.email||""})}else i(null);o(!1)});return U.auth.getSession().then(({data:{session:m}})=>{r((m==null?void 0:m.user)??null),m!=null&&m.user?U.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",m.user.id).eq("lead_site_id",s.id).maybeSingle().then(({data:p})=>{p&&i({...p,email:m.user.email||""}),o(!1)}):o(!1)}),()=>h.unsubscribe()},[s.id]);const c=j.useCallback(async h=>{const m=h.email.toLowerCase().trim(),p=h.phone.replace(/\D/g,""),{data:x,error:y}=await U.auth.signUp({email:m,password:p,options:{data:{full_name:h.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(y){if(y.message.includes("already registered")){await d(m,p);return}throw y}if(x.user){const{error:g}=await U.from("lead_site_consumer_profiles").insert({user_id:x.user.id,lead_site_id:s.id,name:h.name.trim(),phone:h.phone.trim()});g&&console.warn("Consumer profile insert error:",g);const{error:b}=await U.from("lead_site_leads").insert({lead_site_id:s.id,name:h.name.trim(),email:m,phone:h.phone.trim(),message:"Created account on website",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,has_account:!0}});b&&console.error("Lead insert error (CRM sync may not trigger):",b),FEn(s.id,{name:h.name.trim(),email:m,phone:h.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}},[s.id]),d=j.useCallback(async(h,m)=>{const p=m.replace(/\D/g,""),{error:x}=await U.auth.signInWithPassword({email:h.toLowerCase().trim(),password:p});if(x)throw x},[]),u=j.useCallback(async()=>{await U.auth.signOut(),r(null),i(null)},[]);return e.jsx(XBt.Provider,{value:{user:n,profile:a,isLoading:l,signUp:c,signIn:d,signOut:u},children:t})}const BEn=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),$En=new Set(["tomlois"]);function QBt(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||BEn.has(s.id||"")||$En.has((s.subdomainSlug||"").toLowerCase())||!s.mlsProviderId:!1}function p$n(s){return`Contact ${s.split(" ")[0]||"Me"}`}const Yq="#c9a96e",UEn="Schedule a Free Consultation",qEn={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function T3({bookingUrl:s,label:t=UEn,className:n="",variant:r="solid",color:a=Yq,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 ${qEn[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(n1,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:t})]})}function f$n({bookingUrl:s,agentName:t,accentColor:n=Yq,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:Vr,title:r.point1Title||"30 Minutes",text:r.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:QW,title:r.point2Title||"A Personal Call",text:r.point2Text||`${t.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:Rr,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(br.div,{initial:{opacity:0,y:24},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{duration:.7},children:[e.jsxs("div",{className:"flex items-center justify-center gap-4 mb-5",children:[e.jsx("div",{className:"h-px w-12 bg-white/10"}),e.jsx("span",{className:"text-[11px] tracking-[0.4em] uppercase",style:{color:n},children:l}),e.jsx("div",{className:"h-px w-12 bg-white/10"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl text-white tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:o}),e.jsx("p",{className:"text-white/50 mt-5 text-lg max-w-2xl mx-auto leading-relaxed",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:c}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-14 text-left",children:u.map((m,p)=>e.jsxs("div",{className:"border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(m.icon,{className:"h-5 w-5 mb-4",style:{color:n}}),e.jsx("p",{className:"text-white text-sm tracking-[0.15em] uppercase mb-2",children:m.title}),e.jsx("p",{className:"text-white/45 text-sm leading-relaxed",children:m.text})]},p))}),e.jsxs("div",{className:"mt-12 flex flex-col items-center gap-4",children:[e.jsx(T3,{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 x$n({bookingUrl:s,accentColor:t=Yq,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(T3,{bookingUrl:s,label:"Schedule Now",color:t,size:"sm",className:"flex-shrink-0",source:l})]}):null}function VEn({bookingUrl:s,accentColor:t=Yq}){const[n,r]=j.useState(!1),[a,i]=j.useState(!1);if(j.useEffect(()=>{sessionStorage.getItem("schedule-cta-dismissed")==="1"&&i(!0);const o=()=>r(window.scrollY>260);return o(),window.addEventListener("scroll",o,{passive:!0}),()=>window.removeEventListener("scroll",o)},[]),!s||a)return null;const l=()=>{sessionStorage.setItem("schedule-cta-dismissed","1"),i(!0)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`md:hidden fixed inset-x-0 bottom-0 z-[60] transition-transform duration-300 ${n?"translate-y-0":"translate-y-full"}`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:e.jsxs("div",{className:"bg-[#0d0b0a]/95 backdrop-blur-lg border-t border-white/10 px-4 py-3 flex items-center gap-3",children:[e.jsxs("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"flex-1 inline-flex items-center justify-center gap-2 rounded-full py-3 text-[11px] font-semibold tracking-[0.18em] uppercase",style:{backgroundColor:t,color:"#0d0b0a"},children:[e.jsx(n1,{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(dr,{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(T3,{bookingUrl:s,label:"Schedule a Free Consultation",size:"sm",color:t,source:"sticky"})})]})}function HEn({bookingUrl:s,agentName:t}){return j.useEffect(()=>{if(s){const n=setTimeout(()=>window.location.replace(s),400);return()=>clearTimeout(n)}},[s]),e.jsx("div",{className:"min-h-[70vh] flex items-center justify-center bg-[#0d0b0a] px-6 text-center",children:e.jsxs("div",{children:[e.jsx(n1,{className:"h-8 w-8 mx-auto mb-6",style:{color:Yq}}),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(T3,{bookingUrl:s,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}function dYe({open:s,mode:t,siteConfig:n,onComplete:r,onSkip:a,theme:i="default",accentColor:l}){var W;const{signUp:o,signIn:c}=bTe(),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,x]=j.useState(""),[y,g]=j.useState(""),[b,v]=j.useState(!1),[k,C]=j.useState(""),T=t==="required",M=i==="luxury",P=l||(M?"#c9a96e":"#2563eb"),L=((W=n.agent)==null?void 0:W.full_name)||"the agent",I={borderColor:`${P}66`,"--tw-ring-color":`${P}66`},O=async G=>{var ee;if(G.preventDefault(),C(""),!p.trim()||!y.trim()){C("Email and phone number are required.");return}if(!d&&!h.trim()){C("Name is required.");return}if(y.replace(/\D/g,"").length<7){C("Please enter a valid phone number.");return}v(!0);try{d?await c(p,y):await o({name:h,email:p,phone:y}),r()}catch(J){(ee=J==null?void 0:J.message)!=null&&ee.includes("Invalid login")?C("Invalid email or phone number. Please try again."):C((J==null?void 0:J.message)||"Something went wrong. Please try again.")}finally{v(!1)}},$=M?"w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2":"w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",q=M?I:void 0;return e.jsx(Fs,{open:s,onOpenChange:T?void 0:G=>{G||a()},children:e.jsxs(Os,{className:`sm:max-w-md ${M?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:T?G=>G.preventDefault():void 0,onEscapeKeyDown:T?G=>G.preventDefault():void 0,children:[e.jsxs($s,{children:[e.jsx(zs,{className:"text-xl",style:M?{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(kr,{className:M?"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 ${L}.`})]}),e.jsxs("form",{onSubmit:O,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:q}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:p,onChange:G=>x(G.target.value),className:$,style:q}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:y,onChange:G=>g(G.target.value),className:$,style:q}),e.jsx("p",{className:`text-xs mt-1 ${M?"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:b,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${M?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:M?{backgroundColor:P}:void 0,children:b?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{u(!d),C("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:P},children:d?"Don't have an account? Sign up":"Already have an account? Sign in"}),!T&&!d&&e.jsx("button",{type:"button",onClick:a,className:`w-full py-2 text-sm transition-colors ${M?"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 ${M?"text-[#8a7869]":"text-gray-400"}`,children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}function uYe({siteConfig:s,pagePath:t}){const n=s.agent;if(!n)return null;const r=s.customDomain?`https://${s.customDomain}`:`https://${s.subdomainSlug}.thelocalmove.com`,i=(n.areas_served||"").split(/,|;|\|/).map(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,C)=>k+(C.rating||5),0)/h.length).toFixed(1),reviewCount:h.length,bestRating:5,worstRating:1}:void 0,p=[n.facebook_url,n.instagram_url,n.linkedin_url].filter(Boolean),x={"@context":"https://schema.org","@type":["RealEstateAgent","LocalBusiness"],"@id":`${r}/#agent`,name:n.full_name,url:r,image:n.avatar_url||s.ogImageUrl||void 0,logo:s.ogImageUrl||n.avatar_url||void 0,email:n.email,telephone:n.phone||void 0,jobTitle:n.title||"Real Estate Agent",description:n.bio||`${n.full_name} is a trusted local real estate professional${l?` serving ${l}`:""}.`,priceRange:"$$",...p.length&&{sameAs:p},...s.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:s.brokerageLegalName,...s.brokerageLicenseNumber&&{identifier:s.brokerageLicenseNumber}}},...s.agentLicenseNumber&&{identifier:s.agentLicenseNumber},...o&&{address:{"@type":"PostalAddress",addressLocality:o,...c&&{addressRegion:c},addressCountry:"US"}},...i.length&&{areaServed:i.map(k=>{const[C,T]=k.split(/,\s*/);return{"@type":"City",name:C,...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,...p.length&&{sameAs:p},...n.years_experience&&{knowsAbout:["Residential Real Estate","Home Buying","Home Selling",l?`${l} Real Estate`:"Local Real Estate"].filter(Boolean)},...u.length&&{hasCredential:u.map(k=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:k}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},g={"@context":"https://schema.org","@type":"WebSite","@id":`${r}/#website`,name:s.siteTitle||`${n.full_name} Real Estate`,url:r,publisher:{"@id":`${r}/#agent`},potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${r}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}},b=[{name:"Search Homes",description:`Browse all current MLS listings${l?` in ${l}`:""}.`,path:"/search"},{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"},{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${n.full_name}${s.brokerageLegalName?` and ${s.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${n.full_name} for buying, selling, or relocation help.`,path:"/contact"}],v={"@context":"https://schema.org","@type":"ItemList","@id":`${r}/#nav`,name:"Main Navigation",itemListElement:b.map((k,C)=>({"@type":"SiteNavigationElement",position:C+1,name:k.name,description:k.description,url:`${r}${k.path}`}))};return e.jsxs(ql,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(x)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(y)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(g)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(v)})]})}function g$n({items:s,siteConfig:t}){const n=t.customDomain?`https://${t.customDomain}`:`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:s.map((a,i)=>({"@type":"ListItem",position:i+1,name:a.name,item:`${n}${a.path}`}))};return e.jsx(ql,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function y$n({listing:s,siteConfig:t}){var a;const n=t.customDomain?`https://${t.customDomain}`:`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"SingleFamilyResidence",name:`${s.address}, ${s.city}, ${s.state} ${s.zip}`,url:`${n}/listing/${s.mlsNumber}`,image:((a=s.photos)==null?void 0:a[0])||void 0,numberOfRooms:s.bedrooms,numberOfBathroomsTotal:s.bathrooms,floorSize:s.sqft?{"@type":"QuantitativeValue",value:s.sqft,unitCode:"FTK"}:void 0,address:{"@type":"PostalAddress",streetAddress:s.address,addressLocality:s.city,addressRegion:s.state,postalCode:s.zip},...s.latitude&&s.longitude&&{geo:{"@type":"GeoCoordinates",latitude:s.latitude,longitude:s.longitude}},offers:{"@type":"Offer",price:s.price,priceCurrency:"USD",availability:s.status==="Active"?"https://schema.org/InStock":"https://schema.org/SoldOut"},...s.yearBuilt&&{yearBuilt:s.yearBuilt}};return e.jsx(ql,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function GEn({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(ql,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function v$n({title:s,description:t,publishedAt:n,imageUrl:r,slug:a,siteConfig:i}){const l=i.customDomain?`https://${i.customDomain}`:`https://${i.subdomainSlug}.thelocalmove.com`,o=i.agent,c={"@context":"https://schema.org","@type":"Article",headline:s,description:t,url:`${l}/blog/${a}`,datePublished:n,...r&&{image:r},author:o?{"@type":"Person",name:o.full_name,url:l}:void 0,publisher:{"@type":"Organization",name:i.siteTitle||(o==null?void 0:o.full_name)||"Agent",url:l}};return e.jsx(ql,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function hYe({siteConfig:s}){var p;const t=s.agent;if(!t)return null;const n=t.full_name,r=s.brokerageLegalName||"their brokerage",a=t.areas_served||"the local market",i=((p=a.split(/,|;|\|/)[0])==null?void 0:p.trim())||"the local area",l=t.years_experience,o=t.phone||"",c=t.email,d=s.agentLicenseNumber,u=(t.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],h=[...new Set(u.map(x=>x.toUpperCase()))],m=[{question:`Who is ${n}?`,answer:`${n} is a ${t.title||"REALTOR®"} with ${r}${l?`, with ${l}+ years of local real estate experience`:""} serving ${a}. ${t.bio?t.bio.slice(0,280):""}`.trim()},{question:`What areas does ${n} serve?`,answer:`${n} serves ${a} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${n.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${n}?`,answer:`You can reach ${n} by ${o?`phone at ${o}, `:""}email at ${c}, or by booking a consultation directly through this website.`},...h.length?[{question:`What real estate designations does ${n} hold?`,answer:`${n} holds the following professional designations: ${h.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...d?[{question:`Is ${n} a licensed real estate agent?`,answer:`Yes, ${n} is a fully licensed real estate professional (License #${d}) with ${r}.`}]:[],{question:`How do I search for homes for sale in ${i}?`,answer:`Use the property search on this site to view all current MLS listings in ${i}. You can filter by price, bedrooms, neighborhood, school district, and more. Save searches to receive instant email alerts when new homes match your criteria.`},{question:`What is the home buying process like in ${i}?`,answer:`${n} guides buyers through every step: getting pre-approved, searching MLS listings, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${n.split(" ")[0]} for a free buyer consultation.`},{question:`How do I find out what my home is worth in ${i}?`,answer:`Request a free, no-obligation home valuation from ${n}. ${n.split(" ")[0]} provides a comparative market analysis (CMA) using recent sold comps and current market conditions in ${i}.`}];return e.jsx(GEn,{faqs:m})}const Qgt="ls_visitor_geo",WEn=1e3*60*60,i8e="lu_lc_attrib_v1",KEn=1e3*60*60*24*90;function YEn(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 ZEn(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 XEn(){try{const s=localStorage.getItem(Qgt);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,XEn().then(l=>{a.current=l}))},[]),j.useEffect(()=>{if(!(s!=null&&s.id))return;const l=n.pathname;if(l===r.current)return;r.current=l;const o=YEn(l),c=ZEn(l,o),d=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,u=a.current;(async()=>{const m=new URLSearchParams(n.search),p=m.get("luc");if(p&&/^[0-9a-f-]{36}$/i.test(p)){try{localStorage.setItem(i8e,JSON.stringify({contact_id:p,ts:Date.now()}))}catch{}return p}const x=m.get("lc");if(x&&/^[0-9a-f-]{36}$/i.test(x)){const{data:y}=await U.from("listing_email_recipients").select("contact_id").eq("id",x).maybeSingle(),g=y==null?void 0:y.contact_id;if(g){try{localStorage.setItem(i8e,JSON.stringify({contact_id:g,ts:Date.now()}))}catch{}return g}}try{const y=localStorage.getItem(i8e);if(y){const g=JSON.parse(y);if(g!=null&&g.contact_id&&Date.now()-(g.ts||0){U.from("lead_site_page_views").insert({lead_site_id:s.id,page_type:o,page_path:l,page_title:c,visitor_fingerprint:d,auth_user_id:t||null,contact_id:m,visitor_city:(u==null?void 0:u.city)||null,visitor_region:(u==null?void 0:u.region)||null,visitor_country:(u==null?void 0:u.country)||null,visitor_lat:(u==null?void 0:u.lat)||null,visitor_lng:(u==null?void 0:u.lng)||null}).then(({error:p})=>{p&&console.error("[PageTracking] insert failed:",p.message)})})},[n.pathname,n.search,s==null?void 0:s.id,t])}const QEn=3e4;function pYe(s,t){const n=$d(),r=j.useRef(null),a=j.useRef(null),i=j.useRef(0),l=n.pathname,o=JEn(l),c=e6n(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;j.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;o==="listing"&&(i.current+=1);const u=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,h=async()=>{const{data:m,error:p}=await U.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:u,current_page_path:l,current_page_title:c,current_mls_number:d,last_seen_at:new Date().toISOString(),listing_views_count:i.current},{onConflict:"lead_site_id,coalesce(auth_user_id::text,visitor_fingerprint,'')"}).select("id, notified_agent").single();!p&&m&&(r.current=m.id,i.current>=2&&!m.notified_agent&&U.functions.invoke("lead-site-presence-notify",{body:{visitor_id:m.id,lead_site_id:s.id}}).catch(()=>{}))};return h(),a.current&&clearInterval(a.current),a.current=setInterval(h,QEn),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),j.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const u=()=>{r.current&&U.from("lead_site_active_visitors").delete().eq("id",r.current).then(()=>{})};return window.addEventListener("beforeunload",u),()=>window.removeEventListener("beforeunload",u)},[s==null?void 0:s.id,t])}function JEn(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 e6n(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 ji=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},t6n=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=s6n},s6n=Number.MAX_SAFE_INTEGER||9007199254740991;let co=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}({}),cr=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}({}),Pt=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 Pc={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},zi={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class m7{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 n6n{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 m7(t),this.fast_=new m7(n),this.defaultTTFB_=a,this.ttfb_=new m7(t)}update(t,n){const{slow_:r,fast_:a,ttfb_:i}=this;r.halfLife!==t&&(this.slow_=new m7(t,r.getEstimate(),r.getTotalWeight())),a.halfLife!==n&&(this.fast_=new m7(n,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new m7(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 r6n(s,t,n){return(t=i6n(t))in s?Object.defineProperty(s,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[t]=n,s}function ah(){return ah=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):bA}function e0t(s,t,n){return t[s]?t[s].bind(t):l6n(s,n)}const PBe=LBe();function c6n(s,t,n){const r=LBe();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{r[i]=e0t(i,s,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return LBe()}a.forEach(i=>{PBe[i]=e0t(i,s)})}else ah(PBe,r);return r}const Ku=PBe;function UE(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function d6n(s){return typeof self<"u"&&s===self.ManagedMediaSource}function JBt(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 J_(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 G0(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(!ji(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return Yf(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 m6n extends t$t{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 s$t(s,t){const n=Object.getPrototypeOf(s);if(n){const r=Object.getOwnPropertyDescriptor(n,t);return r||s$t(n,t)}}function p6n(s,t){const n=s$t(s,t);n&&(n.enumerable=!0,Object.defineProperty(s,t,n))}const s0t=Math.pow(2,32)-1,f6n=[].push,n$t={video:1,audio:2,id3:3,text:4};function Jx(s){return String.fromCharCode.apply(null,s)}function r$t(s,t){const n=s[t]<<8|s[t+1];return n<0?65536+n:n}function jl(s,t){const n=a$t(s,t);return n<0?4294967296+n:n}function n0t(s,t){let n=jl(s,t);return n*=Math.pow(2,32),n+=jl(s,t+4),n}function a$t(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function x6n(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 kc(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=kc(s.subarray(a+8,o),t.slice(1));c.length&&f6n.apply(n,c)}a=o}return n}function g6n(s){const t=[],n=s[0];let r=8;const a=jl(s,r);r+=4;let i=0,l=0;n===0?(i=jl(s,r),l=jl(s,r+4),r+=8):(i=n0t(s,r),l=n0t(s,r+8),r+=16),r+=2;let o=s.length+l;const c=r$t(s,r);r+=2;for(let d=0;d>>31===1)return Ku.warn("SIDX has hierarchical references (not supported)"),null;const x=jl(s,u);u+=4,t.push({referenceSize:m,subsegmentDuration:x,info:{duration:x/a,start:o,end:o+m-1}}),o+=m,u+=4,r=u}return{earliestPresentationTime:i,timescale:a,version:n,referencesCount:c,references:t}}function i$t(s){const t=[],n=kc(s,["moov","trak"]);for(let a=0;a{const i=jl(a,4),l=t[i];l&&(l.default={duration:jl(a,12),flags:jl(a,20)})}),t}function y6n(s){const t=s.subarray(8),n=t.subarray(86),r=Jx(t.subarray(4,8));let a=r,i;const l=r==="enca"||r==="encv";if(l){const d=kc(t,[r])[0].subarray(r==="enca"?28:78);kc(d,["sinf"]).forEach(h=>{const m=kc(h,["schm"])[0];if(m){const p=Jx(m.subarray(4,8));if(p==="cbcs"||p==="cenc"){const x=kc(h,["frma"])[0];x&&(a=Jx(x))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=kc(n,["avcC"])[0];c&&c.length>3&&(a+="."+vre(c[1])+vre(c[2])+vre(c[3]),i=yre(o==="avc1"?"dva1":"dvav",n));break}case"mp4a":{const c=kc(t,[r])[0],d=kc(c.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=c8e(d,u),u+=2;const h=d[u++];if(h&128&&(u+=2),h&64&&(u+=d[u++]),d[u++]!==4)break;u=c8e(d,u);const m=d[u++];if(m===64)a+="."+vre(m);else break;if(u+=12,d[u++]!==5)break;u=c8e(d,u);const p=d[u++];let x=(p&248)>>3;x===31&&(x+=1+((p&7)<<3)+((d[u]&224)>>5)),a+="."+x}break}case"hvc1":case"hev1":{const c=kc(n,["hvcC"])[0];if(c&&c.length>12){const d=c[1],u=["","A","B","C"][d>>6],h=d&31,m=jl(c,2),p=(d&32)>>5?"H":"L",x=c[12],y=c.subarray(6,12);a+="."+u+h,a+="."+v6n(m).toString(16).toUpperCase(),a+="."+p+x;let g="";for(let b=y.length;b--;){const v=y[b];(v||g)&&(g="."+v.toString(16).toUpperCase()+g)}a+=g}i=yre(o=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=yre(a,n)||a;break}case"vp09":{const c=kc(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=kc(n,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,u=c[1]&31,h=c[2]>>>7?"H":"M",m=(c[2]&64)>>6,p=(c[2]&32)>>5,x=d===2&&m?p?12:10:m?10:8,y=(c[2]&16)>>4,g=(c[2]&8)>>3,b=(c[2]&4)>>2,v=c[2]&3;a+="."+d+"."+Bk(u)+h+"."+Bk(x)+"."+y+"."+g+b+v+"."+Bk(1)+"."+Bk(1)+"."+Bk(1)+"."+0,i=yre("dav1",n)}break}}return{codec:a,encrypted:l,supplemental:i}}function yre(s,t){const n=kc(t,["dvvC"]),r=n.length?n[0]:kc(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 v6n(s){let t=0;for(let n=0;n<32;n++)t|=(s>>n&1)<<31-n;return t>>>0}function c8e(s,t){const n=t+5;for(;s[t++]&128&&t{const i=r.subarray(8,24);i.some(l=>l!==0)||(Ku.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${G0(i)} -> ${G0(n)}`),r.set(n,8))})}function _6n(s){const t=[];return o$t(s,n=>t.push(n.subarray(8,24))),t}function o$t(s,t){kc(s,["moov","trak"]).forEach(r=>{const a=kc(r,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=kc(i,["enca"]);const o=l.length>0;o||(l=kc(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);kc(d,["sinf"]).forEach(h=>{const m=l$t(h);m&&t(m,o)})})})}function l$t(s){const t=kc(s,["schm"])[0];if(t){const n=Jx(t.subarray(4,8));if(n==="cbcs"||n==="cenc"){const r=kc(s,["schi","tenc"])[0];if(r)return r}}}function w6n(s,t,n){const r={},a=kc(s,["moof","traf"]);for(let i=0;ir[i].duration)){let i=1/0,l=0;const o=kc(s,["sidx"]);for(let c=0;ch+m.info.duration||0,0);l=Math.max(l,u+d.earliestPresentationTime/d.timescale)}}l&&ji(l)&&Object.keys(r).forEach(c=>{r[c].duration||(r[c].duration=l*r[c].timescale-r[c].start)})}return r}function j6n(s){const t={valid:null,remainder:null},n=kc(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 Vj(s,t){const n=new Uint8Array(s.length+t.length);return n.set(s),n.set(t,s.length),n}function r0t(s,t){const n=[],r=t.samples,a=t.timescale,i=t.id;let l=!1;return kc(r,["moof"]).map(c=>{const d=c.byteOffset-8;kc(c,["traf"]).map(h=>{const m=kc(h,["tfdt"]).map(p=>{const x=p[0];let y=jl(p,4);return x===1&&(y*=Math.pow(2,32),y+=jl(p,8)),y/a})[0];return m!==void 0&&(s=m),kc(h,["tfhd"]).map(p=>{const x=jl(p,4),y=jl(p,0)&16777215,g=(y&1)!==0,b=(y&2)!==0,v=(y&8)!==0;let k=0;const C=(y&16)!==0;let T=0;const M=(y&32)!==0;let P=8;x===i&&(g&&(P+=8),b&&(P+=4),v&&(k=jl(p,P),P+=4),C&&(T=jl(p,P),P+=4),M&&(P+=4),t.type==="video"&&(l=_Te(t.codec)),kc(h,["trun"]).map(L=>{const I=L[0],O=jl(L,0)&16777215,$=(O&1)!==0;let q=0;const W=(O&4)!==0,G=(O&256)!==0;let K=0;const ee=(O&512)!==0;let J=0;const le=(O&1024)!==0,ue=(O&2048)!==0;let oe=0;const ie=jl(L,4);let de=8;$&&(q=jl(L,de),de+=4),W&&(de+=4);let we=q+d;for(let je=0;je>1&63;return n===39||n===40}else return(t&31)===6}function gYe(s,t,n,r){const a=c$t(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){Ku.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[u++]===181){const m=r$t(a,u);if(u+=2,m===49){const p=jl(a,u);if(u+=4,p===1195456820){const x=a[u++];if(x===3){const y=a[u++],g=31&y,b=64&y,v=b?2+g*3:0,k=new Uint8Array(v);if(b){k[0]=y;for(let C=1;C16){const h=[];for(let x=0;x<16;x++){const y=a[u++].toString(16);h.push(y.length==1?"0"+y:y),(x===3||x===5||x===7||x===9)&&h.push("-")}const m=o-16,p=new Uint8Array(m);for(let x=0;x>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=r&255,i.set(s,4),a=0,r=8;a0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const l=new Uint8Array(4);return n.byteLength>0&&new DataView(l.buffer).setUint32(0,n.byteLength,!1),S6n([112,115,115,104],new Uint8Array([r,0,0,0]),s,i,a,l,n)}function A6n(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=G0(new Uint8Array(l,n+12,16));let c=null,d=null,u=0;if(i===0)u=28;else{const m=s.getUint32(28);if(!m||r<32+m*16)return{offset:n,size:t};c=[];for(let p=0;p/\(Windows.+Firefox\//i.test(navigator.userAgent),wU={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 yYe(s,t){const n=wU[t];return!!n&&!!n[s.slice(0,4)]}function _X(s,t,n=!0){return!s.split(",").some(r=>!vYe(r,t,n))}function vYe(s,t,n=!0){var r;const a=UE(n);return(r=a==null?void 0:a.isTypeSupported(wX(s,t)))!=null?r:!1}function wX(s,t){return`${t}/mp4;codecs=${s}`}function a0t(s){if(s){const t=s.substring(0,4);return wU.video[t]}return 2}function LSe(s){const t=d$t();return s.split(",").reduce((n,r)=>{const i=t&&_Te(r)?9:wU.video[r];return i?(i*2+n)/(n?3:2):(wU.audio[r]+n)/(n?2:1)},0)}const d8e={};function E6n(s,t=!0){if(d8e[s])return d8e[s];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;aE6n(n.toLowerCase(),t))}function L6n(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)&&(i0t(s,"audio")||i0t(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 i0t(s,t){return yYe(s,t)&&vYe(s,t)}function P6n(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 I6n(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 o0t(s){const t=UE(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 IBe(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const R6n={supported:!0,powerEfficient:!0,smooth:!0},D6n={supported:!1,smooth:!1,powerEfficient:!1},u$t={supported:!0,configurations:[],decodingInfoResults:[R6n]};function h$t(s,t){return{supported:!1,configurations:t,decodingInfoResults:[D6n],error:s}}function O6n(s,t,n,r,a,i){const l=s.videoCodec,o=s.audioCodec?s.audioGroups:null,c=i==null?void 0:i.audioCodec,d=i==null?void 0:i.channels,u=d?parseInt(d):c?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=t.groups[o[0]].channels:h=o.reduce((m,p)=>{if(p){const x=t.groups[p];if(!x)throw new Error(`Audio track group ${p} not found`);Object.keys(x.channels).forEach(y=>{m[y]=(m[y]||0)+x.channels[y]})}return m},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(m=>_Te(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&&ji(u)&&Object.keys(h).some(m=>parseInt(m)>u)}function m$t(s,t,n,r={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!n)return Promise.resolve(u$t);const i=[],l=F6n(s),o=l.length,c=z6n(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=>_Te(h))&&d$t())return Promise.resolve(h$t(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const h=$6n(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 F6n(s){var t;const n=(t=s.videoCodec)==null?void 0:t.split(","),r=p$t(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:wX(I6n(c),"video"),width:a,height:i,bitrate:r,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function z6n(s,t,n){var r;const a=(r=s.audioCodec)==null?void 0:r.split(","),i=p$t(s);return a&&s.audioGroups?s.audioGroups.reduce((l,o)=>{var c;const d=o?(c=t.groups[o])==null?void 0:c.tracks:null;return d?d.reduce((u,h)=>{if(h.groupId===o){const m=parseFloat(h.channels||"");a.forEach(p=>{const x={contentType:wX(p,"audio"),bitrate:n?B6n(p,i):i};m&&(x.channels=""+m),u.push(x)})}return u},l):l},[]):[]}function B6n(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 p$t(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function $6n(s){let t="";const{audio:n,video:r}=s;if(r){const a=IBe(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=IBe(n.contentType);t+=`${r?"_":""}${a}_c${n.channels}`}return t}const RBe=["NONE","TYPE-0","TYPE-1",null];function U6n(s){return RBe.indexOf(s)>-1}const ISe=["SDR","PQ","HLG"];function q6n(s){return!!s&&ISe.indexOf(s)>-1}var A2e={No:"",Yes:"YES",v2:"v2"};function l0t(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 d0t(this._audioGroups,t)}hasSubtitleGroup(t){return d0t(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 d0t(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function V6n(){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 H6n(s,t){let n=!1,r=[];if(s&&(n=s!=="SDR",r=[s]),t){r=t.allowedVideoRanges||ISe.slice(0);const a=r.join("")!=="SDR"&&!t.videoCodec;n=t.preferHDR!==void 0?t.preferHDR:a&&V6n(),n||(r=["SDR"])}return{preferHDR:n,allowedVideoRanges:r}}const G6n=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}},Sh=(s,t)=>JSON.stringify(s,G6n(t));function W6n(s,t,n,r,a){const i=Object.keys(s),l=r==null?void 0:r.channels,o=r==null?void 0:r.audioCodec,c=a==null?void 0:a.videoCodec,d=l&&parseInt(l)===2;let u=!1,h=!1,m=1/0,p=1/0,x=1/0,y=1/0,g=0,b=[];const{preferHDR:v,allowedVideoRanges:k}=H6n(t,a);for(let L=i.length;L--;){const I=s[i[L]];u||(u=I.channels[2]>0),m=Math.min(m,I.minHeight),p=Math.min(p,I.minFramerate),x=Math.min(x,I.minBitrate),k.filter($=>I.videoRanges[$]>0).length>0&&(h=!0)}m=ji(m)?m:0,p=ji(p)?p:0;const C=Math.max(1080,m),T=Math.max(30,p);x=ji(x)?x:n,n=Math.max(x,n),h||(t=void 0);const M=i.length>1;return{codecSet:i.reduce((L,I)=>{const O=s[I];if(I===L)return L;if(b=h?k.filter($=>O.videoRanges[$]>0):[],M){if(O.minBitrate>n)return kk(I,`min bitrate of ${O.minBitrate} > current estimate of ${n}`),L;if(!O.hasDefaultAudio)return kk(I,"no renditions with default or auto-select sound found"),L;if(o&&I.indexOf(o.substring(0,4))%5!==0)return kk(I,`audio codec preference "${o}" not found`),L;if(l&&!d){if(!O.channels[l])return kk(I,`no renditions with ${l} channel sound found (channels options: ${Object.keys(O.channels)})`),L}else if((!o||d)&&u&&O.channels[2]===0)return kk(I,"no renditions with stereo sound found"),L;if(O.minHeight>C)return kk(I,`min resolution of ${O.minHeight} > maximum of ${C}`),L;if(O.minFramerate>T)return kk(I,`min framerate of ${O.minFramerate} > maximum of ${T}`),L;if(!b.some($=>O.videoRanges[$]>0))return kk(I,`no variants with VIDEO-RANGE of ${Sh(b)} found`),L;if(c&&I.indexOf(c.substring(0,4))%5!==0)return kk(I,`video codec preference "${c}" not found`),L;if(O.maxScore=LSe(L)||O.fragmentError>s[L].fragmentError)?L:(y=O.minIndex,g=O.maxScore,I)},void 0),videoRanges:b,preferHDR:v,minFramerate:p,minBitrate:x,minIndex:y}}function kk(s,t){Ku.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function f$t(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 K6n(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 u0t(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 C5(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 $I(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 X6n(s,t,n,r,a){const i=t[r],o=t.reduce((m,p,x)=>{const y=p.uri;return(m[y]||(m[y]=[])).push(x),m},{})[i.uri];o.length>1&&(r=Math.max.apply(Math,o));const c=i.videoRange,d=i.frameRate,u=i.codecSet.substring(0,4),h=h0t(t,r,m=>{if(m.videoRange!==c||m.frameRate!==d||m.codecSet.substring(0,4)!==u)return!1;const p=m.audioGroups,x=n.filter(y=>!p||p.indexOf(y.groupId)!==-1);return C5(s,x,a)>-1});return h>-1?h:h0t(t,r,m=>{const p=m.audioGroups,x=n.filter(y=>!p||p.indexOf(y.groupId)!==-1);return C5(s,x,a)>-1})}function h0t(s,t,n){for(let r=t;r>-1;r--)if(n(s[r]))return r;for(let r=t+1;r{var r;const{fragCurrent:a,partCurrent:i,hls:l}=this,{autoLevelEnabled:o,media:c}=l;if(!a||!c)return;const d=performance.now(),u=i?i.stats:a.stats,h=i?i.duration:a.duration,m=d-u.loading.start,p=l.minAutoLevel,x=a.level,y=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||x<=p){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const g=y>-1&&y!==x,b=!!n||g;if(!b&&(c.paused||!c.playbackRate||!c.readyState))return;const v=l.mainForwardBufferInfo;if(!b&&v===null)return;const k=this.bwEstimator.getEstimateTTFB(),C=Math.abs(c.playbackRate);if(m<=Math.max(k,1e3*(h/(C*2))))return;const T=v?v.len/C:0,M=u.loading.first?u.loading.first-u.loading.start:-1,P=u.loaded&&M>-1,L=this.getBwEstimate(),I=l.levels,O=I[x],$=Math.max(u.loaded,Math.round(h*(a.bitrate||O.averageBitrate)/8));let q=P?m-M:m;q<1&&P&&(q=Math.min(m,u.loaded*8/L));const W=P?u.loaded*1e3/q:0,G=k/1e3,K=W?($-u.loaded)/W:$*8/L+G;if(K<=T)return;const ee=W?W*8:L,J=((r=(n==null?void 0:n.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,le=this.hls.config.abrBandWidthUpFactor;let ue=Number.POSITIVE_INFINITY,oe;for(oe=x-1;oe>p;oe--){const je=I[oe].maxBitrate,xe=!I[oe].details||J;if(ue=this.getTimeToLoadFrag(G,ee,h*je,xe),ue=K||ue>h*10)return;P?this.bwEstimator.sample(m-Math.min(k,M),u.loaded):this.bwEstimator.sampleTTFB(m);const ie=I[oe].maxBitrate;this.getBwEstimate()*le>ie&&this.resetEstimator(ie);const de=this.findBestLevel(ie,p,oe,0,T,1,1);de>-1&&(oe=de),this.warn(`Fragment ${a.sn}${i?" part "+i.index:""} of level ${x} is loading too slowly; Fragment duration: ${a.duration.toFixed(3)} Time to underbuffer: ${T.toFixed(3)} s Estimated load time for current fragment: ${K.toFixed(3)} s Estimated load time for down switch fragment: ${ue.toFixed(3)} s TTFB estimate: ${M|0} ms Current BW estimate: ${ji(L)?L|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${oe} @ ${ie|0} bps`),l.nextLoadLevel=l.nextAutoLevel=oe,this.clearTimer();const we=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===oe&&oe>0){const je=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${oe>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${je.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,oe>p){let xe=this.findBestLevel(this.hls.levels[p].bitrate,p,oe,0,je,1,1);xe===-1&&(xe=p),this.hls.nextLoadLevel=this.hls.nextAutoLevel=xe,this.resetEstimator(this.hls.levels[xe].bitrate)}}};g||K>ue*2?we():this.timer=self.setInterval(we,ue*1e3),l.trigger(Pt.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 n6n(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.FRAG_LOADING,this.onFragLoading,this),t.on(Pt.FRAG_LOADED,this.onFragLoaded,this),t.on(Pt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Pt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Pt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Pt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Pt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(Pt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.FRAG_LOADING,this.onFragLoading,this),t.off(Pt.FRAG_LOADED,this.onFragLoaded,this),t.off(Pt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Pt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Pt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Pt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Pt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(Pt.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 cr.BUFFER_ADD_CODEC_ERROR:case cr.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case cr.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;ji(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===zi.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(Pt.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!==zi.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 g=this.findBestLevel(c,l,a,d,0,u,h);if(g>=0)return this.rebufferNotice=-1,g}let m=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const g=this.bitrateTestDelay;g&&(m=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-g,this.info(`bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*m)} ms`),u=h=1)}const p=this.findBestLevel(c,l,a,d,m,u,h);if(this.rebufferNotice!==p&&(this.rebufferNotice=p,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${p}`)),p>-1)return p;const x=r.levels[l],y=r.loadLevelObj;return y&&(x==null?void 0:x.bitrate)=n;ee--){var K;const J=x[ee],le=ee>h;if(!J)continue;if(b.useMediaCapabilities&&!J.supportedResult&&!J.supportedPromise){const xe=navigator.mediaCapabilities;typeof(xe==null?void 0:xe.decodingInfo)=="function"&&O6n(J,O,M,P,t,L)?(J.supportedPromise=m$t(J,O,xe,this.supportedCache),J.supportedPromise.then(fe=>{if(!this.hls)return;J.supportedResult=fe;const Se=this.hls.levels,Ee=Se.indexOf(J);fe.error?this.warn(`MediaCapabilities decodingInfo error: "${fe.error}" for level ${Ee} ${Sh(fe)}`):fe.supported?fe.decodingInfoResults.some(Le=>Le.smooth===!1||Le.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ee} not smooth or powerEfficient: ${Sh(fe)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ee} ${Sh(fe)}`),Ee>-1&&Se.length>1&&(this.log(`Removing unsupported level ${Ee}`),this.hls.removeLevel(Ee),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(fe=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${fe}`)})):J.supportedResult=u$t}if((T&&J.codecSet!==T||M&&J.videoRange!==M||le&&P>J.frameRate||!le&&P>0&&Pxe.smooth===!1))&&(!C||ee!==$)){G.push(ee);continue}const ue=J.details,oe=(p?ue==null?void 0:ue.partTarget:ue==null?void 0:ue.averagetargetduration)||q;let ie;le?ie=o*t:ie=l*t;const de=q&&a>=q*2&&i===0?J.averageBitrate:J.maxBitrate,we=this.getTimeToLoadFrag(W,ie,de*oe,ue===void 0);if(ie>=de&&(ee===u||J.loadError===0&&J.fragmentError===0)&&(we<=W||!ji(we)||k&&!this.bitrateTestDelay||we${ee} adjustedbw(${Math.round(ie)})-bitrate=${Math.round(ie-de)} ttfb:${W.toFixed(1)} avgDuration:${oe.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${we.toFixed(1)} firstSelection:${C} codecSet:${J.codecSet} videoRange:${J.videoRange} hls.loadLevel:${g}`)),C&&(this.firstSelection=ee),ee}}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 x$t={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 J6n(s,t,n){if(t===null||!Array.isArray(s)||!s.length||!ji(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)&&m0t(n,r,i)===0||eMn(i,s,Math.min(a,r))))return i;const l=x$t.search(t,m0t.bind(null,n,r));return l&&(l!==s||!i)?l:i}function eMn(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 m0t(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 tMn(s,t,n){const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>s}function g$t(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 x$t.search(r,l=>l.cct?-1:(i=l,l.end<=n?1:l.start>n?-1:0)),i||null}return null}function DSe(s){switch(s.details){case cr.FRAG_LOAD_TIMEOUT:case cr.KEY_LOAD_TIMEOUT:case cr.LEVEL_LOAD_TIMEOUT:case cr.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function y$t(s){return s.details.startsWith("key")}function v$t(s){return y$t(s)&&!!s.frag&&!s.frag.decryptdata}function p0t(s,t){const n=DSe(t);return s.default[`${n?"timeout":"error"}Retry`]}function bYe(s,t){const n=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(n*s.retryDelayMs,s.maxRetryDelayMs)}function f0t(s){return Uu(Uu({},s),{errorRetry:null,timeoutRetry:null})}function OSe(s,t,n,r){if(!s)return!1;const a=r==null?void 0:r.code,i=t499)}function DBe(s){return s===0&&navigator.onLine===!1}var H0={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},x_={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class nMn extends Jj{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(Pt.ERROR,this.onError,this),t.on(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Pt.ERROR,this.onError,this),t.off(Pt.ERROR,this.onErrorOut,this),t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.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)===zi.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 cr.FRAG_LOAD_ERROR:case cr.FRAG_LOAD_TIMEOUT:case cr.KEY_LOAD_ERROR:case cr.KEY_LOAD_TIMEOUT:n.errorAction=this.getFragRetryOrSwitchAction(n);return;case cr.FRAG_PARSING_ERROR:if((r=n.frag)!=null&&r.gap){n.errorAction=qz();return}case cr.FRAG_GAP:case cr.FRAG_DECRYPT_ERROR:{n.errorAction=this.getFragRetryOrSwitchAction(n),n.errorAction.action=H0.SendAlternateToPenaltyBox;return}case cr.LEVEL_EMPTY_ERROR:case cr.LEVEL_PARSING_ERROR:{var l;const c=n.parent===zi.MAIN?n.level:a.loadLevel;n.details===cr.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 cr.LEVEL_LOAD_ERROR:case cr.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(n.errorAction=this.getPlaylistRetryOrSwitchAction(n,i.level));return;case cr.AUDIO_TRACK_LOAD_ERROR:case cr.AUDIO_TRACK_LOAD_TIMEOUT:case cr.SUBTITLE_LOAD_ERROR:case cr.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===Pc.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===Pc.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){n.errorAction=this.getPlaylistRetryOrSwitchAction(n,a.loadLevel),n.errorAction.action=H0.SendAlternateToPenaltyBox,n.errorAction.flags=x_.MoveAllAlternatesMatchingHost;return}}return;case cr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.errorAction={action:H0.SendAlternateToPenaltyBox,flags:x_.MoveAllAlternatesMatchingHDCP};return;case cr.KEY_SYSTEM_SESSION_UPDATE_FAILED:case cr.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case cr.KEY_SYSTEM_NO_SESSION:n.errorAction={action:H0.SendAlternateToPenaltyBox,flags:x_.MoveAllAlternatesMatchingKey};return;case cr.BUFFER_ADD_CODEC_ERROR:case cr.REMUX_ALLOC_ERROR:case cr.BUFFER_APPEND_ERROR:if(!n.errorAction){var o;n.errorAction=this.getLevelSwitchAction(n,(o=n.level)!=null?o:a.loadLevel)}return;case cr.INTERNAL_EXCEPTION:case cr.BUFFER_APPENDING_ERROR:case cr.BUFFER_FULL_ERROR:case cr.LEVEL_SWITCH_ERROR:case cr.BUFFER_STALLED_ERROR:case cr.BUFFER_SEEK_OVER_HOLE:case cr.BUFFER_NUDGE_ON_STALL:n.errorAction=qz();return}n.type===co.KEY_SYSTEM_ERROR&&(n.levelRetry=!1,n.errorAction=qz())}getPlaylistRetryOrSwitchAction(t,n){const r=this.hls,a=p0t(r.config.playlistLoadPolicy,t),i=this.playlistError++;if(OSe(a,i,DSe(t),t.response))return{action:H0.RetryRequest,flags:x_.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=p0t(y$t(t)?l:i,t),c=n.levels.reduce((u,h)=>u+h.fragmentError,0);if(a&&(t.details!==cr.FRAG_GAP&&a.fragmentError++,!v$t(t)&&OSe(o,c,DSe(t),t.response)))return{action:H0.RetryRequest,flags:x_.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===cr.BUFFER_APPEND_ERROR&&a.fragmentError++;let u=-1;const{levels:h,loadLevel:m,minAutoLevel:p,maxAutoLevel:x}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const y=(i=t.frag)==null?void 0:i.type,b=(y===zi.AUDIO&&d===cr.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===cr.BUFFER_ADD_CODEC_ERROR||d===cr.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:M})=>a.audioCodec!==M),k=t.sourceBufferName==="video"&&(d===cr.BUFFER_ADD_CODEC_ERROR||d===cr.BUFFER_APPEND_ERROR)&&h.some(({codecSet:M,audioCodec:P})=>a.codecSet!==M&&a.audioCodec===P),{type:C,groupId:T}=(l=t.context)!=null?l:{};for(let M=h.length;M--;){const P=(M+m)%h.length;if(P!==m&&P>=p&&P<=x&&h[P].loadError===0){var o,c;const L=h[P];if(d===cr.FRAG_GAP&&y===zi.MAIN&&t.frag){const I=h[P].details;if(I){const O=oO(t.frag,I.fragments,t.frag.start);if(O!=null&&O.gap)continue}}else{if(C===Pc.AUDIO_TRACK&&L.hasAudioGroup(T)||C===Pc.SUBTITLE_TRACK&&L.hasSubtitleGroup(T))continue;if(y===zi.AUDIO&&(o=a.audioGroups)!=null&&o.some(I=>L.hasAudioGroup(I))||y===zi.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(I=>L.hasSubtitleGroup(I))||b&&a.audioCodec===L.audioCodec||k&&a.codecSet===L.codecSet||!b&&a.codecSet!==L.codecSet)continue}u=P;break}}if(u>-1&&r.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:H0.SendAlternateToPenaltyBox,flags:x_.None,nextAutoLevel:u}}return{action:H0.SendAlternateToPenaltyBox,flags:x_.MoveAllAlternatesMatchingHost}}onErrorOut(t,n){var r;switch((r=n.errorAction)==null?void 0:r.action){case H0.DoNothing:break;case H0.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(n),!n.errorAction.resolved&&n.details!==cr.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 x_.None:this.switchLevel(t,i);break;case x_.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=RBe[RBe.indexOf(u)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${n.maxHdcpLevel}" or lower`);break}}case x_.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) ${G0(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=p7(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),bre(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]=x0t(r,a=>a.fragment.sn>=t))}fragBuffered(t,n){const r=p7(t);let a=this.fragments[r];!a&&n&&(a=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),a&&(a.loaded=null,this.bufferedEnd(a,t))}getBufferedTimes(t,n,r,a){const i={time:[],partial:r},l=t.start,o=t.end,c=t.minEndPTS||o,d=t.maxStartPTS||l;for(let u=0;u=h&&c<=m){i.time.push({startPTS:Math.max(l,a.start(u)),endPTS:Math.min(o,a.end(u))});break}else if(lh){const p=Math.max(l,a.start(u)),x=Math.min(o,a.end(u));x>p&&(i.partial=!0,i.time.push({startPTS:p,endPTS:x}))}else if(o<=h)break}return i}getPartialFragment(t){let n=null,r,a,i,l=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(d=>{const u=c[d];u&&bre(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||bre(n))}getState(t){const n=p7(t),r=this.fragments[n];return r?r.buffered?bre(r)?sg.PARTIAL:sg.OK:sg.APPENDING:sg.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=p7(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=p7(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=p7(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const a=t.sn;this.activePartLists[t.type]=x0t(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 bre(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 p7(s){return`${s.type}_${s.level}_${s.sn}`}function x0t(s,t){return s.filter(n=>{const r=t(n);return r||n.clearElementaryStreamInfo(),r})}var qE={cbc:0,ctr:1};class aMn{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 qE.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},n,t);case qE.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 iMn(s){const t=s.byteLength,n=t&&new DataView(s.buffer).getUint8(t-1);return n?s.slice(0,t-n):s}class oMn{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const n=new DataView(t),r=new Uint32Array(4);for(let a=0;a<4;a++)r[a]=n.getUint32(a*4);return r}initTable(){const t=this.sBox,n=this.invSBox,r=this.subMix,a=r[0],i=r[1],l=r[2],o=r[3],c=this.invSubMix,d=c[0],u=c[1],h=c[2],m=c[3],p=new Uint32Array(256);let x=0,y=0,g=0;for(g=0;g<256;g++)g<128?p[g]=g<<1:p[g]=g<<1^283;for(g=0;g<256;g++){let b=y^y<<1^y<<2^y<<3^y<<4;b=b>>>8^b&255^99,t[x]=b,n[b]=x;const v=p[x],k=p[v],C=p[k];let T=p[b]*257^b*16843008;a[x]=T<<24|T>>>8,i[x]=T<<16|T>>>16,l[x]=T<<8|T>>>24,o[x]=T,T=C*16843009^k*65537^v*257^x*16843008,d[b]=T<<24|T>>>8,u[b]=T<<16|T>>>16,h[b]=T<<8|T>>>24,m[b]=T,x?(x=v^p[p[p[C^v]]],y^=p[p[y]]):x=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!==qE.cbc||n.byteLength!==16)return Ku.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=Vj(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 oMn),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 lMn(this.subtle,n,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new aMn(this.subtle,new Uint8Array(r),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(Ku.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%dMn;return r!==t.length&&(n=t.slice(0,r),this.remainderData=t.slice(r)),n}logOnce(t){this.logEnabled&&(Ku.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const g0t=Math.pow(2,17);class uMn{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 y4({type:co.NETWORK_ERROR,details:cr.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(x=>x[0]==="GAP")){c(v0t(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),u=y0t(t);t.loader=d;const h=f0t(a.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:g0t};t.stats=d.stats;const p={onSuccess:(x,y,g,b)=>{this.resetLoader(t,d);let v=x.data;g.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:t,part:null,payload:v,networkDetails:b})},onError:(x,y,g,b)=>{this.resetLoader(t,d),c(new y4({type:co.NETWORK_ERROR,details:cr.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Uu({url:r,data:void 0},x),error:new Error(`HTTP Error ${x.code} ${x.text}`),networkDetails:g,stats:b}))},onAbort:(x,y,g)=>{this.resetLoader(t,d),c(new y4({type:co.NETWORK_ERROR,details:cr.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:g,stats:x}))},onTimeout:(x,y,g)=>{this.resetLoader(t,d),c(new y4({type:co.NETWORK_ERROR,details:cr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:g,stats:x}))}};n&&(p.onProgress=(x,y,g,b)=>n({frag:t,part:null,payload:g,networkDetails:b})),d.load(u,m,p)})}loadPart(t,n,r){this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap||n.gap){c(v0t(t,n));return}const d=this.loader=i?new i(a):new l(a),u=y0t(t,n);t.loader=d;const h=f0t(a.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:g0t};n.stats=d.stats,d.load(u,m,{onSuccess:(p,x,y,g)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,n);const b={frag:t,part:n,payload:p.data,networkDetails:g};r(b),o(b)},onError:(p,x,y,g)=>{this.resetLoader(t,d),c(new y4({type:co.NETWORK_ERROR,details:cr.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:n,response:Uu({url:u.url,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:y,stats:g}))},onAbort:(p,x,y)=>{t.stats.aborted=n.stats.aborted,this.resetLoader(t,d),c(new y4({type:co.NETWORK_ERROR,details:cr.INTERNAL_ABORTED,fatal:!1,frag:t,part:n,error:new Error("Aborted"),networkDetails:y,stats:p}))},onTimeout:(p,x,y)=>{this.resetLoader(t,d),c(new y4({type:co.NETWORK_ERROR,details:cr.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:n,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:y,stats:p}))}})})}updateStatsFromPart(t,n){const r=t.stats,a=n.stats,i=a.total;if(r.loaded+=a.loaded,i){const c=Math.round(t.duration/n.duration),d=Math.min(Math.round(r.loaded/i),c),h=(c-d)*Math.round(r.loaded/d);r.total=r.loaded+h}else r.total=Math.max(r.loaded,r.total);const l=r.loading,o=a.loading;l.start?l.first+=o.first-o.start:(l.start=o.start,l.first=o.first),l.end=o.end}resetLoader(t,n){t.loader=null,this.loader===n&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),n.destroy()}}function y0t(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(ji(a)&&ji(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&hMn((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 v0t(s,t){const n=new Error(`GAP ${s.gap?"tag":"attribute"} found`),r={type:co.MEDIA_ERROR,details:cr.FRAG_GAP,fatal:!1,frag:s,error:n,networkDetails:null};return t&&(r.part=t),(t||s).stats.aborted=!0,new y4(r)}function hMn(s){return s==="AES-128"||s==="AES-256"}class y4 extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class b$t extends Jj{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 wYe{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=_re(),this.buffering={audio:_re(),video:_re(),audiovideo:_re()},this.level=t,this.sn=n,this.id=r,this.size=a,this.part=i,this.partial=l}}function _re(){return{start:0,executeStart:0,executeEnd:0,end:0}}const b0t={length:0,start:()=>0,end:()=>0};class Pl{static isBuffered(t,n){if(t){const r=Pl.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=Pl.getBuffered(t);return Pl.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 w0t(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 mMn(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 pMn=/^(\d+)x(\d+)$/,j0t=/(.+?)=(".*?"|.*?)(?:,|$)/g;class jp{constructor(t,n){typeof t=="string"&&(t=jp.parseAttrList(t,n)),ah(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=pMn.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(j0t.lastIndex=0;(r=j0t.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=OBe(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":Ku.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const fMn="com.apple.hls.interstitial";function xMn(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function gMn(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class w$t{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]){Ku.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=ah(new jp({}),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"]);ji(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?(Ku.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(ji(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===fMn}get isValid(){return!!this.id&&!this._badValueForSameId&&ji(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 yMn=10;class vMn{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?ji(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||yMn}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 FSe(s,t){return s.length===t.length?!s.some((n,r)=>n!==t[r]):!1}function N0t(s,t){return!s&&!t?!0:!s||!t?!1:FSe(s,t)}function Vz(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function jYe(s){switch(s){case"AES-128":case"AES-256":return qE.cbc;case"AES-256-CTR":return qE.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function NYe(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function FBe(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function bMn(s){const t=FBe(s).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function j$t(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 N$t(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=NYe(l)):n=bMn(l)}}return n}const zSe=typeof self<"u"?self:void 0;var Mp={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Z0={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function T2e(s){switch(s){case Z0.FAIRPLAY:return Mp.FAIRPLAY;case Z0.PLAYREADY:return Mp.PLAYREADY;case Z0.WIDEVINE:return Mp.WIDEVINE;case Z0.CLEARKEY:return Mp.CLEARKEY}}function u8e(s){switch(s){case Mp.FAIRPLAY:return Z0.FAIRPLAY;case Mp.PLAYREADY:return Z0.PLAYREADY;case Mp.WIDEVINE:return Z0.WIDEVINE;case Mp.CLEARKEY:return Z0.CLEARKEY}}function pW(s){const{drmSystems:t,widevineLicenseUrl:n}=s,r=t?[Mp.FAIRPLAY,Mp.WIDEVINE,Mp.PLAYREADY,Mp.CLEARKEY].filter(a=>!!t[a]):[];return!r[Mp.WIDEVINE]&&n&&r.push(Mp.WIDEVINE),r}const k$t=function(s){return zSe!=null&&(s=zSe.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function _Mn(s,t,n,r){let a;switch(s){case Mp.FAIRPLAY:a=["cenc","sinf"];break;case Mp.WIDEVINE:case Mp.PLAYREADY:a=["cenc"];break;case Mp.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return wMn(a,t,n,r)}function wMn(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 jMn(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(n=>n==="persistent-license")))}function S$t(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=NYe(o).subarray(0,16);return j$t(c),c}}return null}let f7={};class bE{static clearKeyUriToKeyIdMap(){f7={}}static setKeyIdForUri(t,n){f7[t]=n}static addKeyIdForUri(t){const n=Object.keys(f7).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,n),f7[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&&!Vz(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(e$t(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&FSe(t.keyFormatVersions,this.keyFormatVersions)&&N0t(t.iv,this.iv)&&N0t(t.keyId,this.keyId)}isSupported(){if(this.method){if(Vz(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Z0.FAIRPLAY:case Z0.WIDEVINE:case Z0.PLAYREADY:case Z0.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(Vz(this.method)){let i=this.iv;return i||(typeof t!="number"&&(Ku.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=kMn(t)),new bE(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=f7[this.uri];if(i&&!FSe(this.keyId,i)&&bE.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=N$t(this.uri);if(r)switch(this.keyFormat){case Z0.WIDEVINE:if(this.pssh=r,!this.keyId){const i=A6n(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=k0t(n));break;case Z0.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=C6n(i,null,r),this.keyId=S$t(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=NMn(n),i||(i=k0t(n),i||(i=f7[this.uri])),i&&(this.keyId=i,bE.setKeyIdForUri(this.uri,i))}return this}}function NMn(s){const t=s==null?void 0:s[Z0.WIDEVINE];return t?t.keyId:null}function k0t(s){const t=s==null?void 0:s[Z0.PLAYREADY];if(t){const n=N$t(t.uri);if(n)return S$t(n)}return null}function kMn(s){const t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=s>>8*(15-n)&255;return t}const S0t=/#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,C0t=/#EXT-X-MEDIA:(.*)/g,SMn=/^#EXT(?:INF|-X-TARGETDURATION):/m,h8e=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),CMn=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 A5{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(C0t.lastIndex=0;(a=C0t.exec(t))!==null;){const d=new jp(a[1],r),u=d.TYPE;if(u){const h=o[u],m=i[u]||[];i[u]=m;const p=d.LANGUAGE,x=d["ASSOC-LANGUAGE"],y=d.CHANNELS,g=d.CHARACTERISTICS,b=d["INSTREAM-ID"],v={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||p||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:p,url:d.URI?A5.resolve(d.URI,n):""};if(x&&(v.assocLang=x),y&&(v.channels=y),g&&(v.characteristics=g),b&&(v.instreamId=b),h!=null&&h.length){const k=A5.findGroup(h,v.groupId)||h[0];M0t(v,k,"audioCodec"),M0t(v,k,"textCodec")}m.push(v)}}return i}static parseLevelPlaylist(t,n,r,a,i,l){var o;const c={url:n},d=new vMn(n),u=d.fragments,h=[];let m=null,p=0,x=0,y=0,g=0,b=0,v=null,k=new l8e(a,c),C,T,M,P=-1,L=!1,I=null,O;if(h8e.lastIndex=0,d.m3u8=t,d.hasVariableRefs=_0t(t),((o=h8e.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(C=h8e.exec(t))!==null;){L&&(L=!1,k=new l8e(a,c),k.playlistOffset=y,k.setStart(y),k.sn=p,k.cc=g,b&&(k.bitrate=b),k.level=r,m&&(k.initSegment=m,m.rawProgramDateTime&&(k.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),I&&(k.setByteRange(I),I=null)));const G=C[1];if(G){k.duration=parseFloat(G);const K=(" "+C[2]).slice(1);k.title=K||null,k.tagList.push(K?["INF",G,K]:["INF",G])}else if(C[3]){if(ji(k.duration)){k.playlistOffset=y,k.setStart(y),M&&P0t(k,M,d),k.sn=p,k.level=r,k.cc=g,u.push(k);const K=(" "+C[3]).slice(1);k.relurl=OBe(d,K),zBe(k,v,h),v=k,y+=k.duration,p++,x=0,L=!0}}else{if(C=C[0].match(CMn),!C){Ku.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T0&&I0t(d,K,C),p=d.startSN=parseInt(ee);break;case"SKIP":{d.skippedSegments&&r4(d,K,C);const le=new jp(ee,d),ue=le.decimalInteger("SKIPPED-SEGMENTS");if(ji(ue)){d.skippedSegments+=ue;for(let ie=ue;ie--;)u.push(null);p+=ue}const oe=le.enumeratedString("RECENTLY-REMOVED-DATERANGES");oe&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(oe.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&r4(d,K,C),d.targetduration=Math.max(parseInt(ee),1);break;case"VERSION":d.version!==null&&r4(d,K,C),d.version=parseInt(ee);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||r4(d,K,C),d.live=!1;break;case"#":(ee||J)&&k.tagList.push(J?[ee,J]:[ee]);break;case"DISCONTINUITY":g++,k.tagList.push(["DIS"]);break;case"GAP":k.gap=!0,k.tagList.push([K]);break;case"BITRATE":k.tagList.push([K,ee]),b=parseInt(ee)*1e3,ji(b)?k.bitrate=b:b=0;break;case"DATERANGE":{const le=new jp(ee,d),ue=new w$t(le,d.dateRanges[le.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ue.isValid||d.skippedSegments?d.dateRanges[ue.id]=ue:Ku.warn(`Ignoring invalid DATERANGE tag: "${ee}"`),k.tagList.push(["EXT-X-DATERANGE",ee]);break}case"DEFINE":{{const le=new jp(ee,d);"IMPORT"in le?mMn(d,le,l):w0t(d,le,n)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?r4(d,K,C):u.length>0&&I0t(d,K,C),d.startCC=g=parseInt(ee);break;case"KEY":{const le=A0t(ee,n,d);if(le.isSupported()){if(le.method==="NONE"){M=void 0;break}M||(M={});const ue=M[le.keyFormat];ue!=null&&ue.matches(le)||(ue&&(M=ah({},M)),M[le.keyFormat]=le)}else Ku.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${ee}"`);break}case"START":d.startTimeOffset=T0t(ee);break;case"MAP":{const le=new jp(ee,d);if(k.duration){const ue=new l8e(a,c);L0t(ue,le,r,M),m=ue,k.initSegment=m,m.rawProgramDateTime&&!k.rawProgramDateTime&&(k.rawProgramDateTime=m.rawProgramDateTime)}else{const ue=k.byteRangeEndOffset;if(ue){const oe=k.byteRangeStartOffset;I=`${ue-oe}@${oe}`}else I=null;L0t(k,le,r,M),m=k,L=!0}m.cc=g;break}case"SERVER-CONTROL":{O&&r4(d,K,C),O=new jp(ee),d.canBlockReload=O.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=O.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&O.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=O.optionalFloat("PART-HOLD-BACK",0),d.holdBack=O.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&r4(d,K,C);const le=new jp(ee);d.partTarget=le.decimalFloatingPoint("PART-TARGET");break}case"PART":{let le=d.partList;le||(le=d.partList=[]);const ue=x>0?le[le.length-1]:void 0,oe=x++,ie=new jp(ee,d),de=new m6n(ie,k,c,oe,ue);le.push(de),k.duration+=de.duration;break}case"PRELOAD-HINT":{const le=new jp(ee,d);d.preloadHint=le;break}case"RENDITION-REPORT":{const le=new jp(ee,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(le);break}default:Ku.warn(`line parsed but not handled: ${C}`);break}}}v&&!v.relurl?(u.pop(),y-=v.duration,d.partList&&(d.fragmentHint=v)):d.partList&&(zBe(k,v,h),k.cc=g,d.fragmentHint=k,M&&P0t(k,M,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const $=u.length,q=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),P>0&&(TMn(u,P),q&&h.unshift(q))}return d.fragmentHint&&(y+=d.fragmentHint.duration),d.totalduration=y,h.length&&d.dateRangeTagCount&&q&&C$t(h,d),d.endCC=g,d}}function C$t(s,t){let n=s.length;if(!n)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];s.push(o),n++}else return;const r=s[n-1],a=t.live?1/0:t.totalduration,i=Object.keys(t.dateRanges);for(let o=i.length;o--;){const c=t.dateRanges[i[o]],d=c.startDate.getTime();c.tagAnchor=r.ref;for(let u=n;u--;){var l;if(((l=s[u])==null?void 0:l.sn)=o||r===0){var l;const c=(((l=n[r+1])==null?void 0:l.start)||a)-i.start;if(t<=o+c*1e3){const d=n[r].sn-s.startSN;if(d<0)return-1;const u=s.fragments;if(u.length>n.length){const m=(n[r+1]||u[u.length-1]).sn-s.startSN;for(let p=m;p>d;p--){const x=u[p].programDateTime;if(t>=x&&tr);["video","audio","text"].forEach(r=>{const a=n.filter(i=>yYe(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 M0t(s,t,n){const r=t[n];r&&(s[n]=r)}function TMn(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 zBe(s,t,n){s.rawProgramDateTime?n.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function L0t(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 P0t(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 r4(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function I0t(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function m8e(s,t){const n=t.startPTS;if(ji(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 A$t(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(ji(u)){const b=Math.abs(u-n);s&&b>s.totalduration?l.warn(`media timestamps and playlist times differ by ${b}s for level ${t.level} ${s.url}`):ji(t.deltaPTS)?t.deltaPTS=Math.max(b,t.deltaPTS):t.deltaPTS=b,c=Math.max(n,u),n=Math.min(n,u),a=t.startDTS!==void 0?Math.min(a,t.startDTS):a,d=Math.min(r,h),r=Math.max(r,h),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const m=n-t.start;t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=c,t.startDTS=a,t.endPTS=r,t.minEndPTS=d,t.endDTS=i;const p=t.sn;if(!s||ps.endSN)return 0;let x;const y=p-s.startSN,g=s.fragments;for(g[y]=t,x=y;x>0;x--)m8e(g[x],g[x-1]);for(x=y;x=0;u--){const h=a[u].initSegment;if(h){r=h;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;PMn(s,t,(u,h,m,p)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==u.cc){const x=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=MMn(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?A$t(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,n):T$t(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 MMn(s,t,n){const{dateRanges:r,recentlyRemovedDateranges:a}=t,i=ah({},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 w$t(r[c].attr,d);u.isValid?(i[c]=u,d||(u.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Sh(r[c].attr)}"`)}),i):r}function LMn(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 PMn(s,t,n){const r=t.skippedSegments,a=Math.max(s.startSN,t.startSN)-t.startSN,i=(s.fragmentHint?1:0)+(r?t.endSN:Math.min(s.endSN,t.endSN))-t.startSN,l=t.startSN-s.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,c=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=a;d<=i;d++){const u=c[l+d];let h=o[d];if(r&&!h&&u&&(h=t.fragments[d]=u),u&&h){n(u,h,d,o);const m=u.relurl,p=h.relurl;if(m&&IMn(m,p)){t.playlistParsingError=R0t(`media sequence mismatch ${h.sn}:`,s,t,u,h);return}else if(u.cc!==h.cc){t.playlistParsingError=R0t(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,s,t,u,h);return}}}}function R0t(s,t,n,r,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${n.startSN} ${n.m3u8}`)}function T$t(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 IMn(s,t){return s!==t&&t?O0t(s)!==O0t(t):!1}function O0t(s){return s.replace(/\?[^?]*$/,"")}function xY(s,t){for(let r=0,a=s.length;rs.startCC)}function F0t(s,t){const n=s.start+t;s.startPTS=n,s.setStart(n),s.endPTS=n+s.duration}function I$t(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=Pl.bufferInfo(d||c,h,l.maxBufferHole),p=!m.len;if(this.log(`Media seeking to ${ji(h)?h.toFixed(3):h}, state: ${u}, ${p?"out of":"in"} buffer`),this.state===Yr.ENDED)this.resetLoadingState();else if(o){const x=l.maxFragLookUpTolerance,y=o.start-x,g=o.start+o.duration+x;if(p||gm.end){const b=h>g;(hx&&(this.lastCurrentTime=h),!this.loadingParts){const y=Math.max(m.end,h),g=this.shouldLoadParts(this.getLevelDetails(),y);g&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${y.toFixed(2)}`),this.loadingParts=g)}}this.hls.hasEnoughToStart||(this.log(`Setting ${p?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,p&&(this.startPosition=h)),p&&this.state===Yr.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 uMn(t.config),this.keyLoader=r,this.fragmentTracker=n,this.config=t.config,this.decrypter=new _Ye(t.config)}registerListeners(){const{hls:t}=this;t.on(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Pt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Pt.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===Yr.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=Yr.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=Pl.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===Yr.FRAG_LOADING||!this.fragCurrent&&l===Yr.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=Yr.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(Pt.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===Yr.STOPPED||this.state===Yr.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)===sg.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)===sg.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(Pt.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&&Vz(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,jYe(o.method)).catch(d=>{throw a.trigger(Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const u=self.performance.now();return a.trigger(Pt.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===Yr.STOPPED||this.state===Yr.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!==Yr.STOPPED&&(this.state=Yr.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(Pt.ERROR,{type:co.KEY_SYSTEM_ERROR,details:cr.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?OMn.toString(Pl.getBuffered(r)):"(detached)"})`),Yf(t)){var a;if(t.type!==zi.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=Yr.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=Yr.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 wYe(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=Yr.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(m=>{if(!this.fragContextChanged(m.frag))return this.hls.trigger(Pt.KEY_LOADED,m),this.state===Yr.KEY_LOADING&&(this.state=Yr.IDLE),m}),this.hls.trigger(Pt.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(Yf(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&&Yf(t)){const m=l.partList;if(m&&a){r>l.fragmentEnd&&l.fragmentHint&&(t=l.fragmentHint);const p=this.getNextPart(m,t,r);if(p>-1){const x=m[p];t=this.fragCurrent=x.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${x.index} (${p}/${m.length-1}) of ${this.fragInfo(t,!1,x)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=x.start+x.duration,this.state=Yr.FRAG_LOADING;let y;return o?y=o.then(g=>!g||this.fragContextChanged(g.frag)?null:this.doFragPartsLoad(t,x,n,a)).catch(g=>this.handleFragLoadError(g)):y=this.doFragPartsLoad(t,x,n,a).catch(g=>this.handleFragLoadError(g)),this.hls.trigger(Pt.FRAG_LOADING,{frag:t,part:x,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(Yf(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))}`),ji(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Yr.FRAG_LOADING;const u=this.config.progressive&&t.type!==zi.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(Pt.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,n,r,a){return new Promise((i,l)=>{var o;const c=[],d=(o=r.details)==null?void 0:o.partList,u=h=>{this.fragmentLoader.loadPart(t,h,a).then(m=>{c[h.index]=m;const p=m.part;this.hls.trigger(Pt.FRAG_LOADED,m);const x=D0t(r.details,t.sn,h.index+1)||L$t(d,t.sn,h.index+1);if(x)u(x);else return i({frag:t,part:p,partsLoaded:c})}).catch(l)};u(n)})}handleFragLoadError(t){if("data"in t){const n=t.data;n.frag&&n.details===cr.INTERNAL_ABORTED?this.handleFragLoadAborted(n.frag,n.part):n.frag&&n.type===co.KEY_SYSTEM_ERROR?(n.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(n.frag)):this.hls.trigger(Pt.ERROR,n)}else this.hls.trigger(Pt.ERROR,{type:co.OTHER_ERROR,details:cr.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const n=this.getCurrentContext(t);if(!n||this.state!==Yr.PARSING){!this.fragCurrent&&this.state!==Yr.STOPPED&&this.state!==Yr.ERROR&&(this.state=Yr.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===zi.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?D0t(c,i,l):null,u=d?d.fragment:M$t(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!==Yr.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=Vj(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(Pt.BUFFER_APPENDING,h),t.dropped&&t.independent&&!r){if(i)return;this.flushBufferGap(n)}}flushBufferGap(t){const n=this.media;if(!n)return;if(!Pl.isBuffered(n,n.currentTime)){this.flushMainBuffer(0,t.start);return}const r=n.currentTime,a=Pl.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(!ji(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=Pl.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 Pl.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=zi.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?(g=p,b=p===m?"config":"next load start"):x!==null?(g=x,b="live edge"):(g=t,b="buffer pos"),g=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(z0t(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(z0t(this.config)&&t.type!==zi.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=J6n(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=g$t(t,r.cc,r.end),a&&this.log(`Live playlist, switching playlist, load frag with same CC: ${a.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(a=this.getFragmentAtPosition(i,this.bitrateTest?t.fragmentEnd:t.edge,t))}return a}getFragmentAtPosition(t,n,r){const{config:a}=this;let{fragPrevious:i}=this,{fragments:l,endSN:o}=r;const{fragmentHint:c}=r,{maxFragLookUpTolerance:d}=a,u=r.partList,h=!!(this.loadingParts&&u!=null&&u.length&&c);h&&!this.bitrateTest&&u[u.length-1].fragment.sn===c.sn&&(l=l.concat(c),o=c.sn);let m;if(tn-d||(p=this.media)!=null&&p.paused||!this.startFragRequested?0:d;m=oO(i,l,t,y)}else m=l[l.length-1];if(m){const x=m.sn-r.startSN,y=this.fragmentTracker.getState(m);if((y===sg.OK||y===sg.PARTIAL&&m.gap)&&(i=m),i&&m.sn===i.sn&&(!h||u[0].fragment.sn>m.sn||!r.live)&&m.level===i.level){const b=l[x+1];m.sn${t.startSN} fragments: ${a}`),c}return i}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,n){let r=this.startPosition;r=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(t,n){this.transmuxer&&t.type===this.playlistType&&Yf(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!==Yr.FRAG_LOADING_WAITING_RETRY)&&(this.state=Yr.IDLE)}onFragmentOrKeyLoadError(t,n){var r;if(n.chunkMeta&&!n.frag){const b=this.getCurrentContext(n.chunkMeta);b&&(n.frag=b.frag)}const a=n.frag;if(!a||a.type!==t||!this.levels)return;if(this.fragContextChanged(a)){var i;this.warn(`Frag load error must match current frag to retry ${a.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const l=n.details===cr.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=n.errorAction;if(!o){this.state=Yr.ERROR;return}const{action:c,flags:d,retryCount:u=0,retryConfig:h}=o,m=!!h,p=m&&c===H0.RetryRequest,x=m&&!o.resolved&&d===x_.MoveAllAlternatesMatchingHost,y=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!p&&x&&Yf(a)&&!a.endList&&y&&!v$t(n))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((p||x)&&u=n||r&&!DBe(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Yr.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===Yr.PARSING||this.state===Yr.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===zi.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Yr.STOPPED&&(this.state=Yr.IDLE)}afterBufferFlushed(t,n,r){if(!t)return;const a=Pl.getBuffered(t);this.fragmentTracker.detectEvictedFragments(n,a,r),this.state===Yr.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Yr.STOPPED&&(this.state=Yr.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:A$t(i,t,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(Pt.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(Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.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=Yr.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)})`),this.hls.trigger(Pt.FRAG_PARSED,{frag:t,part:n})}playlistLabel(){return this.playlistType===zi.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 z0t(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class D$t{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=FMn(t,n);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function FMn(s,t){const n=new Uint8Array(t);let r=0;for(let a=0;a0)return s.subarray(n,n+r)}function HMn(s,t,n,r){const a=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=t[n+2],l=i>>2&15;if(l>12){const p=new Error(`invalid ADTS sampling index:${l}`);s.emit(Pt.ERROR,Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.FRAG_PARSING_ERROR,fatal:!0,error:p,reason:p.message});return}const o=(i>>6&3)+1,c=t[n+3]>>6&3|(i&1)<<2,d="mp4a.40."+o,u=a[l];let h=l;(o===5||o===29)&&(h-=3);const m=[o<<3|(h&14)>>1,(h&1)<<7|c<<3];return Ku.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 F$t(s,t){return s[t]===255&&(s[t+1]&246)===240}function z$t(s,t){return s[t+1]&1?7:9}function AYe(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function GMn(s,t){return t+5=s.length)return!1;const r=AYe(s,t);if(r<=n)return!1;const a=t+r;return a===s.length||$Se(s,a)}return!1}function B$t(s,t,n,r,a){if(!s.samplerate){const i=HMn(t,n,r,a);if(!i)return;ah(s,i)}}function $$t(s){return 1024*9e4/s}function YMn(s,t){const n=z$t(s,t);if(t+n<=s.length){const r=AYe(s,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function U$t(s,t,n,r,a){const i=$$t(s.samplerate),l=r+a*i,o=YMn(t,n);let c;if(o){const{frameLength:h,headerLength:m}=o,p=m+h,x=Math.max(0,n+p-t.length);x?(c=new Uint8Array(p-m),c.set(t.subarray(n+m,t.length),0)):c=t.subarray(n+m,n+p);const y={unit:c,pts:l};return x||s.samples.push(y),{sample:y,length:p,missing:x}}const d=t.length-n;return c=new Uint8Array(d),c.set(t.subarray(n,t.length),0),{sample:{unit:c,pts:l},length:d,missing:-1}}function ZMn(s,t){return CYe(s,t)&&wTe(s,t+6)+10<=s.length-t}function XMn(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function f8e(s,t=0,n=1/0){return QMn(s,t,n,Uint8Array)}function QMn(s,t,n,r){const a=JMn(s);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const l=eLn(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 JMn(s){return s instanceof ArrayBuffer?s:s.buffer}function eLn(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function tLn(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=J_(f8e(s.data,1,r)),i=s.data[2+r],l=s.data.subarray(3+r).indexOf(0);if(l===-1)return;const o=J_(f8e(s.data,3+r,l));let c;return a==="-->"?c=J_(f8e(s.data,4+r+l)):c=XMn(s.data.subarray(4+r+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function sLn(s){if(s.size<2)return;const t=J_(s.data,!0),n=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:n.buffer}}function nLn(s){if(s.size<2)return;if(s.type==="TXXX"){let n=1;const r=J_(s.data.subarray(n),!0);n+=r.length+1;const a=J_(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=J_(s.data.subarray(1));return{key:s.type,info:"",data:t}}function rLn(s){if(s.type==="WXXX"){if(s.size<2)return;let n=1;const r=J_(s.data.subarray(n),!0);n+=r.length+1;const a=J_(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=J_(s.data);return{key:s.type,info:"",data:t}}function aLn(s){return s.type==="PRIV"?sLn(s):s.type[0]==="W"?rLn(s):s.type==="APIC"?tLn(s):nLn(s)}function iLn(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),n=wTe(s,4),r=10;return{type:t,size:n,data:s.subarray(r,r+n)}}const wre=10,oLn=10;function q$t(s){let t=0;const n=[];for(;CYe(s,t);){const r=wTe(s,t+6);s[t+5]>>6&1&&(t+=wre),t+=wre;const a=t+r;for(;t+oLn0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:L_.audioId3,duration:Number.POSITIVE_INFINITY});a{if(ji(s))return s*90;const r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r};let jre=null;const dLn=[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],uLn=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],hLn=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],mLn=[0,1,1,4];function H$t(s,t,n,r,a){if(n+24>t.length)return;const i=G$t(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 G$t(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=dLn[c*14+a-1]*1e3,h=uLn[(n===3?0:n===2?1:2)*3+i],m=o===3?1:2,p=hLn[n][r],x=mLn[r],y=p*8*x,g=Math.floor(p*d/h+l)*x;if(jre===null){const k=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);jre=k?parseInt(k[1]):0}return!!jre&&jre<=87&&r===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:h,channelCount:m,frameLength:g,samplesPerFrame:y}}}function MYe(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function W$t(s,t){return t+1{let n=0,r=5;t+=r;const a=new Uint32Array(1),i=new Uint32Array(1),l=new Uint8Array(1);for(;r>0;){l[0]=s[t];const o=Math.min(r,8),c=8-o;i[0]=4278190080>>>24+c<>c,n=n?n<t.length||t[n]!==11||t[n+1]!==119)return-1;const i=t[n+4]>>6;if(i>=3)return-1;const o=[48e3,44100,32e3][i],c=t[n+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+i]*2;if(n+u>t.length)return-1;const h=t[n+6]>>5;let m=0;h===2?m+=2:(h&1&&h!==1&&(m+=2),h&4&&(m+=2));const p=(t[n+6]<<8|t[n+7])>>12-m&1,y=[2,1,2,3,3,4,4,5][h]+p,g=t[n+5]>>3,b=t[n+5]&7,v=new Uint8Array([i<<6|g<<1|b>>2,(b&3)<<6|h<<3|p<<2|c>>4,c<<4&224]),k=1536/o*9e4,C=r+a*k,T=t.subarray(n,n+u);return s.config=v,s.channelCount=y,s.samplerate=o,s.samples.push({unit:T,pts:C}),u}class gLn extends EYe{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=kX(t,0);let r=(n==null?void 0:n.length)||0;if(n&&t[r]===11&&t[r+1]===119&&TYe(n)!==void 0&&Y$t(t,r)<=16)return!1;for(let a=t.length;r{const l=k6n(i);if(yLn.test(l.schemeIdUri)){const o=$0t(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:L_.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=$0t(l,n);r.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:L_.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 $0t(s,t){return ji(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class bLn{constructor(t,n,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new _Ye(n,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,qE.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 X$t{constructor(){this.VideoSample=null}createVideoSample(t,n,r){return{key:t,frame:!1,pts:n,dts:r,units:[],length:0}}getLastNalUnit(t){var n;let r=this.VideoSample,a;if((!r||r.units.length===0)&&(r=t[t.length-1]),(n=r)!=null&&n.units){const i=r.units;a=i[i.length-1]}return a}pushAccessUnit(t,n){if(t.units.length&&t.frame){if(t.pts===void 0){const r=n.samples,a=r.length;if(a){const i=r[a-1];t.pts=i.pts,t.dts=i.dts}else{n.dropped++;return}}n.samples.push(t)}}parseNALu(t,n,r){const a=n.byteLength;let i=t.naluState||0;const l=i,o=[];let c=0,d,u,h,m=-1,p=0;for(i===-1&&(m=0,p=this.getNALuType(n,0),i=0,c=1);c=0){const x={data:n.subarray(m,u),type:p};o.push(x)}else{const x=this.getLastNalUnit(t.samples);x&&(l&&c<=4-l&&x.state&&(x.data=x.data.subarray(0,x.data.byteLength-l)),u>0&&(x.data=Vj(x.data,n.subarray(0,u)),x.state=0))}c=0&&i>=0){const x={data:n.subarray(m,a),type:p,state:i};o.push(x)}if(o.length===0){const x=this.getLastNalUnit(t.samples);x&&(x.data=Vj(x.data,n))}return t.naluState=i,o}}class gY{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&&Ku.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 _Ln extends X$t{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 g=d.data;if(c&&g.length>4){const b=this.readSliceType(g);(b===2||b===4||b===7||b===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,gYe(d.data,1,r.pts,n.samples);break}case 7:{var p,x;o=!0,c=!0;const y=d.data,g=this.readSPS(y);if(!t.sps||t.width!==g.width||t.height!==g.height||((p=t.pixelRatio)==null?void 0:p[0])!==g.pixelRatio[0]||((x=t.pixelRatio)==null?void 0:x[1])!==g.pixelRatio[1]){t.width=g.width,t.height=g.height,t.pixelRatio=g.pixelRatio,t.sps=[y];const b=y.subarray(1,4);let v="avc1.";for(let k=0;k<3;k++){let C=b[k].toString(16);C.length<2&&(C="0"+C),v+=C}t.codec=v}break}case 8:o=!0,t.pps=[d.data];break;case 9:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:o=!0;break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,n){return t[n]&31}readSliceType(t){const n=new gY(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,gYe(d.data,2,r.pts,n.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=ah(t.params,this.readVPS(d.data)),this.initVPS=d.data),t.vps=[d.data];break;case 33:if(o=!0,c=!0,t.vps!==void 0&&t.vps[0]!==this.initVPS&&t.sps!==void 0&&!this.matchSPS(t.sps[0],d.data)&&(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const p=this.readSPS(d.data);t.width=p.width,t.height=p.height,t.pixelRatio=p.pixelRatio,t.codec=p.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const x in p.params)t.params[x]=p.params[x]}this.pushParameterSet(t.sps,d.data,t.vps),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0;break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const p=this.readPPS(d.data);for(const x in p)t.params[x]=p[x]}this.pushParameterSet(t.pps,d.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}pushParameterSet(t,n,r){(r&&r[0]===this.initVPS||!r&&!t.length)&&t.push(n)}getNALuType(t,n){return(t[n]&126)>>>1}ebsp2rbsp(t){const n=new Uint8Array(t.byteLength);let r=0;for(let a=0;a=2&&t[a]===3&&t[a-1]===0&&t[a-2]===0||(n[r]=t[a],r++);return new Uint8Array(n.buffer,0,r)}pushAccessUnit(t,n){super.pushAccessUnit(t,n),this.initVPS&&(this.initVPS=null)}readVPS(t){const n=new gY(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 gY(this.ebsp2rbsp(t));n.readUByte(),n.readUByte(),n.readBits(4);const r=n.readBits(3);n.readBoolean();const a=n.readBits(2),i=n.readBoolean(),l=n.readBits(5),o=n.readUByte(),c=n.readUByte(),d=n.readUByte(),u=n.readUByte(),h=n.readUByte(),m=n.readUByte(),p=n.readUByte(),x=n.readUByte(),y=n.readUByte(),g=n.readUByte(),b=n.readUByte(),v=[],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 Ye=0;Ye0&&nt<16?(de=rt[nt-1],we=Fe[nt-1]):nt===255&&(de=n.readBits(16),we=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()&&(xe=n.readBits(32),fe=n.readBits(32),n.readBoolean()&&n.readUEG(),n.readBoolean())){const Fe=n.readBoolean(),dt=n.readBoolean();let Dt=!1;(Fe||dt)&&(Dt=n.readBoolean(),Dt&&(n.readUByte(),n.readBits(5),n.readBoolean(),n.readBits(5)),n.readBits(4),n.readBits(4),Dt&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5));for(let pt=0;pt<=r;pt++){je=n.readBoolean();const zt=je||n.readBoolean();let Gt=!1;zt?n.readEG():Gt=n.readBoolean();const qs=Gt?1:n.readUEG()+1;if(Fe)for(let As=0;As>Ae&1)<<31-Ae)>>>0;let _e=Ge.toString(16);return l===1&&_e==="2"&&(_e="6"),{codecString:`hvc1.${Be}${l}.${_e}.${i?"H":"L"}${b}.B0`,params:{general_tier_flag:i,general_profile_idc:l,general_profile_space:a,general_profile_compatibility_flags:[o,c,d,u],general_constraint_indicator_flags:[h,m,p,x,y,g],general_level_idc:b,bit_depth:q+8,bit_depth_luma_minus8:q,bit_depth_chroma_minus8:W,min_spatial_segmentation_idc:ie,chroma_format_idc:C,frame_rate:{fixed:je,fps:fe/xe}},width:Le,height:De,pixelRatio:[de,we]}}readPPS(t){const n=new gY(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 Dg=188;class _A{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=_A.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(Dg*5,n-Dg)+1,a=0;for(;a1&&(l===0&&o>2||c+Dg>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:n$t[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=_A.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=_A.createTrack("audio",a),this._id3Track=_A.createTrack("id3"),this._txtTrack=_A.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:n,_id3Track:r}=this;t&&(t.pesData=null),n&&(n.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,n,r=!1,a=!1){r||(this.sampleAes=null);let i;const l=this._videoTrack,o=this._audioTrack,c=this._id3Track,d=this._txtTrack;let u=l.pid,h=l.pesData,m=o.pid,p=c.pid,x=o.pesData,y=c.pesData,g=null,b=this.pmtParsed,v=this._pmtId,k=t.length;if(this.remainderData&&(t=Vj(this.remainderData,t),k=t.length,this.remainderData=null),k>4;let $;if(O>1){if($=P+5+t[P+4],$===P+Dg)continue}else $=P+4;switch(I){case u:L&&(h&&(i=x7(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($,P+Dg)),h.size+=P+Dg-$);break;case m:if(L){if(x&&(i=x7(x,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,i);break;case"mp3":this.parseMPEGPES(o,i);break;case"ac3":this.parseAC3PES(o,i);break}x={data:[],size:0}}x&&(x.data.push(t.subarray($,P+Dg)),x.size+=P+Dg-$);break;case p:L&&(y&&(i=x7(y,this.logger))&&this.parseID3PES(c,i),y={data:[],size:0}),y&&(y.data.push(t.subarray($,P+Dg)),y.size+=P+Dg-$);break;case 0:L&&($+=t[$]+1),v=this._pmtId=jLn(t,$);break;case v:{L&&($+=t[$]+1);const q=NLn(t,$,this.typeSupported,r,this.observer,this.logger);u=q.videoPid,u>0&&(l.pid=u,l.segmentCodec=q.segmentVideoCodec),m=q.audioPid,m>0&&(o.pid=m,o.segmentCodec=q.segmentAudioCodec),p=q.id3Pid,p>0&&(c.pid=p),g!==null&&!b&&(this.logger.warn(`MPEG-TS PMT found at ${P} after unknown PID '${g}'. Backtracking to sync byte @${C} to parse all TS packets.`),g=null,P=C-188),b=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=I;break}}else T++;T>0&&UBe(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=h,o.pesData=x,c.pesData=y;const M={audioTrack:o,videoTrack:l,id3Track:c,textTrack:d};return a&&this.extractRemainingSamples(M),M}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=x7(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=x7(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=x7(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 bLn(this.observer,this.config,n);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new _Ln:t==="hevc"&&(this.videoParser=new wLn))}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=Vj(a.sample.unit,i);else{const p=m-h;a.sample.unit.set(i.subarray(0,h),p),t.samples.push(a.sample),r=a.missing}}let l,o;for(l=r,o=i.length;l0;)o+=c}}parseID3PES(t,n){if(n.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=ah({},n,{type:this._videoTrack?L_.emsg:L_.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}}function $Be(s,t){return((s[t+1]&31)<<8)+s[t+2]}function jLn(s,t){return(s[t+10]&31)<<8|s[t+11]}function NLn(s,t,n,r,a,i){const l={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[t+1]&15)<<8|s[t+2],c=t+3+o-4,d=(s[t+10]&15)<<8|s[t+11];for(t+=12+d;t0){let m=t+5,p=h;for(;p>2;){switch(s[m]){case 106:n.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=u,l.segmentAudioCodec="ac3");break}const y=s[m+1]+2;m+=y,p-=y}}break;case 194:case 135:return UBe(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 UBe(s,t,n,r){r.warn(`parsing error: ${t.message}`),s.emit(Pt.ERROR,Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:t,reason:t.message})}function x8e(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function x7(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]=Vj(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(a=(r[4]<<8)+r[5],a&&a>s.size-6)return null;const u=r[7];u&192&&(l=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(o=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,l-o>60*9e4&&(t.warn(`${Math.round((l-o)/9e4)}s delta between PTS and DTS, align them`),l=o)):o=l),i=r[8];let h=i+9;if(s.size<=h)return null;s.size-=h;const m=new Uint8Array(s.size);for(let p=0,x=c.length;py){h-=y;continue}else r=r.subarray(h),y-=h,h=0;m.set(r,n),n+=y}return a&&(a-=i+3),{data:m,pts:l,dts:o,len:a}}return null}class kLn{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 $C=Math.pow(2,32)-1;class lr{static init(){lr.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 lr.types)lr.types.hasOwnProperty(t)&&(lr.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]);lr.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]);lr.STTS=lr.STSC=lr.STCO=i,lr.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),lr.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),lr.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),lr.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]);lr.FTYP=lr.box(lr.types.ftyp,l,c,l,o),lr.DINF=lr.box(lr.types.dinf,lr.box(lr.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 lr.box(lr.types.mdia,lr.mdhd(t.timescale||0,t.duration||0),lr.hdlr(t.type),lr.minf(t))}static mfhd(t){return lr.box(lr.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"?lr.box(lr.types.minf,lr.box(lr.types.smhd,lr.SMHD),lr.DINF,lr.stbl(t)):lr.box(lr.types.minf,lr.box(lr.types.vmhd,lr.VMHD),lr.DINF,lr.stbl(t))}static moof(t,n,r){return lr.box(lr.types.moof,lr.mfhd(t),lr.traf(r,n))}static moov(t){let n=t.length;const r=[];for(;n--;)r[n]=lr.trak(t[n]);return lr.box.apply(null,[lr.types.moov,lr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(lr.mvex(t)))}static mvex(t){let n=t.length;const r=[];for(;n--;)r[n]=lr.trex(t[n]);return lr.box.apply(null,[lr.types.mvex,...r])}static mvhd(t,n){n*=t;const r=Math.floor(n/($C+1)),a=Math.floor(n%($C+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 lr.box(lr.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=lr.box(lr.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 lr.box(lr.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,lr.box(lr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),lr.box(lr.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 lr.box(lr.types.mp4a,lr.audioStsd(t),lr.box(lr.types.esds,lr.esds(t)))}static mp3(t){return lr.box(lr.types[".mp3"],lr.audioStsd(t))}static ac3(t){return lr.box(lr.types["ac-3"],lr.audioStsd(t),lr.box(lr.types.dac3,t.config))}static stsd(t){const{segmentCodec:n}=t;if(t.type==="audio"){if(n==="aac")return lr.box(lr.types.stsd,lr.STSD,lr.mp4a(t));if(n==="ac3"&&t.config)return lr.box(lr.types.stsd,lr.STSD,lr.ac3(t));if(n==="mp3"&&t.codec==="mp3")return lr.box(lr.types.stsd,lr.STSD,lr.mp3(t))}else if(t.pps&&t.sps){if(n==="avc")return lr.box(lr.types.stsd,lr.STSD,lr.avc1(t));if(n==="hevc"&&t.vps)return lr.box(lr.types.stsd,lr.STSD,lr.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/($C+1)),o=Math.floor(r%($C+1));return lr.box(lr.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=lr.sdtp(t),a=t.id,i=Math.floor(n/($C+1)),l=Math.floor(n%($C+1));return lr.box(lr.types.traf,lr.box(lr.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),lr.box(lr.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])),lr.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,lr.box(lr.types.trak,lr.tkhd(t),lr.mdia(t))}static trex(t){const n=t.id;return lr.box(lr.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 lr.box(lr.types.trun,l)}static initSegment(t){lr.types||lr.init();const n=lr.moov(t);return Vj(lr.FTYP,n)}static hvc1(t){const n=t.params,r=[t.vps,t.sps,t.pps],a=4,i=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),a-1|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]);let l=i.length;for(let x=0;x>8,r[x][y].length&255]),l),l+=2,o.set(r[x][y],l),l+=r[x][y].length}const d=lr.box(lr.types.hvcC,o),u=t.width,h=t.height,m=t.pixelRatio[0],p=t.pixelRatio[1];return lr.box(lr.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,lr.box(lr.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),lr.box(lr.types.pasp,new Uint8Array([m>>24,m>>16&255,m>>8&255,m&255,p>>24,p>>16&255,p>>8&255,p&255])))}}lr.types=void 0;lr.HDLR_TYPES=void 0;lr.STTS=void 0;lr.STSC=void 0;lr.STCO=void 0;lr.STSZ=void 0;lr.VMHD=void 0;lr.SMHD=void 0;lr.STSD=void 0;lr.FTYP=void 0;lr.DINF=void 0;const Q$t=9e4;function LYe(s,t,n=1,r=!1){const a=s*t*n;return r?Math.round(a):a}function SLn(s,t,n=1,r=!1){return LYe(s,t,1/n,r)}function aG(s,t=!1){return LYe(s,1e3,1/Q$t,t)}function CLn(s,t=1){return LYe(s,Q$t,1/t)}function U0t(s){const{baseTime:t,timescale:n,trackId:r}=s;return`${t/n} (${t}/${n}) trackId: ${r}`}const ALn=10*1e3,TLn=1024,ELn=1152,MLn=1536;let g7=null,g8e=null;function q0t(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 E2e extends Jj{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,g7===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);g7=l?parseInt(l[1]):0}if(g8e===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);g8e=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&&U0t(n)} > ${t&&U0t(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=C_(o,r),c=o-i),c>0?i:o},r);return n&&this.debug("PTS rollover detected"),a}remux(t,n,r,a,i,l,o,c){let d,u,h,m,p,x,y=i,g=i;const b=t.pid>-1,v=n.pid>-1,k=n.samples.length,C=t.samples.length>0,T=o&&k>0||k>1;if((!b||C)&&(!v||T)||this.ISGenerated||o){if(this.ISGenerated){var P,L,I,O;const G=this.videoTrackConfig;(G&&(n.width!==G.width||n.height!==G.height||((P=n.pixelRatio)==null?void 0:P[0])!==((L=G.pixelRatio)==null?void 0:L[0])||((I=n.pixelRatio)==null?void 0:I[1])!==((O=G.pixelRatio)==null?void 0:O[1]))||!G&&T||this.nextAudioTs===null&&C)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,n,i,l));const $=this.isVideoContiguous;let q=-1,W;if(T&&(q=LLn(n.samples),!$&&this.config.forceKeyFrameOnDiscontinuity))if(x=!0,q>0){this.warn(`Dropped ${q} out of ${k} video samples due to a missing keyframe`);const G=this.getVideoStartPts(n.samples);n.samples=n.samples.slice(q),n.dropped+=q,g+=(n.samples[0].pts-G)/n.inputTimeScale,W=g}else q===-1&&(this.warn(`No keyframe found out of ${k} video samples`),x=!1);if(this.ISGenerated){if(C&&T){const G=this.getVideoStartPts(n.samples),ee=(C_(t.samples[0].pts,G)-G)/n.inputTimeScale;y+=Math.max(0,ee),g+=Math.max(0,-ee)}if(C){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,v||T||c===zi.AUDIO?g: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,g,$,G)}}else T&&(d=this.remuxVideo(n,g,$,0));d&&(d.firstKeyFrame=q,d.independent=q!==-1,d.firstKeyFramePTS=W)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(p=J$t(r,i,this._initPTS,this._initDTS)),a.samples.length&&(m=eUt(a,i,this._initPTS))),{audio:u,video:d,initSegment:h,independent:x,text:m,id3:p}}computeInitPts(t,n,r,a){const i=Math.round(r*n);let l=C_(t,i);if(l0?ie-1:ie].dts&&(v=!0)}v&&l.sort(function(ie,de){const we=ie.dts-de.dts,je=ie.pts-de.pts;return we||je}),x=l[0].dts,y=l[l.length-1].dts;const C=y-x,T=C?Math.round(C/(c-1)):p||t.inputTimeScale/30;if(r){const ie=x-k,de=ie>T,we=ie<-1;if((de||we)&&(de?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${aG(ie,!0)} ms (${ie}dts) hole between fragments detected at ${n.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${aG(-ie,!0)} ms (${ie}dts) overlapping between fragments detected at ${n.toFixed(3)}`),!we||k>=l[0].pts||g7)){x=k;const je=l[0].pts-ie;if(de)l[0].dts=x,l[0].pts=je;else{let xe=!0;for(let fe=0;feje&&xe);fe++){const Se=l[fe].pts;if(l[fe].dts-=ie,l[fe].pts-=ie,fe0?de.dts-l[ie-1].dts:T;if(xe=ie>0?de.pts-l[ie-1].pts:T,Se.stretchShortVideoTrack&&this.nextAudioTs!==null){const Le=Math.floor(Se.maxBufferHole*i),De=(a?g+a*i:this.nextAudioTs+u)-de.pts;De>Le?(p=De-Ee,p<0?p=Ee:q=!0,this.log(`It is approximately ${De/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=Ee}else p=Ee}const fe=Math.round(de.pts-de.dts);W=Math.min(W,p),K=Math.max(K,p),G=Math.min(G,xe),ee=Math.max(ee,xe),o.push(q0t(de.key,p,je,fe))}if(o.length){if(g7){if(g7<70){const ie=o[0].flags;ie.dependsOn=2,ie.isNonSync=0}}else if(g8e&&ee-G0&&(a&&Math.abs(k-(b+v))<9e3||Math.abs(C_(y[0].pts,k)-(b+v))<20*u),y.forEach(function(ee){ee.pts=C_(ee.pts,k)}),!r||b<0){const ee=y.length;if(y=y.filter(J=>J.pts>=0),ee!==y.length&&this.warn(`Removed ${y.length-ee} of ${ee} samples (initPTS ${v} / ${l})`),!y.length)return;i===0?b=0:a&&!x?b=Math.max(0,k-v):b=y[0].pts-v}if(t.segmentCodec==="aac"){const ee=this.config.maxAudioFramesDrift;for(let J=0,le=b+v;J=ee*u&&de0){P+=g;try{M=new Uint8Array(P)}catch(de){this.observer.emit(Pt.ERROR,Pt.ERROR,{type:co.MUX_ERROR,details:cr.REMUX_ALLOC_ERROR,fatal:!1,error:de,bytes:P,reason:`fail allocating audio mdat ${P}`});return}m||(new DataView(M.buffer).setUint32(0,P),M.set(lr.types.mdat,4))}else return;M.set(ue,g);const ie=ue.byteLength;g+=ie,p.push(q0t(!0,d,ie,0)),T=oe}const I=p.length;if(!I)return;const O=p[p.length-1];b=T-v,this.nextAudioTs=b+c*O.duration;const $=m?new Uint8Array(0):lr.moof(t.sequenceNumber++,C/c,ah({},t,{samples:p}));t.samples=[];const q=(C-v)/l,W=this.nextAudioTs/l,K={data1:$,data2:M,startPTS:q,endPTS:W,startDTS:q,endDTS:W,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,K}}function C_(s,t){let n;if(t===null)return s;for(t4294967296;)s+=n;return s}function LLn(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class PLn extends Jj{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=i$t(t);if(n)b6n(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=V0t(i,yh.AUDIO,this)),l&&(a=V0t(l,yh.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};ji(u)||(u=this.lastEndTime=i||0);const m=n.samples;if(!m.length)return h;const p={initPTS:void 0,timescale:void 0,trackId:void 0};let x=this.initData;if((o=x)!=null&&o.length||(this.generateInitSegment(m),x=this.initData),!((c=x)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(p.tracks=this.initTracks,this.emitInitSegment=!1);const y=w6n(m,x,this),g=x.audio?y[x.audio.id]:null,b=x.video?y[x.video.id]:null,v=Nre(b,1/0),k=Nre(g,1/0),C=Nre(b,0,!0),T=Nre(g,0,!0);let M=i,P=0;const L=g&&(!b||!d&&k0?this.lastEndTime=$:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const q=!!x.audio,W=!!x.video;let G="";q&&(G+="audio"),W&&(G+="video");const K=(x.audio?x.audio.encrypted:!1)||(x.video?x.video.encrypted:!1),ee={data1:m,startPTS:O,startDTS:O,endPTS:$,endDTS:$,type:G,hasAudio:q,hasVideo:W,nb:1,dropped:0,encrypted:K};h.audio=q&&!W?ee:void 0,h.video=W?ee:void 0;const J=b==null?void 0:b.sampleCount;if(J){const le=b.keyFrameIndex,ue=le!==-1;ee.nb=J,ee.dropped=le===0||this.isVideoContiguous?0:ue?le:J,ee.independent=ue,ee.firstKeyFrame=le,ue&&b.keyFrameStart&&(ee.firstKeyFramePTS=(b.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(h.independent=ue),this.isVideoContiguous||(this.isVideoContiguous=ue),ee.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${le}/${J} dropped: ${ee.dropped} start: ${ee.firstKeyFramePTS||"NA"}`)}return h.initSegment=p,h.id3=J$t(r,i,d,d),a.samples.length&&(h.text=eUt(a,i,d)),h}}function Nre(s,t,n=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(n?s.duration:0))/s.timescale:t}function ILn(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 V0t(s,t,n){const r=s.codec;return r&&r.length>4?r:t===yh.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?PSe(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 v4;try{v4=self.performance.now.bind(self.performance)}catch{v4=Date.now}const M2e=[{demux:vLn,remux:PLn},{demux:_A,remux:E2e},{demux:fLn,remux:E2e},{demux:gLn,remux:E2e}];M2e.splice(2,0,{demux:xLn,remux:E2e});class H0t{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=v4();let l=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:c}=this;a&&(this.currentTransmuxState=a);const{contiguous:d,discontinuity:u,trackSwitch:h,accurateTimeOffset:m,timeOffset:p,initSegmentChange:x}=a||o,{audioCodec:y,videoCodec:g,defaultInitPts:b,duration:v,initSegmentData:k}=c,C=RLn(l,n);if(C&&Vz(C.method)){const L=this.getDecrypter(),I=jYe(C.method);if(L.isSync()){let O=L.softwareDecrypt(l,C.key.buffer,C.iv.buffer,I);if(r.part>-1){const q=L.flush();O=q&&q.buffer}if(!O)return i.executeEnd=v4(),y8e(r);l=new Uint8Array(O)}else return this.asyncResult=!0,this.decryptionPromise=L.webCryptoDecrypt(l,C.key.buffer,C.iv.buffer,I).then(O=>{const $=this.push(O,null,r);return this.decryptionPromise=null,$}),this.decryptionPromise}const T=this.needsProbing(u,h);if(T){const L=this.configureTransmuxer(l);if(L)return this.logger.warn(`[transmuxer] ${L.message}`),this.observer.emit(Pt.ERROR,Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.FRAG_PARSING_ERROR,fatal:!1,error:L,reason:L.message}),i.executeEnd=v4(),y8e(r)}(u||h||x||T)&&this.resetInitSegment(k,y,g,v,n),(u||x||T)&&this.resetInitialTimestamp(b),d||this.resetContiguity();const M=this.transmux(l,C,p,m,r);this.asyncResult=SX(M);const P=this.currentTransmuxState;return P.contiguous=!0,P.discontinuity=!1,P.trackSwitch=!1,i.executeEnd=v4(),M}flush(t){const n=t.transmuxing;n.executeStart=v4();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=v4();const h=[y8e(t)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o);return SX(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===zi.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=v4()}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=M2e.length;h0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(n=t),n}const y8e=s=>({remuxResult:{},chunkMeta:s});function SX(s){return"then"in s&&s.then instanceof Function}class DLn{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 OLn{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 G0t=0;class tUt{constructor(t,n,r,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=G0t++,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(Pt.ERROR,{type:co.OTHER_ERROR,details:cr.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===Pt.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new SYe,this.observer.on(Pt.FRAG_DECRYPTED,l),this.observer.on(Pt.ERROR,l);const o=o0t(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||$Mn()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${n}"`),this.workerContext=qMn(i.workerPath)):(c.log(`injecting Web Worker for "${n}"`),this.workerContext=UMn());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:Sh(i)})}catch(u){c.warn(`Error setting up "${n}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new H0t(this.observer,o,i,"",n,t.logger)}return}}this.transmuxer=new H0t(this.observer,o,i,"",n,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=G0t++;const n=this.hls.config,r=o0t(n.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:Sh(n)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),VMn(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const n=this.transmuxer;n&&(n.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,n,r,a,i,l,o,c,d,u){var h,m;d.transmuxing.start=self.performance.now();const{instanceNo:p,transmuxer:x}=this,y=l?l.start:i.start,g=i.decryptdata,b=this.frag,v=!(b&&i.cc===b.cc),k=!(b&&d.level===b.level),C=b?d.sn-b.sn:-1,T=this.part?d.part-this.part.index:-1,M=C===0&&d.id>1&&d.id===(b==null?void 0:b.stats.chunkCount),P=!k&&(C===1||C===0&&(T===1||M&&T<=0)),L=self.performance.now();(k||C||i.stats.parsing.start===0)&&(i.stats.parsing.start=L),l&&(T||!P)&&(l.stats.parsing.start=L);const I=!(b&&((h=i.initSegment)==null?void 0:h.url)===((m=b.initSegment)==null?void 0:m.url)),O=new OLn(v,P,c,k,y,I);if(!P||v||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id===zi.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${v} trackSwitch: ${k} contiguous: ${P} accurateTimeOffset: ${c} timeOffset: ${y} initSegmentChange: ${I}`);const $=new DLn(r,a,n,o,u);this.configureTransmuxer($)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:p,cmd:"demux",data:t,decryptdata:g,chunkMeta:d,state:O},t instanceof ArrayBuffer?[t]:[]);else if(x){const $=x.push(t,g,d,O);SX($)?$.then(q=>{this.handleTransmuxComplete(q)}).catch(q=>{this.transmuxerError(q,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);SX(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(Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.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 W0t=100;class FLn extends kYe{constructor(t,n,r){super(t,n,r,"audio-stream-controller",zi.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(Pt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Pt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(Pt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Pt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Pt.BUFFER_RESET,this.onBufferReset,this),t.on(Pt.BUFFER_CREATED,this.onBufferCreated,this),t.on(Pt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Pt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Pt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Pt.FRAG_LOADING,this.onFragLoading,this),t.on(Pt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(Pt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Pt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(Pt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Pt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Pt.BUFFER_RESET,this.onBufferReset,this),t.off(Pt.BUFFER_CREATED,this.onBufferCreated,this),t.off(Pt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Pt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Pt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Pt.FRAG_LOADING,this.onFragLoading,this),t.off(Pt.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:n,id:r,initPTS:a,timescale:i,trackId:l}){if(r===zi.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===Yr.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===Yr.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=g$t(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===Yr.IDLE&&this.doTickIdle())}startLoad(t,n){if(!this.levels){this.startPosition=t,this.state=Yr.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(W0t),r>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r,this.state=Yr.IDLE):this.state=Yr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}doTick(){switch(this.state){case Yr.IDLE:this.doTickIdle();break;case Yr.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=Yr.WAITING_INIT_PTS}break}case Yr.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Yr.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=Yr.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=Yr.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=Yr.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,yh.AUDIO,zi.AUDIO));const u=this.getFwdBufferInfo(d,zi.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){n.trigger(Pt.BUFFER_EOS,{type:"audio"}),this.state=Yr.ENDED;return}const h=u.len,m=n.maxBufferLength,p=c.fragments,x=p[0].start,y=this.getLoadPosition(),g=this.flushing?y:u.end;if(this.switchingTrack&&a){const k=y;c.PTSKnown&&kx||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=x+.05)}if(h>=m&&!this.switchingTrack&&gv.end){const C=this.fragmentTracker.getFragAtPos(g,zi.MAIN);C&&C.end>v.end&&(v=C,this.mainFragLoading={frag:C,targetBufferTime:null})}if(b.start>v.end)return}this.loadFragment(b,o,g)}onMediaDetaching(t,n){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,n)}onAudioTracksUpdated(t,{audioTracks:n}){this.resetTransmuxer(),this.levels=n.map(r=>new jX(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!==Yr.STOPPED&&(this.setInterval(W0t),this.state=Yr.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(Pt.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!==Yr.STOPPED&&(this.state=Yr.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||(R$t(i,d),i.alignedSliding||BSe(i,d),h=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,h),this.hls.trigger(Pt.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:n.groupId}),this.state===Yr.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=Yr.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 tUt(this.hls,zi.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const p=this.initPTS[r.cc],x=(n=r.initSegment)==null?void 0:n.data;if(p!==void 0){const g=a?a.index:-1,b=g!==-1,v=new wYe(r.level,r.sn,r.stats.chunkCount,i.byteLength,g,b);m.push(i,x,h,"",r,a,u.totalduration,!1,v,p)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:y}=this.waitingData=this.waitingData||{frag:r,part:a,cache:new D$t,complete:!1};y.push(new Uint8Array(i)),this.state!==Yr.STOPPED&&(this.state=Yr.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===zi.MAIN&&Yf(n.frag)&&(this.mainFragLoading=n,this.state===Yr.IDLE&&this.tick())}onFragBuffered(t,n){const{frag:r,part:a}=n;if(r.type!==zi.AUDIO){!this.audioOnly&&r.type===zi.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(Yf(r)){this.fragPrevious=r;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(Pt.AUDIO_TRACK_SWITCHED,Uu({},i)))}this.fragBufferedComplete(r,a),this.media&&this.tick()}onError(t,n){var r;if(n.fatal){this.state=Yr.ERROR;return}switch(n.details){case cr.FRAG_GAP:case cr.FRAG_PARSING_ERROR:case cr.FRAG_DECRYPT_ERROR:case cr.FRAG_LOAD_ERROR:case cr.FRAG_LOAD_TIMEOUT:case cr.KEY_LOAD_ERROR:case cr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(zi.AUDIO,n);break;case cr.AUDIO_TRACK_LOAD_ERROR:case cr.AUDIO_TRACK_LOAD_TIMEOUT:case cr.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===Yr.WAITING_TRACK&&((r=n.context)==null?void 0:r.type)===Pc.AUDIO_TRACK&&(this.state=Yr.IDLE);break;case cr.BUFFER_ADD_CODEC_ERROR:case cr.BUFFER_APPEND_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)||this.resetLoadingState();break;case cr.BUFFER_FULL_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case cr.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onBufferFlushing(t,{type:n}){n!==yh.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:n}){if(n!==yh.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Yr.ENDED&&(this.state=Yr.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,n,zi.AUDIO),this.tick())}}_handleTransmuxComplete(t){var n;const r="audio",{hls:a}=this,{remuxResult:i,chunkMeta:l}=t,o=this.getCurrentContext(l);if(!o){this.resetWhenMissingContext(l);return}const{frag:c,part:d,level:u}=o,{details:h}=u,{audio:m,text:p,id3:x,initSegment:y}=i;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=Yr.PARSING,this.switchingTrack&&m&&this.completeAudioSwitch(this.switchingTrack),y!=null&&y.tracks){const g=c.initSegment||c;if(this.unhandledEncryptionError(y,c))return;this._bufferInitSegment(u,y.tracks,g,l),a.trigger(Pt.FRAG_PARSING_INIT_SEGMENT,{frag:g,id:r,tracks:y.tracks})}if(m){const{startPTS:g,endPTS:b,startDTS:v,endDTS:k}=m;d&&(d.elementaryStreams[yh.AUDIO]={startPTS:g,endPTS:b,startDTS:v,endDTS:k}),c.setElementaryStreamInfo(yh.AUDIO,g,b,v,k),this.bufferFragmentData(m,c,d,l)}if(x!=null&&(n=x.samples)!=null&&n.length){const g=ah({id:r,frag:c,details:h},x);a.trigger(Pt.FRAG_PARSING_METADATA,g)}if(p){const g=ah({id:r,frag:c,details:h},p);a.trigger(Pt.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(t,n,r,a){if(this.state!==Yr.PARSING||(n.video&&delete n.video,n.audiovideo&&delete n.audiovideo,!n.audio))return;const i=n.audio;i.id=zi.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(Pt.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(Pt.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===sg.NOT_LOADED||a===sg.PARTIAL){var i;if(!Yf(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=Yr.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==n.details.fragmentStart&&BSe(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;gD({name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,$I)||(RSe(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(Pt.AUDIO_TRACK_SWITCHED,Uu({},t))}}class PYe extends Jj{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&&l0t(r);return new c0t(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){EMn(r,a,this);const v=a.playlistParsingError;if(v){this.warn(v);const k=this.hls;if(!k.config.ignorePlaylistParsingErrors){var d;const{networkDetails:C}=n;k.trigger(Pt.ERROR,{type:co.NETWORK_ERROR,details:cr.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:v,reason:v.message,level:n.level||void 0,parent:(d=a.fragments[0])==null?void 0:d.type,networkDetails:C,stats:i});return}a.playlistParsingError=null}}a.requestScheduled===-1&&(a.requestScheduled=i.loading.start);const h=this.hls.mainForwardBufferInfo,m=h?h.end-h.len:0,p=(a.edge-m)*1e3,x=E$t(a,p);if(a.requestScheduled+x0){if(I>a.targetduration*3)this.log(`Playlist last advanced ${L.toFixed(2)}s ago. Omitting segment and part directives.`),g=void 0,b=void 0;else if(r!=null&&r.tuneInGoal&&I-a.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${O} with playlist age: ${a.age}`),O=0;else{const $=Math.floor(O/a.targetduration);if(g+=$,b!==void 0){const q=Math.round(O%a.targetduration/a.partTarget);b+=q}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${L.toFixed(2)}s goal: ${O} skip sn ${$} to part ${b}`)}a.tuneInGoal=O}if(y=this.getDeliveryDirectives(a,n.deliveryDirectives,g,b),v||!P){a.requestScheduled=l,this.loadingPlaylist(u,y);return}}else(a.canBlockReload||a.canSkipUntil)&&(y=this.getDeliveryDirectives(a,n.deliveryDirectives,g,b));y&&g!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(x-o*2,x/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=l0t(t);return n!=null&&n.skip&&t.deltaUpdateFailed&&(r=n.msn,a=n.part,i=A2e.No),new c0t(r,a,i)}checkRetry(t){const n=t.details,r=DSe(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===H0.RetryRequest||!a.resolved&&i===H0.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=bYe(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 sUt(s,t){if(s.length!==t.length)return!1;for(let n=0;ns[a]!==t[a])}function qBe(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class zLn extends PYe{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(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Pt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Pt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Pt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Pt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Pt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Pt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Pt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Pt.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,n){this.tracks=n.audioTracks||[]}onAudioTrackLoaded(t,n){const{id:r,groupId:a,details:i}=n,l=this.tracksInGroup[r];if(!l||l.groupId!==a){this.warn(`Audio track with id:${r} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=n.details,this.log(`Audio track ${r} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,n,o)}onLevelLoading(t,n){this.switchLevel(n.level)}onLevelSwitching(t,n){this.switchLevel(n.level)}switchLevel(t){const n=this.hls.levels[t];if(!n)return;const r=n.audioGroups||null,a=this.groupIds;let i=this.currentTrack;if(!r||(a==null?void 0:a.length)!==(r==null?void 0:r.length)||r!=null&&r.some(o=>(a==null?void 0:a.indexOf(o))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(m=>!r||r.indexOf(m.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(m=>m.default)&&(this.selectDefaultTrack=!1),o.forEach((m,p)=>{m.id=p});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!i&&c){const m=C5(c,o,$I);if(m>-1)i=o[m];else{const p=C5(c,this.tracks);i=this.tracks[p]}}let d=this.findTrackId(i);d===-1&&i&&(d=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${r==null?void 0:r.join(",")}`),this.hls.trigger(Pt.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(Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:m})}}}onError(t,n){n.fatal||!n.context||n.context.type===Pc.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&&gD(t,a,$I))return a;const i=C5(t,this.tracksInGroup,$I);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=X6n(t,n.levels,r,l,$I);if(o===-1)return null;n.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=C5(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(Pt.AUDIO_TRACK_SWITCHING,Uu({},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 K0t=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,nUt="HlsJsTrackRemovedError";class $Ln extends Error{constructor(t){super(t),this.name=nUt}}class ULn extends Jj{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(Pt.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=d6n(UE(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(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Pt.BUFFER_RESET,this.onBufferReset,this),t.on(Pt.BUFFER_APPENDING,this.onBufferAppending,this),t.on(Pt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Pt.BUFFER_EOS,this.onBufferEos,this),t.on(Pt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Pt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Pt.FRAG_PARSED,this.onFragParsed,this),t.on(Pt.FRAG_CHANGED,this.onFragChanged,this),t.on(Pt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Pt.BUFFER_RESET,this.onBufferReset,this),t.off(Pt.BUFFER_APPENDING,this.onBufferAppending,this),t.off(Pt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Pt.BUFFER_EOS,this.onBufferEos,this),t.off(Pt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Pt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Pt.FRAG_PARSED,this.onFragParsed,this),t.off(Pt.FRAG_CHANGED,this.onFragChanged,this),t.off(Pt.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?ah(r,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(r[l]=ah({},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=UE(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,Y0t(r),qLn(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: ${Sh(r,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${Sh(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!JBt(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(Pt.MEDIA_DETACHING,{}),this.onMediaAttaching(Pt.MEDIA_ATTACHING,n),t.currentTime=u;return}this.transferData=void 0,i.forEach(c=>{const d=c,u=a[d];if(u){const h=u.buffer;if(h){const m=this.fragmentTracker,p=u.id;if(m.hasFragments(p)||m.hasParts(p)){const g=Pl.getBuffered(h);m.detectEvictedFragments(d,g,p,null,!0)}const x=v8e(d),y=[d,h];this.sourceBuffers[x]=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&&Y0t(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(Pt.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[v8e(t)]=[null,null];const n=this.tracks[t];n&&(n.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new BLn(this.tracks)}onBufferCodecs(t,n){var r;const a=this.tracks,i=Object.keys(n);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const l="audiovideo"in n&&(a.audio||a.video)||a.audiovideo&&("audio"in n||"video"in n),o=!l&&this.sourceBufferCount&&this.media&&i.some(c=>!a[c]);if(l||o){this.warn(`Unsupported transition between "${Object.keys(a)}" and "${i}" SourceBuffers`);return}i.forEach(c=>{var d,u;const h=n[c],{id:m,codec:p,levelCodec:x,container:y,metadata:g,supplemental:b}=h;let v=a[c];const k=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],C=k!=null&&k.buffer?k:v,T=(C==null?void 0:C.pendingCodec)||(C==null?void 0:C.codec),M=C==null?void 0:C.levelCodec;v||(v=a[c]={buffer:void 0,listeners:[],codec:p,supplemental:b,container:y,levelCodec:x,metadata:g,id:m});const P=C2e(T,M),L=P==null?void 0:P.replace(K0t,"$1");let I=C2e(p,x);const O=(u=I)==null?void 0:u.replace(K0t,"$1");I&&P&&L!==O&&(c.slice(0,5)==="audio"&&(I=PSe(I,this.appendSource)),this.log(`switching codec ${T} to ${I}`),I!==(v.pendingCodec||v.codec)&&(v.pendingCodec=I),v.container=y,this.appendChangeType(c,y,I))}),(this.tracksReady||this.sourceBufferCount)&&(n.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!n.video&&((r=n.audio)==null?void 0:r.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,n)=>{const r=this.tracks[n];return t[n]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t},{})}appendChangeType(t,n,r){const a=`${n};codecs=${r}`,i={label:`change-type=${a}`,execute:()=>{const l=this.tracks[t];if(l){const o=l.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${a}`),o.changeType(a),l.codec=r,l.container=n)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:l=>{this.warn(`Failed to change ${t} SourceBuffer type`,l)}};this.append(i,t,this.isPending(this.tracks[t]))}blockAudio(t){var n;const r=t.start,a=r+t.duration*.05;if(((n=this.fragmentTracker.getAppendedFrag(r,zi.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&&Pl.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,zi.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:l,frag:t},this.append(l,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:n}=this;t&&n&&(this.blockedAudioAppend=null,n.unblockAudio(t.op))}onBufferAppending(t,n){const{tracks:r}=this,{data:a,type:i,parent:l,frag:o,part:c,chunkMeta:d,offset:u}=n,h=d.buffering[i],{sn:m,cc:p}=o,x=self.performance.now();h.start=x;const y=o.stats.buffering,g=c?c.stats.buffering:null;y.start===0&&(y.start=x),g&&g.start===0&&(g.start=x);const b=r.audio;let v=!1;i==="audio"&&(b==null?void 0:b.container)==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const k=r.video,C=k==null?void 0:k.buffer;if(C&&m!=="initSegment"){const P=c||o,L=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(k.ending||k.ended)){const O=P.start+P.duration*.05,$=C.buffered,q=this.currentOp("video");!$.length&&!q?this.blockAudio(P):!q&&!Pl.isBuffered(C,O)&&this.lastVideoAppendEndO||I{var P;h.executeStart=self.performance.now();const L=(P=this.tracks[i])==null?void 0:P.buffer;L&&(v?this.updateTimestampOffset(L,T,.1,i,m,p):u!==void 0&&ji(u)&&this.updateTimestampOffset(L,u,1e-6,i,m,p)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{const P=self.performance.now();h.executeEnd=h.end=P,y.first===0&&(y.first=P),g&&g.first===0&&(g.first=P);const L={};this.sourceBuffers.forEach(([I,O])=>{I&&(L[I]=Pl.getBuffered(O))}),this.appendErrors[i]=0,i==="audio"||i==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Pt.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:L})},onError:P=>{var L;const I={type:co.MEDIA_ERROR,parent:o.type,details:cr.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:P,err:P,fatal:!1},O=(L=this.media)==null?void 0:L.error;if(P.code===DOMException.QUOTA_EXCEEDED_ERR||P.name=="QuotaExceededError"||"quota"in P)I.details=cr.BUFFER_FULL_ERROR;else if(P.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!O)I.errorAction=qz(!0);else if(P.name===nUt&&this.sourceBufferCount===0)I.errorAction=qz(!0);else{const $=++this.appendErrors[i];this.warn(`Failed ${$}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${O||"no media error"})`),($>=this.hls.config.appendErrorMaxRetry||O)&&(I.fatal=!0)}this.hls.trigger(Pt.ERROR,I)}};this.log(`queuing "${i}" append sn: ${m}${c?" p: "+c.index:""} of ${o.type===zi.MAIN?"level":"track"} ${o.level} cc: ${p}`),this.append(M,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(Pt.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[yh.AUDIOVIDEO]?i.push("audiovideo"):(l[yh.AUDIO]&&i.push("audio"),l[yh.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(Pt.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(Pt.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(Pt.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===cr.BUFFER_APPEND_ERROR&&n.frag){var r;const a=(r=n.errorAction)==null?void 0:r.nextAutoLevel;ji(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(ji(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(ji(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=Pl.getBuffered(i);if(o.length>0&&r>o.start(0)){var l;this.hls.trigger(Pt.BACK_BUFFER_REACHED,{bufferEnd:r});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(Pt.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(Pt.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:a})}}})}flushFrontBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=Pl.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(Pt.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 ji(i)?{duration:i}:null;const l=this.media.duration,o=ji(r.duration)?r.duration:0;return a>o&&a>l||!ji(l)?{duration:a}:null}updateMediaSource({duration:t,start:n,end:r}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(ji(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}) ${Sh(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(Pt.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(Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.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":""} ${Sh(o)}`);try{const u=r.addSourceBuffer(d),h=v8e(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(Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.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")&&_X(r,"video")&&(a=L6n(a,r));const i=C2e(a,t.levelCodec);return i?n.slice(0,5)==="audio"?PSe(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(Pt.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(Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.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=ji(a.duration)?a.duration:1/0,d=ji(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 $Ln(`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 Y0t(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(n=>{s.removeChild(n)})}function qLn(s,t){const n=self.document.createElement("source");n.type="video/mp4",n.src=t,s.appendChild(n)}function v8e(s){return s==="audio"?1:0}class IYe{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(Pt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Pt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Pt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Pt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(Pt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Pt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Pt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Pt.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&&ji(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,IYe.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 VLn={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},q1=VLn,HLn={HLS:"h"},GLn=HLn;class tS{constructor(t,n){Array.isArray(t)&&(t=t.map(r=>r instanceof tS?r:new tS(r))),this.value=t,this.params=n}}const WLn="Dict";function KLn(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 YLn(s,t,n,r){return new Error(`failed to ${s} "${KLn(t)}" as ${n}`,{cause:r})}function sS(s,t,n){return YLn("serialize",s,t,n)}class rUt{constructor(t){this.description=t}}const Z0t="Bare Item",ZLn="Boolean";function XLn(s){if(typeof s!="boolean")throw sS(s,ZLn);return s?"?1":"?0"}function QLn(s){return btoa(String.fromCharCode(...s))}const JLn="Byte Sequence";function ePn(s){if(ArrayBuffer.isView(s)===!1)throw sS(s,JLn);return`:${QLn(s)}:`}const tPn="Integer";function sPn(s){return s<-999999999999999||99999999999999912)throw sS(s,rPn);const n=t.toString();return n.includes(".")?n:`${n}.0`}const iPn="String",oPn=/[\x00-\x1f\x7f]+/;function lPn(s){if(oPn.test(s))throw sS(s,iPn);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function cPn(s){return s.description||s.toString().slice(7,-1)}const dPn="Token";function X0t(s){const t=cPn(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw sS(t,dPn);return t}function VBe(s){switch(typeof s){case"number":if(!ji(s))throw sS(s,Z0t);return Number.isInteger(s)?aUt(s):aPn(s);case"string":return lPn(s);case"symbol":return X0t(s);case"boolean":return XLn(s);case"object":if(s instanceof Date)return nPn(s);if(s instanceof Uint8Array)return ePn(s);if(s instanceof rUt)return X0t(s);default:throw sS(s,Z0t)}}const uPn="Key";function HBe(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw sS(s,uPn);return s}function RYe(s){return s==null?"":Object.entries(s).map(([t,n])=>n===!0?`;${HBe(t)}`:`;${HBe(t)}=${VBe(n)}`).join("")}function oUt(s){return s instanceof tS?`${VBe(s.value)}${RYe(s.params)}`:VBe(s)}function hPn(s){return`(${s.value.map(oUt).join(" ")})${RYe(s.params)}`}function mPn(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw sS(s,WLn);const n=s instanceof Map?s.entries():Object.entries(s),r=t!=null&&t.whitespace?" ":"";return Array.from(n).map(([a,i])=>{i instanceof tS||(i=new tS(i));let l=HBe(a);return i.value===!0?l+=RYe(i.params):(l+="=",Array.isArray(i.value)?l+=hPn(i):l+=oUt(i)),l}).join(`,${r}`)}function lUt(s,t){return mPn(s,t)}const Sk="CMCD-Object",of="CMCD-Request",xM="CMCD-Session",UC="CMCD-Status",pPn={br:Sk,ab:Sk,d:Sk,ot:Sk,tb:Sk,tpb:Sk,lb:Sk,tab:Sk,lab:Sk,url:Sk,pb:of,bl:of,tbl:of,dl:of,ltc:of,mtp:of,nor:of,nrr:of,rc:of,sn:of,sta:of,su:of,ttfb:of,ttfbb:of,ttlb:of,cmsdd:of,cmsds:of,smrt:of,df:of,cs:of,ts:of,cid:xM,pr:xM,sf:xM,sid:xM,st:xM,v:xM,msd:xM,bs:UC,bsd:UC,cdn:UC,rtp:UC,bg:UC,pt:UC,ec:UC,e:UC},fPn={REQUEST:of};function xPn(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 gPn(s,t){const n={};if(!s)return n;const r=Object.keys(s),a=t?xPn(t):{};return r.reduce((i,l)=>{var o;const c=pPn[l]||a[l]||fPn.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},n)}function yPn(s){return["ot","sf","st","e","sta"].includes(s)}function vPn(s){return typeof s=="number"?ji(s):s!=null&&s!==""&&s!==!1}const cUt="event";function bPn(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 L2e=s=>Math.round(s),GBe=(s,t)=>Array.isArray(s)?s.map(n=>GBe(n,t)):s instanceof tS&&typeof s.value=="string"?new tS(GBe(s.value,t),s.params):(t.baseUrl&&(s=bPn(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),kre=s=>L2e(s/100)*100,_Pn=(s,t)=>{let n=s;return t.version>=2&&(s instanceof tS&&typeof s.value=="string"?n=new tS([s]):typeof s=="string"&&(n=[s])),GBe(n,t)},wPn={br:L2e,d:L2e,bl:kre,dl:kre,mtp:kre,nor:_Pn,rtp:kre,tb:L2e},dUt="request",uUt="response",DYe=["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"],jPn=["e"],NPn=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function jTe(s){return NPn.test(s)}function kPn(s){return DYe.includes(s)||jPn.includes(s)||jTe(s)}const hUt=["d","dl","nor","ot","rtp","su"];function SPn(s){return DYe.includes(s)||hUt.includes(s)||jTe(s)}const CPn=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function APn(s){return DYe.includes(s)||hUt.includes(s)||CPn.includes(s)||jTe(s)}const TPn=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function EPn(s){return TPn.includes(s)||jTe(s)}const MPn={[uUt]:APn,[cUt]:kPn,[dUt]:SPn};function mUt(s,t={}){const n={};if(s==null||typeof s!="object")return n;const r=t.version||s.v||1,a=t.reportingMode||dUt,i=r===1?EPn:MPn[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===uUt||a===cUt;c&&!l.includes("ts")&&l.push("ts"),r>1&&!l.includes("v")&&l.push("v");const d=ah({},wPn,t.formatters),u={version:r,reportingMode:a,baseUrl:t.baseUrl};return l.sort().forEach(h=>{let m=s[h];const p=d[h];if(typeof p=="function"&&(m=p(m,u)),h==="v"){if(r===1)return;m=r}h=="pr"&&m===1||(c&&h==="ts"&&!ji(m)&&(m=Date.now()),vPn(m)&&(yPn(h)&&typeof m=="string"&&(m=new rUt(m)),n[h]=m))}),n}function LPn(s,t={}){const n={};if(!s)return n;const r=mUt(s,t),a=gPn(r,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=lUt(o,{whitespace:!1});return c&&(i[l]=c),i},n)}function PPn(s,t,n){return ah(s,LPn(t,n))}const IPn="CMCD";function RPn(s,t={}){return s?lUt(mUt(s,t),{whitespace:!1}):""}function DPn(s,t={}){if(!s)return"";const n=RPn(s,t);return encodeURIComponent(n)}function OPn(s,t={}){if(!s)return"";const n=DPn(s,t);return`${IPn}=${n}`}const Q0t=/CMCD=[^&#]+/;function FPn(s,t,n){const r=OPn(t,n);if(!r)return s;if(Q0t.test(s))return s.replace(Q0t,r);const a=s.includes("?")?"&":"?";return`${s}${a}${r}`}class zPn{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:q1.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===q1.VIDEO||c===q1.AUDIO||c==q1.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(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Pt.MEDIA_DETACHED,this.onMediaDetached,this),t.on(Pt.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Pt.MEDIA_DETACHED,this.onMediaDetached,this),t.off(Pt.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:GLn.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,n={}){ah(n,this.createData());const r=n.ot===q1.INIT||n.ot===q1.VIDEO||n.ot===q1.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={}),PPn(t.headers,n,i)):t.url=FPn(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 q1.TIMED_TEXT;if(t.sn==="initSegment")return q1.INIT;if(n==="audio")return q1.AUDIO;if(n==="main")return this.hls.audioTracks.length?q1.VIDEO:q1.MUXED}getTopBandwidth(t){let n=0,r;const a=this.hls;if(t===q1.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===q1.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!n?NaN:Pl.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 BPn=3e5;class $Pn extends Jj{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(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Pt.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Pt.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)===H0.SendAlternateToPenaltyBox&&r.flags===x_.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===cr.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: ${Sh(i)} penalized: ${Sh(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]>BPn&&delete r[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,P$t(n),this.hls.trigger(Pt.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 jp(u.attrs);h["PATHWAY-ID"]=l;const m=h.AUDIO&&`${h.AUDIO}_clone_${l}`,p=h.SUBTITLES&&`${h.SUBTITLES}_clone_${l}`;m&&(r[h.AUDIO]=m,h.AUDIO=m),p&&(a[h.SUBTITLES]=p,h.SUBTITLES=p);const x=pUt(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),y=new jX({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:x,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let g=1;g{this.log(`Loaded steering manifest: "${a}"`);const x=u.data;if((x==null?void 0:x.VERSION)!==1){this.log(`Steering VERSION ${x.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=x.TTL;const{"RELOAD-URI":y,"PATHWAY-CLONES":g,"PATHWAY-PRIORITY":b}=x;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),g&&this.clonePathways(g);const v={steeringManifest:x,url:a.toString()};this.hls.trigger(Pt.STEERING_MANIFEST_LOADED,v),b&&this.updatePathwayPriority(b)},onError:(u,h,m,p)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let x=this.timeToLoad*1e3;if(u.code===429){const y=this.loader;if(typeof(y==null?void 0:y.getResponseHeader)=="function"){const g=y.getResponseHeader("Retry-After");g&&(x=parseFloat(g)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,x)},onTimeout:(u,h,m)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${a}`),this.loader.load(i,c,d)}scheduleRefresh(t,n=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const a=(r=this.hls)==null?void 0:r.media;if(a&&!a.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},n)}}function J0t(s,t,n,r){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=ah({},l);return o.details=void 0,o.attrs=new jp(o.attrs),o.url=o.attrs.URI=pUt(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 pUt(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 Jj{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=pW(this.config));const o=l.map(u8e).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=T2e(l);if(r!=="sinf"||o!==Mp.FAIRPLAY){this.log(`Ignoring "${n.type}" event with init data type: "${r}" for selected key-system ${o}`);return}let c;try{const p=Jx(new Uint8Array(a)),x=NYe(JSON.parse(p).sinf),y=l$t(x);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(y.subarray(8,24))}catch(p){this.warn(`${i} Failed to parse sinf: ${p}`);return}const d=G0(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let m=u[d];for(let p=0;pthis.generateRequestWithPreferredKeySession(x,r,a,"encrypted-event-key-match")),m.catch(b=>this.handleError(b));break}}m||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(l=>this.handleError(l))}},this.onWaitingForKey=n=>{this.log(`"${n.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Pt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Pt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Pt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(Pt.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Pt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Pt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(Pt.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===Mp.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 u_?o(h):o(new u_({type:co.KEY_SYSTEM_ERROR,details:cr.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 k$t===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=_Mn(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: ${Sh(i)}`),o=this.requestMediaKeySystemAccess(t,i);const c=l=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${t}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const u=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const h=c.mediaKeys=d.createMediaKeys().then(m=>(this.log(`Media-keys created for "${t}"`),c.hasMediaKeys=!0,u.then(p=>p?this.setMediaKeysServerCertificate(m,t,p):m)));return h.catch(m=>{this.error(`Failed to create media-keys for "${t}"}: ${m}`)}),h})}return o.then(()=>l.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:n,mediaKeys:r}){this.log(`Creating key-system session "${n}" keyId: ${G0(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=Sre(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 ${G0(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})=>u8e(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=u8e(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=pW(this.config),r=t.map(T2e).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 u_){const c=Uu({},o.data);this.getKeyStatus(n)==="internal-error"&&(c.decryptdata=n);const d=new u_(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 u_){n&&(t.data.frag=n);const r=t.data.decryptdata;this.error(`${t.message}${r?` (${G0(r.keyId||[])})`:""}`),this.hls.trigger(Pt.ERROR,t.data)}else this.error(t.message),this.hls.trigger(Pt.ERROR,{type:co.KEY_SYSTEM_ERROR,details:cr.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const n=Sre(t),r=this.keyIdToKeySessionPromise[n];if(!r){const a=T2e(t.keyFormat),i=a?[a]:pW(this.config);return this.attemptKeySystemAccess(i)}return r}getKeySystemSelectionPromise(t){if(t.length||(t=pW(this.config)),t.length===0)throw new u_({type:co.KEY_SYSTEM_ERROR,details:cr.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Sh({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,n){if(this.mediaResolved=void 0,this.mediaKeys===n)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const a=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(n):new Promise((i,l)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return l(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=n,this.media.setMediaKeys(n).then(i).catch(l)}}));return this.mediaKeys=n,this.setMediaKeysQueue.push(a),a.then(()=>{this.log(`Media-keys set for "${t}"`),r.push(a),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>r.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(t,n,r,a){var i;const l=(i=this.config.drmSystems)==null||(i=i[t.keySystem])==null?void 0:i.generateRequest;if(l)try{const x=l.call(this.hls,n,r,t);if(!x)throw new Error("Invalid response from configured generateRequest filter");n=x.initDataType,r=x.initData?x.initData:null,t.decryptdata.pssh=r?new Uint8Array(r):null}catch(x){if(this.warn(x.message),this.hls&&this.hls.config.debug)throw x}if(r===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=Sre(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 SYe,u=t._onmessage=x=>{const y=t.mediaKeysSession;if(!y){d.emit("error",new Error("invalid state"));return}const{messageType:g,message:b}=x;this.log(`"${g}" message event for session "${y.sessionId}" message size: ${b.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(t,b).catch(v=>{d.eventNames().length?d.emit("error",v):this.handleError(v)}):g==="license-release"?t.keySystem===Mp.FAIRPLAY&&this.updateKeySession(t,FBe("acknowledged")).then(()=>this.removeSession(t)).catch(v=>this.handleError(v)):this.warn(`unhandled media key message type "${g}"`)},h=(x,y)=>{y.keyStatus=x;let g;x.startsWith("usable")?d.emit("resolved"):x==="internal-error"||x==="output-restricted"||x==="output-downscaled"?g=eyt(x,y.decryptdata):x==="expired"?g=new Error(`key expired (keyId: ${o})`):x==="released"?g=new Error("key released"):x==="status-pending"||this.warn(`unhandled key status change "${x}" (keyId: ${o})`),g&&(d.eventNames().length?d.emit("error",g):this.handleError(g))},m=t._onkeystatuseschange=x=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const g=this.getKeyStatuses(t);if(!Object.keys(g).some(C=>g[C]!=="status-pending"))return;if(g[o]==="expired"){this.log(`Expired key ${Sh(g)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let v=g[o];if(v)h(v,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`),v="internal-error",h(v,t)},1e3)),this.log(`No status for keyId ${o} (${Sh(g)}).`)}};e1(t.mediaKeysSession,"message",u),e1(t.mediaKeysSession,"keystatuseschange",m);const p=new Promise((x,y)=>{d.on("error",y),d.on("resolved",x)});return t.mediaKeysSession.generateRequest(n,r).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(x=>{throw new u_({type:co.KEY_SYSTEM_ERROR,details:cr.KEY_SYSTEM_NO_SESSION,error:x,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${x}`)}).then(()=>p).catch(x=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw x}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const n={};return t.mediaKeysSession.keyStatuses.forEach((r,a)=>{if(typeof a=="string"&&typeof r=="object"){const o=a;a=r,r=o}const i="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(t.keySystem===Mp.PLAYREADY&&i.length===16){const o=G0(i);n[o]=r,j$t(i)}const l=G0(i);r==="internal-error"&&(this.bannedKeyIds[l]=r),this.log(`key status change "${r}" for keyStatuses keyId: ${l} key-session "${t.mediaKeysSession.sessionId}"`),n[l]=r}),n}fetchServerCertificate(t){const n=this.config,r=n.loader,a=new r(n),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((l,o)=>{const c={responseType:"arraybuffer",url:i},d=n.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(m,p,x,y)=>{l(m.data)},onError:(m,p,x,y)=>{o(new u_({type:co.KEY_SYSTEM_ERROR,details:cr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:x,response:Uu({url:c.url,data:void 0},m)},`"${t}" certificate request failed (${i}). Status: ${m.code} (${m.text})`))},onTimeout:(m,p,x)=>{o(new u_({type:co.KEY_SYSTEM_ERROR,details:cr.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:x,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(m,p,x)=>{o(new Error("aborted"))}};a.load(c,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(t,n,r){return new Promise((a,i)=>{t.setServerCertificate(r).then(l=>{this.log(`setServerCertificate ${l?"success":"not supported by CDM"} (${r.byteLength}) on "${n}"`),a(t)}).catch(l=>{i(new u_({type:co.KEY_SYSTEM_ERROR,details:cr.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 u_({type:co.KEY_SYSTEM_ERROR,details:cr.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 FBe(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 u_({type:co.KEY_SYSTEM_ERROR,details:cr.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==Mp.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,e1(r,"encrypted",this.onMediaEncrypted),e1(r,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=r.mediaKeys}onMediaDetached(){const t=this.media;t&&(db(t,"encrypted",this.onMediaEncrypted),db(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,bE.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(Pt.ERROR,{type:co.OTHER_ERROR,details:cr.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(Pt.ERROR,{type:co.OTHER_ERROR,details:cr.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: ${G0((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(jMn(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(Pt.ERROR,{type:co.OTHER_ERROR,details:cr.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(Pt.ERROR,{type:co.OTHER_ERROR,details:cr.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}Hz.CDMCleanupPromise=void 0;function Sre(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return G0(s.keyId)}function UPn(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 u_ 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 eyt(s,t){const n=s==="output-restricted",r=n?cr.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:cr.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new u_({type:co.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?"HDCP level output restricted":`key status changed to "${s}"`)}class qPn{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(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Pt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Pt.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(Pt.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(Pt.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 fUt(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 xUt(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){Ku.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){Ku.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}n==="disabled"&&(s.mode=n)}function j9(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 WBe(s,t,n,r){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=HPn(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 P2e(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=P2e(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Pt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Pt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Pt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Pt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Pt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Pt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Pt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Pt.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;P2e(r.textTracks).forEach(l=>{j9(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=C5(o,l);if(u>-1)i=l[u];else{const h=C5(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(Pt.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=C5(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(Pt.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:a,deliveryDirectives:n||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const n=P2e(t.textTracks),r=this.currentTrack;let a;if(r&&(a=n.filter(i=>qBe(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||!ji(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(Pt.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(Pt.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 WPn(){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 yY(s){let t=5381,n=s.length;for(;n;)t=t*33^s.charCodeAt(--n);return(t>>>0).toString()}const Gz=.025;let USe=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function KPn(s,t,n){return`${s.identifier}-${n+1}-${yY(t)}`}class YPn{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 b8e(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=b8e(n,t);return n-r<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,n=ji(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 b8e(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 ZPn(this)}}function b8e(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 XPn{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(Pt.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(n);this.interstitial=r,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(Pt.LEVEL_LOADED,l),i.once(Pt.AUDIO_TRACK_LOADED,l),i.once(Pt.SUBTITLE_TRACK_LOADED,l),i.on(Pt.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(Pt.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(Pt.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=gUt(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=Pl.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=Pl.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 tyt=.033;class QPn extends Jj{constructor(t,n){super("interstitials-sched",n),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,n){return this.events?this.events.reduce((r,a)=>t<=a.startOffset&&n>a.startOffset?(delete a.error,r+1):r,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,n){if(t.event)return this.findEventIndex(t.event.identifier);let r=-1;t.nextEvent?r=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(r=this.findEventIndex(t.previousEvent.identifier)+1);const a=this.items;if(a)for(a[r]||(n===void 0&&(n=t.start),r=this.findItemIndexAtTime(n));r>=0&&(i=a[r])!=null&&i.event;){var i;r--}return r}findItemIndexAtTime(t,n){const r=this.items;if(r)for(let a=0;ai.start&&t1)for(let i=0;io&&(n!o.includes(d.identifier)):[];l.length&&l.sort((d,u)=>{const h=d.cue.pre,m=d.cue.post,p=u.cue.pre,x=u.cue.post;if(h&&!p)return-1;if(p&&!h||m&&!x)return 1;if(x&&!m)return-1;if(!h&&!p&&!m&&!x){const y=d.startTime,g=u.startTime;if(y!==g)return y-g}return d.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=l,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(t,c)}updateSchedule(t,n=[],r=!1){const a=this.events||[];if(a.length||n.length||this.length<2){const i=this.items,l=this.parseSchedule(a,t);(r||n.length||(i==null?void 0:i.length)!==l.length||l.some((c,d)=>Math.abs(c.playout.start-i[d].playout.start)>.005||Math.abs(c.playout.end-i[d].playout.end)>.005))&&(this.items=l,this.onScheduleUpdate(n,i))}}parseDateRanges(t,n,r){const a=[],i=Object.keys(t);for(let l=0;l!c.error&&!(c.cue.once&&c.hasPlayed)),t.length){this.resolveOffsets(t,n);let c=0,d=0;if(t.forEach((u,h)=>{const m=u.cue.pre,p=u.cue.post,x=t[h-1]||null,y=u.appendInPlace,g=p?i:u.startOffset,b=u.duration,v=u.timelineOccupancy===USe.Range?b:0,k=u.resumptionOffset,C=(x==null?void 0:x.startTime)===g,T=g+u.cumulativeDuration;let M=y?T+b:g+k;if(m||!p&&g<=0){const L=d;d+=v,u.timelineStart=T;const I=l;l+=b,r.push({event:u,start:T,end:M,playout:{start:I,end:l},integrated:{start:L,end:d}})}else if(g<=i){if(!C){const O=g-c;if(O>tyt){const $=c,q=d;d+=O;const W=l;l+=O;const G={previousEvent:t[h-1]||null,nextEvent:u,start:$,end:$+O,playout:{start:W,end:l},integrated:{start:q,end:d}};r.push(G)}else O>0&&x&&(x.cumulativeDuration+=O,r[r.length-1].end=g)}p&&(M=T),u.timelineStart=T;const L=d;d+=v;const I=l;l+=b,r.push({event:u,start:T,end:M,playout:{start:I,end:l},integrated:{start:L,end:d}})}else return;const P=u.resumeTime;p||P>i?c=i:c=P}),c{const d=o.cue.pre,u=o.cue.post,h=d?0:u?a:o.startTime;this.updateAssetDurations(o),l===h?o.cumulativeDuration=i:(i=0,l=h),!u&&o.snapOptions.in&&(o.resumeAnchor=oO(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+1Gz?(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=oO(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 g=m.data,b=g==null?void 0:g.ASSETS;if(!Array.isArray(b)){const v=this.assignAssetListError(t,cr.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),x.url,p,y);this.hls.trigger(Pt.ERROR,v);return}t.assetListResponse=g,this.hls.trigger(Pt.ASSET_LIST_LOADED,{event:t,assetListResponse:g,networkDetails:y})},onError:(m,p,x,y)=>{const g=this.assignAssetListError(t,cr.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${m.code} ${m.text} (${p.url})`),p.url,y,x);this.hls.trigger(Pt.ERROR,g)},onTimeout:(m,p,x)=>{const y=this.assignAssetListError(t,cr.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${p.url})`),p.url,m,x);this.hls.trigger(Pt.ERROR,y)}};return o.load(c,u,h),this.hls.trigger(Pt.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,n,r,a,i,l){return t.error=r,{type:co.NETWORK_ERROR,details:n,fatal:!1,interstitial:t,url:a,error:r,networkDetails:l,stats:i}}}function syt(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function y7(s,t){return`[${s}] Advancing timeline position to ${t}`}class eIn extends Jj{constructor(t,n){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const a=r-this.timelinePos;if(Math.abs(a)<1/7056e5)return;const l=a<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=r,this.bufferedPos=r;const o=this.playingItem;if(!o){this.checkBuffer();return}if(l&&this.schedule.resetErrorsInRange(r,r-a)&&this.updateSchedule(!0),this.checkBuffer(),l&&r=o.end){var c;const p=this.findItemIndex(o);let x=this.schedule.findItemIndexAtTime(r);if(x===-1&&(x=p+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${r} (resolving from ${p} to ${x})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&x>p){const y=this.schedule.findJumpRestrictedIndex(p+1,x);if(y>p){this.setSchedulePosition(y);return}}this.setSchedulePosition(x);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const p=o.event.assetList[0];p&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,p))}return}const u=d.timelineStart,h=d.duration||0;if(l&&r=u+h){var m;(m=o.event)!=null&&m.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(r)),this.setScheduleToAssetAtTime(r,d)}},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const a=this.playingItem;if(!a||this.playingLastItem)return;if(r>=a.end){this.timelinePos=a.end;const o=this.findItemIndex(a);this.setSchedulePosition(o+1)}const i=this.playingAsset;if(!i)return;const l=i.timelineStart+(i.duration||0);r>=l&&this.setScheduleToAssetAtTime(r,i)},this.onScheduleUpdate=(r,a)=>{const i=this.schedule;if(!i)return;const l=this.playingItem,o=i.events||[],c=i.items||[],d=i.durations,u=r.map(y=>y.identifier),h=!!(o.length||u.length);(h||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(y=>k2(y))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let m=null,p=null;l&&(m=this.updateItem(l,this.timelinePos),this.itemsMatch(l,m)?this.playingItem=m:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const x=this.bufferingItem;if(x&&(p=this.updateItem(x,this.bufferedPos),this.itemsMatch(x,p)?this.bufferingItem=p:x.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(x.event,null))),r.forEach(y=>{y.assetList.forEach(g=>{this.clearAssetPlayer(g.identifier,null)})}),this.playerQueue.forEach(y=>{if(y.interstitial.appendInPlace){const g=y.assetItem.timelineStart,b=y.timelineOffset-g;if(b)try{y.timelineOffset=g}catch(v){Math.abs(b)>Gz&&this.warn(`${v} ("${y.assetId}" ${y.timelineOffset}->${g})`)}}}),h||a){if(this.hls.trigger(Pt.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:d,removedIds:u}),this.isInterstitial(l)&&u.includes(l.event.identifier)){this.warn(`Interstitial "${l.event.identifier}" removed while playing`),this.primaryFallback(l.event);return}l&&this.trimInPlace(m,l),x&&p!==m&&this.trimInPlace(p,x),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=n,this.assetListLoader=new JPn(t),this.schedule=new QPn(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Pt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Pt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(Pt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Pt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(Pt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(Pt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(Pt.BUFFER_APPENDED,this.onBufferAppended,this),t.on(Pt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Pt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(Pt.MEDIA_ENDED,this.onMediaEnded,this),t.on(Pt.ERROR,this.onError,this),t.on(Pt.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Pt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Pt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(Pt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Pt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(Pt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(Pt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(Pt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Pt.BUFFER_APPENDED,this.onBufferAppended,this),t.off(Pt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Pt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(Pt.MEDIA_ENDED,this.onMediaEnded,this),t.off(Pt.ERROR,this.onError,this),t.off(Pt.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){db(t,"play",this.onPlay),db(t,"pause",this.onPause),db(t,"seeking",this.onSeeking),db(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,n){const r=this.media=n.media;e1(r,"seeking",this.onSeeking),e1(r,"timeupdate",this.onTimeupdate),e1(r,"play",this.onPlay),e1(r,"pause",this.onPause)}onMediaAttached(t,n){const r=this.effectivePlayingItem,a=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!a){this.clearScheduleState();const i=this.findItemIndex(r);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,n){const r=!!n.transferMedia,a=this.media;if(this.media=null,!r&&(a&&this.removeMediaListeners(a),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,n=()=>t.bufferingItem||t.waitingItem,r=h=>h&&t.getAssetPlayer(h.identifier),a=(h,m,p,x,y)=>{if(h){let g=h[m].start;const b=h.event;if(b){if(m==="playout"||b.timelineOccupancy!==USe.Point){const v=r(p);(v==null?void 0:v.interstitial)===b&&(g+=v.assetItem.startOffset+v[y])}}else{const v=x==="bufferedPos"?l():t[x];g+=v-h.start}return g}return 0},i=(h,m)=>{var p;if(h!==0&&m!=="primary"&&(p=t.schedule)!=null&&p.length){var x;const y=t.schedule.findItemIndexAtTime(h),g=(x=t.schedule.items)==null?void 0:x[y];if(g){const b=g[m].start-g.start;return h+b}}return h},l=()=>{const h=t.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var m,p;return(m=t.primaryDetails)!=null&&m.live?t.primaryDetails.edge:((p=t.schedule)==null?void 0:p.durations[h])||0},c=(h,m)=>{var p,x;const y=t.effectivePlayingItem;if(y!=null&&(p=y.event)!=null&&p.restrictions.skip||!t.schedule)return;t.log(`seek to ${h} "${m}"`);const g=t.effectivePlayingItem,b=t.schedule.findItemIndexAtTime(h,m),v=(x=t.schedule.items)==null?void 0:x[b],k=t.getBufferingPlayer(),C=k==null?void 0:k.interstitial,T=C==null?void 0:C.appendInPlace,M=g&&t.itemsMatch(g,v);if(g&&(T||M)){const P=r(t.playingAsset),L=(P==null?void 0:P.media)||t.primaryMedia;if(L){const I=m==="primary"?L.currentTime:a(g,m,t.playingAsset,"timelinePos","currentTime"),O=h-I,$=(T?I:L.currentTime)+O;if($>=0&&(!P||T||$<=P.duration)){L.currentTime=$;return}}}if(v){let P=h;if(m!=="primary"){const I=v[m].start,O=h-I;P=v.start+O}const L=!t.isInterstitial(v);if((!t.isInterstitial(g)||g.event.appendInPlace)&&(L||v.event.appendInPlace)){const I=t.media||(T?k==null?void 0:k.media:null);I&&(I.currentTime=P)}else if(g){const I=t.findItemIndex(g);if(b>I){const $=t.schedule.findJumpRestrictedIndex(I+1,b);if($>I){t.setSchedulePosition($);return}}let O=0;if(L)t.timelinePos=P,t.checkBuffer();else{const $=v.event.assetList,q=h-(v[m]||v).start;for(let W=$.length;W--;){const G=$[W];if(G.duration&&q>=G.startOffset&&q{const h=t.effectivePlayingItem;if(t.isInterstitial(h))return h;const m=n();return t.isInterstitial(m)?m:null},u={get bufferedEnd(){const h=n(),m=t.bufferingItem;if(m&&m===h){var p;return a(m,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-m.playout.start||((p=t.bufferingAsset)==null?void 0:p.startOffset)||0}return 0},get currentTime(){const h=d(),m=t.effectivePlayingItem;return m&&m===h?a(m,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-m.playout.start:0},set currentTime(h){const m=d(),p=t.effectivePlayingItem;p&&p===m&&c(h+p.playout.start,"playout")},get duration(){const h=d();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const m=(h=d())==null?void 0:h.event.assetList;return m?m.map(p=>t.getAssetPlayer(p.identifier)):[]},get playingIndex(){var h;const m=(h=d())==null?void 0:h.event;return m&&t.effectivePlayingAsset?m.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var h;return((h=t.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=t.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return d()?u:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return n()},get bufferingIndex(){const h=n();return t.findItemIndex(h)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const h=t.effectivePlayingItem;return t.findItemIndex(h)},primary:{get bufferedEnd(){return l()},get currentTime(){const h=t.timelinePos;return h>0?h:0},set currentTime(h){c(h,"primary")},get duration(){return o("primary")},get seekableStart(){var h;return((h=t.primaryDetails)==null?void 0:h.fragmentStart)||0}},integrated:{get bufferedEnd(){return a(n(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return a(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){c(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){var h;return i(((h=t.primaryDetails)==null?void 0:h.fragmentStart)||0,"integrated")}},skip:()=>{const h=t.effectivePlayingItem,m=h==null?void 0:h.event;if(m&&!m.restrictions.skip){const p=t.findItemIndex(h);if(m.appendInPlace){const x=h.playout.start+h.event.duration;c(x+.001,"playout")}else t.advanceAfterAssetEnded(m,p,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const n=this.playingItem,r=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!n||!r?!1:this.findItemIndex(n)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,n;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let a=this.media;!a&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const i=(n=a)==null?void 0:n.currentTime;if(!(i===void 0||!ji(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} ${Sh(i)}`),this.detachedData=i}else n&&a&&(this.shouldPlay||(this.shouldPlay=!a.paused))}transferMediaTo(t,n){var r,a;if(t.media===n)return;let i=null;const l=this.hls,o=t!==l,c=o&&t.interstitial.appendInPlace,d=(r=this.detachedData)==null?void 0:r.mediaSource;let u;if(l.media)c&&(i=l.transferMedia(),this.detachedData=i),u="Primary";else if(d){const x=this.getBufferingPlayer();x?(i=x.transferMedia(),u=`${x}`):u="detached MediaSource"}else u="detached media";if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${Sh(i)}`);else if(!this.detachedData||l.media===n){const x=this.playerQueue;x.length>1&&x.forEach(y=>{if(o&&y.interstitial.appendInPlace!==c){const g=y.interstitial;this.clearInterstitial(y.interstitial,null),g.appendInPlace=!1,g.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${g}`)}}),this.hls.detachMedia(),this.detachedData={media:n}}}const h=i&&"mediaSource"in i&&((a=i.mediaSource)==null?void 0:a.readyState)!=="closed",m=h&&i?i:n;this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${u} (media.currentTime: ${n.currentTime})`);const p=this.schedule;if(m===i&&p){const x=o&&t.assetId===p.assetIdAtEnd;m.overrides={duration:p.duration,endOfStream:!o||x,cueRemoval:!o}}t.attachMedia(m)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,n=t==null?void 0:t.events;if(!n||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const r=this.timelinePos,a=this.effectivePlayingItem;if(r===-1){const i=this.hls.startPosition;if(this.timelinePos=i,n.length===0)this.setSchedulePosition(0);else if(n[0].cue.pre){this.log(y7("checkStart (preroll)",i));const l=t.findEventIndex(n[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(y7("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(y7("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=_8e(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=_8e(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&&k2(i)}) pos: ${this.timelinePos}`);const l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){const u=l.event,h=this.playingAsset,m=h==null?void 0:h.identifier,p=m?this.getAssetPlayer(m):null;if(p&&m&&(!this.eventItemsMatch(l,i)||n!==void 0&&m!==u.assetList[n].identifier)){var c;const x=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${x+1}/${u.assetList.length} ${G7(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(Pt.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:x,event:u,schedule:a.slice(0),scheduleIndex:t,player:p}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),x);return}this.retreiveMediaSource(m,i),p.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&p.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${k2(l)}`),u.hasPlayed=!0,this.hls.trigger(Pt.INTERSTITIAL_ENDED,{event:u,schedule:a.slice(0),scheduleIndex:t}),u.cue.once)){var d;this.updateSchedule();const x=(d=this.schedule)==null?void 0:d.items;if(i&&x){const y=this.findItemIndex(i);this.advanceSchedule(y,x,n,l,o)}return}}this.advanceSchedule(t,a,n,l,o)}advanceSchedule(t,n,r,a,i){const l=this.schedule;if(!l)return;const o=n[t]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{const h=u.interstitial,m=l.findEventIndex(h.identifier);(mt+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(r===void 0){r=l.findAssetIndex(u,this.timelinePos);const x=_8e(u,r-1);if(u.isAssetPastPlayoutLimit(x)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,t,r);return}r=x}const h=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let m=this.preloadAssets(u,r);if(this.eventItemsMatch(o,h||a)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${k2(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(Pt.INTERSTITIAL_STARTED,{event:u,schedule:n.slice(0),scheduleIndex:t})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const p=u.assetList[r];if(!p){this.advanceAfterAssetEnded(u,t,r||0);return}if(m||(m=this.getAssetPlayer(p.identifier)),m===null||m.destroyed){const x=u.assetList.length;this.warn(`asset ${r+1}/${x} player destroyed ${u}`),m=this.createAssetPlayer(u,p,r),m.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(p))return;this.startAssetPlayer(m,r,n,t,c),this.shouldPlay&&syt(m.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&syt(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 ${k2(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,n),this.log(y7("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 ${k2(t)}`),this.hls.trigger(Pt.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:Pl.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(y7("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(Pt.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Pt.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=Uu(Uu({},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=Uu(Uu({},this.altSelection),{},{audio:r});return}const i=Uu(Uu({},a),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(t,n){const r=this.hls.subtitleTracks[n.id],a=this.mediaSelection;if(!a){this.altSelection=Uu(Uu({},this.altSelection),{},{subtitles:r});return}const i=Uu(Uu({},a),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(t,n){const r=u0t(n);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(n)||a.setAudioOption(r)))}onSubtitleTrackSwitch(t,n){const r=u0t(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=Pl.bufferInfo(this.primaryMedia,r,0);(a.end>r||(a.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${k2(t)} (was ${k2(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=Pl.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=a.len<1),this.updateBufferedPos(a.end,r,t)}updateBufferedPos(t,n,r){const a=this.schedule,i=this.bufferingItem;if(this.bufferedPos>t||!a)return;if(n.length===1&&this.itemsMatch(n[0],i)){this.bufferedPos=t;return}const l=this.playingItem,o=this.findItemIndex(l);let c=a.findItemIndexAtTime(t);if(this.bufferedPos=i.end||(d=m.event)!=null&&d.appendInPlace&&t+.01>=m.start)&&(c=h),this.isInterstitial(i)){const p=i.event;if(h-o>1&&p.appendInPlace===!1||p.assetList.length===0&&p.assetListLoader)return}if(this.bufferedPos=t,c>u&&c>o)this.bufferedToItem(m);else{const p=this.primaryDetails;this.primaryLive&&p&&t>p.edge-p.targetduration&&m.start{const i=this.getAssetPlayer(a.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(n))})}setBufferingItem(t){const n=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(t,n)&&r){const{items:a,events:i}=r;if(!a||!i)return n;const l=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const c=o?o.remaining:n?n.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${k2(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(Pt.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(Pt.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&&C{if(C.live){var T;const L=new Error(`Interstitials MUST be VOD assets ${t}`),I={fatal:!0,type:co.OTHER_ERROR,details:cr.INTERSTITIAL_ASSET_ITEM_ERROR,error:L},O=((T=this.schedule)==null?void 0:T.findEventIndex(t.identifier))||-1;this.handleAssetItemError(I,t,O,r,L.message);return}const M=C.edge-C.fragmentStart,P=n.duration;(y||P===null||M>P)&&(y=!1,this.log(`Interstitial asset "${h}" duration change ${P} > ${M}`),n.duration=M,this.updateSchedule())};x.on(Pt.LEVEL_UPDATED,(C,{details:T})=>g(T)),x.on(Pt.LEVEL_PTS_UPDATED,(C,{details:T})=>g(T)),x.on(Pt.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const b=(C,T)=>{const M=this.getAssetPlayer(h);if(M&&T.tracks){M.off(Pt.BUFFER_CODECS,b),M.tracks=T.tracks;const P=this.primaryMedia;this.bufferingAsset===M.assetItem&&P&&!M.media&&this.bufferAssetPlayer(M,P)}};x.on(Pt.BUFFER_CODECS,b);const v=()=>{var C;const T=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${T}`),!T||!this.schedule)return;const M=this.schedule.findEventIndex(t.identifier),P=(C=this.schedule.items)==null?void 0:C[M];this.isInterstitial(P)&&this.advanceAssetBuffering(P,n)};x.on(Pt.BUFFERED_TO_END,v);const k=C=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const M=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,M,C)};return x.once(Pt.MEDIA_ENDED,k(r)),x.once(Pt.PLAYOUT_LIMIT_REACHED,k(1/0)),x.on(Pt.ERROR,(C,T)=>{if(!this.schedule)return;const M=this.getAssetPlayer(h);if(T.details===cr.BUFFER_STALLED_ERROR){if(M!=null&&M.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}`)}),x.on(Pt.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const T=new Error(`Asset player destroyed unexpectedly ${h}`),M={fatal:!0,type:co.OTHER_ERROR,details:cr.INTERSTITIAL_ASSET_ITEM_ERROR,error:T};this.handleAssetItemError(M,t,this.schedule.findEventIndex(t.identifier),r,T.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${G7(n)}`),this.hls.trigger(Pt.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:n,assetListIndex:r,event:t,player:x}),x}clearInterstitial(t,n){this.clearAssetPlayers(t,n),t.reset()}clearAssetPlayers(t,n){t.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,n)})}resetAssetPlayer(t){const n=this.getAssetPlayerQueueIndex(t);if(n!==-1){this.log(`reset asset player "${t}" after error`);const r=this.playerQueue[n];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(t,n){const r=this.getAssetPlayerQueueIndex(t);if(r!==-1){const a=this.playerQueue[r];this.log(`clear ${a} toSegment: ${n&&k2(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(Pt.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&&!JBt(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)}')`),p={fatal:!0,type:co.OTHER_ERROR,details:cr.INTERSTITIAL_ASSET_ITEM_ERROR,error:m},x=i.findAssetIndex(l);this.handleAssetItemError(p,i,o,x,m.message);return}}this.transferMediaTo(t,n)}handleInPlaceStall(t){const n=this.schedule,r=this.primaryMedia;if(!n||!r)return;const a=r.currentTime,i=n.findAssetIndex(t,a),l=t.assetList[i];if(l){const o=this.getAssetPlayer(l.identifier);if(o){const c=o.currentTime||a-l.timelineStart,d=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${o} ${t} (media.currentTime: ${a})`),c&&(d/r.playbackRate<.5||o.bufferedInPlaceToEnd(r))&&o.hls){const u=n.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,u,i)}}}}advanceInPlace(t){const n=this.primaryMedia;n&&n.currentTime!y.error))n.error=x;else for(let y=a;y{const b=parseFloat(y.DURATION);this.createAsset(i,g,u,c+u,b,y.URI),u+=b}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${i}`);const h=this.waitingItem,m=(h==null?void 0:h.event.identifier)===l;this.updateSchedule();const p=(a=this.bufferingItem)==null?void 0:a.event;if(m){var x;const y=this.schedule.findEventIndex(l),g=(x=this.schedule.items)==null?void 0:x[y];if(g){if(!this.playingItem&&this.timelinePos>g.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(g)}this.setSchedulePosition(y)}else if((p==null?void 0:p.identifier)===l){const y=i.assetList[0];if(y){const g=this.getAssetPlayer(y.identifier);if(p.appendInPlace){const b=this.primaryMedia;g&&b&&this.bufferAssetPlayer(g,b)}else g&&g.loadSource()}}}onError(t,n){if(this.schedule)switch(n.details){case cr.ASSET_LIST_PARSING_ERROR:case cr.ASSET_LIST_LOAD_ERROR:case cr.ASSET_LIST_LOAD_TIMEOUT:{const r=n.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case cr.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 nyt=500;class tIn extends kYe{constructor(t,n,r){super(t,n,r,"subtitle-stream-controller",zi.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(Pt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Pt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Pt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Pt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Pt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(Pt.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Pt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Pt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Pt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Pt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Pt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(Pt.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,n){this.stopLoad(),this.state=Yr.IDLE,this.setInterval(nyt),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)||(Yf(r)&&(this.fragPrevious=r),this.state=Yr.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 jX(r));return}this.tracksBuffered=[],this.levels=n.map(r=>{const a=new jX(r);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,zi.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!==Yr.STOPPED&&this.setInterval(nyt)}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?(BSe(l,h),d=l.fragmentStart):m&&(d=m.start,BBe(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,BBe(l,d))}h&&!this.startFragRequested&&this.setStartPosition(h,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(Pt.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:n.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===Yr.IDLE&&(oO(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&&Vz(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,jYe(a.method)).catch(o=>{throw i.trigger(Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:n}),o}).then(o=>{const c=performance.now();i.trigger(Pt.FRAG_DECRYPTED,{frag:n,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=Yr.IDLE})}}doTick(){if(!this.media){this.state=Yr.IDLE;return}if(this.state===Yr.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=Pl.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,a.maxBufferHole),{end:o,len:c}=l,d=r.details,u=this.hls.maxBufferLength+d.levelTargetDuration;if(c>u)return;const h=d.fragments,m=h.length,p=d.edge;let x=null;const y=this.fragPrevious;if(op-v?0:v;x=oO(y,h,Math.max(h[0].start,o),k),!x&&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 nIn={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},yUt=s=>String.fromCharCode(nIn[s]||s),T2=15,a4=100,rIn={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},aIn={17:2,18:4,21:6,22:8,23:10,19:13,20:15},iIn={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},oIn={25:2,26:4,29:6,30:8,31:10,27:13,28:15},lIn=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class cIn{constructor(){this.time=null,this.verboseLevel=0}log(t,n){if(this.verboseLevel>=t){const r=typeof n=="function"?n():n;Ku.log(`${this.time} [${t}] ${r}`)}}}const gM=function(t){const n=[];for(let r=0;ra4&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=a4)}moveCursor(t){const n=this.pos+t;if(t>1)for(let r=this.pos+1;r=144&&this.backSpace();const n=yUt(t);if(this.pos>=a4){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 = "+Sh(t));let n=t.row-1;if(this.nrRollUpRows&&n"bkgData = "+Sh(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 ryt{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 w8e(r),this.nonDisplayedMemory=new w8e(r),this.lastOutputScreen=new w8e(r),this.currRollUpRow=this.displayedMemory.rows[T2-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[T2-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: "+Sh(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 ayt{constructor(t,n,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=mIn(),this.logger=void 0;const a=this.logger=new cIn;this.channels=[null,new ryt(t,n,a),new ryt(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"["+gM([n[r],n[r+1]])+"] -> ("+gM([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(hIn(a,i,c)){Cre(null,null,c),this.logger.log(3,()=>"Repeated command ("+gM([a,i])+") is dropped");continue}Cre(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 Cre(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 "+gM([a,i])+" orig: "+gM([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 ("+gM([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?rIn[t]:iIn[t]:r=l===1?aIn[t]:oIn[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 '"+yUt(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 = "+gM(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=lIn[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.");M=O,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",i({},h,{get:function(){return P},set:function(O){const $=a(O);if(!$)throw new SyntaxError("An invalid or illegal string was specified.");P=$,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",i({},h,{get:function(){return L},set:function(O){if(O<0||O>100)throw new Error("Size must be between 0 and 100.");L=O,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",i({},h,{get:function(){return I},set:function(O){const $=a(O);if(!$)throw new SyntaxError("An invalid or illegal string was specified.");I=$,this.hasBeenReset=!0}})),u.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class pIn{decode(t,n){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function bUt(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 fIn{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 _Ut(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 KBe=new OYe(0,0,""),Are=KBe.align==="middle"?"middle":"center";function xIn(s,t,n){const r=s;function a(){const o=bUt(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 fIn;_Ut(o,function(m,p){let x;switch(m){case"region":for(let y=n.length-1;y>=0;y--)if(n[y].id===p){d.set(m,n[y].region);break}break;case"vertical":d.alt(m,p,["rl","lr"]);break;case"line":x=p.split(","),d.integer(m,x[0]),d.percent(m,x[0])&&d.set("snapToLines",!1),d.alt(m,x[0],["auto"]),x.length===2&&d.alt("lineAlign",x[1],["start",Are,"end"]);break;case"position":x=p.split(","),d.percent(m,x[0]),x.length===2&&d.alt("positionAlign",x[1],["start",Are,"end","line-left","line-right","auto"]);break;case"size":d.percent(m,p);break;case"align":d.alt(m,p,["start",Are,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&KBe.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",Are);let h=d.get("position","auto");h==="auto"&&KBe.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 wUt(s){return s.replace(//gi,` `)}class gIn{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new pIn,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=wUt(i);l")===-1){n.cue.id=i;continue}case"CUE":if(!n.cue){n.state="BADCUE";continue}try{xIn(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 yIn=/\r\n|\n\r|\n|\r/g,j8e=function(t,n,r=0){return t.slice(r,r+n.length)===n},vIn=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(!ji(n)||!ji(r)||!ji(a)||!ji(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return n+=1e3*r,n+=60*1e3*a,n+=60*60*1e3*i,n};function FYe(s,t,n){return yY(s.toString())+yY(t.toString())+yY(n)}const bIn=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 _In(s,t,n,r,a,i,l){const o=new gIn,c=J_(new Uint8Array(s)).trim().replace(yIn,` `).split(` `),d=[],u=t?CLn(t.baseTime,t.timescale):0;let h="00:00.000",m=0,p=0,x,y=!0;o.oncue=function(g){const b=n[r];let v=n.ccOffset;const k=(m-u)/9e4;if(b!=null&&b.new&&(p!==void 0?v=n.ccOffset=b.start:bIn(n,r,k)),k){if(!t){x=new Error("Missing initPTS for VTT MPEGTS");return}v=k-n.presentationOffset}const C=g.endTime-g.startTime,T=C_((g.startTime+v-p)*9e4,a*9e4)/9e4;g.startTime=Math.max(T,0),g.endTime=Math.max(T+C,0);const M=g.text.trim();g.text=decodeURIComponent(encodeURIComponent(M)),g.id||(g.id=FYe(g.startTime,g.endTime,M)),g.endTime>0&&d.push(g)},o.onparsingerror=function(g){x=g},o.onflush=function(){if(x){l(x);return}i(d)},c.forEach(g=>{if(y)if(j8e(g,"X-TIMESTAMP-MAP=")){y=!1,g.slice(16).split(",").forEach(b=>{j8e(b,"LOCAL:")?h=b.slice(6):j8e(b,"MPEGTS:")&&(m=parseInt(b.slice(7)))});try{p=vIn(h)/1e3}catch(b){x=b}return}else g===""&&(y=!1);o.parse(g+` `)}),o.flush()}const N8e="stpp.ttml.im1t",jUt=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,NUt=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,wIn={left:"start",center:"center",right:"end",start:"start",end:"end"};function iyt(s,t,n,r){const a=kc(new Uint8Array(s),["mdat"]);if(a.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>J_(o)),l=SLn(t.baseTime,1,t.timescale);try{i.forEach(o=>n(jIn(o,l)))}catch(o){r(o)}}function jIn(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=oyt(k8e(a,"styling","style")),d=oyt(k8e(a,"layout","region")),u=k8e(a,"body","[begin]");return[].map.call(u,h=>{const m=kUt(h,o);if(!m||!h.hasAttribute("begin"))return null;const p=C8e(h.getAttribute("begin"),l),x=C8e(h.getAttribute("dur"),l);let y=C8e(h.getAttribute("end"),l);if(p===null)throw lyt(h);if(y===null){if(x===null)throw lyt(h);y=p+x}const g=new OYe(p-t,y-t,m);g.id=FYe(g.startTime,g.endTime,g.text);const b=d[h.getAttribute("region")],v=c[h.getAttribute("style")],k=NIn(b,v,c),{textAlign:C}=k;if(C){const T=wIn[C];T&&(g.lineAlign=T),g.align=C}return ah(g,k),g}).filter(h=>h!==null)}function k8e(s,t,n){const r=s.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function oyt(s){return s.reduce((t,n)=>{const r=n.getAttribute("xml:id");return r&&(t[r]=n),t},{})}function kUt(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?kUt(r,t):t?n+r.textContent.trim().replace(/\s+/g," "):n+r.textContent},"")}function NIn(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=S8e(t,r,c)||S8e(s,r,c)||S8e(a,r,c);return d&&(o[c]=d),o},{})}function S8e(s,t,n){return s&&s.hasAttributeNS(t,n)?s.getAttributeNS(t,n):null}function lyt(s){return new Error(`Could not parse ttml timestamp ${s}`)}function C8e(s,t){if(!s)return null;let n=bUt(s);return n===null&&(jUt.test(s)?n=kIn(s,t):NUt.test(s)&&(n=SIn(s,t))),n}function kIn(s,t){const n=jUt.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 SIn(s,t){const n=NUt.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 Tre{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 CIn{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=dyt(),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(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Pt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Pt.FRAG_LOADING,this.onFragLoading,this),t.on(Pt.FRAG_LOADED,this.onFragLoaded,this),t.on(Pt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(Pt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(Pt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Pt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(Pt.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Pt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Pt.FRAG_LOADING,this.onFragLoading,this),t.off(Pt.FRAG_LOADED,this.onFragLoaded,this),t.off(Pt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(Pt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(Pt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Pt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(Pt.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Tre(this,"textTrack1"),n=new Tre(this,"textTrack2"),r=new Tre(this,"textTrack3"),a=new Tre(this,"textTrack4");this.cea608Parser1=new ayt(1,t,n),this.cea608Parser2=new ayt(3,r,a)}addCues(t,n,r,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=AIn(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(Pt.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===zi.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(Pt.FRAG_LOADED,c):this.hls.trigger(Pt.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{j9(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=dyt(),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===N8e);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(sUt(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const l=this.media,o=l?P2e(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(Pt.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===zi.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===zi.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===N8e?this._parseIMSC1(r,a):this._parseVTTs(n)}}else this.hls.trigger(Pt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,n){const r=this.hls;iyt(n,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(Pt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{r.logger.log(`Failed to parse IMSC1: ${a}`),r.trigger(Pt.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?Vj(r.initSegment.data,new Uint8Array(a)).buffer:a;_In(d,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),c.trigger(Pt.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(Pt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(t,n){const r=this.tracks[t.level];r.textCodec||iyt(n,this.initPTS[t.cc],()=>{r.textCodec=N8e,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=>xUt(a,i))}else{const a=this.tracks[n];if(!a)return;const i=a.default?"default":"subtitles"+n;r.trigger(Pt.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,n){const{frag:r}=n;r.type===zi.SUBTITLE&&this.onFragLoaded(Pt.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===zi.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let i=0;iWBe(o[c],n,r))}if(this.config.renderTextTracksNatively&&n===0&&a!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>WBe(o[c],n,a))}}}extractCea608Data(t){const n=[[],[]],r=t[0]&31;let a=2;for(let i=0;i=16?c--:c++;const p=wUt(d.trim()),x=FYe(t,n,p);s!=null&&(h=s.cues)!=null&&h.getCueById(x)||(l=new u(t,n,p),l.id=x,l.line=m+1,l.align="left",l.position=10+Math.min(80,Math.floor(c*8/32)*10),a.push(l))}return s&&a.length&&(a.sort((m,p)=>m.line==="auto"||p.line==="auto"?0:m.line>8&&p.line>8?p.line-m.line:m.line-p.line),a.forEach(m=>xUt(s,m))),a}};function MIn(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const LIn=/(\d+)-(\d+)\/(\d+)/;class uyt{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||DIn,this.controller=new self.AbortController,this.stats=new xYe}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=PIn(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&&ji(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},n.timeout),(SX(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var m;this.response=this.loader=h;const p=Math.max(self.performance.now(),a.loading.start);if(self.clearTimeout(this.requestTimeout),n.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},d-(p-a.loading.start)),!h.ok){const{status:y,statusText:g}=h;throw new OIn(g||"fetch, bad network response",y,h)}a.loading.first=p,a.total=RIn(h.headers)||a.total;const x=(m=this.callbacks)==null?void 0:m.onProgress;return x&&ji(n.highWaterMark)?this.loadProgressively(h,a,t,n.highWaterMark,x):l?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var m,p;const x=this.response;if(!x)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);const y=h[o];y&&(a.loaded=a.total=y);const g={url:x.url,data:h,code:x.status},b=(m=this.callbacks)==null?void 0:m.onProgress;b&&!ji(n.highWaterMark)&&b(a,t,h,x),(p=this.callbacks)==null||p.onSuccess(g,a,t,x)}).catch(h=>{var m;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const p=h&&h.code||0,x=h?h.message:null;(m=this.callbacks)==null||m.onError({code:p,text:x},t,h?h.details:null,a)})}getCacheAge(){let t=null;if(this.response){const n=this.response.headers.get("age");t=n?parseFloat(n):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,n,r,a=0,i){const l=new D$t,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 PIn(s,t){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(ah({},s.headers))};return s.rangeEnd&&n.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),n}function IIn(s){const t=LIn.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function RIn(s){const t=s.get("Content-Range");if(t){const r=IIn(t);if(ji(r))return r}const n=s.get("Content-Length");if(n)return parseInt(n)}function DIn(s,t){return new self.Request(s.url,t)}class OIn extends Error{constructor(t,n,r){super(t),this.code=void 0,this.details=void 0,this.code=n,this.details=r}}const FIn=/^age:\s*[\d.]+\s*$/im;class CUt{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 xYe,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&&ji(i)?i:l,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()}readystatechange(){const{context:t,loader:n,stats:r}=this;if(!t||!n)return;const a=n.readyState,i=this.config;if(!r.aborted&&a>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),a===4)){self.clearTimeout(this.requestTimeout),n.onreadystatechange=null,n.onprogress=null;const d=n.status,u=n.responseType==="text"?n.responseText:null;if(d>=200&&d<300){const x=u??n.response;if(x!=null){var l,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const y=n.responseType==="arraybuffer"?x.byteLength:x.length;r.loaded=r.total=y,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const g=(l=this.callbacks)==null?void 0:l.onProgress;g&&g(r,t,x,n);const b={url:n.responseURL,data:x,code:d};(o=this.callbacks)==null||o.onSuccess(b,r,t,n);return}}const h=i.loadPolicy.errorRetry,m=r.retry,p={url:t.url,data:void 0,code:d};if(OSe(h,m,!1,p))this.retry(h);else{var c;Ku.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(OSe(t,n,!0))this.retry(t);else{var r;Ku.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=bYe(t,r.retry),r.retry++,Ku.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&&FIn.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 zIn={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},BIn=Uu(Uu({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:CUt,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Q6n,bufferController:ULn,capLevelController:IYe,errorController:nMn,fpsController:qPn,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:k$t,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:zIn},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},$In()),{},{subtitleStreamController:tIn,subtitleTrackController:GPn,timelineController:CIn,audioStreamController:FLn,audioTrackController:zLn,emeController:Hz,cmcdController:zPn,contentSteeringController:$Pn,interstitialsController:eIn});function $In(){return{cueHandler:EIn,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 UIn(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=YBe(s),a=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return a.forEach(l=>{const o=`${l==="level"?"playlist":l}LoadPolicy`,c=t[o]===void 0,d=[];i.forEach(u=>{const h=`${l}Loading${u}`,m=t[h];if(m!==void 0&&c){d.push(h);const p=r[o].default;switch(t[o]={default:p},u){case"TimeOut":p.maxLoadTimeMs=m,p.maxTimeToFirstByteMs=m;break;case"MaxRetry":p.errorRetry.maxNumRetry=m,p.timeoutRetry.maxNumRetry=m;break;case"RetryDelay":p.errorRetry.retryDelayMs=m,p.timeoutRetry.retryDelayMs=m;break;case"MaxRetryTimeout":p.errorRetry.maxRetryDelayMs=m,p.timeoutRetry.maxRetryDelayMs=m;break}}}),d.length&&n.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${Sh(t[o])}`)}),Uu(Uu({},r),t)}function YBe(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(YBe):Object.keys(s).reduce((t,n)=>(t[n]=YBe(s[n]),t),{}):s}function qIn(s,t){const n=s.loader;n!==uyt&&n!==CUt?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):MIn()&&(s.loader=uyt,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const I2e=2,VIn=.1,HIn=.05,GIn=100;class WIn extends b$t{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(Pt.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=n,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Pt.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Pt.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(GIn),this.mediaSource=n.mediaSource;const r=this.media=n.media;e1(r,"playing",this.onMediaPlaying),e1(r,"waiting",this.onMediaWaiting),e1(r,"ended",this.onMediaEnded)}onMediaDetaching(t,n){this.clearInterval();const{media:r}=this;r&&(db(r,"playing",this.onMediaPlaying),db(r,"waiting",this.onMediaWaiting),db(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(Pt.MEDIA_ENDED,{stalled:!1}));return}if(!Pl.getBuffered(l).length){this.nudgeRetry=0;return}const h=Pl.bufferInfo(l,t,0),m=h.nextStart||0,p=this.fragmentTracker;if(o&&p&&this.hls){const M=hyt(this.hls.inFlightFragments,t),P=h.len>I2e,L=!m||M||m-t>I2e&&!p.getPartialFragment(t);if(P||L)return;this.moved=!1}const x=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&p){if(!(h.len>0)&&!m)return;const P=Math.max(m,h.start||0)-t,I=!!(x!=null&&x.live)?x.targetduration*2:I2e,O=Ere(t,p);if(P>0&&(P<=I||O)){l.paused||this._trySkipBufferHole(O);return}}const y=i.detectStallWithCurrentTimeMs,g=self.performance.now(),b=this.waiting;let v=this.stalled;if(v===null)if(b>0&&g-b=y||b)&&this.hls){var C;if(((C=this.mediaSource)==null?void 0:C.readyState)==="ended"&&!(x!=null&&x.live)&&Math.abs(t-((x==null?void 0:x.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(Pt.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const T=Pl.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(Pt.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=Pl.bufferedInfo(Pl.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&n>=i.start){const l=Pl.timeRangesToArray(a),o=Pl.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=Ere(t,this.fragmentTracker);m&&"fragment"in m?m=m.fragment:m||(m=void 0);const p=Pl.bufferInfo(this.media,t,0);this.hls.trigger(Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:m,buffer:p.len,bufferInfo:p})}}}}}_tryFixBufferStall(t,n,r){var a,i;const{fragmentTracker:l,media:o}=this,c=(a=this.hls)==null?void 0:a.config;if(!o||!l||!c)return;const d=(i=this.hls)==null?void 0:i.latestLevelDetails,u=Ere(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,zi.MAIN),l=r.getFragAtPos(a,zi.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 (${Sh(t)})`);this.warn(l.message),n.trigger(Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.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=Pl.bufferInfo(a,l,0),c=l0&&o.len<1&&a.readyState<3,m=c-l;if(m>0&&(u||h)){if(m>i.maxBufferHole){let x=!1;if(l===0){const y=r.getAppendedFrag(0,zi.MAIN);y&&c"u"))return self.VTTCue||self.TextTrackCue}function A8e(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,Sh(a?Uu({type:a},r):r))}return i}const Mre=(()=>{const s=ZBe();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class YIn{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(Pt.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(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(Pt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Pt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Pt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(Pt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(Pt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Pt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Pt.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&&j9(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;nMre&&(h=Mre),h-u<=0&&(h=u+KIn);for(let p=0;pu.type===L_.audioId3&&c:a==="video"?d=u=>u.type===L_.emsg&&o:d=u=>u.type===L_.audioId3&&c||u.type===L_.emsg&&o,WBe(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=ZBe();if(r&&a&&!l){const{fragmentStart:y,fragmentEnd:g}=t;let b=this.assetCue;b?(b.startTime=y,b.endTime=g):o&&(b=this.assetCue=A8e(o,y,g,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),b&&(b.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(b),b.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=t,u=Object.keys(d);let h=this.dateRangeCuesAppended;if(c&&n){var m;if((m=c.cues)!=null&&m.length){const y=Object.keys(h).filter(g=>!u.includes(g));for(let g=y.length;g--;){var p;const b=y[g],v=(p=h[b])==null?void 0:p.cues;delete h[b],v&&Object.keys(v).forEach(k=>{const C=v[k];if(C){C.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(C)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const x=t.fragments[t.fragments.length-1];if(!(u.length===0||!ji(x==null?void 0:x.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let y=0;y{if(q!==b.id){const W=d[q];if(W.class===b.class&&W.startDate>b.startDate&&(!$||b.startDate<$.startDate))return W}return $},null);O&&(M=O.startTime,T=!0)}const I=Object.keys(b.attr);for(let O=0;O.01&&(q.startTime=v,q.endTime=M);else if(o){let W=b.attr[$];gMn($)&&(W=e$t(W));const K=A8e(o,v,M,{key:$,data:W},L_.dateRange);K&&(K.id=g,this.id3Track.addCue(K),C[$]=K,l&&($==="X-ASSET-LIST"||$==="X-ASSET-URL")&&K.addEventListener("enter",this.onEventCueEnter))}}h[g]={cues:C,dateRange:b,durationKnown:T}}}}}class ZIn{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:n}=this,r=this.levelDetails;if(!n||!r)return;this.currentTime=n.currentTime;const a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:l}=this.config;if(!i||l===1||!r.live)return;const o=this.targetLatency;if(o===null)return;const c=a-o,d=Math.min(this.maxLatency,o+r.targetduration);if(c.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,l)),m=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,p=Math.min(h,Math.max(1,m));this.changeMediaPlaybackRate(n,p)}else n.playbackRate!==1&&n.playbackRate!==0&&this.changeMediaPlaybackRate(n,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const n=this.levelDetails;return n?t.liveMaxLatencyDurationCount*n.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||this.hls===null)return null;const{holdBack:n,partHoldBack:r,targetduration:a}=t,{liveSyncDuration:i,liveSyncDurationCount:l,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let d=o&&r||n;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=i!==void 0?i:l*a);const u=a;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),n=this.targetLatency;if(t===null||n===null)return null;const r=this.levelDetails;if(r===null)return null;const a=r.edge,i=t-n-this.edgeStalled,l=a-r.totalduration,o=a-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(l,i),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null)return 0;const n=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-n,0)}get forwardBufferLength(){const{media:t}=this,n=this.levelDetails;if(!t||!n)return 0;const r=t.buffered.length;return(r?t.buffered.end(r-1):n.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Pt.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Pt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Pt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Pt.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===cr.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 XIn extends PYe{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(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Pt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Pt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Pt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Pt.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Pt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Pt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Pt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Pt.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(n=>{n.loadError=0,n.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,n){this.resetLevels()}onManifestLoaded(t,n){const r=this.hls.config.preferManagedMediaSource,a=[],i={},l={};let o=!1,c=!1,d=!1;n.levels.forEach(u=>{const h=u.attrs;let{audioCodec:m,videoCodec:p}=u;m&&(u.audioCodec=m=PSe(m,r)||void 0),p&&(p=u.videoCodec=P6n(p));const{width:x,height:y,unknownCodecs:g}=u,b=(g==null?void 0:g.length)||0;if(o||(o=!!(x&&y)),c||(c=!!p),d||(d=!!m),b||m&&!this.isAudioSupported(m)||p&&!this.isVideoSupported(p)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:v,"FRAME-RATE":k,"HDCP-LEVEL":C,"PATHWAY-ID":T,RESOLUTION:M,"VIDEO-RANGE":P}=h,I=`${`${T||"."}-`}${u.bitrate}-${M}-${k}-${v}-${P}-${C}`;if(i[I])if(i[I].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const O=l[I]+=1;u.attrs["PATHWAY-ID"]=new Array(O+1).join(".");const $=this.createLevel(u);i[I]=$,a.push($)}else i[I].addGroupId("audio",h.AUDIO),i[I].addGroupId("text",h.SUBTITLES);else{const O=this.createLevel(u);i[I]=O,l[I]=1,a.push(O)}}),this.filterAndSortMediaOptions(a,n,o,c,d)}createLevel(t){const n=new jX(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=h$t(a,[])}return n}isAudioSupported(t){return _X(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return _X(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,n,r,a,i){var l;let o=[],c=[],d=t;const u=((l=n.stats)==null?void 0:l.parsing)||{};if((r||a)&&i&&(d=d.filter(({videoCodec:v,videoRange:k,width:C,height:T})=>(!!v||!!(C&&T))&&q6n(k))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let v="no level with compatible codecs found in manifest",k=v;n.levels.length&&(k=`one or more CODECS in variant not supported: ${Sh(n.levels.map(T=>T.attrs.CODECS).filter((T,M,P)=>P.indexOf(T)===M))}`,this.warn(k),v+=` (${k})`);const C=new Error(v);this.hls.trigger(Pt.ERROR,{type:co.MEDIA_ERROR,details:cr.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:n.url,error:C,reason:k})}}),u.end=performance.now();return}n.audioTracks&&(o=n.audioTracks.filter(v=>!v.audioCodec||this.isAudioSupported(v.audioCodec)),pyt(o)),n.subtitles&&(c=n.subtitles,pyt(c));const h=d.slice(0);d.sort((v,k)=>{if(v.attrs["HDCP-LEVEL"]!==k.attrs["HDCP-LEVEL"])return(v.attrs["HDCP-LEVEL"]||"")>(k.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&v.height!==k.height)return v.height-k.height;if(v.frameRate!==k.frameRate)return v.frameRate-k.frameRate;if(v.videoRange!==k.videoRange)return ISe.indexOf(v.videoRange)-ISe.indexOf(k.videoRange);if(v.videoCodec!==k.videoCodec){const C=a0t(v.videoCodec),T=a0t(k.videoCodec);if(C!==T)return T-C}if(v.uri===k.uri&&v.codecSet!==k.codecSet){const C=LSe(v.codecSet),T=LSe(k.codecSet);if(C!==T)return T-C}return v.averageBitrate!==k.averageBitrate?v.averageBitrate-k.averageBitrate:0});let m=h[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==h.length)){for(let v=0;vC&&C===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}const x=i&&!a,y=this.hls.config,g=!!(y.audioStreamController&&y.audioTrackController),b={levels:d,audioTracks:o,subtitleTracks:c,sessionData:n.sessionData,sessionKeys:n.sessionKeys,firstLevel:this._firstLevel,stats:n.stats,audio:i,video:a,altAudio:g&&!x&&o.some(v=>!!v.url)};u.end=performance.now(),this.hls.trigger(Pt.MANIFEST_PARSED,b)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const n=this._levels;if(n.length===0)return;if(t<0||t>=n.length){const u=new Error("invalid level idx"),h=t<0;if(this.hls.trigger(Pt.ERROR,{type:co.OTHER_ERROR,details:cr.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(Pt.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===Pc.LEVEL&&n.context.level===this.level&&this.checkRetry(n)}onFragBuffered(t,{frag:n}){if(n!==void 0&&n.type===zi.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(Pt.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));P$t(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(Pt.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(Pt.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:n,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function pyt(s){const t={};s.forEach(n=>{const r=n.groupId||"";n.id=t[r]=t[r]||0,t[r]++})}function AUt(){return self.SourceBuffer||self.WebKitSourceBuffer}function TUt(){if(!UE())return!1;const t=AUt();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function QIn(){if(!TUt())return!1;const s=UE();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(wX(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(wX(t,"audio"))))}function JIn(){var s;const t=AUt();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const e8n=100;class t8n extends kYe{constructor(t,n,r){super(t,n,r,"stream-controller",zi.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||!ji(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,zi.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(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Pt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Pt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Pt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(Pt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Pt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(Pt.BUFFER_CREATED,this.onBufferCreated,this),t.on(Pt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Pt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Pt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Pt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Pt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Pt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(Pt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Pt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(Pt.BUFFER_CREATED,this.onBufferCreated,this),t.off(Pt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Pt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Pt.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(e8n),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=Yr.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=Yr.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Yr.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=Yr.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Yr.IDLE;break}break}case Yr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Yr.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(Pt.BUFFER_EOS,y),this.state=Yr.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===Yr.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=Yr.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,h=this.getMaxBufferLength(l.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const m=this.backtrackFragment?this.backtrackFragment.start:o.end;let p=this.getNextFragment(m,d);if(this.couldBacktrack&&!this.fragPrevious&&p&&Yf(p)&&this.fragmentTracker.getState(p)!==sg.OK){var x;const g=((x=this.backtrackFragment)!=null?x:p).sn-d.startSN,b=d.fragments[g-1];b&&p.cc===b.cc&&(p=b,this.fragmentTracker.removeFragment(b))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(p&&this.isLoopLoading(p,m)){if(!p.gap){const g=this.audioOnly&&!this.altAudio?yh.AUDIO:yh.VIDEO,b=(g===yh.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;b&&this.afterBufferFlushed(b,g,zi.MAIN)}p=this.getNextFragmentLoopLoading(p,d,o,zi.MAIN,h)}p&&(this.exceedsMaxBuffer(o,h,p)||(p.initSegment&&!p.initSegment.data&&!this.bitrateTest&&(p=p.initSegment),this.loadFragment(p,l,m)))}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);a===sg.NOT_LOADED||a===sg.PARTIAL?Yf(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,zi.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(Pt.AUDIO_TRACK_SWITCHED,n)}),r.trigger(Pt.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(Pt.AUDIO_TRACK_SWITCHED,n)}}onAudioTrackSwitched(t,n){const r=RSe(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===zi.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===Yr.PARSED&&(this.state=Yr.IDLE);return}const o=a?a.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Yf(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,a)}const l=this.media;l&&(!this._hasEnoughToStart&&Pl.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=Yr.ERROR;return}switch(n.details){case cr.FRAG_GAP:case cr.FRAG_PARSING_ERROR:case cr.FRAG_DECRYPT_ERROR:case cr.FRAG_LOAD_ERROR:case cr.FRAG_LOAD_TIMEOUT:case cr.KEY_LOAD_ERROR:case cr.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(zi.MAIN,n);break;case cr.LEVEL_LOAD_ERROR:case cr.LEVEL_LOAD_TIMEOUT:case cr.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===Yr.WAITING_LEVEL&&((r=n.context)==null?void 0:r.type)===Pc.LEVEL&&(this.state=Yr.IDLE);break;case cr.BUFFER_ADD_CODEC_ERROR:case cr.BUFFER_APPEND_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&this.resetLoadingState();break;case cr.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 cr.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onFragLoadEmergencyAborted(){this.state=Yr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:n}){if(n!==yh.AUDIO||!this.altAudio){const r=(n===yh.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,n,zi.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=Yr.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(Pt.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===Yr.STOPPED||this.state===Yr.ERROR||(this.warn(r),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const n=this.playlistType,{hls:r}=this,{remuxResult:a,chunkMeta:i}=t,l=this.getCurrentContext(i);if(!l){this.resetWhenMissingContext(i);return}const{frag:o,part:c,level:d}=l,{video:u,text:h,id3:m,initSegment:p}=a,{details:x}=d,y=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Yr.PARSING,p){const g=p.tracks;if(g){const C=o.initSegment||o;if(this.unhandledEncryptionError(p,o))return;this._bufferInitSegment(d,g,C,i),r.trigger(Pt.FRAG_PARSING_INIT_SEGMENT,{frag:C,id:n,tracks:g})}const b=p.initPTS,v=p.timescale,k=this.initPTS[o.cc];if(ji(b)&&(!k||k.baseTime!==b||k.timescale!==v)){const C=p.trackId;this.initPTS[o.cc]={baseTime:b,timescale:v,trackId:C},r.trigger(Pt.INIT_PTS_FOUND,{frag:o,id:n,initPTS:b,timescale:v,trackId:C})}}if(u&&x){y&&u.type==="audiovideo"&&this.logMuxedErr(o);const g=x.fragments[o.sn-1-x.startSN],b=o.sn===x.startSN,v=!g||o.cc>g.cc;if(a.independent!==!1){const{startPTS:k,endPTS:C,startDTS:T,endDTS:M}=u;if(c)c.elementaryStreams[u.type]={startPTS:k,endPTS:C,startDTS:T,endDTS:M};else if(u.firstKeyFrame&&u.independent&&i.id===1&&!v&&(this.couldBacktrack=!0),u.dropped&&u.independent){const P=this.getMainFwdBufferInfo(),L=(P?P.end:this.getLoadPosition())+this.config.maxBufferHole,I=u.firstKeyFramePTS?u.firstKeyFramePTS:k;if(!b&&LI2e&&(o.gap=!0);o.setElementaryStreamInfo(u.type,k,C,T,M),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,i,b||v)}else if(b||v)o.gap=!0;else{this.backtrack(o);return}}if(y){const{startPTS:g,endPTS:b,startDTS:v,endDTS:k}=y;c&&(c.elementaryStreams[yh.AUDIO]={startPTS:g,endPTS:b,startDTS:v,endDTS:k}),o.setElementaryStreamInfo(yh.AUDIO,g,b,v,k),this.bufferFragmentData(y,o,c,i)}if(x&&m!=null&&m.samples.length){const g={id:n,frag:o,details:x,samples:m.samples};r.trigger(Pt.FRAG_PARSING_METADATA,g)}if(x&&h){const g={id:n,frag:o,details:x,samples:h.samples};r.trigger(Pt.FRAG_PARSING_USERDATA,g)}}logMuxedErr(t){this.warn(`${Yf(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,n,r,a){if(this.state!==Yr.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=C2e(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=zi.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=zi.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(Pt.BUFFER_CODECS,n),!this.hls)return;c.forEach(d=>{const h=n[d].initSegment;h!=null&&h.byteLength&&this.hls.trigger(Pt.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,zi.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=Yr.IDLE}checkFragmentChanged(){const t=this.media;let n=null;if(t&&t.readyState>1&&t.seeking===!1){const r=t.currentTime;if(Pl.isBuffered(t,r)?n=this.getAppendedFrag(r):Pl.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(Pt.FRAG_CHANGED,{frag:n}),(!a||a.level!==i)&&this.hls.trigger(Pt.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 ji(n)?this.getAppendedFrag(n):null}get currentProgramDateTime(){var t;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(ji(n)){const r=this.getLevelDetails(),a=this.currentFrag||(r?oO(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 s8n extends Jj{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=cr.KEY_LOAD_ERROR,r,a,i){return new y4({type:co.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=T2e(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=pW(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,cr.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,cr.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=T8e(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: "+G0(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,cr.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=_6n(n.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${G0(o)}`),bE.setKeyIdForUri(t.decryptdata.uri,o)):(o=bE.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${G0(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!Yf(n))return Promise.resolve(r);const i=this.emeController.loadKey(r);return(t.keyLoadPromise=i.then(l=>(t.mediaKeySessionContext=l,r))).catch(l=>{throw t.keyLoadPromise=null,"data"in l&&(l.data.frag=n),l})}return Promise.resolve(r)}loadKeyHTTP(t,n){const r=this.config,a=r.loader,i=new a(r);return n.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((l,o)=>{const c={keyInfo:t,frag:n,responseType:"arraybuffer",url:t.decryptdata.uri},d=r.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(m,p,x,y)=>{const{frag:g,keyInfo:b}=x,v=T8e(b.decryptdata);if(!g.decryptdata||b!==this.keyIdToKeyInfo[v])return o(this.createKeyLoadError(g,cr.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),y));b.decryptdata.key=g.decryptdata.key=new Uint8Array(m.data),g.keyLoader=null,b.loader=null,l({frag:g,keyInfo:b})},onError:(m,p,x,y)=>{this.resetLoader(p),o(this.createKeyLoadError(n,cr.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),x,Uu({url:c.url,data:void 0},m)))},onTimeout:(m,p,x)=>{this.resetLoader(p),o(this.createKeyLoadError(n,cr.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),x))},onAbort:(m,p,x)=>{this.resetLoader(p),o(this.createKeyLoadError(n,cr.INTERNAL_ABORTED,new Error("key loading aborted"),x))}};i.load(c,u,h)})}resetLoader(t){const{frag:n,keyInfo:r,url:a}=t,i=r.loader;n.keyLoader===i&&(n.keyLoader=null,r.loader=null);const l=T8e(r.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function T8e(s){if(s.keyFormat!==Z0.FAIRPLAY){const t=s.keyId;if(t)return G0(t)}return s.uri}function fyt(s){const{type:t}=s;switch(t){case Pc.AUDIO_TRACK:return zi.AUDIO;case Pc.SUBTITLE_TRACK:return zi.SUBTITLE;default:return zi.MAIN}}function E8e(s,t){let n=s.url;return(n===void 0||n.indexOf("data:")===0)&&(n=t.url),n}class n8n{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(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Pt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Pt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(Pt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(Pt.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(Pt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Pt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Pt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(Pt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(Pt.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:Pc.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:Pc.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:Pc.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:Pc.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,n){const r=this.loaders[Pc.LEVEL];if(r){const a=r.context;a&&!n.levels.some(i=>i===a.levelOrTrack)&&(r.abort(),delete this.loaders[Pc.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===Pc.MANIFEST?i=r.manifestLoadPolicy.default:i=ah({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),ji((n=t.deliveryDirectives)==null?void 0:n.part)){let d;if(t.type===Pc.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===Pc.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===Pc.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=ah({},i,{maxTimeToFirstByteMs:Math.min(m,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(m,i.maxTimeToFirstByteMs)})}}}const l=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:(d,u,h,m)=>{const p=this.getInternalLoader(h);this.resetInternalLoader(h.type);const x=d.data;u.parsing.start=performance.now(),A5.isMediaPlaylist(x)||h.type!==Pc.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,h,m||null,p):this.handleMasterPlaylist(d,u,h,m)},onError:(d,u,h,m)=>{this.handleNetworkError(u,h,!1,d,m)},onTimeout:(d,u,h)=>{this.handleNetworkError(u,h,!0,void 0,d)}};a.load(t,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:n},forceStartLoad:r}=this.hls;(t||r)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${n}`),this.hls.startLoad(n))}handleMasterPlaylist(t,n,r,a){const i=this.hls,l=t.data,o=E8e(t,r),c=A5.parseMasterPlaylist(l,o);if(c.playlistParsingError){n.parsing.end=performance.now(),this.handleManifestParsingError(t,r,c.playlistParsingError,a,n);return}const{contentSteering:d,levels:u,sessionData:h,sessionKeys:m,startTimeOffset:p,variableList:x}=c;this.variableList=x,u.forEach(v=>{const{unknownCodecs:k}=v;if(k){const{preferManagedMediaSource:C}=this.hls.config;let{audioCodec:T,videoCodec:M}=v;for(let P=k.length;P--;){const L=k[P];_X(L,"audio",C)?(v.audioCodec=T=T?`${T},${L}`:L,wU.audio[T.substring(0,4)]=2,k.splice(P,1)):_X(L,"video",C)&&(v.videoCodec=M=M?`${M},${L}`:L,wU.video[M.substring(0,4)]=2,k.splice(P,1))}}});const{AUDIO:y=[],SUBTITLES:g,"CLOSED-CAPTIONS":b}=A5.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 jp({}),bitrate:0,url:""})),i.trigger(Pt.MANIFEST_LOADED,{levels:u,audioTracks:y,subtitles:g,captions:b,contentSteering:d,url:o,stats:n,networkDetails:a,sessionData:h,sessionKeys:m,startTimeOffset:p,variableList:x})}handleTrackOrLevelPlaylist(t,n,r,a,i){const l=this.hls,{id:o,level:c,type:d}=r,u=E8e(t,r),h=ji(c)?c:ji(o)?o:0,m=fyt(r),p=A5.parseLevelPlaylist(t.data,u,h,m,0,this.variableList);if(d===Pc.MANIFEST){const x={attrs:new jp({}),bitrate:0,details:p,name:"",url:u};p.requestScheduled=n.loading.start+E$t(p,0),l.trigger(Pt.MANIFEST_LOADED,{levels:[x],audioTracks:[],url:u,stats:n,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}n.parsing.end=performance.now(),r.levelDetails=p,this.handlePlaylistLoaded(p,t,n,r,a,i)}handleManifestParsingError(t,n,r,a,i){this.hls.trigger(Pt.ERROR,{type:co.NETWORK_ERROR,details:cr.MANIFEST_PARSING_ERROR,fatal:n.type===Pc.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===Pc.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===Pc.AUDIO_TRACK||t.type===Pc.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=cr.UNKNOWN,d=!1;const u=this.getInternalLoader(t);switch(t.type){case Pc.MANIFEST:c=r?cr.MANIFEST_LOAD_TIMEOUT:cr.MANIFEST_LOAD_ERROR,d=!0;break;case Pc.LEVEL:c=r?cr.LEVEL_LOAD_TIMEOUT:cr.LEVEL_LOAD_ERROR,d=!1;break;case Pc.AUDIO_TRACK:c=r?cr.AUDIO_TRACK_LOAD_TIMEOUT:cr.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Pc.SUBTITLE_TRACK:c=r?cr.SUBTITLE_TRACK_LOAD_TIMEOUT:cr.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(t.type);const h={type:co.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=Uu({url:m,data:void 0},a)}this.hls.trigger(Pt.ERROR,h)}handlePlaylistLoaded(t,n,r,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:u,id:h,groupId:m,deliveryDirectives:p}=a,x=E8e(n,a),y=fyt(a);let g=typeof a.level=="number"&&y===zi.MAIN?d:void 0;const b=t.playlistParsingError;if(b){if(this.hls.logger.warn(`${b} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(Pt.ERROR,{type:co.NETWORK_ERROR,details:cr.LEVEL_PARSING_ERROR,fatal:!1,url:x,error:b,reason:b.message,response:n,context:a,level:g,parent:y,networkDetails:i,stats:r});return}t.playlistParsingError=null}if(!t.fragments.length){const v=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(Pt.ERROR,{type:co.NETWORK_ERROR,details:cr.LEVEL_EMPTY_ERROR,fatal:!1,url:x,error:v,reason:v.message,response:n,context:a,level:g,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 Pc.MANIFEST:case Pc.LEVEL:if(g){if(!u)g=0;else if(u!==o.levels[g]){const v=o.levels.indexOf(u);v>-1&&(g=v)}}o.trigger(Pt.LEVEL_LOADED,{details:t,levelInfo:u||o.levels[0],level:g||0,id:h||0,stats:r,networkDetails:i,deliveryDirectives:p,withoutMultiVariant:c===Pc.MANIFEST});break;case Pc.AUDIO_TRACK:o.trigger(Pt.AUDIO_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:p});break;case Pc.SUBTITLE_TRACK:o.trigger(Pt.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:p});break}}}class y5{static get version(){return NX}static isMSESupported(){return TUt()}static isSupported(){return QIn()}static getMediaSource(){return UE()}static get Events(){return Pt}static get MetadataSchema(){return L_}static get ErrorTypes(){return co}static get ErrorDetails(){return cr}static get DefaultConfig(){return y5.defaultConfig?y5.defaultConfig:BIn}static set DefaultConfig(t){y5.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 SYe,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=c6n(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=UIn(y5.DefaultConfig,t,n);this.userConfig=t,r.progressive&&qIn(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 rMn(this),m=r.interstitialsController,p=m?this.interstitialsController=new m(this,y5):null,x=this.bufferController=new i(this,h),y=this.capLevelController=new l(this),g=new c(this),b=new n8n(this),v=r.contentSteeringController,k=v?new v(this):null,C=this.levelController=new XIn(this,k),T=new YIn(this),M=new s8n(this.config,this.logger),P=this.streamController=new t8n(this,h,M),L=this.gapController=new WIn(this,h);y.setStreamController(P),g.setStreamController(P);const I=[b,C,P];p&&I.splice(1,0,p),k&&I.splice(1,0,k),this.networkControllers=I;const O=[u,x,L,y,g,T,h];this.audioTrackController=this.createController(r.audioTrackController,I);const $=r.audioStreamController;$&&I.push(this.audioStreamController=new $(this,h,M)),this.subtitleTrackController=this.createController(r.subtitleTrackController,I);const q=r.subtitleStreamController;q&&I.push(this.subtititleStreamController=new q(this,h,M)),this.createController(r.timelineController,O),M.emeController=this.emeController=this.createController(r.emeController,O),this.cmcdController=this.createController(r.cmcdController,O),this.latencyController=this.createController(ZIn,O),this.coreComponents=O,I.push(d);const W=d.onErrorOut;typeof W=="function"&&this.on(Pt.ERROR,W,d),this.on(Pt.MANIFEST_LOADED,b.onManifestLoaded,b)}createController(t,n){if(t){const r=new t(this);return n&&n.push(r),r}return null}on(t,n,r=this){this._emitter.on(t,n,r)}once(t,n,r=this){this._emitter.once(t,n,r)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,n,r=this,a){this._emitter.off(t,n,r,a)}listeners(t){return this._emitter.listeners(t)}emit(t,n,r){return this._emitter.emit(t,n,r)}trigger(t,n){if(this.config.debug)return this.emit(t,t,n);try{return this.emit(t,t,n)}catch(r){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const a=t===Pt.ERROR;this.trigger(Pt.ERROR,{type:co.OTHER_ERROR,details:cr.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(Pt.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(Pt.ERROR,{type:co.OTHER_ERROR,details:cr.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(Pt.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Pt.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(Pt.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const n=this.media,r=this._url,a=this._url=fYe.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(Pt.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={[zi.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[zi.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[zi.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=WPn()),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){U6n(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=f$t(n);return m$t(t,r,navigator.mediaCapabilities)}}y5.defaultConfig=void 0;const r8n=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function N9(s){return!!s&&r8n.test(s)&&!/\.mp4($|\?)/i.test(s)}function a8n(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function i8n(s,t){if(!s)return null;const n=a8n(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 o8n(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const XBe=j.forwardRef(function({sourceUrl:t,thumbnailUrl:n,autoPlay:r,muted:a,loop:i,playsInline:l=!0,...o},c){const d=j.useRef(null),[u,h]=j.useState(null),m=j.useMemo(()=>i8n(t,{autoplay:!!r,muted:!!a,loop:!!i}),[t,r,a,i]);j.useEffect(()=>{let x=!1;if(!t){h(null);return}if(!N9(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 g=await y.text();return o8n(g)}).then(y=>{x||h(y)}).catch(()=>{x||h(null)}),()=>{x=!0}},[m,t]),j.useEffect(()=>{const x=d.current;if(!x||!u)return;let y=null;const g=()=>{if(!r)return;const v=x.play();v&&v.catch(()=>{})};if(x.muted=!!a,x.loop=!!i,u.endsWith(".m3u8")){if(x.canPlayType("application/vnd.apple.mpegurl")){x.src=u;const v=()=>g();return x.addEventListener("loadedmetadata",v),()=>{x.removeEventListener("loadedmetadata",v),x.removeAttribute("src"),x.load()}}return y5.isSupported()?(y=new y5({enableWorker:!0,lowLatencyMode:!0}),y.loadSource(u),y.attachMedia(x),y.on(y5.Events.MANIFEST_PARSED,g),()=>{y==null||y.destroy(),x.removeAttribute("src"),x.load()}):void 0}x.src=u;const b=()=>g();return x.addEventListener("loadedmetadata",b),()=>{x.removeEventListener("loadedmetadata",b),x.removeAttribute("src"),x.load()}},[r,i,a,u]),j.useEffect(()=>{const x=d.current;if(x){if(x.muted=!!a,x.loop=!!i,r&&u){const y=x.play();y&&y.catch(()=>{});return}x.pause()}},[r,i,a,u]);const p=x=>{if(d.current=x,typeof c=="function"){c(x);return}c&&(c.current=x)};return e.jsx("video",{ref:p,poster:n||void 0,autoPlay:r,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),l8n={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 c8n(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function xyt(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 zYe({config:s,appSlug:t="video_greeter",preview:n=!1,embedded:r=!1}){const[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!0),[u,h]=j.useState(!1),[m,p]=j.useState("portrait"),[x,y]=j.useState(!1),[g,b]=j.useState(!1),[v,k]=j.useState({name:"",email:"",phone:""}),[C,T]=j.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),M=j.useRef(null),P=j.useRef(null),L=j.useRef(!1),I=async(Ae,Xe)=>{if(!n)try{await U.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:Ae,visitor_token:c8n(),page_url:typeof window<"u"?window.location.href:null,metadata:Xe||{}})}catch{}};j.useEffect(()=>{if(u)return;const Ae=typeof window<"u"?window.location.pathname:"/",Xe=s.targeting||{mode:"all"};if(Xe.mode==="include"&&!xyt(Xe.include,Ae)||Xe.mode==="exclude"&&xyt(Xe.exclude,Ae))return;const Ue=s.trigger||{type:"immediate"};if(Ue.type==="immediate"||n){i(!0);return}if(Ue.type==="delay"){const Ze=(Ue.value||3)*1e3,Qe=setTimeout(()=>i(!0),Ze);return()=>clearTimeout(Qe)}if(Ue.type==="scroll"){const Ze=(Ue.value||25)/100,Qe=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=Ze&&(i(!0),window.removeEventListener("scroll",Qe))};return window.addEventListener("scroll",Qe,{passive:!0}),()=>window.removeEventListener("scroll",Qe)}if(Ue.type==="exit_intent"){const Ze=Qe=>{Qe.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",Ze),()=>document.removeEventListener("mouseleave",Ze)}},[u,s.targeting,s.trigger,n]),j.useEffect(()=>{a&&!L.current&&(L.current=!0,I("impression"))},[a]),j.useEffect(()=>{if(l&&P.current&&!N9(s.video_url)){P.current.currentTime=0,P.current.muted=!1,d(!1);const Ae=P.current.play();Ae&&Ae.catch(()=>{})}else l&&N9(s.video_url)&&d(!1)},[l,s.video_url]),j.useEffect(()=>{if(!s.thumbnail_url)return;let Ae=!1;const Xe=new Image;return Xe.onload=()=>{Ae||p(Xe.naturalWidth>Xe.naturalHeight?"landscape":"portrait")},Xe.src=s.thumbnail_url,()=>{Ae=!0}},[s.thumbnail_url]),j.useEffect(()=>{const Ae=()=>{T({width:window.innerWidth,height:window.innerHeight})};return Ae(),window.addEventListener("resize",Ae),()=>window.removeEventListener("resize",Ae)},[]);const O=()=>{o(!0),I("expand")},$=Ae=>{Ae.stopPropagation(),h(!0),o(!1)},q=Ae=>{I("cta_click",{cta_id:Ae.id,label:Ae.label,url:Ae.url})},W=async Ae=>{if(Ae.preventDefault(),n){y(!0);return}if(!(!v.email||!v.name)){b(!0);try{const{error:Xe}=await U.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:t,name:v.name,email:v.email,phone:v.phone||void 0,page_url:window.location.href}});if(Xe)throw Xe;I("lead_capture",{email:v.email}),y(!0)}catch(Xe){console.error("lead submit failed",Xe)}finally{b(!1)}}};if(!a||u||!s.video_url&&!s.video_embed_url)return null;const G=l8n[m][s.size||"md"],K=r?"absolute left-2 bottom-2":n?s.position==="bottom-right"?"absolute right-4 bottom-4":"absolute left-4 bottom-4":s.position==="bottom-right"?"fixed right-4 bottom-4 md:right-6 md:bottom-6":"fixed left-4 bottom-4 md:left-6 md:bottom-6",ee=s.shape==="circle"?"rounded-full":"rounded-2xl",J=n?m==="landscape"?"w-[280px]":"w-[220px]":m==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",le=m==="landscape"?"aspect-video":"aspect-[9/16]",ue=s.agent||{},oe=s.lead_form_fields||["name","email","phone"],ie=!!(s.show_socials&&(ue.instagram_url||ue.facebook_url||ue.linkedin_url)),de=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!x?72+oe.length*42:0)+(x?40:0)+(ie?34:0),we=Math.max(300,C.height-32),je=Math.max(220,C.width-32),xe=Math.max(150,we-de),fe=Math.floor(m==="landscape"?xe*(16/9):xe*(9/16)),Se=m==="landscape"?Math.max(220,Math.min(420,je,fe)):Math.max(180,Math.min(340,je,fe)),Ee=r?"bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col":`${J} max-h-[calc(100dvh-2rem)] bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col`,Le=r?{width:`${Se}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,De=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",_e=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",Oe=r?"w-full flex items-center justify-center gap-2 px-3 py-2 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60":"w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60";return e.jsx("div",{"data-vg-widget":!0,"data-expanded":l?"true":"false",className:`${K} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:Ee,style:Le,children:[e.jsxs("div",{className:`relative bg-black ${le}`,children:[N9(s.video_url)?e.jsx(XBe,{ref:P,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:Ae=>{const{videoWidth:Xe,videoHeight:Ue}=Ae.currentTarget;Xe&&Ue&&p(Xe>Ue?"landscape":"portrait")},onEnded:()=>I("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:P,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,playsInline:!0,controls:!1,className:"w-full h-full object-cover",onEnded:()=>I("watch_complete"),onLoadedMetadata:Ae=>{const{videoWidth:Xe,videoHeight:Ue}=Ae.currentTarget;Xe&&Ue&&p(Xe>Ue?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{P.current&&(P.current.muted=!P.current.muted,d(P.current.muted))},className:"absolute bottom-3 right-3 w-9 h-9 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur",children:c?e.jsx(vK,{className:"w-4 h-4"}):e.jsx(yK,{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(dr,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:De,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ue.avatar_url&&e.jsx("img",{src:ue.avatar_url,alt:ue.name||"",className: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:()=>q(Ae),className:`flex items-center justify-between gap-2 ${r?"px-3 py-2":"px-3.5 py-2.5"} rounded-xl text-sm font-semibold transition-colors ${Ae.style==="secondary"?"bg-gray-100 text-gray-900 hover:bg-gray-200":"bg-gray-900 text-white hover:bg-gray-800"}`,children:[e.jsx("span",{children:Ae.label}),e.jsx(Tr,{className:"w-3.5 h-3.5 opacity-60"})]},Ae.id)})}),s.lead_form_enabled&&!x&&e.jsxs("form",{onSubmit:W,className:"space-y-2 pt-1",children:[oe.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:v.name,onChange:Ae=>k({...v,name:Ae.target.value}),className:_e}),oe.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:v.email,onChange:Ae=>k({...v,email:Ae.target.value}),className:_e}),oe.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:v.phone,onChange:Ae=>k({...v,phone:Ae.target.value}),className:_e}),e.jsxs("button",{type:"submit",disabled:g,className:Oe,children:[e.jsx(Dr,{className:"w-3.5 h-3.5"}),g?"Sending...":"Send"]})]}),x&&e.jsx("p",{className:"text-sm text-emerald-600 font-medium text-center py-2",children:"Thanks! I'll be in touch shortly."}),s.show_socials&&(ue.instagram_url||ue.facebook_url||ue.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[ue.instagram_url&&e.jsx("a",{href:ue.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>I("cta_click",{social:"instagram"}),children:e.jsx(vm,{className:"w-4 h-4"})}),ue.facebook_url&&e.jsx("a",{href:ue.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>I("cta_click",{social:"facebook"}),children:e.jsx(sx,{className:"w-4 h-4"})}),ue.linkedin_url&&e.jsx("a",{href:ue.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>I("cta_click",{social:"linkedin"}),children:e.jsx(ry,{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:O,className:`relative ${ee} 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:[N9(s.video_url)?e.jsx(XBe,{ref:M,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:Ue}=Ae.currentTarget;Xe&&Ue&&p(Xe>Ue?"landscape":"portrait")}},`collapsed-${s.video_url}-${s.thumbnail_url||"no-thumb"}`):e.jsx("video",{ref:M,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:Ue}=Ae.currentTarget;Xe&&Ue&&p(Xe>Ue?"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(dr,{className:"w-3.5 h-3.5"})})]})})}function BYe({slug:s}){const[t,n]=j.useState(null);return j.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await U.rpc("get_public_video_greeter_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(zYe,{config:t}):null}const EUt="eip_last_shown",gyt="eip_visitor_token";function d8n(){try{let s=localStorage.getItem(gyt);return s||(s=crypto.randomUUID(),localStorage.setItem(gyt,s)),s}catch{return}}function u8n(s){try{const t=Number(localStorage.getItem(EUt)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function h8n(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 MUt({config:s,preview:t=!1,forceOpen:n=!1}){const[r,a]=j.useState(n),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState({name:"",email:"",phone:""}),h=j.useRef(!1),m=j.useRef(!1),p=async(M,P={})=>{if(!t)try{await U.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:M,visitor_token:d8n(),page_url:window.location.href,metadata:P})}catch{}};j.useEffect(()=>{if(t||!h8n(s.targeting)||!u8n(s.frequency_days))return;const M=/Mobi|Android/i.test(navigator.userAgent),P={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,L=q=>{if(!h.current){h.current=!0,a(!0);try{localStorage.setItem(EUt,String(Date.now()))}catch{}p("impression",{reason:q})}},I=q=>{q.clientY<=P&&L("mouse_leave")},O=()=>{s.enable_mobile_back&&M&&L("back_button")};if(s.enable_mobile_back&&M){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",O)}else document.addEventListener("mouseleave",I);let $;return s.enable_time_fallback&&($=window.setTimeout(()=>L("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",I),window.removeEventListener("popstate",O),$&&window.clearTimeout($)}},[s,t]),j.useEffect(()=>{r&&!m.current&&!t&&!h.current&&(m.current=!0)},[r,t]);const x=()=>{a(!1),t||p("close")},y=async M=>{if(M.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:P}=await U.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"exit_intent",name:d.name,email:d.email,phone:d.phone||void 0,page_url:window.location.href}});if(P)throw P;p("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(P){console.error("exit intent submit failed",P)}finally{c(!1)}}};if(!r)return null;const g=s.form_fields||["name","email"],b=s.agent||{},v=[b.first_name,b.last_name].filter(Boolean).join(" "),k=s.use_agent_photo&&b.avatar_url||s.image_url,C=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:M=>M.stopPropagation(),children:[e.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${C}, ${M8e(C,-25)})`}}),e.jsx("button",{onClick:x,className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full bg-background/80 backdrop-blur hover:bg-background flex items-center justify-center text-muted-foreground hover:text-foreground transition","aria-label":"Close",children:e.jsx(dr,{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:v||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${C}33`,"--tw-ring-color":C}}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${C}1A`,color:C},children:[e.jsx(yn,{className:"w-3 h-3"}),s.offer_label]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.headline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.subheadline})]}),i?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${C}10`,color:C},children:[e.jsx("div",{className:"text-3xl",children:"🎉"}),e.jsx("p",{className:"text-sm font-medium",style:{color:C},children:s.success_message})]}):s.form_enabled?e.jsxs("form",{onSubmit:y,className:"space-y-2.5",children:[g.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:M=>u({...d,name:M.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":C},required:!0}),g.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:M=>u({...d,email:M.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":C},required:!0}),g.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:M=>u({...d,phone:M.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":C}}),e.jsx("button",{type:"submit",disabled:o,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60",style:{background:`linear-gradient(135deg, ${C}, ${M8e(C,-20)})`},children:o?"Sending...":s.cta_label}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We respect your inbox. Unsubscribe anytime."})]}):e.jsx("a",{href:s.cta_url||"#",onClick:()=>p("cta_click",{url:s.cta_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 transition",style:{background:`linear-gradient(135deg, ${C}, ${M8e(C,-20)})`},children:s.cta_label}),v&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",v]})]})]})})}function M8e(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 $Ye({slug:s}){const[t,n]=j.useState(null);return j.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await U.rpc("get_public_exit_intent_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(MUt,{config:t}):null}const yyt="lm_dismissed",vyt="lm_visitor_token";function m8n(){try{let s=localStorage.getItem(vyt);return s||(s=crypto.randomUUID(),localStorage.setItem(vyt,s)),s}catch{return}}function p8n(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 UYe({config:s,preview:t=!1}){const[n,r]=j.useState(!1),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState({name:"",email:"",phone:""}),m=j.useRef(!1),p=async(k,C={})=>{if(!t)try{await U.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:k,visitor_token:m8n(),page_url:window.location.href,metadata:C})}catch{}};j.useEffect(()=>{if(t){r(!0);return}if(!p8n(s.targeting))return;try{if(sessionStorage.getItem(yyt))return}catch{}const k=()=>{m.current||(m.current=!0,r(!0),p("impression"))};if(s.trigger_type==="immediate")k();else if(s.trigger_type==="delay"){const C=window.setTimeout(k,Math.max(0,s.trigger_value)*1e3);return()=>window.clearTimeout(C)}else if(s.trigger_type==="scroll"){const C=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(s.trigger_value||30)&&k()};return window.addEventListener("scroll",C,{passive:!0}),()=>window.removeEventListener("scroll",C)}},[s,t]);const x=()=>{r(!1);try{sessionStorage.setItem(yyt,"1")}catch{}t||p("close")},y=async k=>{if(k.preventDefault(),t){o(!0);return}if(!(!u.email||!u.name)){d(!0);try{const{error:C}=await U.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"lead_magnet",name:u.name,email:u.email,phone:u.phone||void 0,page_url:window.location.href}});if(C)throw C;p("lead_capture",{email:u.email}),o(!0),(s.delivery_method==="instant"||s.delivery_method==="both")&&s.download_url&&setTimeout(()=>{const 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(C){console.error("lead magnet submit failed",C)}finally{d(!1)}}};if(!n)return null;const g=s.theme_color||"#2563eb",b=t?s.position==="bottom-left"?"absolute left-4 bottom-4":"absolute right-4 bottom-4":s.position==="bottom-left"?"fixed left-4 bottom-4 md:left-6 md:bottom-6":"fixed right-4 bottom-4 md:right-6 md:bottom-6";if(s.display_style==="bar")return e.jsxs("div",{className:t?"absolute left-0 right-0 bottom-0 z-10":"fixed left-0 right-0 bottom-0 z-[75]",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"text-white shadow-2xl",style:{background:`linear-gradient(90deg, ${g}, ${iG(g,-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(zo,{className:"w-5 h-5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:s.title}),e.jsx("p",{className:"text-xs text-white/80 truncate",children:s.description})]}),e.jsx("button",{onClick:()=>{i(!0),p("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:g},children:s.download_label}),e.jsx("button",{onClick:x,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx(dr,{className:"w-4 h-4"})})]})}),a&&v()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),p("expand")},className:`${b} z-[75] group flex items-center gap-3 pl-3 pr-4 py-3 rounded-2xl shadow-2xl hover:shadow-3xl transition-all hover:scale-[1.03] animate-in fade-in slide-in-from-bottom-4 duration-500`,style:{background:`linear-gradient(135deg, ${g}, ${iG(g,-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(Op,{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(),x()},className:"ml-1 w-6 h-6 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white","aria-label":"Close",children:e.jsx(dr,{className:"w-3 h-3"})})]}),a&&v()]});return v();function v(){const k=s.form_fields||["name","email"],C=s.agent||{},T=[C.first_name,C.last_name].filter(Boolean).join(" ");return e.jsx("div",{className:t?"absolute inset-0 flex items-center justify-center p-4 z-20":"fixed inset-0 z-[85] flex items-center justify-center p-4",style:{background:t?"transparent":"rgba(0,0,0,0.6)"},onClick:()=>i(!1),children:e.jsxs("div",{className:"relative w-full max-w-lg bg-background rounded-2xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-300",onClick:M=>M.stopPropagation(),children:[e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${g}, ${iG(g,-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($r,{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:g},children:[e.jsx(zo,{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(dr,{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:`${g}10`},children:[e.jsx(ii,{className:"w-8 h-8 mx-auto",style:{color:g}}),e.jsx("p",{className:"text-sm font-medium",style:{color:g},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:g},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:M=>h({...u,name:M.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":g},required:!0}),k.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:u.email,onChange:M=>h({...u,email:M.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":g},required:!0}),k.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:u.phone,onChange:M=>h({...u,phone:M.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":g}}),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, ${g}, ${iG(g,-20)})`},children:[e.jsx(ii,{className:"w-4 h-4"}),c?"Sending...":s.download_label]}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We'll email you a copy too. No spam — promise."})]}):e.jsx("a",{href:s.download_url||"#",target:"_blank",rel:"noopener",onClick:()=>p("cta_click",{url:s.download_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg",style:{background:`linear-gradient(135deg, ${g}, ${iG(g,-20)})`},children:s.download_label}),T&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",T]})]})]})})}}function iG(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 qYe({slug:s}){const[t,n]=j.useState(null);return j.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await U.rpc("get_public_lead_magnet_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(UYe,{config:t}):null}function f8n({children:s,siteConfig:t}){var we,je,xe,fe,Se,Ee,Le,De,Be;const n=$d(),r=Hn(),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState([]),[m,p]=j.useState([]),[x,y]=j.useState(null),g=j.useRef(null),b=j.useRef(null),{user:v,profile:k,signOut:C}=bTe();mYe(t,v==null?void 0:v.id),pYe(t,v==null?void 0:v.id);const T=((we=t.agent)==null?void 0:we.full_name)||"Agent",M=t.siteTitle||`${T} Real Estate`,P=n.pathname==="/search",L=n.pathname==="/",I=t.leadRegistrationMode!=="disabled";j.useEffect(()=>{(async()=>{const{data:Ge}=await U.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});h(Ge||[])})()},[t.id]),j.useEffect(()=>{(async()=>{const{data:Ge}=await U.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});p(Ge||[])})()},[t.id]),j.useEffect(()=>{const Ne=Ge=>{g.current&&!g.current.contains(Ge.target)&&d(!1),b.current&&!b.current.contains(Ge.target)&&y(null)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[]);const O=QBt(t),$=t==null?void 0:t.bookingUrl,q=O?m.filter(Ne=>{const Ge=String(Ne.target_url||"").toLowerCase(),_e=String(Ne.label||"").toLowerCase();return Ge!=="/search"&&!Ge.startsWith("/search?")&&!_e.includes("search")}):m,W=q.length>0,G=[{to:"/",label:"Home"},...O?[]:[{to:"/search",label:"Search"}],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],K=W?[]:G,ee=q.filter(Ne=>!Ne.parent_id),J=Ne=>q.filter(Ge=>Ge.parent_id===Ne),le=L?"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`,oe=t.siteTagline||`Browse homes and listings with ${T}`,ie=t.ogImageUrl||((je=t.agent)==null?void 0:je.avatar_url)||"",de=`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${P?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(uYe,{siteConfig:t,pagePath:n.pathname}),e.jsx(hYe,{siteConfig:t}),e.jsxs(ql,{children:[e.jsx("title",{children:ue}),e.jsx("meta",{name:"description",content:oe}),e.jsx("meta",{property:"og:title",content:ue}),e.jsx("meta",{property:"og:description",content:oe}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:de+n.pathname}),ie&&e.jsx("meta",{property:"og:image",content:ie}),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:oe}),ie&&e.jsx("meta",{name:"twitter:image",content:ie}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${de}${n.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${L?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${le}`,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(Yn,{to:"/",className:"flex items-center gap-3",children:[((xe=t.agent)==null?void 0:xe.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:M})})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[t.bookingUrl&&e.jsx(T3,{bookingUrl:t.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),K.map(Ne=>e.jsx(Yn,{to:Ne.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname===Ne.to?L?"bg-white/15 text-white":"bg-gray-100 text-gray-900":L?"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&&ee.map(Ne=>{if(Ne.item_type==="dropdown"){const Ge=J(Ne.id);return e.jsxs("div",{ref:b,className:"relative",children:[e.jsxs("button",{onClick:()=>y(x===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 ${L?"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(Po,{className:`h-3.5 w-3.5 transition-transform ${x===Ne.id?"rotate-180":""}`})]}),x===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(_e=>e.jsx(Lre,{item:_e,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"},_e.id))})]},Ne.id)}return e.jsx(Lre,{item:Ne,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${L?"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:g,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-")?L?"bg-white/15 text-white":"bg-gray-100 text-gray-900":L?"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(Po,{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))})]}),v?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(Yn,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${L?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(mo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(Yn,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${L?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(Eo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((fe=k==null?void 0:k.name)==null?void 0:fe.split(" ")[0])||"Account"})]})]}):I?e.jsx("button",{onClick:()=>o(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${L?"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 ${L?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:a?e.jsx(dr,{className:"h-5 w-5"}):e.jsx(YT,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${L?"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(T3,{bookingUrl:t.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),K.map(Ne=>e.jsx(Yn,{to:Ne.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===Ne.to?L?"bg-white/15 text-white":"bg-gray-100 text-gray-900":L?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Ne.label},Ne.to)),W&&ee.map(Ne=>{if(Ne.item_type==="dropdown"){const Ge=J(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 ${L?"text-white/40":"text-gray-400"}`,children:Ne.label}),Ge.map(_e=>e.jsx(Lre,{item:_e,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${L?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},_e.id))]},Ne.id)}return e.jsx(Lre,{item:Ne,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${L?"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 ${L?"text-white/40":"text-gray-400"}`,children:"Cities"}),u.map(Ne=>e.jsx(Yn,{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}`?L?"bg-white/15 text-white":"bg-gray-100 text-gray-900":L?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Ne.city_name},Ne.city_slug))]}),v?e.jsxs(e.Fragment,{children:[e.jsx(Yn,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${L?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"My Account"}),e.jsx("button",{onClick:async()=>{await C(),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${L?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"Sign Out"})]}):I?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${L?"text-white/70 hover:bg-white/10":"text-blue-600 hover:bg-blue-50"}`,children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!P&&e.jsx("footer",{className:"bg-gray-950 text-gray-400",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-16",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[((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:((Ee=t.agent)==null?void 0:Ee.title)||"Real Estate Professional"})]})]}),((Le=t.agent)==null?void 0:Le.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(pa,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((De=t.agent)==null?void 0:De.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(on,{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:[K.map(Ne=>e.jsx("li",{children:e.jsx(Yn,{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:O?"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(Yn,{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."]})]})]})]})}),!P&&((Be=t.agent)==null?void 0:Be.avatar_url)&&e.jsx(x8n,{agent:t.agent,bookingUrl:$}),l&&e.jsx(dYe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(BYe,{slug:t.subdomainSlug}),e.jsx($Ye,{slug:t.subdomainSlug}),e.jsx(qYe,{slug:t.subdomainSlug})]})}function x8n({agent:s,bookingUrl:t}){var i;const[n,r]=j.useState(!1),a=Hn();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(pa,{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(on,{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(dr,{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 Lre({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(Yn,{to:r,className:t,onClick:n,children:s.label})}const byt={california:"California DRE License",ca:"California DRE License"};function QBe(s){const t=(s||"").trim();if(!t)return"Real Estate License";const n=t.toLowerCase();return byt[n]?byt[n]:`${t.replace(/\b\w/g,a=>a.toUpperCase())} Real Estate License`}function _yt(s){if(s)return s.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function g8n({children:s,siteConfig:t}){var fe,Se,Ee,Le,De,Be,Ne,Ge;const n=$d(),r=Hn(),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState([]),[x,y]=j.useState(!1),g=j.useRef(null),b=j.useRef(null),{user:v,profile:k,signOut:C}=bTe();mYe(t,v==null?void 0:v.id),pYe(t,v==null?void 0:v.id);const T=((fe=t.agent)==null?void 0:fe.full_name)||"Agent",M=_yt(t.agentLicenseNumber),P=_yt(t.brokerageLicenseNumber),L=t.siteTitle||`${T} Real Estate`,I=_e=>{if(!_e)return _e;const Oe=T.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ae=new RegExp(`^\\s*${Oe}\\s*[|\\-–—:]\\s*`,"i");return _e.replace(Ae,"").trim()},O=L&&L!==`${T} Real Estate`?L:null,$=O?I(O):null,q=$&&$.toLowerCase()!==T.toLowerCase()?$:null,W=n.pathname==="/search",G=n.pathname==="/",K=t.leadRegistrationMode!=="disabled",ee="#c9a96e",J=t.bookingUrl;j.useEffect(()=>{const _e=()=>y(window.scrollY>80);return window.addEventListener("scroll",_e,{passive:!0}),()=>window.removeEventListener("scroll",_e)},[]),j.useEffect(()=>{(async()=>{const{data:Oe}=await U.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});p(Oe||[])})()},[t.id]),j.useEffect(()=>{const _e=Oe=>{g.current&&!g.current.contains(Oe.target)&&d(!1),b.current&&!b.current.contains(Oe.target)&&h(!1)};return document.addEventListener("mousedown",_e),()=>document.removeEventListener("mousedown",_e)},[]);const le=(((Se=t.themeConfig)==null?void 0:Se.focusPages)??[]).filter(_e=>_e==null?void 0:_e.slug).map(_e=>({to:`/${_e.slug}`,label:_e.navLabel||_e.title})),ue=[{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"}],oe=[...ue,...le],ie=t.siteTitle||`${T} - Real Estate`,de=t.siteTagline||`Browse homes and listings with ${T}`,we=t.ogImageUrl||((Ee=t.agent)==null?void 0:Ee.avatar_url)||"",je=`https://${t.subdomainSlug||""}.thelocalmove.com`,xe=G?x?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return e.jsxs("div",{className:`flex flex-col ${W?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(uYe,{siteConfig:t,pagePath:n.pathname}),e.jsx(hYe,{siteConfig:t}),e.jsxs(ql,{children:[e.jsx("title",{children:ie}),e.jsx("meta",{name:"description",content:de}),e.jsx("meta",{property:"og:title",content:ie}),e.jsx("meta",{property:"og:description",content:de}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:je+n.pathname}),we&&e.jsx("meta",{property:"og:image",content:we}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ie}),e.jsx("meta",{name:"twitter:description",content:de}),we&&e.jsx("meta",{name:"twitter:image",content:we}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${je}${n.pathname}`}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap",rel:"stylesheet"})]}),e.jsxs("header",{className:`${G?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${xe}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between min-h-20 py-3 gap-6",children:[e.jsx(Yn,{to:"/",className:"flex items-center gap-3 shrink-0",children:e.jsxs("span",{className:"flex flex-col leading-tight",children:[e.jsx("span",{className:"block whitespace-nowrap text-white text-base sm:text-lg xl:text-xl tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:T}),t.brokerageLegalName&&e.jsx("span",{className:"hidden sm:block whitespace-nowrap text-[10px] sm:text-[11px] tracking-[0.14em] uppercase text-white/60",children:t.brokerageLegalName}),q&&e.jsx("span",{className:"hidden xl:block whitespace-nowrap text-[10px] tracking-[0.18em] uppercase text-white/40",children:q})]})}),e.jsxs("nav",{className:"hidden lg:flex items-center justify-end gap-0 flex-1 min-w-0",children:[ue.map(_e=>e.jsx(Yn,{to:_e.to,className:`whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname===_e.to?"text-white":"text-white/40 hover:text-white"}`,children:_e.label},_e.to)),le.length>0&&e.jsxs("div",{ref:b,className:"relative",children:[e.jsxs("button",{onClick:()=>h(!u),className:`flex items-center gap-1 whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${le.some(_e=>n.pathname===_e.to)?"text-white":"text-white/40 hover:text-white"}`,children:["Specialty"," ",e.jsx(Po,{className:`h-3 w-3 transition-transform ${u?"rotate-180":""}`})]}),u&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:le.map(_e=>e.jsx(Yn,{to:_e.to,onClick:()=>h(!1),className:`block px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors ${n.pathname===_e.to?"text-white":""}`,children:_e.label},_e.to))})]}),m.length>0&&e.jsxs("div",{ref:g,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",e.jsx(Po,{className:`h-3 w-3 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:m.map(_e=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${_e.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:_e.city_name},_e.city_slug))})]}),v?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(Yn,{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(mo,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(Yn,{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(Eo,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((Le=k==null?void 0:k.name)==null?void 0:Le.split(" ")[0])||"Account"})]})]}):K?e.jsx("button",{onClick:()=>o(!0),className:"ml-3 px-5 py-2 text-xs tracking-[0.2em] uppercase border border-white/20 text-white/60 hover:bg-white hover:text-black transition-all duration-500",children:"Sign In"}):null,J&&e.jsx(T3,{bookingUrl:J,label:"Schedule",size:"sm",className:"ml-3",source:"nav"})]}),e.jsxs("button",{onClick:()=>i(!a),className:"lg:hidden p-2 text-white/60 hover:text-white",children:[e.jsx("div",{className:"flex flex-col items-center gap-0.5",children:a?e.jsx(dr,{className:"h-5 w-5"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-6 h-px bg-current"}),e.jsx("div",{className:"w-4 h-px bg-current mt-1.5"}),e.jsx("div",{className:"w-6 h-px bg-current mt-1.5"})]})}),e.jsx("span",{className:"text-[8px] tracking-[0.3em] uppercase mt-1 block",children:"MENU"})]})]})}),a&&e.jsx("div",{className:"lg:hidden border-t border-white/5 bg-[#0d0b0a]/98 backdrop-blur-lg",children:e.jsxs("div",{className:"px-6 py-4 space-y-1",children:[J&&e.jsx(T3,{bookingUrl:J,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),ue.map(_e=>e.jsx(Yn,{to:_e.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${n.pathname===_e.to?"text-white":"text-white/40 hover:text-white"}`,children:_e.label},_e.to)),le.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:ee},children:"Specialty"}),le.map(_e=>e.jsx(Yn,{to:_e.to,onClick:()=>i(!1),className:`block px-3 py-2.5 text-xs tracking-wider uppercase transition-colors ${n.pathname===_e.to?"text-white":"text-white/40 hover:text-white"}`,children:_e.label},_e.to))]}),m.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:ee},children:"Cities"}),m.map(_e=>e.jsx(Yn,{to:`/homes-for-sale-in-${_e.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:_e.city_name},_e.city_slug))]}),v?e.jsxs(e.Fragment,{children:[e.jsx(Yn,{to:"/account",onClick:()=>i(!1),className:"block px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"My Account"}),e.jsx("button",{onClick:async()=>{await C(),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign Out"})]}):K?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!W&&e.jsx("footer",{className:"bg-[#0a0908] text-white/70 border-t border-white/10",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-20",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-16",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-white text-xl tracking-tight mb-3",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:T}),e.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((De=t.agent)==null?void 0:De.title)||"Real Estate Professional"}),(M||P)&&e.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[M&&e.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[QBe(t.licenseState)," #",M]}),P&&e.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",P]})]}),((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(pa,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),((Ne=t.agent)==null?void 0:Ne.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(on,{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:ee},children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3",children:[oe.map(_e=>e.jsx("li",{children:e.jsx(Yn,{to:_e.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:_e.label})},_e.to)),J&&e.jsx("li",{children:e.jsx("a",{href:J,target:"_blank",rel:"noopener noreferrer",className:"text-xs tracking-wider uppercase transition-colors hover:opacity-80",style:{color:Yq},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:ee},children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-white/70 leading-relaxed mb-6",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:"Ready to experience luxury real estate? Let's connect."}),e.jsxs("div",{className:"flex flex-col items-start gap-3",children:[J&&e.jsx(T3,{bookingUrl:J,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),e.jsx(Yn,{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:[T," · ",t.brokerageLegalName]}),M&&e.jsxs("span",{children:[QBe(t.licenseState)," #",M]}),P&&e.jsxs("span",{children:["Brokerage #",P]})]}),t.mlsDisclaimerText&&e.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[t.mlsLogoUrl&&e.jsx("img",{src:t.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-70"}),e.jsx("p",{className:"text-[11px] text-white/70 leading-relaxed max-w-3xl text-center",children:t.mlsDisclaimerText})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[11px] text-white/70 tracking-wider uppercase",children:[t.equalHousingEnabled&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:e.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),e.jsx("span",{children:"Equal Housing Opportunity"})]}),e.jsxs("span",{children:["© ",new Date().getFullYear()," ",T,". Powered by LevelUp."]})]})]})]})}),!W&&((Ge=t.agent)==null?void 0:Ge.avatar_url)&&e.jsx(y8n,{agent:t.agent,agentLicense:M,siteConfig:t,accentColor:ee}),l&&e.jsx(dYe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:ee}),e.jsx(BYe,{slug:t.subdomainSlug}),e.jsx($Ye,{slug:t.subdomainSlug}),e.jsx(qYe,{slug:t.subdomainSlug})]})}function y8n({agent:s,agentLicense:t,siteConfig:n,accentColor:r}){var o;const[a,i]=j.useState(!1),l=Hn();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:QBe(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(pa,{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(on,{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(dr,{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 oG="#2c1810",Ck="#b8860b";function v8n({children:s,siteConfig:t}){var L,I,O;const n=$d();Hn();const[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState([]),[h,m]=j.useState(!1),p=j.useRef(null),{user:x,profile:y,signOut:g}=bTe();mYe(t,x==null?void 0:x.id),pYe(t,x==null?void 0:x.id);const b=((L=t.agent)==null?void 0:L.full_name)||"Agent",v=t.siteTitle||`${b} Land & Ranch`,k=n.pathname==="/",C=t.leadRegistrationMode!=="disabled";j.useEffect(()=>{const $=()=>m(window.scrollY>80);return window.addEventListener("scroll",$,{passive:!0}),()=>window.removeEventListener("scroll",$)},[]),j.useEffect(()=>{(async()=>{const{data:q}=await U.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");q&&u(q)})()},[t.id]),j.useEffect(()=>{const $=q=>{p.current&&!p.current.contains(q.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"}],M=h||!k?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",P=h||!k?oG:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(ql,{children:[e.jsx("title",{children:v}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700;800&family=Lora:wght@400;500;600&display=swap",rel:"stylesheet"})]}),e.jsx(uYe,{siteConfig:t}),e.jsx(hYe,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${M}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between h-16 md:h-20",children:[e.jsxs(Yn,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(RR,{className:"w-7 h-7",style:{color:Ck}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:P,fontFamily:"'Playfair Display', Georgia, serif"},children:v})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[T.map($=>e.jsx(Yn,{to:$.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:n.pathname===$.path?Ck:P},children:$.label},$.path)),d.length>0&&e.jsxs("div",{ref:p,className:"relative",children:[e.jsxs("button",{onClick:()=>c(!o),className:"px-4 py-2 text-sm font-medium tracking-wide uppercase flex items-center gap-1 transition-colors hover:opacity-80",style:{color:P},children:["Areas ",e.jsx(Po,{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(Yn,{to:`/homes-for-sale-in-${$.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:oG},onClick:()=>c(!1),children:$.city_name},$.city_slug))})]}),x?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(Yn,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:Ck,color:P},children:[e.jsx(Eo,{className:"w-4 h-4 inline mr-1.5"}),(y==null?void 0:y.name)||"Account"]})}):C?e.jsx("button",{onClick:()=>l(!0),className:"ml-3 px-5 py-2.5 text-sm font-semibold text-white rounded-full hover:shadow-lg transition-all hover:scale-105",style:{backgroundColor:Ck},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!r),className:"md:hidden p-2",style:{color:P},children:r?e.jsx(dr,{className:"w-6 h-6"}):e.jsx(YT,{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(Yn,{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?Ck:oG},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(Yn,{to:`/homes-for-sale-in-${$.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:oG},onClick:()=>a(!1),children:$.city_name},$.city_slug))]}),!x&&C&&e.jsx("button",{onClick:()=>{l(!0),a(!1)},className:"w-full mt-3 px-5 py-3 text-white font-semibold rounded-full",style:{backgroundColor:Ck},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:oG},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(RR,{className:"w-6 h-6",style:{color:Ck}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:v})]}),e.jsx("p",{className:"text-white/60 text-sm leading-relaxed",children:"Your trusted specialist in land, ranch, and rural properties. Expert guidance for every acre."})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-white font-semibold mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsx("div",{className:"space-y-2",children:T.map($=>e.jsx(Yn,{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:[((I=t.agent)==null?void 0:I.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-2 text-white/60 hover:text-white text-sm transition-colors",children:[e.jsx(pa,{className:"w-4 h-4",style:{color:Ck}}),t.agent.phone]}),((O=t.agent)==null?void 0:O.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(on,{className:"w-4 h-4",style:{color:Ck}}),t.agent.email]})]})]})]}),e.jsxs("div",{className:"mt-12 pt-8 border-t border-white/10 flex items-center justify-between",children:[e.jsxs("p",{className:"text-white/40 text-xs",children:["© ",new Date().getFullYear()," ",v,". All rights reserved."]}),e.jsx("div",{className:"h-px w-16",style:{backgroundColor:Ck}})]})]})}),i&&e.jsx(dYe,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(BYe,{slug:t.subdomainSlug}),e.jsx($Ye,{slug:t.subdomainSlug}),e.jsx(qYe,{slug:t.subdomainSlug})]})}function b8n(){const{pathname:s}=$d();return j.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[s]),null}const _8n=j.lazy(()=>Mi(()=>import("./LeadSiteHome-BlWsMnVB.js"),__vite__mapDeps([0,1,2,3,4]))),w8n=j.lazy(()=>Mi(()=>import("./LeadSiteLuxuryHome-RM_sMFXO.js"),__vite__mapDeps([5,2,3,4]))),j8n=j.lazy(()=>Mi(()=>import("./LeadSiteLandRanchHome-Cae7QDsl.js"),__vite__mapDeps([6,1,2,3,4]))),N8n=j.lazy(()=>Mi(()=>import("./LeadSiteSearch-DHUN_sPZ.js"),__vite__mapDeps([7,1,8,4,9]))),k8n=j.lazy(()=>Mi(()=>import("./LeadSiteLuxurySearch-YoFqLRzL.js"),__vite__mapDeps([10,1,8,4,9]))),S8n=j.lazy(()=>Mi(()=>import("./LeadSiteListingDetail-CU7xIBbl.js"),__vite__mapDeps([11,12,4,13]))),C8n=j.lazy(()=>Mi(()=>import("./LeadSiteLuxuryListingDetail-C9N50Ua6.js"),__vite__mapDeps([14,12,4,13]))),A8n=j.lazy(()=>Mi(()=>import("./LeadSiteAbout-CiiEv6Lp.js"),[])),T8n=j.lazy(()=>Mi(()=>import("./LeadSiteLuxuryAbout-D1MdX2sS.js"),[])),E8n=j.lazy(()=>Mi(()=>import("./LeadSiteContact-D3dI8slx.js"),[])),M8n=j.lazy(()=>Mi(()=>import("./LeadSiteLuxuryContact-DmFxmRUV.js"),[])),L8n=j.lazy(()=>Mi(()=>import("./LeadSiteConsumerDashboard-DrTyi5oz.js"),[])),wyt=j.lazy(()=>Mi(()=>import("./LeadSiteBlog-DUubUefS.js"),[])),P8n=j.lazy(()=>Mi(()=>import("./LeadSiteCommunity-vxj4LcJW.js"),[])),I8n=j.lazy(()=>Mi(()=>import("./LeadSiteSellers-CH3RPtte.js"),[])),R8n=j.lazy(()=>Mi(()=>import("./LeadSiteCityPage-BLS3CJTU.js"),__vite__mapDeps([15,4,9]))),D8n=j.lazy(()=>Mi(()=>import("./LeadSiteSubdivisionPage-CupSLk0R.js"),__vite__mapDeps([16,4]))),O8n=j.lazy(()=>Mi(()=>import("./LeadSiteCustomPage-BdKmVVzq.js"),[])),F8n=j.lazy(()=>Mi(()=>import("./LeadSiteFocusPage-BrTDiI1y.js"),__vite__mapDeps([17,3,4])));function z8n(){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 B8n(){var d;const{siteConfig:s,themeConfig:t,isLoading:n,error:r}=OEn();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?v8n:a?g8n:f8n,o=QBt(s,t),c=i?e.jsx(j8n,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(w8n,{siteConfig:s,themeConfig:t??void 0}):e.jsx(_8n,{siteConfig:s,themeConfig:t??void 0});return e.jsxs(zEn,{siteConfig:s,children:[e.jsx(b8n,{}),e.jsxs(l,{siteConfig:s,children:[e.jsx(j.Suspense,{fallback:e.jsx(z8n,{}),children:e.jsxs(GY,{children:[e.jsx(fs,{path:"/",element:c}),e.jsx(fs,{path:"/search",element:o?e.jsx(Tj,{to:"/contact",replace:!0}):a?e.jsx(k8n,{siteConfig:s}):e.jsx(N8n,{siteConfig:s})}),e.jsx(fs,{path:"/listing/:mlsNumber",element:o?e.jsx(Tj,{to:"/contact",replace:!0}):a?e.jsx(C8n,{siteConfig:s}):e.jsx(S8n,{siteConfig:s})}),e.jsx(fs,{path:"/about",element:a?e.jsx(T8n,{siteConfig:s}):e.jsx(A8n,{siteConfig:s})}),e.jsx(fs,{path:"/contact",element:a?e.jsx(M8n,{siteConfig:s}):e.jsx(E8n,{siteConfig:s})}),e.jsx(fs,{path:"/account",element:e.jsx(L8n,{siteConfig:s})}),e.jsx(fs,{path:"/blog",element:e.jsx(wyt,{siteConfig:s,isLuxury:a})}),e.jsx(fs,{path:"/blog/:slug",element:e.jsx(wyt,{siteConfig:s,isLuxury:a})}),e.jsx(fs,{path:"/sell",element:e.jsx(I8n,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(fs,{path:"/community",element:e.jsx(P8n,{siteConfig:s,isLuxury:a})}),e.jsx(fs,{path:"/schedule",element:e.jsx(HEn,{bookingUrl:s.bookingUrl,agentName:((d=s.agent)==null?void 0:d.full_name)||"your agent"})}),((t==null?void 0:t.focusPages)??[]).map(u=>e.jsx(fs,{path:`/${u.slug}`,element:e.jsx(F8n,{siteConfig:s,page:u,accentColor:(t==null?void 0:t.accentColor)||s.accentColor||"#c9a96e"})},u.slug)),e.jsx(fs,{path:"/p/:pageSlug",element:e.jsx(O8n,{siteConfig:s})}),e.jsx(fs,{path:"/*",element:e.jsx($8n,{siteConfig:s,referralMode:o})})]})}),e.jsx(VEn,{bookingUrl:s.bookingUrl})]})]})}function $8n({siteConfig:s,referralMode:t}){const n=$d(),r=n.pathname.match(/^\/homes-in-(.+)$/);if(r)return e.jsx(D8n,{siteConfig:s,subdivisionSlug:r[1]});const a=n.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(R8n,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}function U8n(){const{user:s,loading:t}=Ns(),{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 U.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key","levelup_attract").maybeSingle();if(i)throw i;return a?{hasAccess:a.enabled&&(!a.expires_at||new Date(a.expires_at).getTime()>Date.now()),tier:a.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:!!(n!=null&&n.hasAccess),tier:(n==null?void 0:n.tier)??null,isLoading:t||r}}function q8n({children:s}){const{user:t,loading:n}=Ns(),{hasAccess:r,isLoading:a}=U8n(),i=$d();return j.useEffect(()=>{!n&&!a&&t&&!r&&re.error("LevelUp Attract isn't available for your account yet.")},[n,a,t,r]),n||t&&a?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t?r?e.jsx(e.Fragment,{children:s}):e.jsx(Tj,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(Tj,{to:"/auth",replace:!0}))}function jyt({children:s}){const{user:t,loading:n}=Ns(),{hasAccess:r,isLoading:a}=nVe(),i=$d();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(Tj,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(Tj,{to:"/auth",replace:!0}))}const JBe={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"},V8n=["First-time buyers","Move-up buyers","Luxury","New construction","Investors","Relocation","Downsizing / seniors","Military / VA","Land & ranch","Waterfront","Condos","Multi-family"],H8n=["Buyers","Sellers","Both equally","Investors","Renters","Builders / developers"],G8n=["Warm & approachable","Bold & direct","Educational & analytical","Playful & funny","Polished & luxury","Down-to-earth & local","High-energy & motivational"],W8n=[{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"}],K8n=["Under $250k","$250k – $500k","$500k – $750k","$750k – $1M","$1M – $2M","$2M+"],Y8n=["Brand new (under 1 year)","1–3 years","3–5 years","5–10 years","10–20 years","20+ years"],Z8n=[{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"}],X8n=[{value:"instagram",label:"Instagram"},{value:"tiktok",label:"TikTok"},{value:"facebook",label:"Facebook"},{value:"youtube",label:"YouTube Shorts"},{value:"linkedin",label:"LinkedIn"}],Q8n=[{value:"15-30s",label:"15–30 seconds"},{value:"30-45s",label:"30–45 seconds"},{value:"45-60s",label:"45–60 seconds"}],J8n=[{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"}],eRn=[{value:"local",label:"Mostly local market content"},{value:"evergreen",label:"Mostly evergreen content"},{value:"mix",label:"A healthy mix of both"}];function LUt({value:s,label:t}){const[n,r]=j.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),re.success(`${t} copied`),setTimeout(()=>r(!1),1600)},children:[n?e.jsx(da,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ja,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}):null}function yM({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(LUt,{value:n,label:s}):null]}),e.jsx("div",{className:"text-[14.5px] leading-relaxed text-foreground whitespace-pre-wrap",children:t})]})}function R2e({reel:s,index:t,onUpdate:n,readOnly:r}){var c;const[a,i]=j.useState(t===0),l=!!s.recorded_at,o=!!s.posted_at;return e.jsx(be,{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(qe,{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(qe,{variant:"outline",className:"text-[10.5px] font-medium text-muted-foreground",children:JBe[s.category]??s.category}):null,o?e.jsx(qe,{className:"bg-emerald-100 text-emerald-800 border-0 text-[10.5px]",children:"Posted"}):l?e.jsx(qe,{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:Et("h-9 w-9 shrink-0",s.favorited&&"text-amber-500"),onClick:()=>n({favorited:!s.favorited}),children:e.jsx(Wa,{className:Et("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(LUt,{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(yM,{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(Zr,{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(Dr,{className:"h-3.5 w-3.5 mr-1.5"}),o?"Posted":"Mark as posted"]})]}):null,e.jsxs(i0,{open:a,onOpenChange:i,children:[e.jsx(o0,{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(Po,{className:Et("h-4 w-4 transition-transform",a&&"rotate-180")})]})}),e.jsxs(l0,{className:"space-y-5 pt-2",children:[e.jsx(Xl,{}),s.filming_directions?e.jsx(yM,{label:"How to film it",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(O9,{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(yM,{label:"Caption",copyValue:s.caption,children:s.caption}):null,(c=s.hashtags)!=null&&c.length?e.jsx(yM,{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(yM,{label:"Pinned comment",copyValue:s.pinned_comment,children:s.pinned_comment}):null,s.reply_strategy?e.jsx(yM,{label:"Reply strategy",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(ro,{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(yn,{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(yM,{label:"Bonus content idea",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(xN,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:s.bonus_idea})]})}):null]})]})]})})}function PUt(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 Nyt(){const s=PUt(),[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 vY(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 VYe(s){const{user:t}=Ns(),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 U.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 U.from("weekly_reel_packs").select("*").eq("user_id",n).order("week_start_date",{ascending:!1}).limit(52);if(m)throw m;const p=(h??[]).map(y=>y.id);let x=[];if(p.length){const{data:y,error:g}=await U.from("weekly_reels").select("*").in("pack_id",p).order("position",{ascending:!0});if(g)throw g;x=y??[]}return(h??[]).map(y=>({...y,reels:x.filter(g=>g.pack_id===y.id)}))}}),l=vt({mutationFn:async h=>{if(!n)throw new Error("Not signed in");const m={...h,user_id:n,...h.onboarding_completed?{onboarding_completed_at:new Date().toISOString()}:{}},{error:p}=await U.from("weekly_reel_profiles").upsert(m,{onConflict:"user_id"});if(p)throw p},onSuccess:()=>{r.invalidateQueries({queryKey:["weekly-reels-profile",n]})},onError:h=>re.error(h.message)}),o=vt({mutationFn:async({id:h,values:m})=>{const{error:p}=await U.from("weekly_reels").update(m).eq("id",h);if(p)throw p},onSuccess:()=>r.invalidateQueries({queryKey:["weekly-reels-packs",n]}),onError:h=>re.error(h.message)}),c=PUt(),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 Pre({icon:s,label:t,value:n}){return e.jsxs("div",{className:"neon-tile neon-topline px-4 py-3.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10.5px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("div",{className:"neon-stat mt-1.5 text-[17px] font-black leading-snug",children:n})]})}function tRn(){var O,$,q,W,G;const s=Hn(),{user:t}=Ns(),{profile:n,packs:r,currentPack:a,history:i,saveProfile:l,updateReel:o}=VYe(),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,p]=j.useState(""),[x,y]=j.useState("all"),[g,b]=j.useState("all"),v=(((O=n.data)==null?void 0:O.full_name)||(($=t==null?void 0:t.user_metadata)==null?void 0:$.full_name)||"there").split(" ")[0],k=!!((q=n.data)!=null&&q.onboarding_completed),C=j.useMemo(()=>(r.data??[]).flatMap(K=>K.reels.map(ee=>({reel:ee,pack:K}))),[r.data]),T=j.useMemo(()=>{const K=m.trim().toLowerCase();return C.filter(({pack:ee})=>g==="all"?!0:ee.week_start_date===g).filter(({reel:ee})=>x==="all"?!0:ee.category===x).filter(({reel:ee})=>K?`${ee.topic} ${ee.hook} ${ee.script}`.toLowerCase().includes(K):!0)},[C,m,x,g]),M=C.filter(({reel:K})=>K.favorited),P=async()=>{d(!0);try{const{data:K,error:ee}=await U.functions.invoke("weekly-reels-generate",{body:{action:"generate_pack",force:!0}});if(ee)throw ee;if(K!=null&&K.error)throw new Error(K.error);await r.refetch(),re.success(K!=null&&K.skipped?String(K.skipped):"Your pack is ready")}catch(K){re.error(K instanceof Error?K.message:"Generation failed")}finally{d(!1)}},L=async()=>{if(a){h(!0);try{const{data:K,error:ee}=await U.functions.invoke("weekly-reels-generate",{body:{action:"send_pack_email",packId:a.id}});if(ee)throw ee;if(K!=null&&K.error)throw new Error(K.error);await r.refetch(),re.success(`Sent to ${(K==null?void 0:K.recipient)??"your inbox"}`)}catch(K){re.error(K instanceof Error?K.message:"Could not send the email")}finally{h(!1)}}},I=K=>ee=>o.mutate({id:K.id,values:ee});return!n.isLoading&&!k?e.jsx(Vs,{title:"Weekly Reels",children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsx("div",{className:"relative mx-auto w-full max-w-2xl px-4 py-16 sm:px-6",children:e.jsxs(be,{className:"neon-topline p-8 text-center sm:p-12",children:[e.jsx("div",{className:"mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/15",children:e.jsx(wh,{className:"h-7 w-7 text-primary"})}),e.jsx("p",{className:"neon-eyebrow mt-6 font-semibold",children:"Weekly Reels"}),e.jsx("h1",{className:"neon-title mx-auto mt-2 w-fit text-3xl font-black uppercase tracking-tight sm:text-4xl",children:"5 Reels. Every Monday."}),e.jsx("p",{className:"mx-auto mt-3 max-w-md text-[15px] leading-relaxed text-muted-foreground",children:"Tell us about your market, your niche and how you actually talk. Then every Monday at 9:00 AM you get five ready-to-film Reels written for you — hook, word-for-word script, caption, hashtags and all."}),e.jsxs(B,{size:"lg",className:"neon-cta mt-7",onClick:()=>s("/weekly-reels/onboarding"),children:[e.jsx(yn,{className:"h-4 w-4 mr-2"})," Start setup — about 5 minutes"]})]})})})}):e.jsx(Vs,{title:"Weekly Reels",children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-5xl px-4 py-8 sm:px-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"neon-eyebrow font-semibold",children:"Weekly Reels"}),e.jsxs("h1",{className:"neon-title mt-2 w-fit text-3xl font-black uppercase tracking-tight sm:text-4xl",children:["Welcome back, ",v]}),e.jsx("p",{className:"mt-2 text-[15px] text-muted-foreground",children:"Your Reels for the week, written around your market and your voice."})]}),e.jsxs(B,{variant:"outline",onClick:()=>s("/weekly-reels/onboarding"),children:[e.jsx(tE,{className:"h-4 w-4 mr-2"})," Edit my profile"]})]}),e.jsxs(be,{className:"mt-6 p-5 sm:p-6",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Pre,{icon:Rr,label:"Onboarding",value:k?"Complete":"Incomplete"}),e.jsx(Pre,{icon:O9,label:"Weekly delivery",value:(W=n.data)!=null&&W.delivery_active?"Active":"Paused"}),e.jsx(Pre,{icon:ym,label:"Next pack",value:Nyt()}),e.jsx(Pre,{icon:on,label:"Email this week",value:(a==null?void 0:a.delivery_status)==="sent"?"Delivered":(a==null?void 0:a.delivery_status)==="failed"?"Failed":"Scheduled"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center justify-between gap-3 border-t border-border/60 pt-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Mn,{checked:!!((G=n.data)!=null&&G.delivery_active),onCheckedChange:K=>l.mutate({delivery_active:K}),"aria-label":"Weekly email delivery"}),e.jsx("span",{className:"text-[14px] text-muted-foreground",children:"Email me my pack every Monday at 9:00 AM ET"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&a.reels.length?e.jsxs(B,{variant:"outline",size:"sm",onClick:L,disabled:u,children:[u?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(on,{className:"h-4 w-4 mr-2"}),"Email me this week's pack"]}):null,e.jsxs(B,{size:"sm",className:"neon-cta",onClick:P,disabled:c,children:[c?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-2"}),a&&a.reels.length?"Regenerate this week":"Generate this week's pack"]})]})]})]}),e.jsxs(fa,{defaultValue:"current",className:"mt-8",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"current",children:"This week"}),e.jsx(ss,{value:"history",children:"History"}),e.jsxs(ss,{value:"saved",children:["Saved",M.length?` (${M.length})`:""]})]}),e.jsx(ns,{value:"current",className:"mt-6",children:r.isLoading?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a&&a.reels.length?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[e.jsxs(qe,{variant:"outline",className:"text-[11.5px]",children:["Week of ",vY(a.week_start_date)]}),e.jsxs("span",{className:"text-[13px] text-muted-foreground",children:[a.reels.filter(K=>K.posted_at).length," of ",a.reels.length," posted"]})]}),e.jsx("div",{className:"space-y-4",children:a.reels.map((K,ee)=>e.jsx(R2e,{reel:K,index:ee,onUpdate:I(K)},K.id))})]}):e.jsxs(be,{className:"neon-topline p-10 text-center sm:p-14",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-muted",children:e.jsx(wh,{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: ",Nyt(),". Don't want to wait? Write them now."]}),e.jsxs(B,{className:"neon-cta mt-6",onClick:P,disabled:c,children:[c?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Generate it now"]})]})}),e.jsxs(ns,{value:"history",className:"mt-6",children:[e.jsx(be,{className:"rounded-2xl p-4 sm:p-5",children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr_auto_auto]",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{value:m,onChange:K=>p(K.target.value),placeholder:"Search topics and scripts...",className:"pl-9"})]}),e.jsxs(vs,{value:x,onValueChange:y,children:[e.jsx(gs,{className:"sm:w-[190px]",children:e.jsx(bs,{placeholder:"All topics"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All topics"}),Object.entries(JBe).map(([K,ee])=>e.jsx(Je,{value:K,children:ee},K))]})]}),e.jsxs(vs,{value:g,onValueChange:b,children:[e.jsx(gs,{className:"sm:w-[180px]",children:e.jsx(bs,{placeholder:"All weeks"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All weeks"}),(r.data??[]).map(K=>e.jsx(Je,{value:K.week_start_date,children:vY(K.week_start_date)},K.id))]})]})]})}),T.length?e.jsx(vO,{type:"multiple",className:"mt-4 space-y-3",children:T.map(({reel:K,pack:ee})=>e.jsxs(l6,{value:K.id,className:"rounded-2xl border border-border/70 bg-card px-4 sm:px-5",children:[e.jsx(c6,{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(qe,{variant:"outline",className:"text-[10.5px] shrink-0",children:vY(ee.week_start_date)}),K.category?e.jsx(qe,{className:"bg-muted text-muted-foreground border-0 text-[10.5px] shrink-0",children:JBe[K.category]??K.category}):null,e.jsx("span",{className:"truncate text-[14.5px] font-medium text-foreground",children:K.topic})]})}),e.jsx(d6,{className:"pb-4",children:e.jsx(R2e,{reel:K,index:K.position-1,onUpdate:I(K)})})]},K.id))}):e.jsxs(be,{className:"mt-4 rounded-2xl p-10 text-center sm:p-14",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-muted",children:e.jsx(Fr,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("h3",{className:"mt-5 text-lg font-semibold text-foreground",children:"Nothing here yet"}),e.jsx("p",{className:"mx-auto mt-2 max-w-sm text-[14.5px] text-muted-foreground",children:C.length?"No Reels match these filters. Try widening your search.":"Your past packs will collect here once a few weeks have gone by."})]})]}),e.jsx(ns,{value:"saved",className:"mt-6",children:M.length?e.jsx("div",{className:"space-y-4",children:M.map(({reel:K},ee)=>e.jsx(R2e,{reel:K,index:ee,onUpdate:I(K)},K.id))}):e.jsxs(be,{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 vM=[{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 sRn(){const s=Hn(),{user:t}=Ns(),{profile:n,saveProfile:r}=VYe(),[a,i]=j.useState(0),[l,o]=j.useState({specialties:[],client_types:[],brand_voice:[],preferred_reel_length:"30-45s",main_platform:"instagram",content_mix:"mix"}),[c,d]=j.useState(!1),[u,h]=j.useState(!1);j.useEffect(()=>{u||n.isLoading||(o(v=>{var k,C,T,M,P,L;return{...v,...n.data??{},full_name:((k=n.data)==null?void 0:k.full_name)??((C=t==null?void 0:t.user_metadata)==null?void 0:C.full_name)??"",email:((T=n.data)==null?void 0:T.email)??(t==null?void 0:t.email)??"",specialties:((M=n.data)==null?void 0:M.specialties)??[],client_types:((P=n.data)==null?void 0:P.client_types)??[],brand_voice:((L=n.data)==null?void 0:L.brand_voice)??[]}}),h(!0))},[n.isLoading,n.data,t,u]);const m=(v,k)=>o(C=>({...C,[v]:k})),p=(v,k)=>o(C=>{const T=C[v]??[];return{...C,[v]:T.includes(k)?T.filter(M=>M!==k):[...T,k]}}),x=j.useMemo(()=>{var v,k,C;return a===0?!!((v=l.full_name)!=null&&v.trim())&&!!((k=l.email)!=null&&k.trim()):a===1?!!((C=l.primary_market)!=null&&C.trim()):a===2?(l.brand_voice??[]).length>0:!0},[a,l]),y=async(v,k)=>{if(t){d(!0);try{const C=v.name.split(".").pop(),T=`${t.id}/weekly-reels-${k}-${Date.now()}.${C}`,{error:M}=await U.storage.from("avatars").upload(T,v,{upsert:!0});if(M)throw M;const{data:P}=U.storage.from("avatars").getPublicUrl(T);m(k,P.publicUrl),re.success("Image uploaded")}catch(C){re.error(C instanceof Error?C.message:"Upload failed")}finally{d(!1)}}},g=async()=>{await r.mutateAsync({...l,onboarding_completed:!0}),re.success("You're all set — your first pack is on the way."),s("/weekly-reels")},b=async()=>{await r.mutateAsync(l),re.success("Progress saved")};return e.jsx(Vs,{title:"Weekly Reels",children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-3xl px-4 py-8 sm:px-6",children:[e.jsxs("div",{className:"mb-8",children:[e.jsx("p",{className:"neon-eyebrow font-semibold",children:"Weekly Reels"}),e.jsx("h1",{className:"neon-title mt-2 w-fit text-3xl font-black uppercase tracking-tight sm:text-4xl",children:"Let's make these scripts sound like you"}),e.jsx("p",{className:"mt-2 text-[15px] leading-relaxed text-muted-foreground",children:"Five minutes now means every Monday you get 5 Reels built around your market, your niche and your personality — not generic real estate filler."})]}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center justify-between text-[12.5px] font-medium text-muted-foreground",children:[e.jsxs("span",{children:["Step ",a+1," of ",vM.length," · ",vM[a].title]}),e.jsxs("span",{className:"neon-stat font-black",children:[Math.round((a+1)/vM.length*100),"%"]})]}),e.jsx(qi,{value:(a+1)/vM.length*100,className:"mt-2 h-1.5"})]}),e.jsxs(be,{className:"neon-topline rounded-2xl p-5 sm:p-7",children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight text-foreground",children:vM[a].title}),e.jsx("p",{className:"mt-1 text-[14px] text-muted-foreground",children:vM[a].blurb}),e.jsxs("div",{className:"mt-6 space-y-5",children:[a===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Full name *"}),e.jsx(ye,{value:l.full_name??"",onChange:v=>m("full_name",v.target.value),placeholder:"Jane Realtor"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email *"}),e.jsx(ye,{type:"email",value:l.email??"",onChange:v=>m("email",v.target.value),placeholder:"jane@brokerage.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Mobile number"}),e.jsx(ye,{value:l.mobile_number??"",onChange:v=>m("mobile_number",v.target.value),placeholder:"Optional"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(ye,{value:l.brokerage??"",onChange:v=>m("brokerage",v.target.value)})]})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:["headshot_url","logo_url"].map(v=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{children:[v==="headshot_url"?"Headshot":"Logo"," (optional)"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[l[v]?e.jsx("img",{src:l[v],alt:v==="headshot_url"?"Your headshot":"Your logo",className:"h-12 w-12 rounded-lg object-cover"}):null,e.jsxs("label",{className:"flex-1",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:k=>{var T;const C=(T=k.target.files)==null?void 0:T[0];C&&y(C,v)}}),e.jsxs("span",{className:"flex h-10 cursor-pointer items-center justify-center gap-2 rounded-md border border-input text-[13.5px] text-muted-foreground hover:bg-accent",children:[c?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ja,{className:"h-4 w-4"}),"Upload"]})]})]})]},v))})]}),a===1&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Primary market — city & state *"}),e.jsx(ye,{value:l.primary_market??"",onChange:v=>m("primary_market",v.target.value),placeholder:"Tulsa, OK"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Neighborhoods or service areas"}),e.jsx(Ds,{rows:2,value:l.service_areas??"",onChange:v=>m("service_areas",v.target.value),placeholder:"Jenks, Bixby, Broken Arrow, midtown Tulsa"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Years in real estate"}),e.jsxs(vs,{value:l.years_in_real_estate??"",onValueChange:v=>m("years_in_real_estate",v),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:Y8n.map(v=>e.jsx(Je,{value:v,children:v},v))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Typical price point"}),e.jsxs(vs,{value:l.typical_price_point??"",onValueChange:v=>m("typical_price_point",v),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:K8n.map(v=>e.jsx(Je,{value:v,children:v},v))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Primary specialties / niches"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:V8n.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(wi,{checked:(l.specialties??[]).includes(v),onCheckedChange:()=>p("specialties",v)}),v]},v))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Client types you serve"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:H8n.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(wi,{checked:(l.client_types??[]).includes(v),onCheckedChange:()=>p("client_types",v)}),v]},v))})]})]}),a===2&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Brand voice — pick everything that fits *"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:G8n.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(wi,{checked:(l.brand_voice??[]).includes(v),onCheckedChange:()=>p("brand_voice",v)}),v]},v))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Anything else about how you talk?"}),e.jsx(Ds,{rows:2,value:l.brand_voice_notes??"",onChange:v=>m("brand_voice_notes",v.target.value),placeholder:"I say 'y'all' a lot and I hate corporate jargon."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Humor level"}),e.jsx(ob,{value:l.humor_level??"",onValueChange:v=>m("humor_level",v),className:"space-y-1.5",children:W8n.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(eh,{value:v.value}),v.label]},v.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Personal interests & hobbies"}),e.jsx(Ds,{rows:2,value:l.personal_interests??"",onChange:v=>m("personal_interests",v.target.value),placeholder:"Golf, smoking brisket, coaching my son's baseball team"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Family or community details you're happy to reference"}),e.jsx(Ds,{rows:2,value:l.family_community_notes??"",onChange:v=>m("family_community_notes",v.target.value),placeholder:"Married with two kids, active in the Jenks chamber"})]})]}),a===3&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Preferred Reel length"}),e.jsxs(vs,{value:l.preferred_reel_length??"30-45s",onValueChange:v=>m("preferred_reel_length",v),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Q8n.map(v=>e.jsx(Je,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Preferred CTA style"}),e.jsxs(vs,{value:l.preferred_cta_style??"",onValueChange:v=>m("preferred_cta_style",v),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:Z8n.map(v=>e.jsx(Je,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Main social platform"}),e.jsxs(vs,{value:l.main_platform??"instagram",onValueChange:v=>m("main_platform",v),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:X8n.map(v=>e.jsx(Je,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Instagram handle"}),e.jsx(ye,{value:l.instagram_handle??"",onChange:v=>m("instagram_handle",v.target.value),placeholder:"@janerealtor"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Website"}),e.jsx(ye,{value:l.website??"",onChange:v=>m("website",v.target.value),placeholder:"https://janerealtor.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"On-camera comfort level"}),e.jsx(ob,{value:l.content_comfort_level??"",onValueChange:v=>m("content_comfort_level",v),className:"space-y-1.5",children:J8n.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(eh,{value:v.value}),v.label]},v.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Local vs evergreen content"}),e.jsx(ob,{value:l.content_mix??"mix",onValueChange:v=>m("content_mix",v),className:"space-y-1.5",children:eRn.map(v=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(eh,{value:v.value}),v.label]},v.value))})]})]}),a===4&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Topics you love talking about"}),e.jsx(Ds,{rows:2,value:l.topics_enjoyed??"",onChange:v=>m("topics_enjoyed",v.target.value),placeholder:"Renovation ROI, negotiating repairs, small-town living"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Topics you never want to cover"}),e.jsx(Ds,{rows:2,value:l.topics_avoided??"",onChange:v=>m("topics_avoided",v.target.value),placeholder:"Politics, interest rate predictions, dancing trends"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Lead magnets or offers to promote"}),e.jsx(Ds,{rows:2,value:l.lead_magnets??"",onChange:v=>m("lead_magnets",v.target.value),placeholder:"Free home value report, first-time buyer guide"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Current business goals"}),e.jsx(Ds,{rows:2,value:l.business_goals??"",onChange:v=>m("business_goals",v.target.value),placeholder:"Two listings a month and more sphere referrals"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Compliance or brokerage disclaimer notes"}),e.jsx(Ds,{rows:2,value:l.compliance_notes??"",onChange:v=>m("compliance_notes",v.target.value),placeholder:"Must include brokerage name on any listing content"})]})]})]}),e.jsxs("div",{className:"mt-8 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs(B,{type:"button",variant:"ghost",disabled:a===0,onClick:()=>i(v=>Math.max(0,v-1)),children:[e.jsx(_a,{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:b,disabled:r.isPending,children:"Save draft"}),ai(v=>v+1),children:["Continue ",e.jsx(Xa,{className:"h-4 w-4 ml-1.5"})]}):e.jsxs(B,{className:"neon-cta",type:"button",onClick:g,disabled:r.isPending,children:[r.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(da,{className:"h-4 w-4 mr-1.5"}),"Finish setup"]})]})]})]})]})})})}function IUt(s,t=!1){const{user:n}=Ns(),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:O,error:$}=await U.from("feature_entitlements").select("user_id").eq("feature_key",d9).eq("enabled",!0);if($)throw $;if(y=(O??[]).map(q=>q.user_id),!y.length)return[]}let g=U.from("profiles").select("id, email, name").order("name",{ascending:!0}).limit(t?1e3:100);if(y&&(g=g.in("id",y)),s.trim()){const O=`%${s.trim()}%`;g=g.or(`email.ilike.${O},name.ilike.${O}`)}const{data:b,error:v}=await g;if(v)throw v;const k=(b??[]).map(O=>O.id);if(!k.length)return[];const[{data:C},{data:T},{data:M}]=await Promise.all([U.from("feature_entitlements").select("user_id, enabled, tier, expires_at").eq("feature_key",d9).in("user_id",k),U.from("weekly_reel_profiles").select("user_id, onboarding_completed, delivery_active, primary_market").in("user_id",k),U.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})]),P=new Map((C??[]).map(O=>[O.user_id,O])),L=new Map((T??[]).map(O=>[O.user_id,O])),I=new Map;return(M??[]).forEach(O=>{I.has(O.user_id)||I.set(O.user_id,O)}),(b??[]).map(O=>{const $=P.get(O.id),q=L.get(O.id),W=I.get(O.id);return{user_id:O.id,email:O.email,full_name:O.name,enabled:!!($!=null&&$.enabled),tier:($==null?void 0:$.tier)??null,expires_at:($==null?void 0:$.expires_at)??null,onboarded:!!(q!=null&&q.onboarding_completed),delivery_active:(q==null?void 0:q.delivery_active)??!1,primary_market:(q==null?void 0:q.primary_market)??null,latest_week:(W==null?void 0:W.week_start_date)??null,latest_pack_id:(W==null?void 0:W.id)??null,latest_generation_status:(W==null?void 0:W.generation_status)??null,latest_delivery_status:(W==null?void 0:W.delivery_status)??null}})}}),i=mt({queryKey:["wr-admin-generation-logs"],enabled:!!n,queryFn:async()=>{const{data:y,error:g}=await U.from("weekly_reel_generation_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(g)throw g;return y??[]}}),l=mt({queryKey:["wr-admin-delivery-logs"],enabled:!!n,queryFn:async()=>{const{data:y,error:g}=await U.from("weekly_reel_delivery_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(g)throw g;return y??[]}}),o=()=>{r.invalidateQueries({queryKey:["wr-admin-members"]}),r.invalidateQueries({queryKey:["wr-admin-generation-logs"]}),r.invalidateQueries({queryKey:["wr-admin-delivery-logs"]})},c=vt({mutationFn:async({userId:y,enabled:g})=>{const{error:b}=await U.from("feature_entitlements").upsert({user_id:y,feature_key:d9,enabled:g,tier:"member",enabled_by:n.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(b)throw b;await U.from("feature_entitlement_audit").insert({feature_key:d9,target_user_id:y,action:g?"grant":"revoke",performed_by:n.id})},onSuccess:(y,g)=>{o(),re.success(g.enabled?"Access granted":"Access revoked")},onError:y=>re.error(y.message)}),d=async y=>{const{data:g,error:b}=await U.functions.invoke("weekly-reels-generate",{body:y});if(b)throw b;if(g!=null&&g.error)throw new Error(String(g.error));return g},u=vt({mutationFn:y=>d({action:"generate_pack",userId:y.userId,force:y.force??!0}),onSuccess:()=>{o(),re.success("Pack generated")},onError:y=>re.error(y.message)}),h=vt({mutationFn:y=>d({action:"regenerate_reel",reelId:y.reelId,instructions:y.instructions}),onSuccess:()=>{o(),re.success("Reel regenerated")},onError:y=>re.error(y.message)}),m=vt({mutationFn:y=>d({action:"send_pack_email",packId:y.packId}),onSuccess:()=>{o(),re.success("Pack emailed")},onError:y=>re.error(y.message)}),p=vt({mutationFn:y=>d({action:"send_test_email",packId:y.packId,to:y.to}),onSuccess:()=>re.success("Test email sent"),onError:y=>re.error(y.message)}),x=vt({mutationFn:()=>d({action:"run_weekly"}),onSuccess:y=>{o(),re.success(`Weekly run complete${(y==null?void 0:y.processed)!=null?` — ${y.processed} agents`:""}`)},onError:y=>re.error(y.message)});return{members:a,generationLogs:i,deliveryLogs:l,setAccess:c,generatePack:u,regenerateReel:h,sendPack:m,sendTest:p,runWeekly:x}}function k9({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(qe,{className:`${t} border-0 text-[11px] capitalize`,children:s})}function nRn({member:s,onClose:t}){var m,p,x;const n=IUt(""),{packs:r,profile:a}=VYe(s==null?void 0:s.user_id),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(null),h=((m=r.data)==null?void 0:m[0])??null;return e.jsx(Fs,{open:!!s,onOpenChange:y=>!y&&t(),children:e.jsxs(Os,{className:"max-w-3xl max-h-[88vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:(s==null?void 0:s.full_name)||(s==null?void 0:s.email)}),e.jsxs(kr,{children:[((p=a.data)==null?void 0:p.primary_market)??"No market on file"," ·"," ",(x=a.data)!=null&&x.onboarding_completed?"Onboarded":"Onboarding incomplete"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>s&&n.generatePack.mutate({userId:s.user_id}),disabled:n.generatePack.isPending,children:[n.generatePack.isPending?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yn,{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(on,{className:"h-4 w-4 mr-2"})," Email latest pack"]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 rounded-xl bg-muted/60 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-[200px] space-y-1.5",children:[e.jsx(se,{className:"text-[12px]",children:"Send a test copy to"}),e.jsx(ye,{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(Dr,{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(qe,{variant:"outline",children:["Week of ",vY(h.week_start_date)]}),e.jsx(k9,{value:h.generation_status}),e.jsx(k9,{value:h.delivery_status})]}),h.reels.map((y,g)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(R2e,{reel:y,index:g,readOnly:!0}),d===y.id?e.jsxs("div",{className:"rounded-xl border border-border/70 p-3 space-y-2",children:[e.jsx(Ds,{rows:2,value:o,onChange:b=>c(b.target.value),placeholder:"Optional guidance: make it more local, less salesy, focus on sellers..."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ki,{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(Ki,{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(Nr,{children:e.jsx(B,{variant:"outline",onClick:t,children:"Close"})})]})})}function rRn(){const[s,t]=j.useState(""),[n,r]=j.useState(!1),[a,i]=j.useState(null),l=IUt(s,n),o=j.useMemo(()=>l.members.data??[],[l.members.data]);return e.jsxs(Vs,{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(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Run this week now"]})]}),e.jsxs(fa,{defaultValue:"members",className:"mt-7",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"members",children:"Members"}),e.jsx(ss,{value:"generation",children:"Generation log"}),e.jsx(ss,{value:"delivery",children:"Delivery log"})]}),e.jsxs(ns,{value:"members",className:"mt-5",children:[e.jsx(be,{className:"rounded-2xl p-4 sm:p-5",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"relative min-w-[220px] flex-1",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{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(Mn,{checked:n,onCheckedChange:r}),"Only members with access"]})]})}),e.jsx(be,{className:"mt-4 rounded-2xl overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Market"}),e.jsx(Tt,{children:"Onboarded"}),e.jsx(Tt,{children:"Latest week"}),e.jsx(Tt,{children:"Generation"}),e.jsx(Tt,{children:"Delivery"}),e.jsx(Tt,{className:"text-right",children:"Access"}),e.jsx(Tt,{})]})}),e.jsx(za,{children:l.members.isLoading?e.jsx(un,{children:e.jsx(xt,{colSpan:8,className:"py-10 text-center",children:e.jsx(Wt,{className:"mx-auto h-5 w-5 animate-spin text-muted-foreground"})})}):o.length?o.map(c=>e.jsxs(un,{children:[e.jsxs(xt,{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(xt,{className:"text-[13.5px] text-muted-foreground",children:c.primary_market||"—"}),e.jsx(xt,{children:c.onboarded?e.jsx(qe,{className:"bg-emerald-100 text-emerald-800 border-0 text-[11px]",children:"Yes"}):e.jsx("span",{className:"text-muted-foreground",children:"No"})}),e.jsx(xt,{className:"text-[13.5px] text-muted-foreground",children:c.latest_week?vY(c.latest_week):"—"}),e.jsx(xt,{children:e.jsx(k9,{value:c.latest_generation_status})}),e.jsx(xt,{children:e.jsx(k9,{value:c.latest_delivery_status})}),e.jsx(xt,{className:"text-right",children:e.jsx(Mn,{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(xt,{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(xt,{colSpan:8,className:"py-10 text-center text-muted-foreground",children:"No members match this search."})})})]})})]}),e.jsx(ns,{value:"generation",className:"mt-5",children:e.jsx(be,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"When"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Model"}),e.jsx(Tt,{children:"Tokens"}),e.jsx(Tt,{children:"Cost"}),e.jsx(Tt,{children:"Error"})]})}),e.jsx(za,{children:(l.generationLogs.data??[]).map(c=>e.jsxs(un,{children:[e.jsx(xt,{className:"text-[13px]",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsx(xt,{children:e.jsx(k9,{value:c.status})}),e.jsx(xt,{className:"text-[13px] text-muted-foreground",children:c.model??"—"}),e.jsx(xt,{className:"text-[13px]",children:c.total_tokens??0}),e.jsxs(xt,{className:"text-[13px]",children:["$",Number(c.estimated_cost??0).toFixed(4)]}),e.jsx(xt,{className:"max-w-[280px] truncate text-[12.5px] text-muted-foreground",children:c.error_message??"—"})]},c.id))})]})})}),e.jsx(ns,{value:"delivery",className:"mt-5",children:e.jsx(be,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Oa,{children:[e.jsx(Fa,{children:e.jsxs(un,{children:[e.jsx(Tt,{children:"When"}),e.jsx(Tt,{children:"Recipient"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Error"})]})}),e.jsx(za,{children:(l.deliveryLogs.data??[]).map(c=>e.jsxs(un,{children:[e.jsx(xt,{className:"text-[13px]",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsx(xt,{className:"text-[13px]",children:c.recipient_email??"—"}),e.jsx(xt,{children:e.jsx(k9,{value:c.status})}),e.jsx(xt,{className:"max-w-[280px] truncate text-[12.5px] text-muted-foreground",children:c.failure_reason??"—"})]},c.id))})]})})})]})]}),e.jsx(nRn,{member:a,onClose:()=>i(null)})]})}function Zq(){const{user:s}=Ns(),t=as(),n=mt({queryKey:["attract-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await U.from("attract_settings").select("*").eq("user_id",s.id).maybeSingle();if(l)throw l;return i}}),r=vt({mutationFn:async i=>{const l={...i,user_id:s.id},{data:o,error:c}=await U.from("attract_settings").upsert(l,{onConflict:"user_id"}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),re.success("Settings saved")},onError:i=>re.error(i.message)}),a=vt({mutationFn:async()=>{const{error:i}=await U.from("attract_settings").update({onboarding_completed_at:null}).eq("user_id",s.id);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),re.success("Onboarding reset — run it again anytime")}});return{settings:n.data,isLoading:n.isLoading,save:r,upsert:r,resetOnboarding:a}}const RUt="v1",xh={recency:22,consistency:16,value_delivered:14,kit_engagement:16,event_participation:12,follow_up_discipline:10,pipeline_momentum:10};Object.values(xh).reduce((s,t)=>s+t,0);const DUt=864e5,Qx=(s,t=new Date)=>Math.floor((new Date(t).getTime()-new Date(s).getTime())/DUt),OUt=["touch_logged","call","text","email","dm","meeting","note"];function aRn(s,t,n=new Date){var y,g,b;const a=t.activities.filter(v=>v.agent_id===s.id).filter(v=>OUt.includes(v.activity_type)).sort((v,k)=>+new Date(k.created_at)-+new Date(v.created_at)),i=s.last_touch_at||((y=a[0])==null?void 0:y.created_at)||null,l=t.shares.filter(v=>v.agent_id===s.id),o=new Set(l.map(v=>v.id)),c=t.kitEvents.filter(v=>o.has(v.share_id)),d={};for(const v of l)d[v.id]=[];for(const v of c)(d[g=v.share_id]||(d[g]=[])).push(v);const u=t.attendees.filter(v=>v.agent_id===s.id),h=t.followUps.filter(v=>v.agent_id===s.id),m=h.filter(v=>!v.completed_at),p=t.stageChanges.filter(v=>v.agent_id===s.id).sort((v,k)=>+new Date(k.created_at)-+new Date(v.created_at)),x=new Set(a.filter(v=>Qx(v.created_at,n)<=180).map(v=>v.created_at.slice(0,7)));return{agent:s,touches:a,lastTouchAt:i,daysSinceTouch:i?Qx(i,n):null,touches90:a.filter(v=>Qx(v.created_at,n)<=90).length,touches30:a.filter(v=>Qx(v.created_at,n)<=30).length,distinctTouchMonths:x.size,shares:l,shareEvents:d,highIntentShares:l.filter(v=>v.engagement_level==="high_intent"||v.engagement_level==="engaged"),lastShareAt:l.map(v=>v.created_at).sort().reverse()[0]||null,totalKitOpens:l.reduce((v,k)=>v+(k.open_count||0),0),downloads:c.filter(v=>v.event_type==="file_download").length,ctaClicks:c.filter(v=>v.event_type==="primary_cta_click"||v.event_type==="external_link_click").length,questions:c.filter(v=>v.event_type==="question_submitted").length,meetingRequests:c.filter(v=>v.event_type==="meeting_requested").length+u.filter(v=>v.meeting_requested).length,attendees:u,attended:u.filter(v=>!!v.checked_in_at||v.status==="attended").length,noShows:u.filter(v=>!!v.no_show_at||v.status==="no_show").length,invitedNotRegistered:u.filter(v=>!!v.invited_at&&!v.registered_at&&!v.checked_in_at).length,openFollowUps:m,overdueFollowUps:m.filter(v=>v.due_at&&new Date(v.due_at)!!v.completed_at),stageChanges:p,lastStageChangeAt:((b=p[0])==null?void 0:b.created_at)||null,daysSinceStageChange:p[0]?Qx(p[0].created_at,n):null,scoreEvents:t.scoreEvents.filter(v=>v.agent_id===s.id)}}const D2e=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined"],O2e=["not_right_now","not_a_fit","long_term_relationship"];function iRn(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=xh.recency,c=`Last meaningful touch ${l} day(s) ago.`,r.push("Recent personal contact")):l<=21?(o=xh.recency*.85,c=`Last touch ${l} days ago.`,r.push("Contact is still fresh")):l<=45?(o=xh.recency*.6,c=`Last touch ${l} days ago.`,i.push("Reach out within the next week to keep momentum.")):l<=90?(o=xh.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=xh.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:xh.recency,earned:Math.round(o),detail:c,direction:o>=xh.recency*.6?"positive":"negative"});const d=Math.min(s.distinctTouchMonths,6),u=xh.consistency*(d/6),h=s.touches30>6;n.push({key:"consistency",label:"Consistency of touches",weight:xh.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>=xh.consistency*.5?"positive":"neutral"}),d>=4&&r.push("Consistent rhythm across months"),d<=1&&i.push("Aim for at least one touch per month rather than bursts."),h&&a.push(`${s.touches30} touches in the last 30 days — give them room to breathe`);const m=s.shares.length,p=xh.value_delivered*Math.min(m/3,1);n.push({key:"value_delivered",label:"Value delivered",weight:xh.value_delivered,earned:Math.round(p),detail:m?`${m} resource kit share(s) sent.`:"No resource kit shared yet.",direction:m?"positive":"neutral"}),m?r.push(`${m} resource kit share(s) delivered`):i.push("Share a relevant Resource Kit — value first, no ask.");const x=(s.totalKitOpens>0?4:0)+Math.min(s.downloads,2)*2+Math.min(s.ctaClicks,2)*2+(s.questions>0?2:0)+(s.meetingRequests>0?4:0),y=Math.min(x,xh.kit_engagement);n.push({key:"kit_engagement",label:"Kit engagement",weight:xh.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 g=Math.min(s.attended,2)*5+(s.attendees.length?2:0)-Math.min(s.noShows,2)*2,b=Math.max(0,Math.min(g,xh.event_participation));n.push({key:"event_participation",label:"Event participation",weight:xh.event_participation,earned:b,detail:s.attendees.length?`${s.attended} attended, ${s.noShows} no-show(s), ${s.attendees.length} total invitation(s)/registration(s).`:"Never invited to an event.",direction:b>0?"positive":"neutral"}),s.attended>0&&r.push(`${s.attended} event(s) attended`),s.attendees.length||i.push("Invite them to your next event or mastermind."),s.noShows>0&&a.push(`${s.noShows} no-show(s)`);const v=s.completedFollowUps.length+s.openFollowUps.length;let k=v===0?xh.follow_up_discipline*.4:xh.follow_up_discipline*(s.completedFollowUps.length/v);k-=Math.min(s.overdueFollowUps.length,3)*2,k=Math.max(0,Math.min(k,xh.follow_up_discipline)),n.push({key:"follow_up_discipline",label:"Follow-up discipline",weight:xh.follow_up_discipline,earned:Math.round(k),detail:v?`${s.completedFollowUps.length} of ${v} follow-ups completed, ${s.overdueFollowUps.length} overdue.`:"No follow-ups created yet.",direction:s.overdueFollowUps.length?"negative":"positive"}),s.overdueFollowUps.length&&(a.push(`${s.overdueFollowUps.length} overdue commitment(s)`),i.push("Clear the overdue follow-up you promised."));const C=D2e.indexOf(s.agent.stage);let T=0,M;if(O2e.includes(s.agent.stage))T=xh.pipeline_momentum*.3,M="Relationship is intentionally parked — long-term nurture.";else if(C<0)T=xh.pipeline_momentum*.3,M=`Stage "${s.agent.stage}" is outside the advancing ladder.`;else{const I=xh.pipeline_momentum*(C/(D2e.length-1)),O=s.daysSinceStageChange!==null&&s.daysSinceStageChange>60;T=O?I*.5:I,M=`Stage ${C+1} of ${D2e.length}`+(s.daysSinceStageChange!==null?`, last moved ${s.daysSinceStageChange} days ago.`:", never moved."),O&&(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:xh.pipeline_momentum,earned:Math.round(T),detail:M,direction:T>xh.pipeline_momentum*.5?"positive":"neutral"});let P=n.reduce((I,O)=>I+O.earned,0);s.agent.temperature==="hot"&&(P+=4,r.push("You marked this relationship hot")),s.agent.temperature==="cold"&&(P-=4,a.push("You marked this relationship cold")),h&&(P-=3),P=Math.max(0,Math.min(100,Math.round(P)));const L=P>=75?"thriving":P>=55?"healthy":P>=35?"cooling":"at_risk";return{agent_id:s.agent.id,score:P,band:L,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:{...xh},engine_version:RUt,calculated_at:t.toISOString()}}const FUt=[{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"}],oRn={urgent:100,high:70,medium:40,low:15},Hw=(s,t=new Date)=>new Date(t.getTime()+s*DUt).toISOString(),Pk=s=>s.first_name||"there",lRn=3;function Gw(s,t,n={}){var o,c;const r=Pk(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 cRn(s,t,n=new Date){const r=[],a=s.agent;if(a.stage==="not_a_fit")return r;const i=s.daysSinceTouch!==null&&s.daysSinceTouch{var b;return(b=t.kits.find(v=>v.id===g))==null?void 0:b.title},o=g=>{r.push({...g,message_source:"rules",rank_score:g.rank_score??oRn[g.priority]})},c=s.shares.find(g=>g.engagement_level==="high_intent");if(s.meetingRequests>0||s.questions>0||c){const g=c?l(c.kit_id):void 0,b=[s.meetingRequests>0&&`${s.meetingRequests} meeting request(s) submitted`,s.questions>0&&`${s.questions} question(s) asked inside a shared kit`,c&&`Kit engagement is classified High Intent (${c.open_count} opens)`,s.downloads>0&&`${s.downloads} file download(s)`].filter(Boolean);o({agent_id:a.id,rec_key:"high_intent",signal_group:"high_intent",signal_label:"High-intent engagement",action_type:"respond_to_intent",channel:s.meetingRequests>0?"call":"text",title:`Call ${Pk(a)} — they are actively engaging`,reasons:b,priority:"urgent",suggested_due_at:Hw(1,n),draft_message:Gw("high_intent",s,{kitTitle:g}),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(g=>g.last_opened_at&&g.first_opened_at&&Qx(g.last_opened_at,n)<=7&&Qx(g.first_opened_at,g.last_opened_at)>=14&&(g.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:`${Pk(a)} came back to a kit you shared`,reasons:[`Re-opened "${l(d.kit_id)??"a shared kit"}" ${Qx(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:Hw(2,n),draft_message:Gw("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(g=>g.checked_in_at&&Qx(g.checked_in_at,n)<=7&&g.followup_status!=="done").sort((g,b)=>+new Date(b.checked_in_at)-+new Date(g.checked_in_at))[0];if(u){const g=t.events.find(v=>v.id===u.event_id),b=Math.round((n.getTime()-new Date(u.checked_in_at).getTime())/36e5);o({agent_id:a.id,rec_key:`event_follow_up:${u.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"event_follow_up",channel:"call",title:`Follow up on ${(g==null?void 0:g.title)??"the event"} — ${b}h since they attended`,reasons:[`Checked in to "${(g==null?void 0:g.title)??"event"}" ${b} hours ago`,`Follow-up status is "${u.followup_status??"pending"}"`,b<=48?"Inside the 48-hour window where follow-up matters most":"Past the ideal 48-hour window — still worth doing today"],priority:b<=48?"urgent":"high",suggested_due_at:Hw(b<=48?1:0,n),draft_message:Gw("event_follow_up",s,{eventTitle:g==null?void 0:g.title}),suggested_event_id:u.event_id,suggested_kit_id:(g==null?void 0:g.resource_kit_id)??null,source_signals:{attendee_id:u.id,hours_since:b},rank_score:b<=48?96:74})}else{const g=s.attendees.find(b=>b.no_show_at&&Qx(b.no_show_at,n)<=10);if(g){const b=t.events.find(v=>v.id===g.event_id);o({agent_id:a.id,rec_key:`event_no_show:${g.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"no_show_recovery",channel:"text",title:`${Pk(a)} missed ${(b==null?void 0:b.title)??"an event"} — recover gracefully`,reasons:[`Registered but did not attend "${(b==null?void 0:b.title)??"event"}"`,"No-show recovery works best within a week, with zero guilt"],priority:"medium",suggested_due_at:Hw(2,n),draft_message:Gw("event_no_show",s,{eventTitle:b==null?void 0:b.title}),suggested_event_id:g.event_id,source_signals:{attendee_id:g.id},rank_score:52})}}const h=s.shares.find(g=>g.first_opened_at&&Qx(g.first_opened_at,n)>=3&&Qx(g.first_opened_at,n)<=30&&(s.daysSinceTouch===null||s.lastTouchAt&&new Date(s.lastTouchAt)!g.first_opened_at&&Qx(g.created_at,n)>=5&&g.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 ${Qx(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:Hw(2,n),draft_message:Gw("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 ${Pk(a)} personally`,reasons:[`Shared ${Qx(m.created_at,n)} days ago and never opened`,"A personal message beats a resend"],priority:"medium",suggested_due_at:Hw(2,n),draft_message:Gw("resource_unopened",s,{kitTitle:l(m.kit_id)}),suggested_kit_id:m.kit_id,source_signals:{share_id:m.id},rank_score:46});const p=s.overdueFollowUps.sort((g,b)=>+new Date(g.due_at)-+new Date(b.due_at))[0];if(p){const g=Qx(p.due_at,n);o({agent_id:a.id,rec_key:`overdue:${p.id}`,signal_group:"overdue_commitment",signal_label:"Overdue commitment",action_type:"clear_overdue",channel:p.touch_type||"call",title:`Overdue ${g} day(s): ${p.title}`,reasons:[`Follow-up "${p.title}" was due ${g} day(s) ago`,`Priority: ${p.priority??"medium"}`],priority:g>7?"urgent":"high",suggested_due_at:Hw(0,n),draft_message:Gw("overdue_commitment",s,{followUpTitle:p.title}),source_signals:{follow_up_id:p.id,days_late:g},rank_score:92+Math.min(g,8)})}const x=D2e.indexOf(a.stage);if(!O2e.includes(a.stage)&&x>=2&&s.attended>0&&(s.totalKitOpens>0||s.downloads>0)&&(s.daysSinceStageChange===null||s.daysSinceStageChange>21)&&o({agent_id:a.id,rec_key:"ready_deeper",signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"deeper_conversation",channel:"call",title:`Have the honest next-chapter conversation with ${Pk(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:Hw(4,n),draft_message:Gw("ready_deeper",s),source_signals:{stage:a.stage,attended:s.attended},rank_score:72}),s.daysSinceTouch===null&&Qx(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 ${Pk(a)}`,reasons:[`Added to your pipeline ${Qx(a.created_at,n)} days ago`,"No touch, kit, or event activity logged"],priority:"medium",suggested_due_at:Hw(3,n),draft_message:Gw("no_touch",s),source_signals:{created_at:a.created_at},rank_score:48});else if(s.daysSinceTouch!==null){const g=a.temperature==="hot"?14:a.temperature==="cold"?90:45;if(s.daysSinceTouch>g){const b=s.daysSinceTouch>g*2;o({agent_id:a.id,rec_key:b?"no_touch_long":"going_cold",signal_group:b?"no_touch":"going_cold",signal_label:b?"No meaningful touch recently":"Relationship going cold",action_type:"check_in",channel:"personal_check_in",title:`${Pk(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 ${g} days`,s.touches90?`${s.touches90} touch(es) in the last 90 days`:"No touches in the last 90 days"],priority:b?"high":"medium",suggested_due_at:Hw(3,n),draft_message:Gw(b?"no_touch":"going_cold",s),source_signals:{days_since_touch:s.daysSinceTouch,threshold:g},rank_score:b?62:44})}}if(!s.shares.length&&!O2e.includes(a.stage)&&t.primaryPillar==="provide"){const g=t.kits.find(b=>b.status==="published"&&(!b.audience||!a.production_context||!0));g&&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 "${g.title}" with ${Pk(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:Hw(5,n),draft_message:Gw("share_value",s,{kitTitle:g.title}),suggested_kit_id:g.id,source_signals:{pillar:"provide"},rank_score:38})}if(!s.attendees.length&&!O2e.includes(a.stage)&&t.primaryPillar==="connect"){const g=t.events.filter(b=>b.status==="published"&&b.starts_at&&new Date(b.starts_at)>n).sort((b,v)=>+new Date(b.starts_at)-+new Date(v.starts_at))[0];g&&o({agent_id:a.id,rec_key:`invite_event:${g.id}`,signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"invite_to_event",channel:"event_invitation",title:`Invite ${Pk(a)} to ${g.title}`,reasons:["Never invited to an event",`"${g.title}" is published and upcoming`,"Your 90-day plan primary pillar is Connect"],priority:"medium",suggested_due_at:Hw(4,n),draft_message:Gw("event_invite_nudge",s,{eventTitle:g.title,eventWhen:g.starts_at?new Date(g.starts_at).toLocaleDateString():void 0}),suggested_event_id:g.id,source_signals:{pillar:"connect",event_id:g.id},rank_score:40})}return(i?r.filter(g=>g.priority==="urgent"):r).sort((g,b)=>b.rank_score-g.rank_score).slice(0,3)}const kyt=[{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"]}],dRn={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 uRn(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:OUt.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 hRn(s,t,n){return s.shares.slice().sort((r,a)=>+new Date(a.created_at)-+new Date(r.created_at)).map(r=>{var m;const a=s.shareEvents[r.id]??[],i=a.filter(p=>p.event_type==="file_download").length,l=a.filter(p=>p.event_type==="primary_cta_click"||p.event_type==="external_link_click").length,o=a.filter(p=>p.event_type==="question_submitted").length,c=a.filter(p=>p.event_type==="meeting_requested").length,d=r.engagement_level==="high_intent"||c>0?"High Intent":r.engagement_level==="engaged"||i>0||l>0||o>0?"Engaged":r.first_opened_at?"Viewed":"Sent",u=t.followUps.filter(p=>p.agent_id===s.agent.id&&new Date(p.created_at)>=new Date(r.created_at)).sort((p,x)=>+new Date(p.created_at)-+new Date(x.created_at))[0]??null,h=s.stageChanges.filter(p=>new Date(p.created_at)>new Date(r.created_at)).sort((p,x)=>+new Date(p.created_at)-+new Date(x.created_at))[0]??null;return{share:r,kitTitle:((m=t.kits.find(p=>p.id===r.kit_id))==null?void 0:m.title)??"Resource kit",shareUrl:`${n}/attract-kit/${r.share_token}`,events:a,firstViewedAt:r.first_opened_at??null,lastViewedAt:r.last_opened_at??null,visits:r.open_count??0,downloads:i,ctaClicks:l,questions:o,meetingRequests:c,classification:d,followUp:u,stageAdvancedAfter:h}})}function mRn(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 Ju=U;function pRn(){const{user:s}=Ns();return mt({queryKey:["attract-intel-data",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{var x,y;const[t,n,r,a,i,l,o,c,d,u,h,m]=await Promise.all([Ju.from("attract_agents").select("*").order("updated_at",{ascending:!1}),Ju.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(2e3),Ju.from("attract_follow_ups").select("*").order("created_at",{ascending:!1}).limit(2e3),Ju.from("attract_kit_shares").select("*").order("created_at",{ascending:!1}).limit(1e3),Ju.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Ju.from("attract_event_attendees").select("*").order("created_at",{ascending:!1}).limit(2e3),Ju.from("attract_events").select("id, title, starts_at, status, resource_kit_id, public_slug").limit(500),Ju.from("attract_pipeline_history").select("*").order("created_at",{ascending:!1}).limit(2e3),Ju.from("attract_score_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Ju.from("attract_resource_kits").select("id, title, audience, pillar, status, is_template").eq("is_template",!1),Ju.from("attract_event_notes").select("*").order("created_at",{ascending:!1}).limit(1e3),Ju.from("attract_settings").select("primary_pillar, attraction_style, ninety_day_plan").eq("user_id",s.id).maybeSingle()]),p=[t,n,r,a,i,l,o,c,d,u,h].find(g=>g.error);if(p)throw p.error;return{agents:t.data??[],activities:n.data??[],followUps:r.data??[],shares:a.data??[],kitEvents:i.data??[],attendees:l.data??[],events:o.data??[],stageChanges:c.data??[],scoreEvents:d.data??[],kits:u.data??[],eventNotes:h.data??[],primaryPillar:((x=m==null?void 0:m.data)==null?void 0:x.primary_pillar)??((y=m==null?void 0:m.data)==null?void 0:y.attraction_style)??null}}})}function A6(){const s=pRn(),t=j.useMemo(()=>{if(!s.data)return[];const r=new Date;return s.data.agents.map(a=>{const i=aRn(a,s.data,r),l=iRn(i,r),o=cRn(i,s.data,r);return{agent:a,signals:i,score:l,recommendations:o,primary:o[0]??null}})},[s.data]),n=j.useMemo(()=>new Map(t.map(r=>[r.agent.id,r])),[t]);return{...s,dataset:s.data,intel:t,byId:n}}function fRn(s){const{dataset:t,byId:n,isLoading:r,error:a,refetch:i}=A6(),l=s?n.get(s)??null:null,o=j.useMemo(()=>l&&t?uRn(l.signals,t,t.eventNotes??[]):[],[l,t]),c=j.useMemo(()=>l&&t?hRn(l.signals,t,typeof window<"u"?window.location.origin:""):[],[l,t]),d=j.useMemo(()=>l&&t?mRn(l.signals,t):null,[l,t]);return{item:l,dataset:t,timeline:o,valueShared:c,nextKit:d,isLoading:r,error:a,refetch:i}}function zUt(){const{user:s}=Ns(),t=as();return vt({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:RUt,calculated_at:i.score.calculated_at}));for(let i=0;i{t.invalidateQueries({queryKey:["attract-score-snapshots"]}),n&&!r&&re.success(`Recalculated ${n} relationship score${n===1?"":"s"}`)},onError:n=>re.error(n.message??"Could not save scores")})}function bee(){const{user:s}=Ns();return mt({queryKey:["attract-recommendations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Ju.from("attract_recommendations").select("*").order("rank_score",{ascending:!1});if(n)throw n;return t??[]}})}function NTe(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{if(!s)return{inserted:0,refreshed:0};const r=n.flatMap(u=>u.recommendations),{data:a,error:i}=await Ju.from("attract_recommendations").select("id, agent_id, rec_key, status, snoozed_until");if(i)throw i;const l=new Map((a??[]).map(u=>[`${u.agent_id}|${u.rec_key}`,u])),o=[],c=[],d=new Date;for(const u of r){const h=`${u.agent_id}|${u.rec_key}`,m=l.get(h),p={user_id:s.id,agent_id:u.agent_id,rec_key:u.rec_key,signal_group:u.signal_group,action_type:u.action_type,channel:u.channel,title:u.title,reasons:u.reasons,priority:u.priority,rank_score:u.rank_score,suggested_due_at:u.suggested_due_at,draft_message:u.draft_message,message_source:u.message_source,suggested_kit_id:u.suggested_kit_id??null,suggested_event_id:u.suggested_event_id??null,source_signals:u.source_signals};m?m.status==="open"?c.push({id:m.id,patch:{...p,generated_at:d.toISOString()}}):m.status==="snoozed"&&m.snoozed_until&&new Date(m.snoozed_until)<=d&&c.push({id:m.id,patch:{...p,status:"open",snoozed_until:null,generated_at:d.toISOString()}}):o.push(p)}if(o.length){const{error:u}=await Ju.from("attract_recommendations").insert(o);if(u)throw u}for(const u of c)await Ju.from("attract_recommendations").update(u.patch).eq("id",u.id);return{inserted:o.length,refreshed:c.length}},onSuccess:()=>t.invalidateQueries({queryKey:["attract-recommendations"]}),onError:n=>re.error(n.message??"Could not sync recommendations")})}function BUt(){const{user:s}=Ns(),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=vt({mutationFn:async({id:c,patch:d})=>{const{error:u}=await Ju.from("attract_recommendations").update(d).eq("id",c);if(u)throw u},onSuccess:n,onError:c=>re.error(c.message)}),a=vt({mutationFn:async c=>{const{error:d}=await Ju.from("attract_recommendations").update({status:"dismissed",dismissed_at:new Date().toISOString()}).eq("id",c);if(d)throw d},onSuccess:()=>{n(),re.success("Dismissed")}}),i=vt({mutationFn:async({id:c,days:d})=>{const u=new Date(Date.now()+d*864e5).toISOString(),{error:h}=await Ju.from("attract_recommendations").update({status:"snoozed",snoozed_until:u}).eq("id",c);if(h)throw h},onSuccess:()=>{n(),re.success("Snoozed")}}),l=vt({mutationFn:async c=>{if(c.follow_up_id){const{data:h}=await Ju.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 Ju.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 Ju.from("attract_recommendations").update({follow_up_id:d.id}).eq("id",c.id),{id:d.id,existed:!1}},onSuccess:c=>{n(),re.success(c.existed?"Follow-up already exists":"Follow-up created")},onError:c=>re.error(c.message)}),o=vt({mutationFn:async({rec:c,note:d})=>{const u=new Date().toISOString(),{error:h}=await Ju.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 Ju.from("attract_follow_ups").update({completed_at:u}).eq("id",c.follow_up_id).is("completed_at",null),await Ju.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 Ju.from("attract_recommendations").update({status:"completed",completed_at:u}).eq("id",c.id);if(m)throw m},onSuccess:()=>{n(),t.invalidateQueries({queryKey:["attract-score"]}),re.success("Logged — timeline and score updated")},onError:c=>re.error(c.message)});return{update:r,dismiss:a,snooze:i,createFollowUp:l,logCompleted:o}}function xRn(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{const{error:r}=await Ju.from("attract_activities").insert({user_id:s.id,...n});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]}),t.invalidateQueries({queryKey:["attract-agents"]}),re.success("Logged")},onError:n=>re.error(n.message)})}const Syt={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 HYe({score:s,className:t}){const n=Syt[s.band]??Syt.cooling;return e.jsxs(qe,{variant:"outline",className:Et("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 $Ut({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(HYe,{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:Et("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(kl,{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(vN,{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(gN,{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 Cyt({className:s}){const{intel:t}=A6(),[n,r]=j.useState(""),[a,i]=j.useState(!1),l=Hn(),o=j.useMemo(()=>{const c=n.trim().toLowerCase();return c?t.filter(d=>{const u=d.agent;return[u.first_name,u.last_name,u.brokerage,u.city,u.email,...u.tags??[]].filter(Boolean).join(" ").toLowerCase().includes(c)}).slice(0,6):[]},[t,n]);return e.jsxs("div",{className:Et("relative",s),children:[e.jsx(Fr,{className:"h-3.5 w-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:n,onChange:c=>{r(c.target.value),i(!0)},onFocus:()=>i(!0),onBlur:()=>setTimeout(()=>i(!1),150),placeholder:"Search relationships","aria-label":"Search relationships",className:"w-full h-9 rounded-full bg-white/5 border border-white/10 pl-9 pr-3 text-[12.5px] text-white placeholder:text-slate-500 focus:outline-none focus:ring-1 focus:ring-violet-500/60"}),a&&!!o.length&&e.jsx("div",{className:"absolute z-50 mt-1.5 w-full rounded-xl bg-white shadow-xl ring-1 ring-slate-200 overflow-hidden",children:o.map(c=>e.jsxs("button",{onMouseDown:()=>{l(`/attract/agents/${c.agent.id}`),r(""),i(!1)},className:"w-full text-left px-3 py-2.5 hover:bg-slate-50 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[13px] font-medium text-slate-900 truncate",children:[c.agent.first_name,c.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("span",{className:"block text-[11px] text-slate-500 truncate capitalize",children:[c.agent.stage.replace(/_/g," "),c.agent.brokerage?` · ${c.agent.brokerage}`:""]})]}),e.jsx(HYe,{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 L8e=[{to:"/attract",label:"Today",icon:Aj,exact:!0},{to:"/attract/relationships",label:"Relationships",icon:Bn},{to:"/attract/share",label:"Share Value",icon:FR},{to:"/attract/create",label:"Create Content",icon:um},{to:"/attract/results",label:"Results",icon:ol},{to:"/attract/settings",label:"Settings",icon:ic}],Ayt=[{to:"/attract/plan",label:"90-Day Plan"},{to:"/attract/opportunities",label:"Opportunities"},{to:"/attract/pipeline",label:"Agent Pipeline (legacy)"},{to:"/attract/follow-up",label:"Follow-Up Center"},{to:"/attract/landing-page",label:"Attraction Page"},{to:"/attract/events",label:"Events"},{to:"/attract/provide/kits",label:"Resource Kits"},{to:"/attract/provide/masterclasses",label:"Masterclasses"},{to:"/attract/resources",label:"Resources"},{to:"/attract/templates",label:"Templates & Scripts"},{to:"/attract/digest",label:"Weekly Digest"},{to:"/attract/produce",label:"Produce tools"},{to:"/attract/influence",label:"Influence tools"},{to:"/attract/connect",label:"Connect tools"}];function gRn(){const s=$d(),{settings:t,isLoading:n}=Zq(),r=!n&&!!t&&!t.onboarding_completed_at,a=s.pathname==="/attract/onboarding";if(r&&!a&&!s.pathname.startsWith("/attract/settings"))return e.jsx(Tj,{to:"/attract/onboarding",replace:!0});const i=L8e.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(KC,{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(_a,{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(N3,{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(Cyt,{})}),e.jsxs("nav",{className:"flex-1 overflow-y-auto py-3 px-3",children:[L8e.map(l=>{const o=l.icon;return e.jsxs(KC,{to:l.to,end:l.exact,className:({isActive:c})=>Et("group flex items-center gap-3 px-3 py-2.5 rounded-xl text-[13.5px] font-medium transition-all",c?"bg-gradient-to-r from-violet-600/30 to-indigo-600/10 text-white ring-1 ring-inset ring-violet-500/40":"text-slate-300 hover:bg-white/5 hover:text-white"),children:[e.jsx(o,{className:"h-4 w-4 flex-shrink-0 opacity-80 group-hover:opacity-100"}),e.jsx("span",{className:"flex-1",children:l.label})]},l.to)}),e.jsxs(i0,{className:"mt-4",children:[e.jsxs(o0,{className:"w-full flex items-center justify-between px-3 py-2 text-[11px] uppercase tracking-[0.14em] text-slate-500 font-semibold hover:text-slate-300",children:["All tools ",e.jsx(Po,{className:"h-3.5 w-3.5"})]}),e.jsx(l0,{className:"pt-1",children:Ayt.map(l=>e.jsx(KC,{to:l.to,className:({isActive:o})=>Et("block rounded-lg px-3 py-2 text-[12.5px]",o?"bg-white/10 text-white":"text-slate-400 hover:text-white hover:bg-white/5"),children:l.label},l.to))})]})]}),e.jsx("div",{className:"px-4 py-4 border-t border-white/5",children:e.jsxs("div",{className:"rounded-xl bg-white/5 p-3",children:[e.jsx("div",{className:"text-[11px] font-medium text-violet-300",children:"Beta preview"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 mt-1 leading-snug",children:"Build relationships first. Personalize every message and verify brokerage and compensation info before sharing."})]})})]}),e.jsxs("div",{className:"lg:hidden fixed top-0 inset-x-0 z-40 bg-[#0B0F1E] text-white px-4 py-3 flex items-center gap-3 border-b border-white/10",children:[e.jsx(KC,{to:"/dashboard",className:"text-slate-400",children:e.jsx(_a,{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(N3,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold tracking-tight",children:"LEVELUP ATTRACT"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Attract through value"})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-[#0B0F1E]/95 backdrop-blur border-t border-white/10 flex",children:[i.map(l=>{const o=l.icon;return e.jsxs(KC,{to:l.to,end:l.exact,className:({isActive:c})=>Et("flex-1 min-w-0 flex flex-col items-center gap-1 py-2 text-[10px]",c?"text-white":"text-slate-400"),children:[e.jsx(o,{className:"h-4 w-4"}),e.jsx("span",{className:"truncate max-w-[70px]",children:l.label})]},l.to)}),e.jsxs(v1,{children:[e.jsx(yJ,{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(Hy,{className:"h-4 w-4"}),e.jsx("span",{children:"More"})]})}),e.jsx(rv,{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(Cyt,{className:"mb-4"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"All sections"}),L8e.map(l=>{const o=l.icon;return e.jsxs(KC,{to:l.to,end:l.exact,className:({isActive:c})=>Et("flex items-center gap-3 rounded-xl px-3 py-3 text-[13.5px] font-medium",c?"bg-violet-600/30 text-white":"text-slate-300 hover:bg-white/5"),children:[e.jsx(o,{className:"h-4 w-4 opacity-80"}),e.jsx("span",{children:l.label})]},l.to)}),e.jsx("div",{className:"mt-4 mb-1 text-[10px] uppercase tracking-widest text-slate-500 font-semibold",children:"All tools"}),Ayt.map(l=>e.jsx(KC,{to:l.to,className:({isActive:o})=>Et("block rounded-xl px-3 py-2.5 text-[13px]",o?"bg-white/10 text-white":"text-slate-400 hover:bg-white/5"),children:l.label},l.to))]})})]})]}),e.jsx("main",{className:"flex-1 min-w-0 pt-16 lg:pt-0 pb-24 lg:pb-0",children:e.jsx("div",{className:"max-w-[1400px] mx-auto px-4 sm:px-6 lg:px-10 py-6 lg:py-10",children:e.jsx(Gjt,{})},s.pathname)})]})]})}function lG({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(be,{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:Et("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 yRn(){const{user:s}=Ns();return mt({queryKey:["attract-score",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("attract_score_events").select("category, points, description, created_at");if(n)throw n;const r=t??[],a=r.reduce((l,o)=>l+(o.points??0),0),i={};for(const l of r)i[l.category]=(i[l.category]??0)+l.points;return{total:Math.min(a,100),rows:r,byCategory:i}}})}const vRn=[{key:"relationships_added",label:"Relationships Added",icon:qv,target:15},{key:"follow_ups_completed",label:"Follow-Ups Completed",icon:Rr,target:15},{key:"resources_shared",label:"Resources Shared",icon:zd,target:15},{key:"content_posted",label:"Agent Content Posted",icon:jh,target:15},{key:"events_connections",label:"Events / Connections",icon:hN,target:20},{key:"brokerage_conversations",label:"Brokerage Conversations",icon:X9,target:20}];function UUt(){const{data:s}=yRn(),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(be,{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(kl,{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:vRn.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 cG=U;function x0(){const{user:s}=Ns(),t=as(),n=mt({queryKey:["attract-agents",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await U.from("attract_agents").select("*").order("updated_at",{ascending:!1});if(u)throw u;return d??[]}}),r=()=>{["attract-agents","attract-intel","attract-intelligence","attract-agent-intel","attract-activities","attract-followups","attract-recommendations","attract-score","attract_milestones","attract-daily-plan"].forEach(d=>t.invalidateQueries({queryKey:[d]}))},a=vt({mutationFn:async d=>{const u={...d,user_id:s.id},{data:h,error:m}=d.id?await U.from("attract_agents").update(u).eq("id",d.id).select().single():await U.from("attract_agents").insert(u).select().single();if(m)throw m;return h},onSuccess:()=>{r(),re.success("Saved")},onError:d=>re.error(d.message)}),i=vt({mutationFn:async({id:d,to_stage:u,from_stage:h})=>{const{error:m}=await U.from("attract_agents").update({stage:u}).eq("id",d);if(m)throw m;await U.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:h??null,to_stage:u})},onSuccess:()=>r(),onError:d=>re.error(d.message)}),l=vt({mutationFn:async({id:d,values:u,changedLabels:h,previousStage:m})=>{const{stage:p,...x}=u;if(Object.keys(x).length){const{error:y}=await cG.from("attract_agents").update(x).eq("id",d);if(y)throw y}if(p&&p!==m){const{error:y}=await cG.from("attract_agents").update({stage:p}).eq("id",d);if(y)throw y;await cG.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:m??null,to_stage:p})}h.length&&await cG.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"note",_title:"Contact details updated",_description:`Updated: ${h.join(", ")}`,_pillar:"connect",_agent_id:d,_metadata:{},_dedupe_minutes:1})},onSuccess:()=>{r(),re.success("Contact updated")},onError:d=>re.error(d.message??"Could not save contact")}),o=vt({mutationFn:async({id:d,archived:u})=>{const{error:h}=await cG.from("attract_agents").update({is_archived:u}).eq("id",d);if(h)throw h},onSuccess:(d,u)=>{r(),re.success(u.archived?"Removed from active pipeline":"Restored to pipeline")},onError:d=>re.error(d.message)}),c=vt({mutationFn:async d=>{const{error:u}=await U.from("attract_agents").delete().eq("id",d);if(u)throw u},onSuccess:()=>{r(),re.success("Contact permanently deleted")},onError:d=>re.error(d.message)});return{agents:n.data??[],activeAgents:(n.data??[]).filter(d=>!d.is_archived),isLoading:n.isLoading,upsertAgent:a,saveAgentDetails:l,moveStage:i,archiveAgent:o,deleteAgent:c}}const P8e=[{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 bRn(){const{agents:s}=x0(),t=Math.max(1,...P8e.map(n=>s.filter(r=>r.stage===n.key).length));return e.jsxs(be,{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(Yn,{to:"/attract/relationships",children:["View All Relationships ",e.jsx(Qa,{className:"h-3.5 w-3.5"})]})})]}),e.jsx("div",{className:"space-y-2",children:P8e.map((n,r)=>{const a=s.filter(o=>o.stage===n.key).length,i=30+a/t*70,l=.35+(1-r/P8e.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 qUt(){const{user:s}=Ns(),t=as(),n=mt({queryKey:["attract-daily-plan",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await U.from("attract_daily_plan").select("*").order("sort_order");if(i)throw i;return a??[]}}),r=vt({mutationFn:async a=>{const i=!a.completed,{error:l}=await U.from("attract_daily_plan").update({completed:i,progress:i?a.target:0}).eq("id",a.id);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["attract-daily-plan"]})});return{items:n.data??[],isLoading:n.isLoading,toggle:r}}function kTe(s=!0){const{intel:t,isLoading:n}=A6(),r=zUt(),a=NTe(),i=j.useRef(!1);return j.useEffect(()=>{if(!s||n||i.current||!t.length)return;const o=sessionStorage.getItem("attract-intel-sync"),c=new Date().toISOString().slice(0,13);if(o===c){i.current=!0;return}i.current=!0,sessionStorage.setItem("attract-intel-sync",c),r.mutate({items:t,silent:!0}),a.mutate(t)},[s,n,t]),{runNow:()=>{r.mutate({items:t}),a.mutate(t)},isSyncing:r.isPending||a.isPending}}function _Rn(){const{items:s,toggle:t}=qUt(),{data:n=[]}=bee(),{byId:r}=A6(),{logCompleted:a}=BUt();kTe();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(be,{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(wi,{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(Rr,{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(Yn,{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(qe,{variant:"outline",className:Et("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(Yn,{to:"/attract/relationships",children:["All relationships ",e.jsx(Xa,{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(Yn,{to:"/attract/plan",children:"View full plan"})})]})]})}function GYe(s=12){const{user:t}=Ns(),n=mt({queryKey:["attract-activities",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{const{data:r,error:a}=await U.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(s);if(a)throw a;return r??[]}});return{activities:n.data??[],isLoading:n.isLoading}}const wRn={agent_joined:yn,resource_shared:zd,presentation:yb,conversation:X9,social_engagement:mo,new_agent:Sl,content_posted:jh,follow_up:zp};function jRn(){const{activities:s}=GYe(8);return e.jsxs(be,{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=wRn[t.activity_type]??yn;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:[oc(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 STe(s){const{user:t}=Ns();return mt({queryKey:["attract-events",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let n=U.from("attract_events").select("*").eq("is_template",!1).order("starts_at",{ascending:!0});const{data:r,error:a}=await n;if(a)throw a;return r??[]}})}function WYe(s){return mt({queryKey:["attract-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("attract_events").select("*").eq("id",s).single();if(n)throw n;return t}})}function VUt(s){return mt({queryKey:["attract-event-attendees",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("attract_event_attendees").select("*, attract_agents(id, first_name, last_name, primary_pillar, stage)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function NRn(s){return mt({queryKey:["attract-event-invitations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("attract_event_invitations").select("*, attract_agents(id, first_name, last_name)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function kRn(s){return mt({queryKey:["attract-event-notes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("attract_event_notes").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function HUt(){return mt({queryKey:["attract-event-templates"],queryFn:async()=>{const{data:s,error:t}=await U.from("attract_event_templates").select("*").order("title");if(t)throw t;return s??[]}})}function GUt(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,title:n.title||"Untitled event",starts_at:n.starts_at||new Date(Date.now()+7*864e5).toISOString(),status:"draft",...n},{data:a,error:i}=await U.from("attract_events").insert(r).select().single();if(i)throw i;return a},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function WUt(){const s=as();return vt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await U.from("attract_events").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-events"]}),s.invalidateQueries({queryKey:["attract-event",t.id]})}})}function SRn(){const s=as();return vt({mutationFn:async t=>{const{error:n}=await U.from("attract_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["attract-events"]})})}function KUt(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,...n},{data:a,error:i}=n.id?await U.from("attract_event_attendees").update(r).eq("id",n.id).select().single():await U.from("attract_event_attendees").insert(r).select().single();if(i)throw i;return a},onSuccess:n=>{t.invalidateQueries({queryKey:["attract-event-attendees",n.event_id]}),t.invalidateQueries({queryKey:["attract-event",n.event_id]})}})}function CRn(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("attract_event_notes").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-notes",n.event_id]})})}function ARn(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("attract_event_invitations").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-invitations",n.event_id]})})}function TRn(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await U.from("attract_events").select("*").eq("id",n).single();if(a)throw a;const{id:i,public_slug:l,check_in_token:o,published_at:c,registration_count:d,attendance_count:u,created_at:h,updated_at:m,...p}=r,{data:x,error:y}=await U.from("attract_events").insert({...p,title:r.title+" (Copy)",status:"draft"}).select().single();if(y)throw y;return x},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function CTe(s){return`${window.location.origin}/attract-event/${s}`}function ERn(s,t){return`${window.location.origin}/attract-event-checkin/${s}?a=${encodeURIComponent(t)}`}function YUt(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 ZUt(){const{data:s=[]}=STe(),t=s.slice(0,3);return e.jsxs(be,{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(Js,{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:Bs(r,"MMM")}),e.jsx("div",{className:"text-xl font-semibold leading-tight",children:Bs(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:Bs(r,"p")}),"·",n.event_type==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3 w-3"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(oi,{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(hN,{className:"h-6 w-6 mx-auto text-slate-300 mb-2"}),e.jsx("div",{className:"text-sm",children:"No upcoming events yet."})]})]})]})}function XUt(){const{user:s}=Ns(),t=mt({queryKey:["attract-resources",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await U.from("attract_resources").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}}),n=mt({queryKey:["attract-resource-shares",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await U.from("attract_resource_shares").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}});return{resources:t.data??[],shares:n.data??[],isLoading:t.isLoading}}function MRn(){const{shares:s}=XUt(),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:zd,tone:"text-violet-600 bg-violet-50"},{label:"Emails Sent",value:t.emails,icon:Dr,tone:"text-teal-600 bg-teal-50"},{label:"Agent Opens",value:t.opens,icon:G9,tone:"text-emerald-600 bg-emerald-50"},{label:"Clicks",value:t.clicks,icon:lu,tone:"text-orange-600 bg-orange-50"}];return e.jsxs(be,{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 LRn(){const{agents:s}=x0(),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(be,{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:Su(n)})]})]}),e.jsx(yn,{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?Su(Number(r.est_revenue_share)):"—"}),e.jsx("div",{className:"text-[10.5px] text-slate-400",children:r.joined_at?oc(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 VO(){const{user:s}=Ns(),t=as(),n=mt({queryKey:["attract-followups",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await U.from("attract_follow_ups").select("*").order("due_at",{ascending:!0,nullsFirst:!1});if(i)throw i;return a??[]}}),r=vt({mutationFn:async a=>{const{error:i}=await U.from("attract_follow_ups").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>t.invalidateQueries({queryKey:["attract-followups"]})});return{followUps:n.data??[],isLoading:n.isLoading,complete:r}}function PRn(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 Tyt={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 IRn(){const{user:s}=Ns(),t=Hn(),{agents:n}=x0(),{followUps:r}=VO(),{settings:a}=Zq();j.useState(!1);const i=j.useMemo(()=>{const d=xm(new Date),u=n.filter(g=>!["joined","not_a_fit","not_right_now"].includes(g.stage)).length,h=n.filter(g=>new Date(g.created_at)>jd(d,-30)).length,m=r.filter(g=>!g.completed_at&&g.due_at&&pd(new Date(g.due_at),d)).length,p=r.filter(g=>!g.completed_at&&g.due_at&&W_(new Date(g.due_at),d)).length,y=n.filter(g=>g.stage==="joined").reduce((g,b)=>g+(Number(b.est_revenue_share)||0),0);return{inPipeline:u,newRels:h,dueToday:m,overdue:p,revShare:y}},[n,r]),l=(a==null?void 0:a.primary_pillar)||(a==null?void 0:a.attraction_style)||"balanced",o=Tyt[l]??Tyt.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, ",PRn(s),"."]}),e.jsxs("p",{className:"text-slate-600 mt-1.5",children:["Here's your attraction overview for today · ",Bs(new Date,"EEEE, MMM d")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(vs,{defaultValue:"week",children:[e.jsx(gs,{className:"w-[150px] rounded-full bg-white",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"week",children:"This Week"}),e.jsx(Je,{value:"month",children:"This Month"}),e.jsx(Je,{value:"90",children:"Last 90 Days"})]})]}),e.jsx(B,{variant:"outline",size:"icon",className:"rounded-full",children:e.jsx(Nx,{className:"h-4 w-4"})}),e.jsxs(kd,{children:[e.jsx(Sd,{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(Js,{className:"h-4 w-4"})," Add New ",e.jsx(Po,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(xd,{align:"end",className:"w-64",children:[e.jsx(TE,{children:"Quick add"}),e.jsx(uy,{}),e.jsxs(wa,{onClick:()=>t("/attract/pipeline?new=1"),children:[e.jsx(Sl,{className:"h-4 w-4 mr-2"})," Add Agent to Pipeline"]}),e.jsxs(wa,{onClick:()=>t("/attract/produce/transaction-tracker"),children:[e.jsx(Wa,{className:"h-4 w-4 mr-2"})," Log a Transaction"]}),e.jsxs(wa,{onClick:()=>t("/attract/influence/content-studio"),children:[e.jsx(um,{className:"h-4 w-4 mr-2"})," Create Authority Content"]}),e.jsxs(wa,{onClick:()=>t("/attract/follow-up"),children:[e.jsx(zp,{className:"h-4 w-4 mr-2"})," Add Follow-Up"]}),e.jsxs(wa,{onClick:()=>t("/attract/events/new"),children:[e.jsx(Wy,{className:"h-4 w-4 mr-2"})," Plan an Event"]}),e.jsxs(wa,{onClick:()=>t("/attract/resources"),children:[e.jsx(i1,{className:"h-4 w-4 mr-2"})," Add Resource"]})]})]})]})]}),e.jsx(be,{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(uu,{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(lG,{label:"Agents in Pipeline",value:i.inPipeline,delta:"+3 this week",icon:qv,tone:"violet"}),e.jsx(lG,{label:"New Relationships",value:i.newRels,delta:"+2 this week",icon:kl,tone:"teal"}),e.jsx(lG,{label:"Follow-Ups Due Today",value:i.dueToday,icon:PW,tone:"orange"}),e.jsx(lG,{label:"Overdue Follow-Ups",value:i.overdue,icon:hd,tone:"rose"}),e.jsx(lG,{label:"Est. Revenue Share",value:Su(i.revShare,!0),delta:"annualized",icon:Od,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(UUt,{}),e.jsx(bRn,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(jRn,{}),e.jsx(ZUt,{})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(_Rn,{}),e.jsx(MRn,{}),e.jsx(LRn,{})]})]}),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(Yn,{to:"/attract/plan",children:"View 90-Day Plan"})})]})})]})}const Eyt={call:{icon:pa,label:"Call"},text:{icon:ro,label:"Text"},email:{icon:on,label:"Email"},dm:{icon:Dr,label:"DM"},resource_share:{icon:i1,label:"Share a kit"},event_invitation:{icon:Wy,label:"Invite to event"},personal_check_in:{icon:zR,label:"Personal check-in"}},Myt={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 RRn(s){var t;return((t=FUt.find(n=>n.key===s))==null?void 0:t.blurb)??""}function QUt(s){var t;return((t=FUt.find(n=>n.key===s))==null?void 0:t.label)??s.replace(/_/g," ")}function qSe({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}=BUt(),[p,x]=j.useState(!1),[y,g]=j.useState(s.draft_message??""),b=c.isPending||d.isPending||u.isPending||h.isPending||m.isPending,v=Eyt[s.channel]??Eyt.personal_check_in,k=s.suggested_due_at?new Date(s.suggested_due_at):null,C=k?k{c.mutate({id:s.id,patch:{draft_message:y}},{onSuccess:()=>{x(!1),re.success("Opening message updated")}})},M=async()=>{try{await navigator.clipboard.writeText(s.draft_message??""),re.success("Opening message copied — send it yourself from your phone or inbox")}catch{re.error("Could not copy — select the text manually")}};return e.jsx(be,{className:Et("rounded-2xl border-slate-200/70 bg-white shadow-sm overflow-hidden",o),children:e.jsxs("div",{className:"p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-wrap",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 text-white grid place-items-center shadow-sm flex-shrink-0",children:e.jsx(v.icon,{className:"h-4.5 w-4.5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1 min-w-[180px]",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(qe,{variant:"outline",className:Et("rounded-full text-[10.5px] uppercase tracking-wider font-semibold ring-1 border-transparent",Myt[s.priority]??Myt.medium),children:s.priority}),e.jsx("span",{className:"text-[11px] text-violet-700 font-medium",children:QUt(s.signal_group)}),s.is_demo&&e.jsx(qe,{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(Yn,{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:["· ",v.label]}),k&&e.jsxs("span",{className:Et("inline-flex items-center gap-1",C?"text-rose-600 font-medium":""),children:["· ",e.jsx(Vr,{className:"h-3 w-3"})," ",C?"Due now":`Do by ${k.toLocaleDateString()}`]})]})]}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full","aria-label":"More recommendation actions",children:e.jsx(W0,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",className:"w-56",children:[e.jsx(TE,{children:"Recommendation"}),e.jsx(uy,{}),e.jsxs(wa,{onClick:()=>x(P=>!P),children:[e.jsx(Za,{className:"h-4 w-4 mr-2"})," Edit opening message"]}),e.jsxs(wa,{onClick:M,children:[e.jsx(ja,{className:"h-4 w-4 mr-2"})," Copy message"]}),e.jsx(uy,{}),e.jsxs(wa,{onClick:()=>u.mutate({id:s.id,days:3}),children:[e.jsx(Vr,{className:"h-4 w-4 mr-2"})," Snooze 3 days"]}),e.jsxs(wa,{onClick:()=>u.mutate({id:s.id,days:7}),children:[e.jsx(Vr,{className:"h-4 w-4 mr-2"})," Snooze 1 week"]}),e.jsxs(wa,{className:"text-rose-600",onClick:()=>d.mutate(s.id),children:[e.jsx(dr,{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(I5,{className:"h-3 w-3"})," Why this, right now"]}),e.jsx("ul",{className:"space-y-1",children:s.reasons.map((P,L)=>e.jsxs("li",{className:"text-[12.5px] text-slate-700 flex gap-2",children:[e.jsx("span",{className:"text-violet-500",children:"•"}),e.jsx("span",{children:P})]},L))}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-2",children:RRn(s.signal_group)})]}),!i&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider font-semibold text-slate-500 mb-1.5",children:"Suggested opening"}),p?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ds,{value:y,onChange:P=>g(P.target.value),rows:4,className:"text-[13.5px]","aria-label":"Opening message"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:T,disabled:b,children:"Save message"}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>{g(s.draft_message??""),x(!1)},children:"Cancel"})]})]}):e.jsxs("button",{onClick:()=>x(!0),className:"w-full text-left rounded-xl border border-slate-200 bg-white p-3 text-[13.5px] leading-relaxed text-slate-700 hover:border-violet-300 transition-colors",children:[s.draft_message||"No draft message yet — click to write one.",e.jsx("span",{className:"block text-[11px] text-violet-600 mt-1.5",children:"Click to edit before you send"})]})]}),(r||a)&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11.5px]",children:[r&&e.jsxs("span",{className:"rounded-full bg-teal-50 text-teal-700 px-2.5 py-1",children:["Suggested kit: ",r]}),a&&e.jsxs("span",{className:"rounded-full bg-indigo-50 text-indigo-700 px-2.5 py-1",children:["Suggested event: ",a]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",disabled:b,onClick:()=>m.mutate({rec:s}),children:[e.jsx(da,{className:"h-3.5 w-3.5 mr-1.5"})," I did this"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:b,onClick:()=>h.mutate(s),children:[e.jsx(Wy,{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:M,children:[e.jsx(ja,{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 DRn({label:s="Nothing needs attention right now."}){return e.jsxs(be,{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(da,{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 _E=[{key:"new_relationship",label:"New Relationship",help:"You know each other, but you haven’t built much yet.",color:"#94a3b8",legacy:["new_connection"],canonical:"new_connection"},{key:"building",label:"Building Relationship",help:"Real conversations and value are going back and forth.",color:"#38bdf8",legacy:["building_relationship","engaging_with_value","long_term_relationship"],canonical:"building_relationship"},{key:"curious",label:"Brokerage Curious",help:"They’ve started asking questions about how you work.",color:"#8b5cf6",legacy:["active_conversation","exploring_options"],canonical:"active_conversation"},{key:"considering",label:"Considering a Move",help:"They’re actively weighing a change.",color:"#f59e0b",legacy:["brokerage_presentation","decision_pending"],canonical:"decision_pending"},{key:"joined",label:"Joined",help:"They made the move.",color:"#16a34a",legacy:["joined"],canonical:"joined"}],ATe={key:"set_aside",label:"Set Aside",help:"Not a fit right now — the relationship still matters.",color:"#cbd5e1",legacy:["not_right_now","not_a_fit"],canonical:"not_right_now"},JUt=new Map;for(const s of[..._E,ATe])for(const t of s.legacy)JUt.set(t,s);function Wz(s){return s?JUt.get(s)??_E[0]:_E[0]}function eqt(s){return Wz(s).label}function KYe(s){var n;return((n=[..._E,ATe].find(r=>r.key===s))==null?void 0:n.canonical)??"new_connection"}const I8e={first_name:"",last_name:"",brokerage:"",email:"",phone:"",city:"",source:"",notes:""};function tqt({open:s,onOpenChange:t,defaultStageKey:n,onAdded:r}){const{upsertAgent:a,agents:i}=x0(),[l,o]=j.useState({...I8e}),c=h=>m=>o(p=>({...p,[h]:m.target.value})),d=i.find(h=>{var m;return!!l.email&&((m=h.email)==null?void 0:m.toLowerCase())===l.email.trim().toLowerCase()||!!l.phone&&(h.phone??"").replace(/\D/g,"")===l.phone.replace(/\D/g,"")&&l.phone.replace(/\D/g,"").length>6}),u=()=>{a.mutate({...l,first_name:l.first_name.trim(),stage:KYe(n??"new_relationship"),temperature:"warm"},{onSuccess:h=>{o({...I8e}),t(!1),r==null||r(h==null?void 0:h.id)}})};return e.jsx(Fs,{open:s,onOpenChange:h=>{t(h),h||o({...I8e})},children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Add a relationship"}),e.jsx(kr,{className:"text-[13px]",children:"Just the basics. You can fill in the rest whenever it comes up naturally."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"First name *"}),e.jsx(ye,{value:l.first_name,onChange:c("first_name"),autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last name"}),e.jsx(ye,{value:l.last_name,onChange:c("last_name")})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(ye,{value:l.brokerage,onChange:c("brokerage"),placeholder:"Where they hang their license"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:l.phone,onChange:c("phone")})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Market"}),e.jsx(ye,{value:l.city,onChange:c("city"),placeholder:"City or area"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"How you know each other"}),e.jsx(ye,{value:l.source,onChange:c("source"),placeholder:"Co-op deal, event, referral…"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{children:"Note (optional)"}),e.jsx(Ds,{rows:2,value:l.notes,onChange:c("notes"),placeholder:"Anything worth remembering"})]})]}),d&&e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 px-3 py-2 text-[12.5px] text-amber-900",children:["Heads up — ",d.first_name," ",d.last_name??""," already has this contact info in your relationships."]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",disabled:!l.first_name.trim()||a.isPending,onClick:u,children:"Add relationship"})]})]})})}function ORn(s){var r;const t=(s==null?void 0:s.user_metadata)??{},n=t.full_name||t.name||((r=s==null?void 0:s.email)==null?void 0:r.split("@")[0])||"there";return String(n).split(" ")[0]}function FRn(){const s=new Date().getHours();return s<12?"Good morning":s<18?"Good afternoon":"Good evening"}const Lyt=20;function zRn(){const{user:s}=Ns(),{intel:t,byId:n,isLoading:r}=A6(),{data:a=[],isLoading:i}=bee(),l=NTe();kTe();const{items:o,toggle:c}=qUt(),{agents:d,isLoading:u}=x0(),{followUps:h}=VO(),{activities:m}=GYe(200),[p,x]=j.useState(!1),y=r||i||u,g=j.useMemo(()=>{const C=Date.now();return a.filter(T=>T.status==="open"||T.status==="snoozed"&&T.snoozed_until&&+new Date(T.snoozed_until)<=C).sort((T,M)=>M.rank_score-T.rank_score).slice(0,5)},[a]),b=j.useMemo(()=>{const C=new Date;C.setHours(0,0,0,0),C.setDate(C.getDate()-(C.getDay()+6)%7);const T=m.filter(L=>new Date(L.created_at)>=C).length,M=h.filter(L=>L.completed_at&&new Date(L.completed_at)>=C).length,P=T+M;return{moves:P,pct:Math.min(100,Math.round(P/Lyt*100))}},[m,h]),v=C=>{var M;const T=(M=n.get(C))==null?void 0:M.agent;return T?[T.first_name,T.last_name].filter(Boolean).join(" "):"this relationship"},k=d.length>0;return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(tqt,{open:p,onOpenChange:x}),e.jsxs("div",{className:"mb-7",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"LevelUp Attract"}),e.jsxs("h1",{className:"text-[28px] md:text-[34px] font-semibold tracking-tight text-slate-900 leading-tight",children:[FRn(),", ",ORn(s),". Here are your best moves today."]}),e.jsx("p",{className:"text-slate-600 mt-2 text-[14.5px]",children:"Build relationships. Provide value. Let the opportunity develop naturally."}),e.jsxs("div",{className:"mt-5 rounded-2xl bg-white border border-slate-200/70 px-4 py-3.5 shadow-sm",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[e.jsxs("div",{className:"text-[13.5px] text-slate-700",children:[e.jsxs("span",{className:"font-semibold text-slate-900 tabular-nums",children:[b.moves," of ",Lyt]})," meaningful moves completed this week"]}),e.jsx("span",{className:"text-[11px] uppercase tracking-wider text-slate-400",children:"This week"})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mt-2.5 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500 transition-all",style:{width:`${b.pct}%`}})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-600",children:"Today’s actions"}),!y&&e.jsxs(B,{variant:"ghost",size:"sm",className:"rounded-full text-slate-500 h-8",onClick:()=>l.mutate(t),disabled:l.isPending,children:[e.jsx(Ki,{className:Et("h-3.5 w-3.5 mr-1.5",l.isPending&&"animate-spin")})," Refresh"]})]}),y?e.jsxs("div",{className:"space-y-3","aria-busy":"true",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Looking at your relationships…"}),[0,1,2].map(C=>e.jsx(gn,{className:"h-40 w-full rounded-2xl"},C))]}):g.length?e.jsx("div",{className:"space-y-3",children:g.map(C=>{var T;return e.jsx(qSe,{rec:C,agentName:v(C.agent_id),agentStage:eqt((T=n.get(C.agent_id))==null?void 0:T.agent.stage)},C.id)})}):k?e.jsxs(be,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx(yn,{className:"h-6 w-6 mx-auto text-violet-500 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"You’re caught up."}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"No follow-ups are due. This is a great time to reconnect with someone you haven’t spoken with recently, or share one useful resource."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-4 flex-wrap",children:[e.jsx(B,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(Yn,{to:"/attract/relationships?view=attention",children:"See who’s gone quiet"})}),e.jsx(B,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(Yn,{to:"/attract/share",children:"Share something useful"})})]})]}):e.jsxs(be,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx("div",{className:"h-11 w-11 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(Sl,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Start with five people you already know."}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Add your first five relationships and Attract will begin recommending meaningful next steps — based only on things that actually happened."}),e.jsxs(B,{className:"rounded-full btn-primary text-white mt-4",onClick:()=>x(!0),children:[e.jsx(Sl,{className:"h-4 w-4 mr-1.5"})," Add your first relationship"]})]}),!!o.length&&e.jsxs(be,{className:"mt-6 p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsx("div",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-600 mb-3",children:"Your daily rhythm"}),e.jsx("ul",{className:"space-y-1",children:o.map(C=>e.jsxs("li",{onClick:()=>c.mutate(C),className:"flex items-center gap-3 px-2 py-2 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors",children:[e.jsx(wi,{checked:C.completed,className:"border-slate-300 data-[state=checked]:bg-violet-600 data-[state=checked]:border-violet-600"}),e.jsx("span",{className:Et("flex-1 text-[13.5px]",C.completed?"line-through text-slate-400":"text-slate-800"),children:C.label}),e.jsxs("span",{className:"text-[11px] tabular-nums text-slate-400",children:[C.progress,"/",C.target]})]},C.id))})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(R8e,{icon:Sl,label:"Add a relationship",onClick:()=>x(!0)}),e.jsx(R8e,{icon:i1,label:"Share something useful",to:"/attract/share"}),e.jsx(R8e,{icon:um,label:"Create content",to:"/attract/create"})]}),e.jsxs("div",{className:"mt-6 space-y-3",children:[e.jsxs(i0,{children:[e.jsxs(o0,{className:"w-full flex items-center justify-between rounded-2xl bg-white border border-slate-200/70 px-4 py-3 text-[13.5px] font-medium text-slate-700 hover:bg-slate-50",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(hN,{className:"h-4 w-4 text-violet-500"})," Upcoming conversations & events"]}),e.jsx(Po,{className:"h-4 w-4 text-slate-400"})]}),e.jsx(l0,{className:"pt-3",children:e.jsx(ZUt,{})})]}),e.jsxs(i0,{children:[e.jsxs(o0,{className:"w-full flex items-center justify-between rounded-2xl bg-white border border-slate-200/70 px-4 py-3 text-[13.5px] font-medium text-slate-700 hover:bg-slate-50",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-4 w-4 text-violet-500"})," View coaching insights"]}),e.jsx(Po,{className:"h-4 w-4 text-slate-400"})]}),e.jsx(l0,{className:"pt-3",children:e.jsx(UUt,{})})]})]}),e.jsx("div",{className:"mt-6 flex justify-center",children:e.jsx(B,{variant:"ghost",className:"rounded-full text-violet-700",asChild:!0,children:e.jsxs(Yn,{to:"/attract/relationships?view=attention",children:["See everyone who needs attention ",e.jsx(Xa,{className:"h-3.5 w-3.5 ml-1.5"})]})})}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400 max-w-lg mx-auto",children:"Attract never sends messages for you, and it only recommends actions backed by something that actually happened. Verify brokerage and compensation details before you share them."})]})}function R8e({icon:s,label:t,to:n,onClick:r}){const a=e.jsxs("div",{className:"rounded-2xl bg-white border border-slate-200/70 px-4 py-4 text-left hover:border-violet-300 hover:shadow-sm transition-all h-full",children:[e.jsx(s,{className:"h-4.5 w-4.5 text-violet-600 mb-2"}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-800",children:t})]});return n?e.jsx(Yn,{to:n,children:a}):e.jsx("button",{className:"text-left w-full",onClick:r,children:a})}function Wh({eyebrow:s,title:t,description:n,actions:r,className:a}){return e.jsxs("div",{className:Et("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 HO(){return e.jsxs("div",{className:"rounded-2xl border border-violet-200 bg-violet-50/60 px-5 py-3.5 text-[13px] text-violet-900 flex items-start gap-3",children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-violet-600 grid place-items-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-white text-[11px] font-bold",children:"✓"})}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Build relationships first."})," ","Personalize every message and verify brokerage and compensation information before sharing."]})]})}function BRn(s){const t=[];let n="",r=[],a=!1;for(let o=0;oo.some(c=>c.trim()!==""));if(!i.length)return[];const l=i[0].map(o=>o.trim().toLowerCase());return i.slice(1).map(o=>{const c={};return l.forEach((d,u)=>{c[d]=(o[u]??"").trim()}),c})}const i4=(s,t)=>{for(const n of t)if(s[n])return s[n];return""};function $Rn({open:s,onOpenChange:t}){const{user:n}=Ns(),r=as(),[a,i]=j.useState([]),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=()=>{i([]),o("")},h=async x=>{if(!x)return;const y=await x.text(),g=BRn(y);if(!g.length){re.error("That file looks empty.");return}o(x.name),i(g)},m=a.map(x=>{const y=i4(x,["name","full name","full_name"]),g=i4(x,["first name","first_name","firstname"])||y.split(" ")[0]||"",b=i4(x,["last name","last_name","lastname"])||y.split(" ").slice(1).join(" ")||null;return{first_name:g,last_name:b,email:i4(x,["email","email address","e-mail"])||null,phone:i4(x,["phone","phone number","mobile","cell"])||null,brokerage:i4(x,["brokerage","company","office"])||null,city:i4(x,["city"])||null,state:i4(x,["state","province"])||null,notes:i4(x,["notes","note"])||null,source:"csv_import",stage:"prospect"}}).filter(x=>x.first_name),p=async()=>{if(!(!n||!m.length)){d(!0);try{const x=m.map(g=>({...g,user_id:n.id}));let y=0;for(let g=0;g{x||u(),t(x)},children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Import relationships"}),e.jsx(kr,{children:"Upload a CSV. We'll look for columns like name, email, phone, brokerage, city, state and notes."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ye,{type:"file",accept:".csv,text/csv",onChange:x=>{var y;return h((y=x.target.files)==null?void 0:y[0])}}),!!a.length&&e.jsxs("div",{className:"rounded-xl border p-3 text-sm space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(pN,{className:"h-4 w-4"})," ",l]}),e.jsxs("div",{className:"text-muted-foreground",children:[m.length," of ",a.length," rows ready to import."]}),e.jsxs("div",{className:"text-muted-foreground text-xs",children:["Preview: ",m.slice(0,3).map(x=>`${x.first_name} ${x.last_name??""}`.trim()).join(", "),m.length>3?"…":""]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:p,disabled:c||!m.length,children:[e.jsx(Ja,{className:"h-4 w-4 mr-1.5"}),c?"Importing…":`Import ${m.length||""}`.trim()]})]})]})})}const URn=["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"],qRn={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"},Og=s=>typeof s=="string"&&s.trim()===""?null:s,v7=s=>{const t=s.trim();return t?/^https?:\/\//i.test(t)?t:`https://${t}`:null},VRn=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},dG=s=>(s??"").replace(/[^\d]/g,""),HRn=s=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim()),Ire=s=>s?String(s).slice(0,10):"";function Pyt(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:Ire(s.birthday_on),work_anniversary_on:Ire(s.work_anniversary_on),license_anniversary_on:Ire(s.license_anniversary_on),next_follow_up_at:Ire(s.next_follow_up_at)}}function b7({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 Dm({label:s,value:t,onChange:n,className:r,...a}){return e.jsxs("div",{className:r,children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:s}),e.jsx(ye,{className:"mt-1",value:t,onChange:i=>n(i.target.value),...a})]})}function YYe({agent:s,open:t,onOpenChange:n,onDeleted:r}){const{agents:a,saveAgentDetails:i,archiveAgent:l,deleteAgent:o}=x0(),[c,d]=j.useState({}),[u,h]=j.useState(!1),[m,p]=j.useState(!1),[x,y]=j.useState(!1);j.useEffect(()=>{s&&t&&(d(Pyt(s)),y(!1))},[s==null?void 0:s.id,t]);const g=j.useMemo(()=>s?Pyt(s):{},[s]),b=j.useMemo(()=>Object.keys(c).filter(L=>String(c[L]??"")!==String(g[L]??"")),[c,g]),v=b.length>0,k=(L,I)=>d(O=>({...O,[L]:I}));if(!s)return null;const C=L=>{if(!L&&v){h(!0);return}n(L)},T=()=>{var $;const L=($=c.email)==null?void 0:$.trim().toLowerCase(),I=dG(c.phone),O=`${c.first_name} ${c.last_name}`.trim().toLowerCase();return a.filter(q=>{var W;return q.id===s.id||q.is_archived?!1:!!(L&&((W=q.email)==null?void 0:W.toLowerCase())===L||I.length>=10&&dG(q.phone)===I||O&&`${q.first_name} ${q.last_name??""}`.trim().toLowerCase()===O)})},M=()=>{var q,W,G;if(!((q=c.first_name)!=null&&q.trim())){re.error("First name is required");return}if((W=c.email)!=null&&W.trim()&&!HRn(c.email)){re.error("That email address looks incomplete");return}const L=T(),I=L.some(K=>{var ee,J;return((ee=c.email)==null?void 0:ee.trim())&&((J=K.email)==null?void 0:J.toLowerCase())===c.email.trim().toLowerCase()||dG(c.phone).length>=10&&dG(K.phone)===dG(c.phone)});if(L.length&&!x){y(!0),re.warning(I?`${L[0].first_name} ${L[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 O={first_name:c.first_name.trim(),last_name:Og(c.last_name),preferred_name:Og(c.preferred_name),email:(G=c.email)!=null&&G.trim()?c.email.trim().toLowerCase():null,phone:VRn(c.phone??""),website_url:v7(c.website_url??""),instagram_url:v7(c.instagram_url??""),linkedin_url:v7(c.linkedin_url??""),facebook_url:v7(c.facebook_url??""),other_url:v7(c.other_url??""),photo_url:v7(c.photo_url??""),brokerage:Og(c.brokerage),team_name:Og(c.team_name),city:Og(c.city),state:Og(c.state),postal_code:Og(c.postal_code),market_area:Og(c.market_area),source:Og(c.source),relationship_owner:Og(c.relationship_owner),temperature:c.temperature,primary_pillar:c.primary_pillar==="none"?null:c.primary_pillar,tags:String(c.tags??"").split(",").map(K=>K.trim()).filter(Boolean),goals:Og(c.goals),challenges:Og(c.challenges),interests:Og(c.interests),production_context:Og(c.production_context),notes:Og(c.notes),birthday_on:Og(c.birthday_on),work_anniversary_on:Og(c.work_anniversary_on),license_anniversary_on:Og(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(b.forEach(K=>{K in O&&($[K]=O[K])}),!Object.keys($).length){n(!1);return}i.mutate({id:s.id,values:$,changedLabels:b.map(K=>qRn[K]??K),previousStage:s.stage},{onSuccess:()=>n(!1)})},P=T();return e.jsxs(e.Fragment,{children:[e.jsx(v1,{open:t,onOpenChange:C,children:e.jsxs(rv,{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(Lb,{className:"space-y-1 text-left",children:[e.jsxs(Pb,{className:"text-white text-lg",children:["Edit ",[s.first_name,s.last_name].filter(Boolean).join(" ")]}),e.jsx(vJ,{className:"text-slate-300 text-[12.5px]",children:"Only the fields you change are saved. Stage changes are recorded in pipeline history."})]})}),e.jsxs("div",{className:"px-5 py-5 space-y-7 pb-40",children:[!!P.length&&e.jsxs("div",{className:"rounded-xl bg-amber-50 ring-1 ring-amber-200 p-3 text-[12.5px] text-amber-800 flex gap-2",children:[e.jsx(hd,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Possible duplicate: ",P.slice(0,3).map(L=>`${L.first_name} ${L.last_name??""}`.trim()).join(", "),". You can still save — just double-check first."]})]}),e.jsxs(b7,{title:"Basic info",children:[e.jsx(Dm,{label:"First name *",value:c.first_name,onChange:L=>k("first_name",L)}),e.jsx(Dm,{label:"Last name",value:c.last_name,onChange:L=>k("last_name",L)}),e.jsx(Dm,{label:"Preferred name",value:c.preferred_name,onChange:L=>k("preferred_name",L),placeholder:"What they go by"}),e.jsx(Dm,{label:"Photo / headshot URL",value:c.photo_url,onChange:L=>k("photo_url",L),placeholder:"https://…"})]}),e.jsxs(b7,{title:"Contact & social",children:[e.jsx(Dm,{label:"Email",type:"email",value:c.email,onChange:L=>k("email",L)}),e.jsx(Dm,{label:"Phone",value:c.phone,onChange:L=>k("phone",L)}),e.jsx(Dm,{label:"Website",value:c.website_url,onChange:L=>k("website_url",L)}),e.jsx(Dm,{label:"Instagram",value:c.instagram_url,onChange:L=>k("instagram_url",L)}),e.jsx(Dm,{label:"LinkedIn",value:c.linkedin_url,onChange:L=>k("linkedin_url",L)}),e.jsx(Dm,{label:"Facebook",value:c.facebook_url,onChange:L=>k("facebook_url",L)}),e.jsx(Dm,{label:"Other link",value:c.other_url,onChange:L=>k("other_url",L),className:"sm:col-span-2"})]}),e.jsxs(b7,{title:"Brokerage & market",children:[e.jsx(Dm,{label:"Brokerage",value:c.brokerage,onChange:L=>k("brokerage",L)}),e.jsx(Dm,{label:"Team",value:c.team_name,onChange:L=>k("team_name",L)}),e.jsx(Dm,{label:"City",value:c.city,onChange:L=>k("city",L)}),e.jsx(Dm,{label:"State",value:c.state,onChange:L=>k("state",L)}),e.jsx(Dm,{label:"ZIP / postal code",value:c.postal_code,onChange:L=>k("postal_code",L)}),e.jsx(Dm,{label:"Market / service area",value:c.market_area,onChange:L=>k("market_area",L)})]}),e.jsxs(b7,{title:"Relationship intelligence",hint:"These drive scoring, recommendations, filters and reports.",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Pipeline stage"}),e.jsxs(vs,{value:c.stage,onValueChange:L=>k("stage",L),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:URn.map(L=>e.jsx(Je,{value:L,className:"capitalize",children:L.replace(/_/g," ")},L))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Temperature"}),e.jsxs(vs,{value:c.temperature,onValueChange:L=>k("temperature",L),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:["cold","warm","hot"].map(L=>e.jsx(Je,{value:L,className:"capitalize",children:L},L))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Primary pillar"}),e.jsxs(vs,{value:c.primary_pillar,onValueChange:L=>k("primary_pillar",L),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"Not set"}),["produce","influence","provide","connect"].map(L=>e.jsx(Je,{value:L,className:"capitalize",children:L},L))]})]})]}),e.jsx(Dm,{label:"Source",value:c.source,onChange:L=>k("source",L),placeholder:"Event, referral, social…"}),e.jsx(Dm,{label:"Relationship owner",value:c.relationship_owner,onChange:L=>k("relationship_owner",L),placeholder:"You, or a teammate"}),e.jsx(Dm,{label:"Tags (comma separated)",value:c.tags,onChange:L=>k("tags",L),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(L=>L.trim()).filter(Boolean).map(L=>e.jsx(qe,{variant:"outline",className:"rounded-full text-[11px]",children:L},L))})]}),e.jsxs(b7,{title:"Important dates",hint:"Birthdays and anniversaries feed Milestones & Celebrations automatically — no duplicate entry needed.",children:[e.jsx(Dm,{label:"Birthday",type:"date",value:c.birthday_on,onChange:L=>k("birthday_on",L)}),e.jsx(Dm,{label:"Work anniversary",type:"date",value:c.work_anniversary_on,onChange:L=>k("work_anniversary_on",L)}),e.jsx(Dm,{label:"License anniversary",type:"date",value:c.license_anniversary_on,onChange:L=>k("license_anniversary_on",L)}),e.jsx(Dm,{label:"Next follow-up",type:"date",value:c.next_follow_up_at,onChange:L=>k("next_follow_up_at",L)})]}),e.jsxs(b7,{title:"Notes",children:[e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Goals"}),e.jsx(Ds,{className:"mt-1",rows:2,value:c.goals,onChange:L=>k("goals",L.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Challenges"}),e.jsx(Ds,{className:"mt-1",rows:2,value:c.challenges,onChange:L=>k("challenges",L.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Interests"}),e.jsx(Ds,{className:"mt-1",rows:2,value:c.interests,onChange:L=>k("interests",L.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Production context"}),e.jsx(Ds,{className:"mt-1",rows:2,value:c.production_context,onChange:L=>k("production_context",L.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(se,{className:"text-[12px] text-slate-600",children:"Personal notes"}),e.jsx(Ds,{className:"mt-1",rows:4,value:c.notes,onChange:L=>k("notes",L.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(gm,{className:"h-3.5 w-3.5 mr-1.5"}),s.is_archived?"Restore to pipeline":"Remove from pipeline (archive)"]}),e.jsxs(B,{variant:"destructive",size:"sm",className:"rounded-full",onClick:()=>p(!0),children:[e.jsx(Rn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete permanently"]})]}),e.jsx("p",{className:"text-[12px] text-rose-700/80",children:"Archiving keeps every note, touch and score. Deleting is permanent."})]})]}),e.jsxs("div",{className:"sticky bottom-0 bg-white/95 backdrop-blur border-t px-5 py-3 flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-[12px] text-slate-500",children:i.isPending?"Saving…":v?`${b.length} unsaved change${b.length>1?"s":""}`:"All changes saved"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"ghost",className:"rounded-full",onClick:()=>C(!1),children:[e.jsx(dr,{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:!v||i.isPending,onClick:M,children:[i.isPending&&e.jsx(Wt,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save changes"]})]})]})]})}),e.jsx(Nl,{open:u,onOpenChange:h,children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Discard unsaved changes?"}),e.jsxs(xl,{children:["You have ",b.length," unsaved change(s) on this contact."]})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Keep editing"}),e.jsx(cl,{onClick:()=>{h(!1),n(!1)},children:"Discard"})]})]})}),e.jsx(Nl,{open:m,onOpenChange:p,children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete this contact permanently?"}),e.jsx(xl,{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(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{className:"bg-rose-600 hover:bg-rose-700",onClick:()=>o.mutate(s.id,{onSuccess:()=>{p(!1),n(!1),r==null||r()}}),children:"Delete forever"})]})]})})]})}function GRn(){const s=Hn(),[t,n]=dc(),{agents:r,activeAgents:a,isLoading:i,moveStage:l}=x0(),{followUps:o,complete:c}=VO(),{data:d=[]}=bee();kTe();const u=t.get("view")||"attention",h=K=>n(ee=>(ee.set("view",K),ee),{replace:!0}),[m,p]=j.useState(""),[x,y]=j.useState("all"),[g,b]=j.useState(!1),[v,k]=j.useState(!1),[C,T]=j.useState(!1),[M,P]=j.useState(null),[L,I]=j.useState(null),O=K=>!!K.is_archived!==g||x!=="all"&&Wz(K.stage).key!==x?!1:m.trim()?`${K.first_name} ${K.last_name??""} ${K.brokerage??""} ${K.city??""} ${(K.tags??[]).join(" ")} ${K.email??""}`.toLowerCase().includes(m.trim().toLowerCase()):!0,$=j.useMemo(()=>r.filter(O),[r,m,x,g]),q=j.useMemo(()=>{const K=xm(new Date),ee=o.filter(de=>!de.completed_at),J=d.filter(de=>de.status==="open"),le=ee.filter(de=>de.due_at&&W_(new Date(de.due_at),K)),ue=ee.filter(de=>de.due_at&&Jg(new Date(de.due_at))),oe=a.filter(de=>{const we=de.last_touch_at?new Date(de.last_touch_at):null;return we?Date.now()-+we>45*864e5:!!de.created_at&&Date.now()-+new Date(de.created_at)>14*864e5}),ie=a.filter(de=>!de.next_follow_up_at&&!ee.some(we=>we.agent_id===de.id));return{overdue:le,dueToday:ue,quiet:oe,noNextStep:ie,openRecs:J}},[o,d,a]),W=K=>{const ee=r.find(J=>J.id===K);return ee?`${ee.first_name} ${ee.last_name??""}`.trim():"Someone"},G=[{label:"Relationships",value:a.length,icon:qv},{label:"Overdue",value:q.overdue.length,icon:po,tone:"text-rose-600"},{label:"Due today",value:q.dueToday.length,icon:po,tone:"text-orange-600"},{label:"Gone quiet",value:q.quiet.length,icon:po,tone:"text-slate-600"}];return e.jsxs("div",{children:[e.jsx(tqt,{open:v,onOpenChange:k,onAdded:K=>K&&s(`/attract/agents/${K}`)}),e.jsx($Rn,{open:C,onOpenChange:T}),e.jsx(YYe,{agent:M?r.find(K=>K.id===M.id)??M:null,open:!!M,onOpenChange:K=>!K&&P(null)}),e.jsx(Wh,{eyebrow:"Relationships",title:"The people you're building with",description:"Everyone you know, who needs attention, and what you promised — in one place.",actions:e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>T(!0),children:[e.jsx(Ja,{className:"h-3.5 w-3.5 mr-1.5"})," Import"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",onClick:()=>k(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," Add relationship"]})]})}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5",children:G.map(K=>e.jsxs(be,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:Et("text-2xl font-semibold tabular-nums text-slate-900",K.tone),children:K.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:K.label})]},K.label))}),e.jsxs(be,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px]",children:[e.jsx(Fr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(ye,{value:m,onChange:K=>p(K.target.value),placeholder:"Search name, brokerage, market, tag…",className:"pl-9 rounded-full h-9","aria-label":"Search relationships"})]}),e.jsxs(vs,{value:x,onValueChange:y,children:[e.jsx(gs,{className:"w-[190px] h-9 rounded-full text-[13px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All stages"}),[..._E,ATe].map(K=>e.jsx(Je,{value:K.key,children:K.label},K.key))]})]}),e.jsxs(B,{variant:g?"default":"outline",size:"sm",className:"rounded-full h-9",onClick:()=>b(K=>!K),children:[e.jsx(gm,{className:"h-3.5 w-3.5 mr-1.5"})," ",g?"Archived":"Active"]}),e.jsx("div",{className:"flex bg-slate-100 rounded-full p-0.5",children:[["attention","Needs attention"],["stages","Stages"],["list","List"]].map(([K,ee])=>e.jsxs("button",{onClick:()=>h(K),className:Et("rounded-full h-8 px-3 text-[12.5px] font-medium transition-colors",u===K?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-800"),children:[K==="stages"?e.jsx(r0,{className:"h-3.5 w-3.5 mr-1 inline"}):K==="list"?e.jsx(ug,{className:"h-3.5 w-3.5 mr-1 inline"}):null,ee]},K))})]}),i?e.jsxs("div",{className:"space-y-3","aria-busy":"true",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Loading your relationships…"}),[0,1,2].map(K=>e.jsx(gn,{className:"h-24 w-full rounded-2xl"},K))]}):r.length?u==="attention"?e.jsxs("div",{className:"space-y-6",children:[e.jsx(Rre,{title:"Overdue commitments",tone:"#f43f5e",items:q.overdue,render:K=>e.jsx(Iyt,{f:K,name:W(K.agent_id),onDone:()=>c.mutate(K.id)},K.id)}),e.jsx(Rre,{title:"Due today",tone:"#f97316",items:q.dueToday,render:K=>e.jsx(Iyt,{f:K,name:W(K.agent_id),onDone:()=>c.mutate(K.id)},K.id)}),e.jsx(Rre,{title:"Haven't talked in a while",tone:"#8b5cf6",items:q.quiet.filter(O),render:K=>e.jsx(D8e,{a:K,note:K.last_touch_at?`Last touch ${Bs(new Date(K.last_touch_at),"MMM d")}`:"No meaningful touch yet"},K.id)}),e.jsx(Rre,{title:"No next step set",tone:"#94a3b8",items:q.noNextStep.filter(O),render:K=>e.jsx(D8e,{a:K,note:"Decide one small next step"},K.id)}),!q.overdue.length&&!q.dueToday.length&&!q.quiet.length&&!q.noNextStep.length&&e.jsxs(be,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Nothing needs attention."}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1",children:"Great time to reconnect with someone you haven’t spoken with recently."})]})]}):u==="stages"?e.jsxs(lo,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:_E.length*290},children:_E.map(K=>{const ee=$.filter(J=>Wz(J.stage).key===K.key);return e.jsxs("div",{className:"w-[275px] flex-shrink-0",onDragOver:J=>{J.preventDefault(),J.dataTransfer.dropEffect="move"},onDrop:J=>{J.preventDefault();const le=r.find(ue=>ue.id===L);le&&Wz(le.stage).key!==K.key&&l.mutate({id:le.id,to_stage:KYe(K.key),from_stage:le.stage}),I(null)},children:[e.jsxs("div",{className:"px-1 mb-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:K.color}}),e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:K.label}),e.jsx(qe,{variant:"secondary",className:"text-[10px] h-5 px-1.5",children:ee.length})]}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-0.5 pl-4.5",children:K.help})]}),e.jsxs("div",{className:"rounded-2xl bg-slate-100/60 p-2 space-y-2 min-h-[180px]",children:[ee.map(J=>e.jsxs("div",{draggable:!0,onDragStart:()=>I(J.id),onClick:()=>s(`/attract/agents/${J.id}`),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:K.color},children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[J.first_name," ",J.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 flex items-center gap-1 mt-0.5 truncate",children:[e.jsx(Ni,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:J.brokerage??"Brokerage not set"})]}),!J.email&&!J.phone&&e.jsx("div",{className:"mt-1.5 text-[10.5px] text-amber-700",children:"No contact info yet"})]},J.id)),!ee.length&&e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center py-4",children:"Drag someone here"})]})]},K.key)})}),e.jsx(KU,{orientation:"horizontal"})]}):e.jsxs(be,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:[$.map(K=>e.jsx(D8e,{a:K,onEdit:()=>P(K)},K.id)),!$.length&&e.jsx("div",{className:"p-10 text-center text-[13px] text-slate-500",children:"No one matches this view."})]}):e.jsx(WRn,{onAdd:()=>k(!0)})]})}function Rre({title:s,tone:t,items:n,render:r}){return n.length?e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:t}}),e.jsx("h3",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-700",children:s}),e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:n.length})]}),e.jsx(be,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:n.slice(0,12).map(r)})]}):null}function Iyt({f:s,name:t,onDone:n}){return e.jsxs("div",{className:"flex items-start gap-3 p-4 hover:bg-slate-50",children:[e.jsx(wi,{checked:!1,onCheckedChange:n,className:"mt-0.5","aria-label":"Mark complete"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:s.title}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[s.agent_id?e.jsxs(Yn,{to:`/attract/agents/${s.agent_id}`,className:"hover:text-violet-700",children:["for ",t]}):"Personal task",s.due_at&&e.jsxs(e.Fragment,{children:[" · due ",Bs(new Date(s.due_at),"MMM d")]})]})]})]})}function D8e({a:s,note:t,onEdit:n}){var i,l;const r=Wz(s.stage),a=`${((i=s.first_name)==null?void 0:i[0])??""}${((l=s.last_name)==null?void 0:l[0])??""}`.toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3 p-4 hover:bg-slate-50",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-violet-100 text-violet-700 grid place-items-center text-[12px] font-semibold flex-shrink-0",children:a||"?"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs(Yn,{to:`/attract/agents/${s.id}`,className:"text-[13.5px] font-medium text-slate-900 hover:text-violet-700",children:[s.first_name," ",s.last_name]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5 flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Ni,{className:"h-3 w-3"}),s.brokerage??"Brokerage not set"]}),s.city&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(oi,{className:"h-3 w-3"}),s.city]}),t&&e.jsxs("span",{className:"text-slate-400",children:["· ",t]})]})]}),e.jsx(qe,{variant:"outline",className:"rounded-full text-[10.5px] hidden sm:inline-flex",style:{borderColor:`${r.color}55`,color:r.color},children:r.label}),n&&e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:n,children:"Edit"})]})}function WRn({onAdd:s}){return e.jsxs(be,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-10 text-center",children:[e.jsx("div",{className:"h-11 w-11 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(qv,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Add your first five relationships"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Start with agents you already know — co-op partners, people from your office, agents you met at an event. Attract will begin recommending meaningful next steps."}),e.jsxs(B,{className:"rounded-full btn-primary text-white mt-4",onClick:s,children:[e.jsx(Js,{className:"h-4 w-4 mr-1.5"})," Add a relationship"]})]})}const KRn=[{icon:i1,title:"Helpful Resource",blurb:"One useful document, guide or tool.",to:"/attract/resources"},{icon:Eu,title:"Resource Kit",blurb:"A themed bundle you can personalize and track.",to:"/attract/provide/kits"},{icon:Uh,title:"Training or Masterclass",blurb:"Invite someone to learn something with you.",to:"/attract/provide/masterclasses"},{icon:hN,title:"Event Invitation",blurb:"A room worth being in — online or in person.",to:"/attract/events"},{icon:xb,title:"Coffee Invitation",blurb:"One conversation is enough.",to:"/attract/relationships?view=attention"},{icon:N3,title:"My Brokerage Story",blurb:"Your personal “why I’m here” page.",to:"/attract/landing-page"},{icon:Ni,title:"Brokerage Information",blurb:"Approved, verified brokerage facts only.",to:"/attract/templates"},{icon:az,title:"Comparison Guide",blurb:"A fair, honest side-by-side.",to:"/attract/templates"}],YRn=["Agent Business Planning Kit","Open House Conversion Kit","Listing Marketing Kit","Database Follow-Up Kit","AI for Realtors Kit","New Agent Success Kit","Team-Building Guide","Brokerage Evaluation Checklist","Production Growth Kit","90-Day Agent Business Plan","Social Media Planning Kit","Buyer & Seller Lead Conversion Kit"];function ZRn(){return e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsx(Wh,{eyebrow:"Share Value",title:"What would you like to share?",description:"Give something genuinely useful. Curiosity follows value — it never has to be pushed."}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:KRn.map(s=>e.jsxs(Yn,{to:s.to,className:"rounded-2xl bg-white border border-slate-200/70 p-4 hover:border-violet-300 hover:shadow-sm transition-all flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-violet-50 text-violet-600 grid place-items-center flex-shrink-0",children:e.jsx(s.icon,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:s.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:s.blurb})]})]},s.title))}),e.jsxs(be,{className:"mt-6 p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-600",children:"Ready-to-personalize kits"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-xl",children:"LevelUp-built starting points. Your headshot, contact details and branding are added automatically — you never re-enter your profile."})]}),e.jsx(B,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(Yn,{to:"/attract/provide/kits/templates",children:["Browse kit templates ",e.jsx(Xa,{className:"h-3.5 w-3.5 ml-1.5"})]})})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:YRn.map(s=>e.jsx("span",{className:"rounded-full bg-slate-50 border border-slate-200 px-3 py-1.5 text-[12px] text-slate-700",children:s},s))})]}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400 max-w-lg mx-auto",children:"Engagement means someone found your resource useful — not that they want to change brokerages. Treat it as a reason to keep the relationship going."})]})}function XRn(){const{settings:s}=Zq(),{activeAgents:t}=x0(),n=j.useMemo(()=>{const r=(s==null?void 0:s.primary_pillar)??(s==null?void 0:s.attraction_style)??"balanced",a=((s==null?void 0:s.audiences)??[])[0];return[{icon:Zr,kind:"Talking-head video",title:"Share one thing that changed in your business this year",why:"Personal experience is the only thing no other agent can copy.",to:"/attract/influence/content-studio"},{icon:U9,kind:"Educational carousel",title:"Break down a system other agents could steal from you",why:r==="provide"?"Teaching is your strongest pillar — this plays to it.":"Useful teaching creates curiosity without a pitch.",to:"/attract/influence/content-studio"},{icon:Y9,kind:"Conversation starter",title:a?`Ask ${a} what they’re struggling with right now`:"Ask agents what they’re struggling with right now",why:t.length?`Replies become real conversations with the ${t.length} people you’re already building with.`:"Replies are the easiest way to start new relationships.",to:"/attract/influence/content-studio"}]},[s,t.length]);return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(Wh,{eyebrow:"Create Content",title:"Here are three ways to build attraction through content this week.",description:"Start from a real thing that happened in your business — not a blank page."}),e.jsx("div",{className:"space-y-3",children:n.map(r=>e.jsx(be,{className:"p-5 rounded-2xl border-slate-200/70",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-violet-50 text-violet-600 grid place-items-center flex-shrink-0",children:e.jsx(r.icon,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(qe,{variant:"outline",className:"rounded-full text-[10.5px] uppercase tracking-wider",children:r.kind}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-900 mt-1.5 leading-snug",children:r.title}),e.jsx("p",{className:"text-[12.5px] text-slate-500 mt-1",children:r.why}),e.jsx(B,{size:"sm",className:"rounded-full btn-primary text-white mt-3",asChild:!0,children:e.jsxs(Yn,{to:r.to,children:[e.jsx(um,{className:"h-3.5 w-3.5 mr-1.5"})," Build it"]})})]})]})},r.title))}),e.jsxs("div",{className:"mt-6 grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(O8e,{icon:um,label:"Content Studio",to:"/attract/influence/content-studio"}),e.jsx(O8e,{icon:on,label:"Content calendar",to:"/attract/influence/content-calendar"}),e.jsx(O8e,{icon:Sj,label:"Speaking opportunities",to:"/attract/influence/speaking"})]}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400",children:"Every piece you mark as posted counts toward your weekly attraction plan."})]})}function O8e({icon:s,label:t,to:n}){return e.jsxs(Yn,{to:n,className:"rounded-2xl bg-white border border-slate-200/70 px-4 py-4 hover:border-violet-300 hover:shadow-sm transition-all block",children:[e.jsx(s,{className:"h-4.5 w-4.5 text-violet-600 mb-2"}),e.jsxs("div",{className:"text-[13.5px] font-medium text-slate-800 flex items-center gap-1",children:[t," ",e.jsx(Xa,{className:"h-3 w-3 opacity-40"})]})]})}const Dre=[{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"}],Ryt={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 QRn(){const s=Hn(),{agents:t,isLoading:n,upsertAgent:r,moveStage:a,archiveAgent:i,deleteAgent:l}=x0(),[o,c]=j.useState("kanban"),[d,u]=j.useState(""),[h,m]=j.useState(!1),[p,x]=j.useState(!1),[y,g]=j.useState(),[b,v]=j.useState(null),[k,C]=j.useState(null),[T,M]=j.useState(null),[P,L]=j.useState(null),{gmailEmail:I}=Tf(),O=t.filter(W=>!!W.is_archived!==h?!1:d?`${W.first_name} ${W.last_name??""} ${W.brokerage??""} ${W.city??""} ${(W.tags??[]).join(" ")} ${W.email??""}`.toLowerCase().includes(d.toLowerCase()):!0),$=b?t.find(W=>W.id===b.id)??b:null,q=({agent:W})=>e.jsxs(kd,{children:[e.jsx(Sd,{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(W0,{className:"h-3.5 w-3.5"})})}),e.jsxs(xd,{align:"end",onClick:G=>G.stopPropagation(),children:[e.jsxs(wa,{onClick:()=>C(W),children:[e.jsx(Za,{className:"h-3.5 w-3.5 mr-2"})," Edit contact"]}),e.jsxs(wa,{onClick:()=>s(`/attract/agents/${W.id}`),children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-2"})," Open relationship"]}),e.jsx(uy,{}),e.jsxs(wa,{onClick:()=>i.mutate({id:W.id,archived:!W.is_archived}),children:[e.jsx(gm,{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(Wh,{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(r0,{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(ug,{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:()=>{g(void 0),x(!0)},children:[e.jsx(Js,{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(Fr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(ye,{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(gm,{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:[O.length," agents"]})]}),e.jsx("div",{className:"mb-4",children:e.jsx(HO,{})}),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:Dre.length*300},children:Dre.map(W=>{const G=O.filter(K=>K.stage===W.key);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:K=>{K.preventDefault(),K.dataTransfer.dropEffect="move"},onDrop:K=>{if(K.preventDefault(),T){const ee=t.find(J=>J.id===T);ee&&ee.stage!==W.key&&a.mutate({id:T,to_stage:W.key,from_stage:ee.stage}),M(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(qe,{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:()=>{g(W.key),x(!0)},children:e.jsx(Js,{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(K=>e.jsxs("div",{draggable:!0,onDragStart:()=>M(K.id),onClick:()=>v(K),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:W.color},children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[K.first_name," ",K.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 flex items-center gap-1 mt-0.5 truncate",children:[e.jsx(Ni,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:K.brokerage??"—"})]})]}),K.temperature&&e.jsxs(qe,{variant:"outline",className:`text-[9.5px] px-1.5 py-0 ${Ryt[K.temperature]}`,children:[e.jsx(uK,{className:"h-2.5 w-2.5 mr-0.5"}),K.temperature]}),e.jsx(q,{agent:K})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-[11px] text-slate-500",children:[e.jsx(oi,{className:"h-3 w-3"}),e.jsxs("span",{className:"truncate",children:[K.city,K.state&&`, ${K.state}`]})]}),K.next_follow_up_at&&e.jsxs("div",{className:"mt-1.5 text-[10.5px] text-violet-700 font-medium",children:["Next touch · ",Bs(new Date(K.next_follow_up_at),"MMM d")]})]},K.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(KU,{orientation:"horizontal"})]}):e.jsx(be,{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:[O.map(W=>{const G=Dre.find(K=>K.key===W.stage);return e.jsxs("tr",{onClick:()=>v(W),className:"border-t border-slate-100 hover:bg-slate-50 cursor-pointer",children:[e.jsxs("td",{className:"px-4 py-3 font-medium text-slate-900",children:[W.first_name," ",W.last_name]}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:W.brokerage}),e.jsxs("td",{className:"px-4 py-3 text-slate-600",children:[W.city,", ",W.state]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(qe,{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(qe,{variant:"outline",className:Ryt[W.temperature],children:W.temperature})}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:W.next_follow_up_at?Bs(new Date(W.next_follow_up_at),"MMM d"):"—"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(q,{agent:W})})]},W.id)}),O.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(JRn,{open:p,onOpenChange:x,defaultStage:y,onSubmit:W=>r.mutate(W,{onSuccess:()=>x(!1)})}),e.jsx(YYe,{agent:k?t.find(W=>W.id===k.id)??k:null,open:!!k,onOpenChange:W=>!W&&C(null),onDeleted:()=>v(null)}),e.jsx(v1,{open:!!b,onOpenChange:W=>!W&&v(null),children:e.jsx(rv,{className:"w-full sm:max-w-lg overflow-y-auto",children:$&&e.jsxs(e.Fragment,{children:[e.jsxs(Lb,{children:[e.jsxs(Pb,{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(Ni,{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:()=>C($),children:[e.jsx(Za,{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:()=>L($),children:[e.jsx(on,{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(pa,{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(ro,{className:"h-3.5 w-3.5"})," Log touch"]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Stage"}),e.jsxs(vs,{value:$.stage,onValueChange:W=>a.mutate({id:$.id,to_stage:W,from_stage:$.stage}),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:Dre.map(W=>e.jsx(Je,{value:W.key,children:W.label},W.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Temperature"}),e.jsxs(vs,{value:$.temperature??"warm",onValueChange:W=>r.mutate({id:$.id,first_name:$.first_name,temperature:W}),children:[e.jsx(gs,{className:"mt-1",children:e.jsx(bs,{})}),e.jsx(ys,{children:["cold","warm","hot"].map(W=>e.jsx(Je,{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(qe,{variant:"outline",className:"rounded-full",children:W},W))}),e.jsx(F8e,{label:"Notes",value:$.notes}),e.jsx(F8e,{label:"Goals",value:$.goals}),e.jsx(F8e,{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(gm,{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:()=>C($),children:[e.jsx(Rn,{className:"h-4 w-4 mr-1"})," Delete…"]})]})]})]})})}),(P==null?void 0:P.email)&&e.jsx(cw,{open:!!P,onOpenChange:W=>!W&&L(null),contact:{id:P.id,first_name:P.preferred_name||P.first_name,last_name:P.last_name||"",email:P.email},gmailEmail:I,sendSource:"attract",logTouchpoint:!1})]})}function F8e({label:s,value:t}){return e.jsxs("div",{children:[e.jsx(se,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:s}),e.jsx("div",{className:"mt-1 text-[13.5px] text-slate-800 whitespace-pre-wrap min-h-[24px]",children:t||e.jsx("span",{className:"text-slate-400",children:"Not set"})})]})}function JRn({open:s,onOpenChange:t,defaultStage:n,onSubmit:r}){const[a,i]=j.useState({first_name:"",last_name:"",brokerage:"",city:"",state:"",temperature:"warm",primary_pillar:"connect",stage:n??"new_connection",notes:""});return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx($s,{children:e.jsx(zs,{children:"Add an agent to your pipeline"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"First name *"}),e.jsx(ye,{value:a.first_name,onChange:l=>i({...a,first_name:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last name"}),e.jsx(ye,{value:a.last_name,onChange:l=>i({...a,last_name:l.target.value})})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{children:"Current brokerage"}),e.jsx(ye,{value:a.brokerage,onChange:l=>i({...a,brokerage:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"City"}),e.jsx(ye,{value:a.city,onChange:l=>i({...a,city:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(ye,{value:a.state,onChange:l=>i({...a,state:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Temperature"}),e.jsxs(vs,{value:a.temperature,onValueChange:l=>i({...a,temperature:l}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"cold",children:"Cold"}),e.jsx(Je,{value:"warm",children:"Warm"}),e.jsx(Je,{value:"hot",children:"Hot"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Primary pillar"}),e.jsxs(vs,{value:a.primary_pillar,onValueChange:l=>i({...a,primary_pillar:l}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"produce",children:"Produce"}),e.jsx(Je,{value:"influence",children:"Influence"}),e.jsx(Je,{value:"provide",children:"Provide"}),e.jsx(Je,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(se,{children:"Notes"}),e.jsx(Ds,{rows:3,value:a.notes,onChange:l=>i({...a,notes:l.target.value})})]})]}),e.jsxs(Nr,{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 eDn={call:pa,email:on,coffee:xb,gift:zo,text:on,event:ym};function tDn(){const{followUps:s,complete:t}=VO(),{agents:n}=x0(),r=j.useMemo(()=>{const l=xm(new Date),o=[],c=[],d=[],u=[],h=[];for(const m of s){if(m.completed_at){h.push(m);continue}if(!m.due_at){u.push(m);continue}const p=new Date(m.due_at);W_(p,l)?o.push(m):Jg(p)?c.push(m):zhs(p)?d.push(m):u.push(m)}return{overdue:o,today:c,tomorrow:d,later:u,done:h}},[s]),a=new Map(n.map(l=>[l.id,l])),i=[{label:"Overdue",value:r.overdue.length,tone:"text-rose-600 bg-rose-50",icon:po},{label:"Due Today",value:r.today.length,tone:"text-orange-600 bg-orange-50",icon:Vr},{label:"Completed This Week",value:r.done.filter(l=>l.completed_at&&new Date(l.completed_at)>jd(new Date,-7)).length,tone:"text-emerald-600 bg-emerald-50",icon:Rr}];return e.jsxs("div",{children:[e.jsx(Wh,{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(be,{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(HO,{})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(uG,{title:"Overdue",items:r.overdue,agentMap:a,onComplete:l=>t.mutate(l),tone:"rose"}),e.jsx(uG,{title:"Today",items:r.today,agentMap:a,onComplete:l=>t.mutate(l),tone:"orange"}),e.jsx(uG,{title:"Tomorrow",items:r.tomorrow,agentMap:a,onComplete:l=>t.mutate(l),tone:"violet"}),e.jsx(uG,{title:"Later This Week",items:r.later,agentMap:a,onComplete:l=>t.mutate(l),tone:"slate"}),r.done.length>0&&e.jsx(uG,{title:"Recently Completed",items:r.done.slice(0,5),agentMap:a,onComplete:()=>{},tone:"emerald",done:!0})]})]})}function uG({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(qe,{variant:"secondary",className:"text-[10px]",children:t.length})]}),e.jsx(be,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:t.map(o=>{const c=n.get(o.agent_id),d=eDn[o.touch_type??""]??on;return e.jsxs("div",{className:`flex items-start gap-3 p-4 hover:bg-slate-50 ${i?"opacity-60":""}`,children:[e.jsx(wi,{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:Bs(new Date(o.due_at),"MMM d")}),e.jsx(B,{variant:"ghost",size:"sm",children:"Snooze"})]},o.id)})})]})}const sDn={pdf:$r,link:Rc,video:Zr,tool:O5,guide:Op},nDn={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 rDn(){const{resources:s,isLoading:t}=XUt(),[n,r]=j.useState(""),[a,i]=j.useState("all"),l=Array.from(new Set(s.map(c=>c.category).filter(Boolean))),o=s.filter(c=>(a==="all"||c.category===a)&&(!n||`${c.title} ${c.description??""}`.toLowerCase().includes(n.toLowerCase())));return e.jsxs("div",{children:[e.jsx(Wh,{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(Js,{className:"h-4 w-4 mr-1"})," Add Resource"]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px] max-w-md",children:[e.jsx(Fr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(ye,{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(be,{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=sDn[c.resource_type]??$r;return e.jsxs(be,{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(qe,{className:`${nDn[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(zd,{className:"h-3.5 w-3.5"})," Share"]})]})]},c.id)})})]})}const aDn=[{category:"First Touch",icon:ro,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:on,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:xb,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:pa,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 iDn(){const s=t=>{navigator.clipboard.writeText(t),re.success("Template copied")};return e.jsxs("div",{children:[e.jsx(Wh,{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:aDn.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(be,{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(qe,{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(ja,{className:"h-3.5 w-3.5"})," Copy"]})})]},r.title))})]},t.category)})})]})}const oDn={produce:"#7c3aed",influence:"#4f46e5",provide:"#0d9488",connect:"#9333ea"};function Dyt(){const{agents:s}=x0(),{activities:t}=GYe(180),n=j.useMemo(()=>Array.from({length:12},(l,o)=>xg(kK(new Date,(11-o)*7))).map(l=>{const o=jd(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:oDn[l]}))},[t]),a=j.useMemo(()=>["new_connection","building_relationship","engaging_with_value","active_conversation","brokerage_presentation","joined"].map(l=>({stage:l.replace(/_/g," "),count:s.filter(o=>o.stage===l).length})),[s]);return e.jsxs("div",{children:[e.jsx(Wh,{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(be,{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(jb,{width:"100%",height:260,children:e.jsxs(mWe,{data:n,children:[e.jsx(p1,{dataKey:"week",tick:{fontSize:11}}),e.jsx(f1,{tick:{fontSize:11}}),e.jsx(ff,{}),e.jsx(MO,{type:"monotone",dataKey:"activities",stroke:"#7c3aed",strokeWidth:2.5,dot:{r:3}})]})})]}),e.jsxs(be,{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(jb,{width:"100%",height:260,children:e.jsxs(pWe,{children:[e.jsx($N,{data:r,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",innerRadius:55,outerRadius:90,paddingAngle:2,children:r.map((i,l)=>e.jsx(_q,{fill:i.color},l))}),e.jsx(ff,{}),e.jsx(iD,{})]})})]}),e.jsxs(be,{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(jb,{width:"100%",height:280,children:e.jsxs(CAe,{data:a,children:[e.jsx(p1,{dataKey:"stage",tick:{fontSize:10}}),e.jsx(f1,{tick:{fontSize:11}}),e.jsx(ff,{}),e.jsx(Bj,{dataKey:"count",fill:"#4f46e5",radius:[8,8,0,0]})]})})]})]})]})}function lDn(){const{settings:s,upsert:t,resetOnboarding:n}=Zq(),[r,a]=j.useState({});j.useEffect(()=>{s&&a(s)},[s]);const i=l=>a({...r,...l});return e.jsxs("div",{className:"max-w-3xl",children:[e.jsx(Wh,{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(be,{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(uu,{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(Yn,{to:"/attract/plan",children:"View plan"})}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>n.mutate(),children:[e.jsx(bm,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Your voice & story"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"Used to personalize scripts, invites, and shared content."}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Elevator introduction"}),e.jsx(Ds,{rows:3,value:r.elevator_intro??"",onChange:l=>i({elevator_intro:l.target.value}),placeholder:"I help agents scale their business by trading isolation for a real team..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Focus market"}),e.jsx(ye,{value:r.focus_market??"",onChange:l=>i({focus_market:l.target.value}),placeholder:"Orange County, CA"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Annual attraction goal"}),e.jsx(ye,{type:"number",value:r.annual_attract_goal??"",onChange:l=>i({annual_attract_goal:Number(l.target.value)||null}),placeholder:"12"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:'Your "why" for attraction'}),e.jsx(Ds,{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(be,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Cadence & rhythm"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"How often should we remind you to show up for agents at each stage?"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Hot leads follow-up"}),e.jsxs(vs,{value:String(r.hot_cadence_days??3),onValueChange:l=>i({hot_cadence_days:Number(l)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"1",children:"Every day"}),e.jsx(Je,{value:"3",children:"Every 3 days"}),e.jsx(Je,{value:"7",children:"Every week"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Warm leads follow-up"}),e.jsxs(vs,{value:String(r.warm_cadence_days??14),onValueChange:l=>i({warm_cadence_days:Number(l)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"7",children:"Weekly"}),e.jsx(Je,{value:"14",children:"Every 2 weeks"}),e.jsx(Je,{value:"30",children:"Monthly"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Long-term nurture"}),e.jsxs(vs,{value:String(r.longterm_cadence_days??60),onValueChange:l=>i({longterm_cadence_days:Number(l)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"30",children:"Monthly"}),e.jsx(Je,{value:"60",children:"Every 2 months"}),e.jsx(Je,{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(Mn,{checked:r.weekly_digest_enabled??!0,onCheckedChange:l=>i({weekly_digest_enabled:l})})]})})]})]}),e.jsxs(be,{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 e$e=[{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."}],t$e={live:"Live",partial:"Partial",placeholder:"Placeholder",integration_required:"Integration required"},sqt={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 cDn({tool:s,accent:t}){const[n,r]=j.useState(!1),a=Hn(),i=s.icon,l=!!s.to,o=e$e.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(be,{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 ${sqt[c]}`,children:[c==="live"&&e.jsx(yn,{className:"h-2.5 w-2.5"}),t$e[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(Fs,{open:n,onOpenChange:r,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl grid place-items-center mb-2",style:{background:`${t}18`,color:t},children:e.jsx(i,{className:"h-6 w-6"})}),e.jsx(zs,{children:s.title})]}),e.jsxs("div",{className:"text-[14px] text-slate-700 leading-relaxed",children:[s.description,e.jsx("div",{className:"mt-4 rounded-xl bg-violet-50 border border-violet-100 p-4 text-[13px] text-violet-900",children:"This tool is on the roadmap. Mark your interest and it will jump the queue in your next release."})]}),e.jsxs(Nr,{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:()=>{re.success("Added to your plan"),r(!1)},children:"Add to My Plan"})]})]})})]})}function ZYe({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(cDn,{tool:c,accent:a},c.key))})]})}function Oyt(){return e.jsx(ZYe,{pillar:"01",title:"Produce",accent:"#7c3aed",icon:ll,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:oy,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:cu,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:V_,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:kl,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 Fyt(){return e.jsx(ZYe,{pillar:"02",title:"Influence",accent:"#4f46e5",icon:yn,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:w3,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:Vc,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:Sj,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:Uh,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:Zr,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:Bn,title:"Agent Roundtables",description:"Host small-group conversations using the Connect Event Engine — value first, no pitching.",to:"/attract/events/new"}]})}const W7=["attract-kits"],hG=s=>["attract-kit-items",s],mG=s=>["attract-kit-shares",s??"all"],dDn=s=>["attract-kit-events",s??"all"],uDn=["attract-kit-templates"];function Xq(){const{user:s}=Ns(),t=as(),n=mt({queryKey:[...W7,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await U.from("attract_resource_kits").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=vt({mutationFn:async o=>{if(!s)throw new Error("not authenticated");const{data:c,error:d}=await U.from("attract_resource_kits").insert({user_id:s.id,title:o.title||"Untitled Kit",...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:W7})}),a=vt({mutationFn:async({id:o,patch:c})=>{const{data:d,error:u}=await U.from("attract_resource_kits").update(c).eq("id",o).select("*").single();if(u)throw u;return d},onSuccess:()=>t.invalidateQueries({queryKey:W7})}),i=vt({mutationFn:async o=>{const{error:c}=await U.from("attract_resource_kits").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:W7})}),l=vt({mutationFn:async o=>{const{data:c,error:d}=await U.rpc("duplicate_attract_kit",{_kit_id:o});if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:W7})});return{kits:n.data??[],isLoading:n.isLoading,create:r,update:a,remove:i,duplicate:l}}function nqt(s){return mt({queryKey:["attract-kit",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("attract_resource_kits").select("*").eq("id",s).single();if(n)throw n;return t}})}function hDn(s){const t=as(),n=mt({queryKey:hG(s??""),enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await U.from("attract_resource_kit_items").select("*").eq("kit_id",s).order("sort_order");if(c)throw c;return o??[]}}),r=vt({mutationFn:async o=>{var u;const{data:c,error:d}=await U.from("attract_resource_kit_items").insert({kit_id:s,type:"text",title:"New item",sort_order:((u=n.data)==null?void 0:u.length)??0,...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:hG(s??"")})}),a=vt({mutationFn:async({id:o,patch:c})=>{const{error:d}=await U.from("attract_resource_kit_items").update(c).eq("id",o);if(d)throw d},onSuccess:()=>t.invalidateQueries({queryKey:hG(s??"")})}),i=vt({mutationFn:async o=>{const{error:c}=await U.from("attract_resource_kit_items").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:hG(s??"")})}),l=vt({mutationFn:async o=>{await Promise.all(o.map((c,d)=>U.from("attract_resource_kit_items").update({sort_order:d}).eq("id",c)))},onSuccess:()=>t.invalidateQueries({queryKey:hG(s??"")})});return{items:n.data??[],isLoading:n.isLoading,add:r,update:a,remove:i,reorder:l}}function rqt(s){const{user:t}=Ns(),n=as(),r=mt({queryKey:mG(s),enabled:!!t,queryFn:async()=>{let l=U.from("attract_kit_shares").select("*").order("created_at",{ascending:!1});s&&(l=l.eq("kit_id",s));const{data:o,error:c}=await l;if(c)throw c;return o??[]}}),a=vt({mutationFn:async l=>{if(!t)throw new Error("not authenticated");const{data:o,error:c}=await U.from("attract_kit_shares").insert({owner_user_id:t.id,...l}).select("*").single();if(c)throw c;return o},onSuccess:l=>{var o;n.invalidateQueries({queryKey:mG(s)}),n.invalidateQueries({queryKey:mG()});try{(o=navigator.clipboard)==null||o.writeText(iqt(l.share_token)),re.success("Share link created and copied")}catch{re.success("Share link created")}},onError:l=>re.error((l==null?void 0:l.message)||"Could not create share link")}),i=vt({mutationFn:async l=>{const{error:o}=await U.from("attract_kit_shares").update({status:"revoked"}).eq("id",l);if(o)throw o},onSuccess:()=>{n.invalidateQueries({queryKey:mG(s)}),n.invalidateQueries({queryKey:mG()}),re.success("Link revoked")},onError:l=>re.error((l==null?void 0:l.message)||"Could not revoke link")});return{shares:r.data??[],isLoading:r.isLoading,create:a,revoke:i}}function aqt(s){return mt({queryKey:dDn(s),queryFn:async()=>{let t=U.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(500);s&&(t=t.eq("kit_id",s));const{data:n,error:r}=await t;if(r)throw r;return n??[]}})}function mDn(){return mt({queryKey:uDn,queryFn:async()=>{const{data:s,error:t}=await U.from("attract_kit_templates").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function pDn(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.rpc("clone_attract_kit_template",{_template_id:t});if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:W7})})}function iqt(s){return`${typeof window<"u"?window.location.origin:""}/attract-kit/${s}`}function zyt(){const{kits:s}=Xq(),{data:t=[]}=aqt(),{followUps:n}=VO(),r=j.useMemo(()=>{const l=o=>t.filter(c=>c.event_type===o).length;return{published:s.filter(o=>o.status==="published").length,drafts:s.filter(o=>o.status==="draft").length,views:l("page_view"),downloads:l("file_download"),cta:l("primary_cta_click"),questions:l("question_submitted")}},[s,t]),a=t.slice(0,8),i=n.filter(l=>!l.completed_at&&l.touch_type==="kit_engagement").slice(0,6);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{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(Yn,{to:"/attract/provide/kits/templates",children:[e.jsx(i1,{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(Yn,{to:"/attract/provide/kits/new",children:[e.jsx(Js,{className:"h-4 w-4 mr-2"}),"New kit"]})})]})}),e.jsx(be,{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(FR,{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(Yn,{to:"/attract/provide/kits/new",children:"Start a kit"})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(Yn,{to:"/attract/provide/kits/templates",children:"Browse 10 starter kits"})})]})]})]})}),e.jsx(be,{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(yn,{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(Yn,{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(_7,{label:"Published",value:r.published}),e.jsx(_7,{label:"Drafts",value:r.drafts}),e.jsx(_7,{label:"Views",value:r.views,icon:ma}),e.jsx(_7,{label:"Downloads",value:r.downloads,icon:ii}),e.jsx(_7,{label:"CTA clicks",value:r.cta,icon:lu}),e.jsx(_7,{label:"Questions",value:r.questions,icon:Yd})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(be,{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(Yn,{to:"/attract/provide/kits",children:["View kits ",e.jsx(Xa,{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:oc(new Date(l.created_at),{addSuffix:!0})})]},l.id))})]}),e.jsxs(be,{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 ",oc(new Date(l.due_at),{addSuffix:!0})]})]},l.id))})]})]}),e.jsxs(be,{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(Yn,{to:"/attract/provide/kits",children:["See all ",e.jsx(Xa,{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(Yn,{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(Yn,{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(qe,{variant:"outline",className:"capitalize",children:l.status}),l.pillar&&e.jsx(qe,{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(HO,{})]})}function _7({label:s,value:t,icon:n}){return e.jsxs(be,{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 Byt(){return e.jsx(ZYe,{pillar:"04",title:"Connect",accent:"#9333ea",icon:zR,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:xb,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:ra,title:"Attraction Events",description:"Design intimate gatherings — happy hours, dinners, mastermind lunches — with registration and check-in.",to:"/attract/events"},{key:"milestones",icon:Wm,title:"Milestones & Celebrations",description:"Never miss a birthday, license anniversary, or business milestone for a prospective agent.",to:"/attract/connect/milestones"},{key:"checkins",icon:Yd,title:"Personal Check-Ins",description:"Relationship-first check-ins surfaced by your intelligence layer, ranked by signal.",to:"/attract/opportunities"},{key:"circles",icon:qv,title:"Agent Circles",description:"Small peer groups you host quarterly — built on the Connect Event Engine.",to:"/attract/events/new"}]})}const fDn=[{key:"coffee",label:"Coffee & Conversation",icon:xb,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:qv,tone:"from-violet-500 to-indigo-500",description:"4–6 agents share what is actually working right now."},{key:"mastermind",label:"Mastermind",icon:yn,tone:"from-fuchsia-500 to-pink-500",description:"A quarterly small group solving each other’s biggest questions."},{key:"workshop",label:"Workshop / Webinar",icon:uu,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:bK,tone:"from-rose-500 to-red-500",description:"The relationship-first gathering. No agenda, just presence."},{key:"networking_plan",label:"Networking Game Plan",icon:zR,tone:"from-teal-500 to-emerald-500",description:"Not an event — a plan for the next 5 rooms you will walk into."}];function xDn(){const s=Hn(),{data:t=[]}=STe(),{followUps:n}=VO(),{agents:r}=x0(),a=j.useMemo(()=>{const l=new Date,o=jd(l,7),c=t.filter(m=>m.status==="published"&&vb(new Date(m.starts_at),l)),d=t.filter(m=>m.status==="draft").length,u=t.reduce((m,p)=>m+(vb(new Date(p.created_at),jd(l,-7))?p.registration_count:0),0),h=n.filter(m=>!m.completed_at&&m.due_at&&W_(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(ra,{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(Js,{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:ra,tone:"text-violet-700 bg-violet-100"},{label:"Drafts needing invites",value:a.draftsNeedingInvites,icon:Dr,tone:"text-amber-700 bg-amber-100"},{label:"Registrations this week",value:a.regs,icon:kl,tone:"text-emerald-700 bg-emerald-100"},{label:"48-hour follow-ups due",value:a.dueSoon,icon:zp,tone:"text-rose-700 bg-rose-100"}].map(l=>e.jsxs(be,{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(be,{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:[Bs(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(qe,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[i.registration_count," registered"]}),i.capacity&&e.jsxs(qe,{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(Xa,{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(be,{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(Yn,{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:fDn.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(Xa,{className:"h-3 w-3"})]})]},l.key))})]}),e.jsxs(be,{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:xb,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:yn,tone:"text-violet-600 bg-violet-50"},{label:"People in pipeline",target:r.length,actual:r.length,icon:qv,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 gDn(){const s=Hn(),{data:t=[],isLoading:n}=STe(),r=TRn(),a=SRn(),[i,l]=j.useState("all"),[o,c]=j.useState(""),d=j.useMemo(()=>t.filter(u=>!(i!=="all"&&u.status!==i||o&&!u.title.toLowerCase().includes(o.toLowerCase()))),[t,i,o]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Connect · Events"}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:"Events"}),e.jsx("p",{className:"text-slate-600 mt-1",children:"Every room you have built — drafted, live, and complete."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{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(Js,{className:"h-4 w-4 mr-2"})," New event"]})]})]}),e.jsxs(fa,{value:i,onValueChange:u=>l(u),children:[e.jsxs(xa,{className:"rounded-full bg-white border border-slate-200",children:[e.jsxs(ss,{value:"all",className:"rounded-full",children:["All (",t.length,")"]}),e.jsxs(ss,{value:"draft",className:"rounded-full",children:["Drafts (",t.filter(u=>u.status==="draft").length,")"]}),e.jsxs(ss,{value:"published",className:"rounded-full",children:["Published (",t.filter(u=>u.status==="published").length,")"]}),e.jsxs(ss,{value:"completed",className:"rounded-full",children:["Completed (",t.filter(u=>u.status==="completed").length,")"]})]}),e.jsx(ns,{value:i,className:"mt-5",children:n?e.jsx(be,{className:"p-12 rounded-2xl text-center text-slate-500",children:"Loading events…"}):d.length===0?e.jsxs(be,{className:"p-12 rounded-2xl text-center border-dashed",children:[e.jsx(ra,{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(Js,{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(be,{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(qe,{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(qe,{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:Bs(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(Zr,{className:"h-3.5 w-3.5"})," Virtual"]}):u.format==="hybrid"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"})," Hybrid"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(oi,{className:"h-3.5 w-3.5"})," ",u.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"})," ",u.registration_count,u.capacity?` / ${u.capacity}`:""]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>r.mutate(u.id),children:[e.jsx(ja,{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(CTe(u.public_slug)),re.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:async()=>{await Bi("Delete this event?")&&a.mutate(u.id)},children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]})]},u.id))})})]})]})}const yDn=[{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 $yt(){const{eventId:s}=$i(),t=Hn(),[n]=dc(),r=n.get("type"),a=!!s,{data:i}=WYe(s),{data:l=[]}=HUt(),{kits:o}=Xq(),c=GUt(),d=WUt(),[u,h]=j.useState({title:"",description:"",event_type_key:r||"coffee",intended_audience:"",related_pillar:"connect",starts_at:new Date(Date.now()+7*864e5).toISOString().slice(0,16),ends_at:"",timezone:"America/New_York",format:"in_person",location:"",address:"",virtual_url:"",capacity:"",waitlist_enabled:!0,host_name:"",cohosts:[],agenda:[],learning_outcomes:[],registration_questions:[],confirmation_message:"",resource_kit_id:null,kit_delivery_trigger:"after_attendance",followup_hours:48});j.useEffect(()=>{i&&h({...i,starts_at:i.starts_at?i.starts_at.slice(0,16):"",ends_at:i.ends_at?i.ends_at.slice(0,16):"",capacity:i.capacity??"",cohosts:i.cohosts||[],agenda:i.agenda||[],learning_outcomes:i.learning_outcomes||[],registration_questions:i.registration_questions||[]})},[i]);const m=b=>h(v=>({...v,...b})),p=j.useMemo(()=>l.slice(0,4),[l]),x=b=>{m({title:b.title,description:b.description,event_type_key:b.event_type_key,related_pillar:b.related_pillar,intended_audience:b.intended_audience,agenda:b.suggested_agenda||[],learning_outcomes:b.suggested_outcomes||[],registration_questions:b.suggested_questions||[],confirmation_message:b.suggested_confirmation}),re.success(`Loaded "${b.title}"`)},y=async(b={})=>{const v={...u,starts_at:u.starts_at?new Date(u.starts_at).toISOString():new Date().toISOString(),ends_at:u.ends_at?new Date(u.ends_at).toISOString():null,capacity:u.capacity===""?null:Number(u.capacity),status:b.publish?"published":u.status||"draft"};if(a)await d.mutateAsync({id:s,patch:v}),re.success(b.publish?"Published":"Saved");else{const k=await c.mutateAsync(v);re.success(b.publish?"Event published":"Draft saved"),t(`/attract/events/${k.id}${b.publish?"":"/edit"}`,{replace:!0})}},g=i!=null&&i.public_slug?CTe(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(_a,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(g),re.success("Registration link copied")},children:[e.jsx(vc,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>y(),children:[e.jsx(Jo,{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(oy,{className:"h-4 w-4 mr-2"})," ",(i==null?void 0:i.status)==="published"?"Update published":"Publish"]})]})]}),!a&&p.length>0&&e.jsxs(be,{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(yn,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:"Start from a premium template"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:p.map(b=>e.jsxs("button",{onClick:()=>x(b),className:"text-left rounded-xl bg-white/70 border border-white p-3 hover:bg-white transition",children:[e.jsx("div",{className:"text-[13.5px] font-semibold text-slate-900",children:b.title}),e.jsx("div",{className:"text-[12px] text-slate-600 line-clamp-2 mt-0.5",children:b.description})]},b.id))})]}),e.jsxs(be,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 1"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Event basics"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:u.title,onChange:b=>m({title:b.target.value}),placeholder:"Coffee & Systems Roundtable"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Event type"}),e.jsxs(vs,{value:u.event_type_key,onValueChange:b=>m({event_type_key:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:yDn.map(b=>e.jsx(Je,{value:b.key,children:b.label},b.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Related pillar"}),e.jsxs(vs,{value:u.related_pillar||"connect",onValueChange:b=>m({related_pillar:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"produce",children:"Produce"}),e.jsx(Je,{value:"influence",children:"Influence"}),e.jsx(Je,{value:"provide",children:"Provide"}),e.jsx(Je,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Intended audience"}),e.jsx(ye,{value:u.intended_audience||"",onChange:b=>m({intended_audience:b.target.value}),placeholder:"Producing agents 1–5 years in"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{rows:4,value:u.description||"",onChange:b=>m({description:b.target.value}),placeholder:"What is this event and why does it matter?"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Starts at"}),e.jsx(ye,{type:"datetime-local",value:u.starts_at||"",onChange:b=>m({starts_at:b.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Ends at"}),e.jsx(ye,{type:"datetime-local",value:u.ends_at||"",onChange:b=>m({ends_at:b.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Time zone"}),e.jsxs(vs,{value:u.timezone||"America/New_York",onValueChange:b=>m({timezone:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Phoenix"].map(b=>e.jsx(Je,{value:b,children:b},b))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Format"}),e.jsxs(vs,{value:u.format,onValueChange:b=>m({format:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"in_person",children:"In person"}),e.jsx(Je,{value:"virtual",children:"Virtual"}),e.jsx(Je,{value:"hybrid",children:"Hybrid"})]})]})]}),u.format!=="virtual"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{children:"Venue / location name"}),e.jsx(ye,{value:u.location||"",onChange:b=>m({location:b.target.value}),placeholder:"Rise Coffee — Downtown"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Address"}),e.jsx(ye,{value:u.address||"",onChange:b=>m({address:b.target.value}),placeholder:"123 Main St, City, ST"})]})]}),u.format!=="in_person"&&e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Virtual meeting URL"}),e.jsx(ye,{value:u.virtual_url||"",onChange:b=>m({virtual_url:b.target.value}),placeholder:"https://zoom.us/…"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Capacity (optional)"}),e.jsx(ye,{type:"number",value:u.capacity,onChange:b=>m({capacity:b.target.value}),placeholder:"No limit"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-6",children:[e.jsx(Mn,{checked:u.waitlist_enabled,onCheckedChange:b=>m({waitlist_enabled:b}),id:"wl"}),e.jsx(se,{htmlFor:"wl",className:"cursor-pointer",children:"Allow waitlist if full"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Host name (as shown publicly)"}),e.jsx(ye,{value:u.host_name||"",onChange:b=>m({host_name:b.target.value}),placeholder:"Jeremy from LevelUp"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Cover image URL"}),e.jsx(ye,{value:u.cover_image_url||"",onChange:b=>m({cover_image_url:b.target.value}),placeholder:"https://…"})]})]})]}),e.jsxs(be,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 2"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Experience & agenda"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{children:"Agenda"}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({agenda:[...u.agenda||[],{time:"",item:""}]}),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Add item"]})]}),e.jsxs("div",{className:"space-y-2",children:[(u.agenda||[]).map((b,v)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{className:"w-24",value:b.time||"",onChange:k=>{const C=[...u.agenda];C[v]={...C[v],time:k.target.value},m({agenda:C})},placeholder:"0:00"}),e.jsx(ye,{value:b.item||"",onChange:k=>{const C=[...u.agenda];C[v]={...C[v],item:k.target.value},m({agenda:C})},placeholder:"What happens here"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>m({agenda:u.agenda.filter((k,C)=>C!==v)}),children:e.jsx(dr,{className:"h-4 w-4"})})]},v)),(u.agenda||[]).length===0&&e.jsx("div",{className:"text-[12px] text-slate-400",children:"Add each moment of the event so attendees know what to expect."})]})]}),e.jsx(Xl,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{children:"What attendees will receive"}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({learning_outcomes:[...u.learning_outcomes||[],""]}),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Add outcome"]})]}),e.jsx("div",{className:"space-y-2",children:(u.learning_outcomes||[]).map((b,v)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:b,onChange:k=>{const C=[...u.learning_outcomes];C[v]=k.target.value,m({learning_outcomes:C})},placeholder:"One clear, honest outcome"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>m({learning_outcomes:u.learning_outcomes.filter((k,C)=>C!==v)}),children:e.jsx(dr,{className:"h-4 w-4"})})]},v))})]})]})]}),e.jsxs(be,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 3"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Registration page"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(se,{children:"Registration questions"}),e.jsxs(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(Js,{className:"h-3.5 w-3.5 mr-1"})," Add question"]})]}),e.jsx("div",{className:"space-y-2",children:(u.registration_questions||[]).map((b,v)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{className:"flex-1",value:b.label,onChange:k=>{const C=[...u.registration_questions];C[v]={...C[v],label:k.target.value,key:b.key||`q${v+1}`},m({registration_questions:C})},placeholder:"Question shown to registrants"}),e.jsxs(vs,{value:b.type,onValueChange:k=>{const C=[...u.registration_questions];C[v]={...C[v],type:k},m({registration_questions:C})},children:[e.jsx(gs,{className:"w-32",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"text",children:"Short text"}),e.jsx(Je,{value:"long",children:"Long text"})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>m({registration_questions:u.registration_questions.filter((k,C)=>C!==v)}),children:e.jsx(dr,{className:"h-4 w-4"})})]},v))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Confirmation message (shown after registration)"}),e.jsx(Ds,{rows:3,value:u.confirmation_message||"",onChange:b=>m({confirmation_message:b.target.value}),placeholder:"You are in — come with one honest question."})]})]})]}),e.jsxs(be,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 4"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Resource Kit & 48-hour follow-up"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Attach a Resource Kit"}),e.jsxs(vs,{value:u.resource_kit_id||"none",onValueChange:b=>m({resource_kit_id:b==="none"?null:b}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"None"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"None"}),(o||[]).map(b=>e.jsx(Je,{value:b.id,children:b.title},b.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Deliver kit"}),e.jsxs(vs,{value:u.kit_delivery_trigger||"after_attendance",onValueChange:b=>m({kit_delivery_trigger:b}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"on_registration",children:"On registration"}),e.jsx(Je,{value:"on_confirmation",children:"On confirmation"}),e.jsx(Je,{value:"on_check_in",children:"At check-in"}),e.jsx(Je,{value:"after_attendance",children:"After attendance"}),e.jsx(Je,{value:"manual",children:"Only manually"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Default follow-up window (hours)"}),e.jsx(ye,{type:"number",value:u.followup_hours??48,onChange:b=>m({followup_hours:Number(b.target.value)})})]})]}),!u.resource_kit_id&&e.jsx("div",{className:"text-[12px] text-amber-700 bg-amber-50 border border-amber-200 rounded-lg p-3 mt-4",children:"Tip: attach a Resource Kit so attendees leave with something valuable — and so follow-ups have a natural reason."})]}),e.jsxs(be,{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(qe,{variant:"secondary",className:"bg-rose-50 text-rose-700 border-rose-200",children:"Add title and start time"}),(u.agenda||[]).length===0&&e.jsx(qe,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No agenda yet"}),(u.learning_outcomes||[]).length===0&&e.jsx(qe,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No stated outcomes"}),!u.resource_kit_id&&e.jsx(qe,{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(Jo,{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(oy,{className:"h-4 w-4 mr-2"})," Publish"]})]})]})]})}const F2e=s=>s?[s.first_name,s.last_name].filter(Boolean).join(" "):"";function vDn(){const{eventId:s}=$i(),t=Hn(),{data:n}=WYe(s),{data:r=[]}=VUt(s),{data:a=[]}=NRn(s),{data:i=[]}=kRn(s),{agents:l}=x0(),{data:o=[]}=HUt(),c=KUt(),d=CRn(),u=ARn(),h=WUt(),m=j.useMemo(()=>{const y=r.length,g=r.filter(I=>I.status==="registered"||I.status==="confirmed").length,b=r.filter(I=>I.status==="attended").length,v=r.filter(I=>I.status==="no_show").length,k=r.filter(I=>I.status==="waitlisted").length,C=g+b+v,T=C>0?Math.round(b/C*100):0,M=a.length>0?Math.round(a.filter(I=>I.viewed_at).length/a.length*100):0,P=r.filter(I=>I.followup_status==="done").length,L=b>0?Math.round(P/b*100):0;return{total:y,registered:g,attended:b,noShow:v,waitlist:k,attendRate:T,invView:M,followed:P,followedRate:L}},[r,a]);if(!n)return e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"});const p=n.public_slug?CTe(n.public_slug):null,x=()=>{const y=new Blob([YUt(n)],{type:"text/calendar"}),g=URL.createObjectURL(y),b=document.createElement("a");b.href=g,b.download=`${n.public_slug||"event"}.ics`,b.click(),URL.revokeObjectURL(g)};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(_a,{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:x,children:[e.jsx(ii,{className:"h-3.5 w-3.5 mr-2"})," ICS"]}),p&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(p),re.success("Link copied")},children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),p&&e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:p,target:"_blank",rel:"noreferrer",children:[e.jsx(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(hg,{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(be,{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(qe,{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(qe,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.related_pillar}),n.event_type_key&&e.jsx(qe,{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(ra,{className:"h-4 w-4"})," ",Bs(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(Zr,{className:"h-4 w-4"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(oi,{className:"h-4 w-4"})," ",n.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Bn,{className:"h-4 w-4"})," ",n.registration_count," registered",n.capacity?` / ${n.capacity}`:""]})]})]}),n.status==="draft"&&e.jsx(B,{className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:async()=>{await h.mutateAsync({id:n.id,patch:{status:"published"}}),re.success("Published")},children:"Publish now"}),n.status==="published"&&new Date(n.starts_at){await h.mutateAsync({id:n.id,patch:{status:"completed"}}),re.success("Marked completed")},children:"Mark completed"})]})}),e.jsxs(fa,{defaultValue:"overview",children:[e.jsxs(xa,{className:"rounded-full bg-white border border-slate-200 flex-wrap h-auto",children:[e.jsx(ss,{value:"overview",className:"rounded-full",children:"Overview"}),e.jsxs(ss,{value:"invitations",className:"rounded-full",children:["Invitations (",a.length,")"]}),e.jsxs(ss,{value:"registrations",className:"rounded-full",children:["Registrations (",r.length,")"]}),e.jsxs(ss,{value:"notes",className:"rounded-full",children:["Notes (",i.length,")"]}),e.jsx(ss,{value:"kit",className:"rounded-full",children:"Resource Kit"}),e.jsx(ss,{value:"followup",className:"rounded-full",children:"48-hour follow-up"}),e.jsx(ss,{value:"analytics",className:"rounded-full",children:"Analytics"})]}),e.jsxs(ns,{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(Ww,{icon:Bn,label:"Registered",value:m.registered+m.attended}),e.jsx(Ww,{icon:da,label:"Attended",value:m.attended}),e.jsx(Ww,{icon:ol,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(Ww,{icon:zp,label:"Follow-up completion",value:`${m.followedRate}%`})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(be,{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,g)=>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})]},g))}),(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,g)=>e.jsxs("li",{className:"text-[13.5px] text-slate-700 flex gap-2",children:[e.jsx(da,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",y]},g))})]})]}),e.jsxs(be,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Share"}),p?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[12px] text-slate-500 mb-1",children:"Registration page"}),e.jsx("div",{className:"text-[12.5px] font-mono bg-slate-50 border border-slate-200 rounded-lg p-2 break-all",children:p}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full mt-2 w-full",onClick:()=>{navigator.clipboard.writeText(p),re.success("Copied")},children:[e.jsx(ja,{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(hg,{className:"h-3.5 w-3.5 mr-2"})," Open check-in"]})]})]})]})]}),e.jsx(ns,{value:"invitations",className:"mt-5",children:e.jsx(bDn,{eventId:n.id,eventSlug:n.public_slug,agents:l,invitations:a,templates:o,onCreate:u.mutate})}),e.jsx(ns,{value:"registrations",className:"mt-5",children:e.jsx(_Dn,{eventId:n.id,attendees:r,onUpsert:c.mutate,checkInToken:n.check_in_token})}),e.jsx(ns,{value:"notes",className:"mt-5",children:e.jsx(wDn,{eventId:n.id,attendees:r,notes:i,onCreate:d.mutate})}),e.jsx(ns,{value:"kit",className:"mt-5",children:e.jsxs(be,{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(ns,{value:"followup",className:"mt-5",children:e.jsx(jDn,{eventId:n.id,attendees:r,onUpsert:c.mutate})}),e.jsxs(ns,{value:"analytics",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(Ww,{icon:Dr,label:"Invitations sent",value:a.length}),e.jsx(Ww,{icon:Tr,label:"Invitation view rate",value:`${m.invView}%`}),e.jsx(Ww,{icon:Bn,label:"Registered",value:m.registered+m.attended}),e.jsx(Ww,{icon:da,label:"Attended",value:m.attended}),e.jsx(Ww,{icon:ol,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(Ww,{icon:zp,label:"Follow-up complete (48h)",value:`${m.followedRate}%`}),e.jsx(Ww,{icon:w3,label:"Notes captured",value:i.length}),e.jsx(Ww,{icon:Sl,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 Ww({icon:s,label:t,value:n}){return e.jsxs(be,{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 bDn({eventId:s,eventSlug:t,agents:n,invitations:r,templates:a,onCreate:i}){const[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,p]=j.useState("email"),[x,y]=j.useState(""),g=a==null?void 0:a[0],b=()=>{if(!g)return;const k=m==="sms"?g.suggested_invitation_sms:m==="dm"?g.suggested_invitation_dm:g.suggested_invitation_email,C=t?`${window.location.origin}/attract-event/${t}`:"";y((k||"").replaceAll("{{first_name}}",(c||"friend").split(" ")[0]).replaceAll("{{link}}",C).replaceAll("{{date}}",""))},v=()=>{if(!c||m==="email"&&!u){re.error("Add a name and email");return}const k=n.find(C=>C.id===l);i({event_id:s,agent_id:l||null,recipient_name:c||F2e(k),recipient_email:u||(k==null?void 0:k.email),channel:m,message_body:x,status:"sent"}),d(""),h(""),y(""),o(""),re.success("Invitation logged")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(be,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Log a personal invitation"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Attract agent (optional)"}),e.jsxs(vs,{value:l||"none",onValueChange:k=>{o(k==="none"?"":k);const C=n.find(T=>T.id===k);C&&(d(F2e(C)),h(C.email||""))},children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Pick an agent"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"Guest (not in pipeline)"}),n.map(k=>e.jsx(Je,{value:k.id,children:F2e(k)},k.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Channel"}),e.jsxs(vs,{value:m,onValueChange:p,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"email",children:"Email"}),e.jsx(Je,{value:"sms",children:"Text message"}),e.jsx(Je,{value:"dm",children:"DM"}),e.jsx(Je,{value:"call",children:"Phone call"}),e.jsx(Je,{value:"in_person",children:"In person"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Recipient name"}),e.jsx(ye,{value:c,onChange:k=>d(k.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Recipient email"}),e.jsx(ye,{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(se,{children:"Message"}),g&&e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full text-xs",onClick:b,children:[e.jsx(yn,{className:"h-3 w-3 mr-1"})," Draft from template"]})]}),e.jsx(Ds,{rows:5,value:x,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:()=>{x&&(navigator.clipboard.writeText(x),re.success("Copied"))},children:[e.jsx(ja,{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:v,children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-2"})," Log invitation"]})]})]})]}),e.jsxs(be,{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(qe,{variant:"secondary",className:"capitalize",children:k.status})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:["via ",k.channel," · ",oc(new Date(k.sent_at))," ago",k.view_count>0?` · viewed ${k.view_count}×`:""]})]},k.id))})]})]})}function _Dn({eventId:s,attendees:t,onUpsert:n,checkInToken:r}){const[a,i]=j.useState(""),[l,o]=j.useState(""),c=()=>{if(!a){re.error("Add a name");return}n({event_id:s,guest_name:a,guest_email:l||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),i(""),o(""),re.success("Walk-in added")};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs(be,{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(ye,{placeholder:"Name",value:a,onChange:d=>i(d.target.value)}),e.jsx(ye,{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(Sl,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]}),e.jsx(be,{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||F2e(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(qe,{variant:"secondary",className:"capitalize",children:d.status}),e.jsxs(vs,{value:d.status,onValueChange:u=>n({id:d.id,event_id:s,status:u,checked_in_at:u==="attended"&&!d.checked_in_at?new Date().toISOString():d.checked_in_at}),children:[e.jsx(gs,{className:"h-8 w-40 text-xs",children:e.jsx(bs,{})}),e.jsx(ys,{children:["invited","registered","confirmed","waitlisted","attended","no_show","cancelled"].map(u=>e.jsx(Je,{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(ERn(r,d.personalized_token)),re.success("Check-in link copied")},children:e.jsx(ja,{className:"h-3.5 w-3.5"})})]})]},d.id))})})]})}function wDn({eventId:s,attendees:t,notes:n,onCreate:r}){const[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState("warm"),[u,h]=j.useState(!1),[m,p]=j.useState(""),x=()=>{if(!l.trim()){re.error("Add a note");return}const y=t.find(g=>g.id===a);r({event_id:s,attendee_id:a||null,agent_id:(y==null?void 0:y.agent_id)||null,note:l,temperature:c,recommended_next_action:m||null,wants_one_on_one:u}),o(""),i(""),p(""),h(!1),re.success("Note captured")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(be,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Capture one honest note"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Attendee (optional)"}),e.jsxs(vs,{value:a||"none",onValueChange:y=>i(y==="none"?"":y),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Anyone in the room"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"General note"}),t.map(y=>e.jsx(Je,{value:y.id,children:y.guest_name||y.guest_email},y.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Note"}),e.jsx(Ds,{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(se,{children:"Relationship temperature"}),e.jsxs(vs,{value:c,onValueChange:d,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["cold","warm","hot"].map(y=>e.jsx(Je,{value:y,children:y},y))})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Recommended next action"}),e.jsx(ye,{value:m,onChange:y=>p(y.target.value),placeholder:"Text them the resource. Book a coffee."})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:u,onChange:y=>h(y.target.checked)}),"They should get a one-on-one conversation"]})]}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:x,children:[e.jsx(Js,{className:"h-4 w-4 mr-2"})," Save note"]})})]}),e.jsxs(be,{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 g=t.find(b=>b.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:(g==null?void 0:g.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(qe,{variant:"secondary",className:"capitalize",children:y.temperature}),y.wants_one_on_one&&e.jsx(qe,{className:"bg-emerald-500",children:"Wants 1:1"}),y.recommended_next_action&&e.jsxs("span",{children:["Next: ",y.recommended_next_action]})]})]},y.id)})})]})]})}function jDn({eventId:s,attendees:t,onUpsert:n}){const r=j.useMemo(()=>({attended_engaged:t.filter(l=>l.status==="attended"&&l.temperature==="hot"),attended_no_notes:t.filter(l=>l.status==="attended"),no_show:t.filter(l=>l.status==="no_show"),meeting_requested:t.filter(l=>l.meeting_requested),not_followed:t.filter(l=>l.status==="attended"&&l.followup_status!=="done")}),[t]),a=(l,o)=>n({id:l,event_id:s,followup_status:o}),i=({title:l,list:o,color:c})=>e.jsxs(be,{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(da,{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 Qq={},NDn=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},oqt={},hw={};let XYe;const kDn=[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];hw.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};hw.getSymbolTotalCodewords=function(t){return kDn[t]};hw.getBCHDigit=function(s){let t=0;for(;s!==0;)t++,s>>>=1;return t};hw.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');XYe=t};hw.isKanjiModeEnabled=function(){return typeof XYe<"u"};hw.toSJIS=function(t){return XYe(t)};var TTe={};(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}}})(TTe);function lqt(){this.buffer=[],this.length=0}lqt.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 SDn=lqt;function _ee(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)}_ee.prototype.set=function(s,t,n,r){const a=s*this.size+t;this.data[a]=n,r&&(this.reservedBit[a]=!0)};_ee.prototype.get=function(s,t){return this.data[s*this.size+t]};_ee.prototype.xor=function(s,t,n){this.data[s*this.size+t]^=n};_ee.prototype.isReserved=function(s,t){return this.reservedBit[s*this.size+t]};var CDn=_ee,cqt={};(function(s){const t=hw.getSymbolSize;s.getRowColCoords=function(r){if(r===1)return[];const a=Math.floor(r/7)+2,i=t(r),l=i===145?26:Math.ceil((i-13)/(2*a-2))*2,o=[i-7];for(let c=1;c=0&&a<=7},s.from=function(a){return s.isValid(a)?parseInt(a,10):void 0},s.getPenaltyN1=function(a){const i=a.size;let l=0,o=0,c=0,d=null,u=null;for(let h=0;h=5&&(l+=t.N1+(o-5)),d=p,o=1),p=a.get(m,h),p===u?c++:(c>=5&&(l+=t.N1+(c-5)),u=p,c=1)}o>=5&&(l+=t.N1+(o-5)),c>=5&&(l+=t.N1+(c-5))}return l},s.getPenaltyN2=function(a){const i=a.size;let l=0;for(let o=0;o=10&&(o===1488||o===93)&&l++,c=c<<1&2047|a.get(u,d),u>=10&&(c===1488||c===93)&&l++}return l*t.N3},s.getPenaltyN4=function(a){let i=0;const l=a.data.length;for(let c=0;c=0;){const l=i[0];for(let c=0;c0){const i=new Uint8Array(this.degree);return i.set(r,a),i}return r};var TDn=QYe,pqt={},T6={},JYe={};JYe.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var bS={};const fqt="[0-9]+",EDn="[A-Z $%*+\\-./:]+";let AX="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";AX=AX.replace(/u/g,"\\u");const MDn="(?:(?![A-Z0-9 $%*+\\-./:]|"+AX+`)(?:.|[\r ]))+`;bS.KANJI=new RegExp(AX,"g");bS.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");bS.BYTE=new RegExp(MDn,"g");bS.NUMERIC=new RegExp(fqt,"g");bS.ALPHANUMERIC=new RegExp(EDn,"g");const LDn=new RegExp("^"+AX+"$"),PDn=new RegExp("^"+fqt+"$"),IDn=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");bS.testKanji=function(t){return LDn.test(t)};bS.testNumeric=function(t){return PDn.test(t)};bS.testAlphanumeric=function(t){return IDn.test(t)};(function(s){const t=JYe,n=bS;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}}})(T6);(function(s){const t=hw,n=ETe,r=TTe,a=T6,i=JYe,l=7973,o=t.getBCHDigit(l);function c(m,p,x){for(let y=1;y<=40;y++)if(p<=s.getCapacity(y,x,m))return y}function d(m,p){return a.getCharCountIndicator(m,p)+4}function u(m,p){let x=0;return m.forEach(function(y){const g=d(y.mode,p);x+=g+y.getBitsLength()}),x}function h(m,p){for(let x=1;x<=40;x++)if(u(m,x)<=s.getCapacity(x,p,a.MIXED))return x}s.from=function(p,x){return i.isValid(p)?parseInt(p,10):x},s.getCapacity=function(p,x,y){if(!i.isValid(p))throw new Error("Invalid QR Code version");typeof y>"u"&&(y=a.BYTE);const g=t.getSymbolTotalCodewords(p),b=n.getTotalCodewordsCount(p,x),v=(g-b)*8;if(y===a.MIXED)return v;const k=v-d(y,p);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(p,x){let y;const g=r.from(x,r.M);if(Array.isArray(p)){if(p.length>1)return h(p,g);if(p.length===0)return 1;y=p[0]}else y=p;return c(y.mode,y.getLength(),g)},s.getEncodedBits=function(p){if(!i.isValid(p)||p<7)throw new Error("Invalid QR Code version");let x=p<<12;for(;t.getBCHDigit(x)-o>=0;)x^=l<=0;)a^=gqt<0&&(r=this.data.substr(n),a=parseInt(r,10),t.put(a,i*3+1))};var ODn=NU;const FDn=T6,z8e=["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 kU(s){this.mode=FDn.ALPHANUMERIC,this.data=s}kU.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};kU.prototype.getLength=function(){return this.data.length};kU.prototype.getBitsLength=function(){return kU.getBitsLength(this.data.length)};kU.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=z8e.indexOf(this.data[n])*45;r+=z8e.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(z8e.indexOf(this.data[n]),6)};var zDn=kU;const BDn=T6;function SU(s){this.mode=BDn.BYTE,typeof s=="string"?this.data=new TextEncoder().encode(s):this.data=new Uint8Array(s)}SU.getBitsLength=function(t){return t*8};SU.prototype.getLength=function(){return this.data.length};SU.prototype.getBitsLength=function(){return SU.getBitsLength(this.data.length)};SU.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 VDn=CU,vqt={exports:{}};(function(s){var t={single_source_shortest_paths:function(n,r,a){var i={},l={};l[r]=0;var o=t.PriorityQueue.make();o.push(r,0);for(var c,d,u,h,m,p,x,y,g;!o.empty();){c=o.pop(),d=c.value,h=c.cost,m=n[d]||{};for(u in m)m.hasOwnProperty(u)&&(p=m[u],x=h+p,y=l[u],g=typeof l[u]>"u",(g||y>x)&&(l[u]=x,o.push(u,x),i[u]=d))}if(typeof a<"u"&&typeof l[a]>"u"){var b=["Could not find a path from ",r," to ",a,"."].join("");throw new Error(b)}return i},extract_shortest_path_from_predecessor_list:function(n,r){for(var a=[],i=r;i;)a.push(i),n[i],i=n[i];return a.reverse(),a},find_path:function(n,r,a){var i=t.single_source_shortest_paths(n,r,a);return t.extract_shortest_path_from_predecessor_list(i,a)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,a={},i;n=n||{};for(i in r)r.hasOwnProperty(i)&&(a[i]=r[i]);return a.queue=[],a.sorter=n.sorter||r.default_sorter,a},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var a={value:n,cost:r};this.queue.push(a),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};s.exports=t})(vqt);var HDn=vqt.exports;(function(s){const t=T6,n=ODn,r=zDn,a=$Dn,i=VDn,l=bS,o=hw,c=HDn;function d(b){return unescape(encodeURIComponent(b)).length}function u(b,v,k){const C=[];let T;for(;(T=b.exec(k))!==null;)C.push({data:T[0],index:T.index,mode:v,length:T[0].length});return C}function h(b){const v=u(l.NUMERIC,t.NUMERIC,b),k=u(l.ALPHANUMERIC,t.ALPHANUMERIC,b);let C,T;return o.isKanjiModeEnabled()?(C=u(l.BYTE,t.BYTE,b),T=u(l.KANJI,t.KANJI,b)):(C=u(l.BYTE_KANJI,t.BYTE,b),T=[]),v.concat(k,C,T).sort(function(P,L){return P.index-L.index}).map(function(P){return{data:P.data,mode:P.mode,length:P.length}})}function m(b,v){switch(v){case t.NUMERIC:return n.getBitsLength(b);case t.ALPHANUMERIC:return r.getBitsLength(b);case t.KANJI:return i.getBitsLength(b);case t.BYTE:return a.getBitsLength(b)}}function p(b){return b.reduce(function(v,k){const C=v.length-1>=0?v[v.length-1]:null;return C&&C.mode===k.mode?(v[v.length-1].data+=k.data,v):(v.push(k),v)},[])}function x(b){const v=[];for(let k=0;k=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 eOn(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 U8e(s,t,n){const r=s.size,a=XDn.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 nOn(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 rOn(s,t,n){const r=new GDn;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),QDn.getCharCountIndicator(c.mode,s)),c.write(r)});const a=LTe.getSymbolTotalCodewords(s),i=r$e.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&&sOn(c,t),nOn(c,l),isNaN(r)&&(r=n$e.getBestMask(c,U8e.bind(null,c,n))),n$e.applyMask(r,c),U8e(c,n,r),{modules:c,version:t,errorCorrectionLevel:n,maskPattern:r,segments:a}}oqt.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=B8e.M,a,i;return typeof n<"u"&&(r=B8e.from(n.errorCorrectionLevel,B8e.M),a=HSe.from(n.version),i=n$e.from(n.maskPattern),n.toSJISFunc&<e.setToSJISFunction(n.toSJISFunc)),iOn(t,a,r,i)};var bqt={},eZe={};(function(s){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(i){return[i,i]}))),r.length===6&&r.push("F","F");const a=parseInt(r.join(""),16);return{r:a>>24&255,g:a>>16&255,b:a>>8&255,a:a&255,hex:"#"+r.slice(0,6).join("")}}s.getOptions=function(r){r||(r={}),r.color||(r.color={});const a=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,i=r.width&&r.width>=21?r.width:void 0,l=r.scale||4;return{width:i,scale:i?4:l,margin:a,color:{dark:t(r.color.dark||"#000000ff"),light:t(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},s.getScale=function(r,a){return a.width&&a.width>=r+a.margin*2?a.width/(r+a.margin*2):a.scale},s.getImageWidth=function(r,a){const i=s.getScale(r,a);return Math.floor((r+a.margin*2)*i)},s.qrToImageData=function(r,a,i){const l=a.modules.size,o=a.modules.data,c=s.getScale(l,i),d=Math.floor((l+i.margin*2)*c),u=i.margin*c,h=[i.color.light,i.color.dark];for(let m=0;m=u&&p>=u&&m"u"&&(!l||!l.getContext)&&(c=l,l=void 0),l||(d=r()),c=t.getOptions(c);const u=t.getImageWidth(i.modules.size,c),h=d.getContext("2d"),m=h.createImageData(u,u);return t.qrToImageData(m.data,i,c),n(h,d,u),h.putImageData(m,0,0),d},s.renderToDataURL=function(i,l,o){let c=o;typeof c>"u"&&(!l||!l.getContext)&&(c=l,l=void 0),c||(c={});const d=s.render(i,l,c),u=c.type||"image/png",h=c.rendererOpts||{};return d.toDataURL(u,h.quality)}})(bqt);var _qt={};const oOn=eZe;function Vyt(s,t){const n=s.a/255,r=t+'="'+s.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function q8e(s,t,n){let r=s+t;return typeof n<"u"&&(r+=" "+n),r}function lOn(s,t,n){let r="",a=0,i=!1,l=0;for(let o=0;o0&&c>0&&s[o-1]||(r+=i?q8e("M",c+n,.5+d+n):q8e("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 cOn=NDn,a$e=oqt,wqt=bqt,dOn=_qt;function tZe(s,t,n,r,a){const i=[].slice.call(arguments,1),l=i.length,o=typeof i[l-1]=="function";if(!o&&!cOn())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=a$e.create(n,r);c(s(u,t,r))}catch(u){d(u)}})}try{const c=a$e.create(n,r);a(null,s(c,t,r))}catch(c){a(c)}}Qq.create=a$e.create;Qq.toCanvas=tZe.bind(null,wqt.render);Qq.toDataURL=tZe.bind(null,wqt.renderToDataURL);Qq.toString=tZe.bind(null,function(s,t,n){return dOn.render(s,n)});function uOn(){const{eventId:s}=$i(),t=Hn(),{data:n}=WYe(s),{data:r=[]}=VUt(s),a=KUt(),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),p=n!=null&&n.public_slug?CTe(n.public_slug):"";j.useEffect(()=>{p&&Qq.toDataURL(p,{width:320,margin:1}).then(m).catch(()=>{})},[p]);const x=j.useMemo(()=>i?r.filter(b=>(b.guest_name||"").toLowerCase().includes(i.toLowerCase())||(b.guest_email||"").toLowerCase().includes(i.toLowerCase())):r,[r,i]),y=b=>{a.mutate({id:b.id,event_id:s,status:"attended",checked_in_at:new Date().toISOString()}),re.success(`${b.guest_name||"Guest"} checked in`)},g=()=>{o&&(a.mutate({event_id:s,guest_name:o,guest_email:d||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),c(""),u(""),re.success("Walk-in checked in"))};return n?e.jsx("div",{className:"min-h-screen bg-slate-50",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 md:p-6",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"rounded-full mb-3",onClick:()=>t(`/attract/events/${s}`),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"})," Back to event"]}),e.jsxs(be,{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(be,{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(hg,{className:"h-4 w-4"})," Registration QR"]}),h?e.jsx("img",{src:h,alt:"QR code",className:"mx-auto mt-3 h-56 w-56"}):e.jsx("div",{className:"text-[12px] text-slate-400 mt-3",children:"Publish this event to generate a QR code."}),p&&e.jsx("div",{className:"text-[11px] font-mono text-center text-slate-500 mt-2 break-all",children:p})]}),e.jsxs(be,{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(ye,{placeholder:"Name",value:o,onChange:b=>c(b.target.value)}),e.jsx(ye,{placeholder:"Email (optional)",value:d,onChange:b=>u(b.target.value)}),e.jsxs(B,{className:"w-full rounded-full",onClick:g,children:[e.jsx(Sl,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]})]}),e.jsxs(be,{className:"mt-4 rounded-2xl border-slate-200 bg-white overflow-hidden",children:[e.jsxs("div",{className:"p-3 border-b border-slate-100 relative",children:[e.jsx(Fr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{placeholder:"Search attendees",value:i,onChange:b=>l(b.target.value),className:"pl-9 rounded-full border-slate-200"})]}),x.length===0?e.jsx("div",{className:"p-8 text-center text-slate-400 text-[13px]",children:"No matches."}):e.jsx("div",{className:"divide-y divide-slate-100 max-h-[60vh] overflow-auto",children:x.map(b=>{const v=b.status==="attended";return e.jsxs("div",{className:"p-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 truncate",children:b.guest_name||b.guest_email}),e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:b.guest_email})]}),v?e.jsxs(qe,{className:"bg-emerald-500",children:[e.jsx(da,{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(b),children:[e.jsx(da,{className:"h-5 w-5 mr-2"})," Check in"]})]},b.id)})})]})]})}):e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"})}const hOn=["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"],mOn=["Lead generation","Database marketing","Listing marketing","Social media/video","Open houses","Negotiation","Systems and technology","Team building","Leadership","New construction","Luxury","Business planning"],Hyt=[{key:"produce",icon:ll,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:yn,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:FR,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:hN,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:N3,title:"Balanced Plan",blurb:"A little of all four. Best for veteran attractors.",example:"Rotate weekly focus between production, teaching, providing, and connecting."}],pOn=[{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"}],Gyt=["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 Wyt(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 fOn(){const s=Hn(),{settings:t,save:n}=Zq(),[r,a]=j.useState(0),[i,l]=j.useState([]),[o,c]=j.useState([]),[d,u]=j.useState(null),[h,m]=j.useState({}),[p,x]=j.useState("");j.useEffect(()=>{var k,C;t&&((k=t.audiences)!=null&&k.length&&l(t.audiences),(C=t.teachables)!=null&&C.length&&c(t.teachables),t.attraction_style&&u(t.attraction_style),t.activity_baseline&&m(t.activity_baseline),t.ninety_day_outcome&&x(t.ninety_day_outcome))},[t==null?void 0:t.user_id]);const y=["Welcome","Audience","Teach","Style","Baseline","Outcome","Plan"],g=j.useMemo(()=>r===1?i.length>0:r===2?o.length>0:r===3?!!d:r===5?!!p:!0,[r,i,o,d,p]),b=(k,C,T)=>{T(k.includes(C)?k.filter(M=>M!==C):[...k,C])},v=async()=>{if(!d)return;const k=Wyt({style:d,baseline:h,outcome:p});await n.mutateAsync({audiences:i,teachables:o,attraction_style:d,activity_baseline:h,ninety_day_outcome:p,ninety_day_plan:k,primary_pillar:d,onboarding_completed_at:new Date().toISOString()}),re.success("Your 90-day plan is ready."),s("/attract")};return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("div",{className:"flex items-center gap-2 mb-8",children:y.map((k,C)=>e.jsx("div",{className:Et("h-1.5 flex-1 rounded-full transition-colors",C<=r?"bg-violet-600":"bg-slate-200")},k))}),e.jsx(QU,{mode:"wait",children:e.jsxs(br.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:Hyt.filter(k=>k.key!=="balanced").map(k=>e.jsxs(be,{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(pG,{icon:Bn,eyebrow:"Who can you best help?",title:"Pick every audience where you naturally shine.",subtitle:"You can adjust these anytime.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:hOn.map(k=>e.jsx(V8e,{label:k,active:i.includes(k),onClick:()=>b(i,k,l)},k))})}),r===2&&e.jsx(pG,{icon:Uh,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:mOn.map(k=>e.jsx(V8e,{label:k,active:o.includes(k),onClick:()=>b(o,k,c)},k))})}),r===3&&e.jsx(pG,{icon:N3,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:Hyt.map(k=>e.jsx(be,{onClick:()=>u(k.key),className:Et("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(da,{className:"h-5 w-5 text-violet-600"})]})},k.key))})}),r===4&&e.jsx(pG,{icon:vf,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:pOn.map(k=>e.jsxs("div",{children:[e.jsx(se,{className:"text-[12.5px] text-slate-700",children:k.label}),e.jsx(ye,{type:"number",min:0,value:h[k.key]??"",onChange:C=>m({...h,[k.key]:Number(C.target.value)||0})})]},k.key))})}),r===5&&e.jsx(pG,{icon:uu,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:[Gyt.map(k=>e.jsx(V8e,{label:k,active:p===k,onClick:()=>x(k),full:!0},k)),e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{className:"text-[12.5px] text-slate-700",children:"Or write your own"}),e.jsx(Ds,{rows:2,placeholder:"A specific outcome you can measure in 90 days...",value:Gyt.includes(p)?"":p,onChange:k=>x(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(jqt,{plan:Wyt({style:d,baseline:h,outcome:p})})]})]},r)}),e.jsxs("div",{className:"mt-10 flex items-center justify-between",children:[e.jsxs(B,{variant:"ghost",onClick:()=>r===0?s("/attract"):a(r-1),children:[e.jsx(_a,{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:!g,onClick:()=>a(r+1),children:["Continue ",e.jsx(Xa,{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:v,disabled:n.isPending,children:[e.jsx(oy,{className:"h-4 w-4 mr-1.5"})," Activate my 90-day plan"]})]})]})}function pG({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 V8e({label:s,active:t,onClick:n,full:r}){return e.jsx("button",{type:"button",onClick:n,className:Et("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(da,{className:"h-4 w-4 text-violet-600"})," ",s]})})}function jqt({plan:s}){return e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs(be,{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(be,{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(be,{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(be,{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(be,{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 xOn(){const{settings:s,resetOnboarding:t}=Zq(),n=s==null?void 0:s.ninety_day_plan;return e.jsxs("div",{className:"max-w-4xl",children:[e.jsx(Wh,{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(bm,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})}),n?e.jsx(jqt,{plan:n}):e.jsxs(be,{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(Yn,{to:"/attract/onboarding",children:"Start onboarding"})})]})]})}async function Kyt(s,t,n,r={}){await U.rpc("award_attract_activity",{_user_id:s,_activity_type:t,_title:n,_description:r.description??null,_pillar:r.pillar??null,_agent_id:r.agent_id??null,_metadata:r.metadata??{},_dedupe_minutes:30})}function Nqt(){const{user:s}=Ns(),t=as(),n=mt({queryKey:["attract-transactions",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await U.from("attract_transactions").select("*").order("closing_date",{ascending:!1,nullsFirst:!1});if(c)throw c;return o??[]}}),r=vt({mutationFn:async o=>{const c=[o.rating_communication,o.rating_professionalism,o.rating_problem_solving].filter(x=>typeof x=="number"),d=c.length?Number((c.reduce((x,y)=>x+y,0)/c.length).toFixed(2)):null,u={...o,user_id:s.id,overall_rating:d},{data:h,error:m}=o.id?await U.from("attract_transactions").update(u).eq("id",o.id).select().single():await U.from("attract_transactions").insert(u).select().single();if(m)throw m;const p=h;return o.id||await Kyt(s.id,"transaction_logged",`Reviewed ${p.property_address}`,{description:p.cooperating_first_name?`Cooperating agent: ${p.cooperating_first_name} ${p.cooperating_last_name??""}`:null,pillar:"produce",metadata:{transaction_id:p.id,overall_rating:d}}),p},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-activities"]}),re.success("Transaction saved")},onError:o=>re.error(o.message)}),a=vt({mutationFn:async({id:o,decision:c,notes:d})=>{const{data:u,error:h}=await U.from("attract_transactions").update({decision:c,decision_notes:d??null}).eq("id",o).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]})}}),i=vt({mutationFn:async o=>{let c=o.attract_agent_id;if(!c){const{data:d}=await U.from("attract_agents").select("id").eq("user_id",s.id).eq("first_name",o.cooperating_first_name??"").eq("last_name",o.cooperating_last_name??"").maybeSingle();if(d!=null&&d.id)c=d.id;else{const{data:u,error:h}=await U.from("attract_agents").insert({user_id:s.id,first_name:o.cooperating_first_name??"Unknown",last_name:o.cooperating_last_name,email:o.cooperating_email,phone:o.cooperating_phone,brokerage:o.cooperating_brokerage,source:"cooperating_transaction",stage:"new_connection",temperature:o.enjoy_business_with==="yes"?"warm":"cold",notes:o.stood_out}).select("id").single();if(h)throw h;c=u.id}}return await U.from("attract_transactions").update({attract_agent_id:c,decision:"add_pipeline"}).eq("id",o.id),await Kyt(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"]}),re.success("Added to Agent Pipeline")},onError:o=>re.error(o.message)}),l=vt({mutationFn:async o=>{const{error:c}=await U.from("attract_transactions").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),re.success("Transaction removed")}});return{transactions:n.data??[],isLoading:n.isLoading,upsert:r,setDecision:a,addToPipeline:i,remove:l}}function gOn({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:Et("h-5 w-5",(s??0)>=n?"fill-amber-400 text-amber-400":"text-slate-300")})},n))})}function yOn(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 vOn={1:"Poor",2:"Fair",3:"OK",4:"Good",5:"Excellent"},H8e={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 bOn(){const{transactions:s,isLoading:t,upsert:n,setDecision:r,addToPipeline:a,remove:i}=Nqt(),[l,o]=j.useState(""),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,p]=j.useState(null),x=j.useMemo(()=>{const g=l.trim().toLowerCase();return g?s.filter(b=>[b.property_address,b.cooperating_first_name,b.cooperating_last_name,b.cooperating_brokerage,b.city].filter(Boolean).some(v=>String(v).toLowerCase().includes(g))):s},[s,l]),y=j.useMemo(()=>{const g=s.length,b=s.filter(C=>C.enjoy_business_with==="yes").length,v=s.filter(C=>C.decision==="add_pipeline").length,k=s.filter(C=>C.follow_up_created).length;return{reviewed:g,highFit:b,inPipeline:v,followUps:k}},[s]);return e.jsxs("div",{children:[e.jsxs(Yn,{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(_a,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Wh,{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(Js,{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(zre,{label:"Transactions reviewed",value:y.reviewed}),e.jsx(zre,{label:"High-fit agents",value:y.highFit,tone:"emerald"}),e.jsx(zre,{label:"Added to pipeline",value:y.inPipeline,tone:"violet"}),e.jsx(zre,{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(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{value:l,onChange:g=>o(g.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(g=>e.jsx(be,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},g))}):x.length===0?e.jsxs(be,{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(yn,{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(Js,{className:"h-4 w-4 mr-1.5"})," Add your first transaction"]})]}):e.jsx("div",{className:"space-y-3",children:x.map(g=>{var b,v;return e.jsx(be,{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:g.property_address}),g.closing_date&&e.jsx(qe,{variant:"outline",className:"text-[10.5px]",children:Bs(new Date(g.closing_date),"MMM d, yyyy")}),e.jsx(qe,{className:Et("text-[10.5px] border-0",((b=H8e[g.decision])==null?void 0:b.color)??H8e.pending.color),children:((v=H8e[g.decision])==null?void 0:v.label)??"Needs review"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1",children:[g.cooperating_first_name||g.cooperating_last_name?`${g.cooperating_first_name??""} ${g.cooperating_last_name??""}`:"Cooperating agent",g.cooperating_brokerage?` · ${g.cooperating_brokerage}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-[12px] text-slate-600",children:[g.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"})," ",g.overall_rating]}),g.enjoy_business_with&&e.jsxs("span",{className:"capitalize",children:["Fit: ",e.jsx("span",{className:Et("font-medium",g.enjoy_business_with==="yes"?"text-emerald-700":g.enjoy_business_with==="maybe"?"text-amber-700":"text-slate-600"),children:g.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(g),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:()=>p(g),children:[e.jsx(Z9,{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(g.id),children:"Remove"})]})]})},g.id)})}),e.jsx("div",{className:"mt-8",children:e.jsx(HO,{})}),e.jsx(_On,{open:c,onClose:()=>d(!1),onSaved:g=>{d(!1),h(g)},upsert:n}),e.jsx(wOn,{tx:u,onClose:()=>h(null),onDecision:g=>u&&r.mutate({id:u.id,decision:g}),onAddToPipeline:()=>u&&a.mutate(u),onMessage:()=>{p(u),h(null)}}),e.jsx(jOn,{tx:m,onClose:()=>p(null)})]})}function zre({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(be,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:Et("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 _On({open:s,onClose:t,onSaved:n,upsert:r}){const[a,i]=j.useState({enjoy_business_with:"maybe"}),l=c=>i({...a,...c}),o=async()=>{var d;if(!((d=a.property_address)!=null&&d.trim())){re.error("Property address is required");return}const c=await r.mutateAsync(a);i({enjoy_business_with:"maybe"}),n(c)};return e.jsx(Fs,{open:s,onOpenChange:c=>!c&&t(),children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Add Transaction"}),e.jsx(kr,{children:"Capture what stood out while it's fresh."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Property address *"}),e.jsx(ye,{value:a.property_address??"",onChange:c=>l({property_address:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"City"}),e.jsx(ye,{value:a.city??"",onChange:c=>l({city:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"State"}),e.jsx(ye,{value:a.state??"",onChange:c=>l({state:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Closing date"}),e.jsx(ye,{type:"date",value:a.closing_date??"",onChange:c=>l({closing_date:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"You represented"}),e.jsxs(vs,{value:a.represented??"",onValueChange:c=>l({represented:c}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Buyer or seller"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"buyer",children:"Buyer"}),e.jsx(Je,{value:"seller",children:"Seller"}),e.jsx(Je,{value:"both",children:"Both"}),e.jsx(Je,{value:"other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Cooperating agent"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"First name"}),e.jsx(ye,{value:a.cooperating_first_name??"",onChange:c=>l({cooperating_first_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Last name"}),e.jsx(ye,{value:a.cooperating_last_name??"",onChange:c=>l({cooperating_last_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{type:"email",value:a.cooperating_email??"",onChange:c=>l({cooperating_email:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:a.cooperating_phone??"",onChange:c=>l({cooperating_phone:c.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(se,{children:"Brokerage"}),e.jsx(ye,{value:a.cooperating_brokerage??"",onChange:c=>l({cooperating_brokerage:c.target.value})})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Experience"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[["rating_communication","Communication"],["rating_professionalism","Professionalism"],["rating_problem_solving","Problem solving"]].map(([c,d])=>e.jsxs("div",{children:[e.jsx(se,{children:d}),e.jsx(gOn,{value:a[c],onChange:u=>l({[c]:u})}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-1",children:vOn[a[c]]??"—"})]},c))}),e.jsxs("div",{className:"mt-4",children:[e.jsx(se,{children:"Would you enjoy being in business with this agent?"}),e.jsx("div",{className:"flex gap-2 mt-2",children:["yes","maybe","no"].map(c=>e.jsx("button",{type:"button",onClick:()=>l({enjoy_business_with:c}),className:Et("rounded-full px-4 py-1.5 text-[12.5px] font-medium border capitalize",a.enjoy_business_with===c?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-700 border-slate-200"),children:c},c))})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(se,{children:"What stood out?"}),e.jsx(Ds,{rows:2,value:a.stood_out??"",onChange:c=>l({stood_out:c.target.value})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(se,{children:"Private notes"}),e.jsx(Ds,{rows:2,value:a.private_notes??"",onChange:c=>l({private_notes:c.target.value}),placeholder:"Only you can see these."})]})]})]}),e.jsxs(Nr,{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 wOn({tx:s,onClose:t,onDecision:n,onAddToPipeline:r,onMessage:a}){return s?e.jsx(Fs,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Would you like to build a relationship?"}),e.jsxs(kr,{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(fG,{icon:Sl,label:"Add to Agent Pipeline",tone:"violet",onClick:r}),e.jsx(fG,{icon:Z9,label:"Send a professional compliment",tone:"teal",onClick:()=>{n("send_compliment"),a()}}),e.jsx(fG,{icon:xb,label:"Invite to coffee",tone:"amber",onClick:()=>{n("invite_coffee"),a()}}),e.jsx(fG,{icon:yn,label:"Share a relevant resource",tone:"sky",onClick:()=>n("share_resource")}),e.jsx(fG,{icon:Rd,label:"No action right now",tone:"slate",onClick:()=>{n("no_action"),t()}})]})]})}):null}function fG({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:Et("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 jOn({tx:s,onClose:t}){const[n,r]=j.useState("warm");if(!s)return null;const a=yOn(s,n);return e.jsx(Fs,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Personalized message"}),e.jsx(kr,{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:Et("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(Ds,{value:a,readOnly:!0,rows:10,className:"font-mono text-[12.5px]"}),e.jsxs(Nr,{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),re.success("Copied to clipboard")},children:[e.jsx(ja,{className:"h-4 w-4 mr-1.5"})," Copy"]})]})]})})}function kqt(){const{user:s}=Ns(),t=as(),n=mt({queryKey:["attract-content",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await U.from("attract_content_drafts").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=vt({mutationFn:async o=>{const{data:c,error:d}=await U.functions.invoke("attract-content-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(c.error);return c},onSuccess:o=>{t.invalidateQueries({queryKey:["attract-content"]}),o.demo?re.info("Demo generation used — configure AI provider for live results"):re.success("Content generated")},onError:o=>re.error(o.message)}),a=vt({mutationFn:async o=>{const{data:c,error:d}=await U.from("attract_content_drafts").update(o).eq("id",o.id).select().single();if(d)throw d;return c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),re.success("Saved")}}),i=vt({mutationFn:async o=>{const{error:c}=await U.from("attract_content_drafts").update({status:"posted",posted_at:new Date().toISOString()}).eq("id",o);if(c)throw c;await U.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"content_posted",_title:"Posted authority content",_description:null,_pillar:"influence",_agent_id:null,_metadata:{draft_id:o},_dedupe_minutes:30})},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),t.invalidateQueries({queryKey:["attract-activities"]}),re.success("Marked as posted")}}),l=vt({mutationFn:async o=>{const{error:c}=await U.from("attract_content_drafts").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),re.success("Draft removed")}});return{drafts:n.data??[],isLoading:n.isLoading,generate:r,save:a,markPosted:i,remove:l}}const i$e=[{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"}]}],NOn=["Direct","Educational","Fun","Contrarian","Encouraging"],kOn=["short","medium","long"],SOn=["instagram","linkedin","facebook","youtube","email"],GSe={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 COn(){const{drafts:s,isLoading:t,generate:n,save:r,markPosted:a,remove:i}=kqt(),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=j.useMemo(()=>({ready:s.filter(h=>h.status==="ready"),draft:s.filter(h=>h.status==="draft"),idea:s.filter(h=>h.status==="idea"),posted:s.filter(h=>h.status==="posted")}),[s]);return e.jsxs("div",{children:[e.jsxs(Yn,{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(_a,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(Wh,{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(um,{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(yn,{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(fa,{defaultValue:"all",className:"mb-8",children:[e.jsxs(xa,{children:[e.jsxs(ss,{value:"all",children:["All (",s.length,")"]}),e.jsxs(ss,{value:"ready",children:["Ready (",u.ready.length,")"]}),e.jsxs(ss,{value:"draft",children:["Draft (",u.draft.length,")"]}),e.jsxs(ss,{value:"posted",children:["Posted (",u.posted.length,")"]})]}),e.jsx(ns,{value:"all",children:e.jsx(Bre,{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(ns,{value:"ready",children:e.jsx(Bre,{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(ns,{value:"draft",children:e.jsx(Bre,{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(ns,{value:"posted",children:e.jsx(Bre,{drafts:u.posted,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:()=>{},onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})})]}),e.jsx(HO,{}),e.jsx(AOn,{open:l,editing:c,onClose:()=>{o(!1),d(null)},generate:n,save:r,markPosted:h=>a.mutate(h)})]})}function Bre({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(be,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},l))}):s.length===0?e.jsxs(be,{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(sN,{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(Js,{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=i$e.find(u=>u.key===l.mode))==null?void 0:c.label)??l.mode;return e.jsx(be,{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(qe,{className:Et("text-[10.5px] border-0",GSe[l.status].color),children:GSe[l.status].label}),e.jsx(qe,{variant:"outline",className:"text-[10.5px]",children:o}),l.tone&&e.jsx(qe,{variant:"outline",className:"text-[10.5px]",children:l.tone}),l.ratio_flag&&e.jsxs(qe,{className:"text-[10.5px] bg-amber-100 text-amber-900 border-0 gap-1",children:[e.jsx(hd,{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 ${Bs(new Date(l.posted_at),"MMM d")}`:`Updated ${Bs(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(da,{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(Rn,{className:"h-3.5 w-3.5"})})]})]})},l.id)})})}function AOn({open:s,editing:t,onClose:n,generate:r,save:a,markPosted:i}){const[l,o]=j.useState((t==null?void 0:t.mode)??"transaction_lesson"),[c,d]=j.useState((t==null?void 0:t.input_json)??{}),[u,h]=j.useState((t==null?void 0:t.topic)??""),[m,p]=j.useState((t==null?void 0:t.tone)??"Educational"),[x,y]=j.useState((t==null?void 0:t.length)??"medium"),[g,b]=j.useState((t==null?void 0:t.platforms)??["instagram"]),[v,k]=j.useState((t==null?void 0:t.include_brokerage_reference)??!1),[C,T]=j.useState(t??null),[M,P]=j.useState(""),[L,I]=j.useState((t==null?void 0:t.status)??"draft"),O=i$e.find(W=>W.key===l),$=async W=>{const G=await r.mutateAsync({mode:l,topic:u,inputs:c,tone:m,length:x,platforms:g,include_brokerage_reference:v,refinement:W??M,draft_id:C==null?void 0:C.id});G!=null&&G.draft&&T(G.draft),P("")},q=async W=>{if(!C)return;const G=await a.mutateAsync({id:C.id,...W});T(G)};return e.jsx(Fs,{open:s,onOpenChange:W=>!W&&n(),children:e.jsx(Os,{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($s,{children:[e.jsx(zs,{className:"text-base",children:"Content Studio"}),e.jsx(kr,{className:"text-[12px]",children:O.blurb})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Content mode"}),e.jsxs(vs,{value:l,onValueChange:W=>{o(W),d({})},children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:i$e.map(W=>e.jsx(Je,{value:W.key,children:W.label},W.key))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Topic (optional)"}),e.jsx(ye,{value:u,onChange:W=>h(W.target.value),placeholder:"1-line summary"})]}),O.fields.map(W=>e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:W.label}),e.jsx(Ds,{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(se,{className:"text-[12px]",children:"Tone"}),e.jsxs(vs,{value:m,onValueChange:p,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:NOn.map(W=>e.jsx(Je,{value:W,children:W},W))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Length"}),e.jsxs(vs,{value:x,onValueChange:y,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:kOn.map(W=>e.jsx(Je,{value:W,children:W},W))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px]",children:"Platforms"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:SOn.map(W=>e.jsx("button",{type:"button",onClick:()=>b(g.includes(W)?g.filter(G=>G!==W):[...g,W]),className:Et("rounded-full px-2.5 py-1 text-[11px] capitalize border",g.includes(W)?"bg-violet-600 text-white border-violet-600":"bg-white border-slate-200 text-slate-700"),children:W},W))})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:W=>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(um,{className:"h-4 w-4 mr-1.5"})," ",r.isPending?"Generating…":C?"Regenerate":"Generate content"]})]})]}),e.jsx("div",{className:"overflow-y-auto p-6",children:C?e.jsxs("div",{className:"space-y-5",children:[C.ratio_flag&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-[12.5px] text-amber-900 flex items-start gap-2",children:[e.jsx(hd,{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(qe,{className:Et("text-[10.5px] border-0",GSe[L].color),children:GSe[L].label}),e.jsxs(vs,{value:L,onValueChange:W=>{I(W),q({status:W})},children:[e.jsx(gs,{className:"h-8 w-32 text-[12px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"idea",children:"Idea"}),e.jsx(Je,{value:"draft",children:"Draft"}),e.jsx(Je,{value:"ready",children:"Ready"}),e.jsx(Je,{value:"posted",children:"Posted"})]})]}),e.jsx(ye,{type:"date",className:"h-8 w-40 text-[12px]",value:C.planned_at?C.planned_at.slice(0,10):"",onChange:W=>q({planned_at:W.target.value?new Date(W.target.value).toISOString():null})}),C.status!=="posted"&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>i(C.id),children:[e.jsx(Dr,{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(Yn,{to:`/attract/provide/kits/new?seed=${encodeURIComponent(C.topic||C.mode)}`,children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Turn into a kit"]})})]}),e.jsx(w7,{title:"Hook options",children:e.jsx("div",{className:"space-y-1.5",children:(C.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(o$e,{value:W})]},G))})}),e.jsx(w7,{title:"Teleprompter script",children:e.jsx(G8e,{value:C.script??"",onSave:W=>q({script:W})})}),e.jsx(w7,{title:"Social caption",children:e.jsx(G8e,{value:C.caption??"",onSave:W=>q({caption:W})})}),e.jsx(w7,{title:"Carousel outline",children:e.jsx("div",{className:"space-y-1.5",children:(C.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(w7,{title:"Email lesson",children:e.jsx(G8e,{value:C.email_lesson??"",onSave:W=>q({email_lesson:W})})}),e.jsx(w7,{title:"CTA options",children:e.jsx("div",{className:"space-y-1.5",children:(C.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(o$e,{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(ye,{value:M,onChange:W=>P(W.target.value),placeholder:"Custom refinement…"}),e.jsxs(B,{variant:"outline",onClick:()=>$(),disabled:r.isPending,children:[e.jsx(Ki,{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(nK,{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 w7({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(ra,{className:"h-3 w-3 opacity-0"})," ",s]}),t]})}function G8e({value:s,onSave:t}){const[n,r]=j.useState(s);return e.jsxs("div",{children:[e.jsx(Ds,{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(o$e,{value:n})]})]})}function o$e({value:s}){return e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(s),re.success("Copied")},children:e.jsx(ja,{className:"h-3.5 w-3.5"})})}const TOn={draft:"bg-slate-100 text-slate-700",published:"bg-emerald-100 text-emerald-800",archived:"bg-amber-100 text-amber-800"};function EOn(){const{kits:s,isLoading:t,create:n,duplicate:r,remove:a}=Xq(),i=Hn(),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(Wh,{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(Yn,{to:"/attract/provide/kits/templates",children:[e.jsx(i1,{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(Js,{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(be,{className:"p-10 text-center rounded-2xl border-dashed border-slate-300 bg-white",children:[e.jsx(yn,{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(Yn,{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(be,{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(qe,{className:TOn[o.status]+" capitalize",children:o.status}),o.pillar&&e.jsx(qe,{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(qe,{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(Yn,{to:`/attract/provide/kits/${o.id}/edit`,children:[e.jsx(ez,{className:"h-3.5 w-3.5 mr-1.5"}),"Edit"]})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(Yn,{to:`/attract/provide/kits/${o.id}/analytics`,children:[e.jsx(ol,{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);re.success("Duplicated"),i(`/attract/provide/kits/${d}/edit`)},children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:async()=>{await Bi("Delete this kit? Shares and events will also be removed.")&&a.mutate(o.id,{onSuccess:()=>re.success("Deleted")})},children:e.jsx(Rn,{className:"h-3.5 w-3.5 text-rose-600"})})]})]},o.id)})})]})}const MOn={pdf:$r,video:fd,link:vc,checklist:zp,template:w3,text:$r,content_studio:yn,resource:$r};function Sqt({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(be,{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:LOn(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=MOn[o.type]??$r;return e.jsx(be,{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(ii,{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 LOn(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 POn=[{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 Yyt(){var W,G;const{kitId:s}=$i(),[t]=dc(),n=Hn(),{user:r}=Ns(),a=s===void 0,{create:i,update:l}=Xq(),{data:o,isLoading:c}=nqt(s),{items:d,add:u,update:h,remove:m,reorder:p}=hDn(s),{shares:x,create:y,revoke:g}=rqt(s),{agents:b}=x0(),[v,k]=j.useState(null),[C,T]=j.useState("desktop"),[M,P]=j.useState("idle"),L=j.useRef(null);j.useEffect(()=>{a&&!v&&(async()=>{const K=t.get("seed"),ee=await i.mutateAsync({title:K?`From: ${K}`:"Untitled Kit",status:"draft"});n(`/attract/provide/kits/${ee.id}/edit`,{replace:!0})})()},[a]),j.useEffect(()=>{o&&k(o)},[o==null?void 0:o.id]);const I=K=>{s&&(k(ee=>({...ee,...K})),P("saving"),clearTimeout(L.current),L.current=setTimeout(async()=>{try{await l.mutateAsync({id:s,patch:K}),P("saved"),setTimeout(()=>P("idle"),1500)}catch(ee){re.error(ee.message??"Save failed"),P("idle")}},800))},O=async K=>{!s||!r||await u.mutateAsync({user_id:r.id,type:K,title:`New ${K.replace("_"," ")}`})},$=(K,ee)=>{const J=[...d],le=K+ee;le<0||le>=J.length||([J[K],J[le]]=[J[le],J[K]],p.mutate(J.map(ue=>ue.id)))},q=x.filter(K=>K.status==="active");return a||!v?e.jsx("div",{className:"text-slate-500 text-sm",children:"Preparing your kit…"}):c?e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}):e.jsxs("div",{children:[e.jsx(Wh,{eyebrow:"Provide · Kit builder",title:v.title||"Untitled Kit",description:M==="saving"?"Saving…":M==="saved"?"Saved":`Last edited ${Bs(new Date(v.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(Yn,{to:"/attract/provide/kits",children:[e.jsx(_a,{className:"h-4 w-4 mr-1"}),"Kits"]})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsx(Yn,{to:`/attract/provide/kits/${s}/analytics`,children:"Analytics"})}),e.jsxs(vs,{value:v.status,onValueChange:K=>I({status:K}),children:[e.jsx(gs,{className:"w-[130px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"draft",children:"Draft"}),e.jsx(Je,{value:"published",children:"Published"}),e.jsx(Je,{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(be,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit details"}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:v.title??"",onChange:K=>I({title:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Short description"}),e.jsx(Ds,{rows:3,value:v.description??"",onChange:K=>I({description:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Cover image URL"}),e.jsx(ye,{placeholder:"https://…",value:v.cover_image_url??"",onChange:K=>I({cover_image_url:K.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Audience"}),e.jsx(ye,{placeholder:"e.g. New agents",value:v.audience??"",onChange:K=>I({audience:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Pillar"}),e.jsxs(vs,{value:v.pillar??"",onValueChange:K=>I({pillar:K}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Choose"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"produce",children:"Produce"}),e.jsx(Je,{value:"influence",children:"Influence"}),e.jsx(Je,{value:"provide",children:"Provide"}),e.jsx(Je,{value:"connect",children:"Connect"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Tags (comma separated)"}),e.jsx(ye,{value:(v.tags??[]).join(", "),onChange:K=>I({tags:K.target.value.split(",").map(ee=>ee.trim()).filter(Boolean)})})]})]})]}),e.jsxs(be,{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(Ds,{rows:4,placeholder:"Write a short personal note that opens the kit.",value:v.intro_text??"",onChange:K=>I({intro_text:K.target.value})}),e.jsxs("div",{children:[e.jsx(se,{children:"Intro video URL (optional)"}),e.jsx(ye,{placeholder:"Loom/YouTube/Vimeo",value:v.intro_video_url??"",onChange:K=>I({intro_video_url:K.target.value})})]})]})]}),e.jsxs(be,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Call to action"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Button label"}),e.jsx(ye,{value:v.cta_label??"",onChange:K=>I({cta_label:K.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Button URL"}),e.jsx(ye,{placeholder:"https://…",value:v.cta_url??"",onChange:K=>I({cta_url:K.target.value})})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(se,{children:"Expiration (optional)"}),e.jsx(ye,{type:"datetime-local",value:v.expires_at?v.expires_at.slice(0,16):"",onChange:K=>I({expires_at:K.target.value?new Date(K.target.value).toISOString():null})})]})]}),e.jsxs(be,{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(IOn,{kitId:s,agents:b,shares:q,onCreate:K=>y.mutate(K),onRevoke:K=>g.mutate(K),status:v.status})]})]}),e.jsx("div",{className:"xl:col-span-5 space-y-4",children:e.jsxs(be,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit sections"}),e.jsx("div",{className:"text-[13px] text-slate-600",children:"Drag order using arrows. Reorder to change how visitors experience the kit."})]}),e.jsxs(vs,{onValueChange:K=>O(K),children:[e.jsx(gs,{className:"w-[180px]",children:e.jsx(bs,{placeholder:"+ Add item"})}),e.jsx(ys,{children:POn.map(K=>e.jsx(Je,{value:K.value,children:K.label},K.value))})]})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[d.length===0&&e.jsx("div",{className:"text-center text-sm text-slate-500 py-10 border border-dashed rounded-xl",children:"No sections yet. Add your first item above."}),d.map((K,ee)=>{var J,le;return e.jsx(be,{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:()=>$(ee,-1),children:e.jsx(Gm,{className:"h-4 w-4"})}),e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>$(ee,1),children:e.jsx(tx,{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(qe,{variant:"outline",className:"capitalize",children:K.type.replace("_"," ")}),e.jsx(ye,{className:"flex-1",value:K.title,onChange:ue=>h.mutate({id:K.id,patch:{title:ue.target.value}})})]}),e.jsx(Ds,{rows:2,placeholder:"Short description",value:K.description??"",onChange:ue=>h.mutate({id:K.id,patch:{description:ue.target.value}})}),["video","pdf","link","resource"].includes(K.type)&&e.jsx(ye,{placeholder:"URL",value:K.url??"",onChange:ue=>h.mutate({id:K.id,patch:{url:ue.target.value}})}),["text","template"].includes(K.type)&&e.jsx(Ds,{rows:4,placeholder:"Body text or script",value:((J=K.content)==null?void 0:J.body)??"",onChange:ue=>h.mutate({id:K.id,patch:{content:{...K.content??{},body:ue.target.value}}})}),K.type==="checklist"&&e.jsx(Ds,{rows:5,placeholder:"One item per line",value:(((le=K.content)==null?void 0:le.items)??[]).join(` `),onChange:ue=>h.mutate({id:K.id,patch:{content:{items:ue.target.value.split(` `).map(oe=>oe.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(Mn,{checked:K.allow_download,onCheckedChange:ue=>h.mutate({id:K.id,patch:{allow_download:ue}})}),"Allow download"]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-600",children:[e.jsx(Mn,{checked:!K.is_hidden,onCheckedChange:ue=>h.mutate({id:K.id,patch:{is_hidden:!ue}})}),"Visible"]}),e.jsxs("button",{className:"ml-auto text-rose-600 text-[12px] flex items-center gap-1",onClick:()=>m.mutate(K.id),children:[e.jsx(Rn,{className:"h-3.5 w-3.5"}),"Delete"]})]})]})]})},K.id)})]})]})}),e.jsx("div",{className:"xl:col-span-3",children:e.jsxs(be,{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(fa,{value:C,onValueChange:K=>T(K),children:e.jsxs(xa,{className:"h-8",children:[e.jsx(ss,{value:"desktop",className:"h-6 px-2",children:e.jsx(Cj,{className:"h-3.5 w-3.5"})}),e.jsx(ss,{value:"mobile",className:"h-6 px-2",children:e.jsx(Jy,{className:"h-3.5 w-3.5"})})]})})]}),e.jsx("div",{className:C==="mobile"?"max-w-[320px] mx-auto":"",children:e.jsx(Sqt,{kit:v,items:d,owner:{display_name:((W=r==null?void 0:r.user_metadata)==null?void 0:W.full_name)||(r==null?void 0:r.email)||"You",avatar_url:((G=r==null?void 0:r.user_metadata)==null?void 0:G.avatar_url)??null,brokerage:null},mode:"preview"})})]})})]})]})}function IOn({kitId:s,agents:t,shares:n,onCreate:r,onRevoke:a,status:i}){const[l,o]=j.useState("general"),[c,d]=j.useState("");return i!=="published"?e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-3",children:"Publish this kit to generate share links."}):e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsxs(vs,{value:l,onValueChange:u=>o(u),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Choose agent"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"general",children:"General share link"}),t.map(u=>e.jsxs(Je,{value:u.id,children:[u.first_name," ",u.last_name??""]},u.id))]})]}),e.jsx(Ds,{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(zd,{className:"h-4 w-4 mr-2"}),"Create share link"]})]}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("div",{className:"text-[12px] text-slate-500",children:"No active links yet."}),n.map(u=>{var p;const h=iqt(u.share_token),m=u.agent_id?((p=t.find(x=>x.id===u.agent_id))==null?void 0:p.first_name)??"Agent":"General";return e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:m}),e.jsx(qe,{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),re.success("Link copied")},children:[e.jsx(ja,{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(R9,{className:"h-3.5 w-3.5 mr-1"}),"Revoke"]})]})]},u.id)})]})]})}const ROn={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 DOn(){const{kitId:s}=$i(),{data:t}=nqt(s),{shares:n}=rqt(s),{data:r=[]}=aqt(s),a=j.useMemo(()=>{const l=d=>r.filter(u=>u.event_type===d).length,o=new Set(n.filter(d=>d.agent_id).map(d=>d.agent_id)).size,c=n.filter(d=>d.first_opened_at).length;return{shares:n.length,uniqueAgents:o,viewRate:n.length?Math.round(c/n.length*100):0,engaged:n.filter(d=>["engaged","high_intent"].includes(d.engagement_level)).length,downloads:l("file_download"),ctaClicks:l("primary_cta_click"),questions:l("question_submitted"),meetings:l("meeting_requested")}},[n,r]),i=j.useMemo(()=>{const l=new Map;return r.forEach(o=>{const c=Bs(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(Wh,{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(Yn,{to:`/attract/provide/kits/${s}/edit`,children:[e.jsx(_a,{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(qC,{label:"Shares",value:a.shares,icon:ma,tone:"violet"}),e.jsx(qC,{label:"Unique agents",value:a.uniqueAgents,icon:ma,tone:"indigo"}),e.jsx(qC,{label:"View rate",value:`${a.viewRate}%`,icon:ma,tone:"teal"}),e.jsx(qC,{label:"Engaged",value:a.engaged,icon:lu,tone:"emerald"}),e.jsx(qC,{label:"Downloads",value:a.downloads,icon:ii,tone:"orange"}),e.jsx(qC,{label:"CTA clicks",value:a.ctaClicks,icon:lu,tone:"rose"}),e.jsx(qC,{label:"Questions",value:a.questions,icon:Yd,tone:"violet"}),e.jsx(qC,{label:"Meetings",value:a.meetings,icon:ym,tone:"indigo"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(be,{className:"p-5 rounded-2xl xl:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Engagement over time"}),e.jsx("div",{className:"h-64",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(mWe,{data:i,children:[e.jsx(KD,{strokeDasharray:"3 3",stroke:"#eee"}),e.jsx(p1,{dataKey:"date",fontSize:11}),e.jsx(f1,{fontSize:11,allowDecimals:!1}),e.jsx(ff,{}),e.jsx(MO,{type:"monotone",dataKey:"count",stroke:"#7c3aed",strokeWidth:2})]})})})]}),e.jsxs(be,{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(ROn).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(be,{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 ",Bs(new Date(l.created_at),"MMM d")," · ",l.open_count," opens",l.last_opened_at&&` · last opened ${Bs(new Date(l.last_opened_at),"MMM d")}`]})]}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:l.engagement_level.replace("_"," ")})]},l.id))]})]})]})}function qC({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(be,{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 OOn(){const{data:s=[],isLoading:t}=mDn(),n=pDn(),r=Hn(),a=async i=>{try{const l=await n.mutateAsync(i);re.success("Added to your drafts"),r(`/attract/provide/kits/${l}/edit`)}catch(l){re.error(l.message??"Could not clone template")}};return e.jsxs("div",{children:[e.jsx(Wh,{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(Yn,{to:"/attract/provide/kits",children:[e.jsx(_a,{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(be,{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(yn,{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(qe,{variant:"outline",className:"capitalize",children:i.pillar}),(i.tags??[]).slice(0,4).map(o=>e.jsxs(qe,{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(um,{className:"h-4 w-4 mr-2"}),"Use this kit"]})]},i.id)})})]})}const FOn=U,zOn=[..._E,ATe],BOn={hot:Fd,warm:Aj,cold:gj},xG=({label:s})=>e.jsxs("span",{className:"text-slate-400 italic",children:["Not recorded",s?` — add ${s}`:""]}),VC=s=>[s.first_name,s.last_name].filter(Boolean).join(" "),$On=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 j7({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 UOn={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 qOn(){const{agentId:s}=$i(),t=Hn(),{item:n,timeline:r,valueShared:a,nextKit:i,isLoading:l,error:o,refetch:c}=fRn(s),{data:d=[]}=bee(),{upsertAgent:u,moveStage:h}=x0(),{followUps:m,complete:p}=VO(),x=xRn(),{gmailEmail:y}=Tf(),[g,b]=j.useState("all"),[v,k]=j.useState(!1),[C,T]=j.useState(!1),[M,P]=j.useState("call"),[L,I]=j.useState(""),[O,$]=j.useState(""),[q,W]=j.useState(!1),[G,K]=j.useState(""),[ee,J]=j.useState(!1),[le,ue]=j.useState(""),[oe,ie]=j.useState(new Date(Date.now()+3*864e5).toISOString().slice(0,10)),[de,we]=j.useState(null),[je,xe]=j.useState(!1),fe=j.useMemo(()=>d.filter(Ae=>Ae.agent_id===s&&Ae.status==="open").sort((Ae,Xe)=>Xe.rank_score-Ae.rank_score),[d,s]),Se=j.useMemo(()=>m.filter(Ae=>Ae.agent_id===s),[m,s]),Ee=j.useMemo(()=>{const Ae=kyt.find(Xe=>Xe.key===g);return!Ae||!Ae.kinds.length?r:r.filter(Xe=>Ae.kinds.includes(Xe.kind))},[r,g]);if(l)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(gn,{className:"h-8 w-40"}),e.jsx(gn,{className:"h-40 w-full rounded-2xl"}),e.jsx(gn,{className:"h-64 w-full rounded-2xl"})]});if(o)return e.jsxs(be,{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(Ki,{className:"h-4 w-4 mr-2"})," Try again"]})]});if(!n)return e.jsxs(be,{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/relationships"),children:"Back to relationships"})]});const Le=n.agent,De=n.signals,Be=BOn[Le.temperature??""]??Aj,Ne=()=>{x.mutate({agent_id:Le.id,activity_type:M,title:L||`${M.replace(/_/g," ")} with ${VC(Le)}`,description:O||void 0},{onSuccess:()=>{k(!1),I(""),$("")}})},Ge=async()=>{var Xe;if(!G.trim())return;const Ae=[(Xe=Le.notes)==null?void 0:Xe.trim(),`[${new Date().toLocaleDateString()}] ${G.trim()}`].filter(Boolean).join(` `);u.mutate({id:Le.id,first_name:Le.first_name,notes:Ae},{onSuccess:()=>{W(!1),K(""),c()}}),x.mutate({agent_id:Le.id,activity_type:"note",title:"Note added",description:G.trim()})},_e=async()=>{if(!le.trim()){re.error("Give the follow-up a title");return}if(Se.find(Ze=>!Ze.completed_at&&Ze.title.trim().toLowerCase()===le.trim().toLowerCase())){re.error("An open follow-up with that title already exists");return}const{data:Xe}=await U.auth.getUser(),{error:Ue}=await FOn.from("attract_follow_ups").insert({user_id:Xe.user.id,agent_id:Le.id,title:le.trim(),due_at:new Date(`${oe}T12:00:00`).toISOString(),touch_type:"call",priority:"medium"});if(Ue){re.error(Ue.message);return}re.success("Follow-up created"),J(!1),ue(""),c()},Oe=()=>{de&&(window.open(de.href,"_self"),x.mutate({agent_id:Le.id,activity_type:de.kind,title:`${de.kind==="call"?"Called":de.kind==="text"?"Texted":"Emailed"} ${VC(Le)}`}),we(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(Yn,{to:"/attract",className:"hover:text-violet-700",children:"Attract"}),e.jsx(Qa,{className:"h-3 w-3"}),e.jsx(Yn,{to:"/attract/relationships",className:"hover:text-violet-700",children:"Relationships"}),e.jsx(Qa,{className:"h-3 w-3"}),e.jsx("span",{className:"text-slate-800 font-medium truncate",children:VC(Le)})]}),e.jsxs(be,{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(_a,{className:"h-3.5 w-3.5 mr-1.5"})," Back"]}),e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[Le.photo_url?e.jsx("img",{src:Le.photo_url,alt:`${VC(Le)} 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:$On(Le)}),e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:VC(Le)}),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:Le.brokerage||"Brokerage not recorded"}),e.jsx("span",{className:"opacity-40",children:"·"}),e.jsx("span",{children:[Le.city,Le.state].filter(Boolean).join(", ")||"Market not recorded"}),Le.is_demo&&e.jsx(qe,{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(qe,{className:"rounded-full bg-white/10 text-white border-transparent",children:eqt(Le.stage)}),e.jsxs(qe,{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"})," ",Le.temperature??"temperature unset"]}),e.jsx(HYe,{score:n.score,className:"bg-white/10 text-white ring-white/20"}),(Le.tags??[]).map(Ae=>e.jsx(qe,{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:Le.email?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`mailto:${Le.email}`,children:Le.email}):"No email on file"}),e.jsx("div",{children:Le.phone?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`tel:${Le.phone}`,children:Le.phone}):"No phone on file"}),e.jsxs("div",{children:["Last meaningful touch: ",De.lastTouchAt?`${new Date(De.lastTouchAt).toLocaleDateString()} (${De.daysSinceTouch}d ago)`:"never logged"]}),e.jsxs("div",{children:["Next follow-up: ",Le.next_follow_up_at?new Date(Le.next_follow_up_at).toLocaleDateString():"none scheduled"]}),e.jsxs("div",{children:["Source: ",Le.source||"not recorded"," · Owner: ",Le.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(Za,{className:"h-3.5 w-3.5 mr-1.5"})," Edit contact"]}),e.jsxs(Fs,{open:v,onOpenChange:k,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-1.5"})," Log touch"]})}),e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Log a conversation"}),e.jsx(kr,{children:"This records what already happened — it does not send anything."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Type"}),e.jsxs(vs,{value:M,onValueChange:P,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["call","text","email","dm","meeting","note"].map(Ae=>e.jsx(Je,{value:Ae,className:"capitalize",children:Ae},Ae))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Title"}),e.jsx(ye,{value:L,onChange:Ae=>I(Ae.target.value),placeholder:`Call with ${Le.first_name}`})]}),e.jsxs("div",{children:[e.jsx(se,{children:"What happened"}),e.jsx(Ds,{rows:4,value:O,onChange:Ae=>$(Ae.target.value)})]})]}),e.jsx(Nr,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Ne,disabled:x.isPending,children:"Log it"})})]})]}),e.jsxs(Fs,{open:q,onOpenChange:W,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(oK,{className:"h-3.5 w-3.5 mr-1.5"})," Add note"]})}),e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Add a relationship note"})}),e.jsx(Ds,{rows:5,value:G,onChange:Ae=>K(Ae.target.value),placeholder:"What did you learn about them?"}),e.jsx(Nr,{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:!Le.phone,onClick:()=>Le.phone&&we({kind:"call",href:`tel:${Le.phone}`}),children:[e.jsx(pa,{className:"h-3.5 w-3.5 mr-1.5"})," Call"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Le.phone,onClick:()=>Le.phone&&we({kind:"text",href:`sms:${Le.phone}`}),children:[e.jsx(ro,{className:"h-3.5 w-3.5 mr-1.5"})," Text"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Le.email,onClick:()=>Le.email&&xe(!0),children:[e.jsx(on,{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(Yn,{to:"/attract/provide/kits",children:[e.jsx(i1,{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(Yn,{to:"/attract/events",children:[e.jsx(Wy,{className:"h-3.5 w-3.5 mr-1.5"})," Invite to event"]})}),e.jsxs(Fs,{open:ee,onOpenChange:J,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(Vr,{className:"h-3.5 w-3.5 mr-1.5"})," Create follow-up"]})}),e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Create a follow-up"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"What will you do?"}),e.jsx(ye,{value:le,onChange:Ae=>ue(Ae.target.value),placeholder:"Call about their Q3 goals"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Due"}),e.jsx(ye,{type:"date",value:oe,onChange:Ae=>ie(Ae.target.value)})]})]}),e.jsx(Nr,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:_e,children:"Create"})})]})]}),e.jsxs(vs,{value:Wz(Le.stage).key,onValueChange:Ae=>{const Xe=KYe(Ae);Xe!==Le.stage&&h.mutate({id:Le.id,to_stage:Xe,from_stage:Le.stage})},children:[e.jsxs(gs,{className:"w-[230px] h-9 rounded-full text-[13px]","aria-label":"Change relationship stage",children:[e.jsx(M5,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(bs,{})]}),e.jsx(ys,{children:zOn.map(Ae=>e.jsx(Je,{value:Ae.key,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{background:Ae.color}}),Ae.label]})},Ae.key))})]})]})]}),e.jsx(Fs,{open:!!de,onOpenChange:Ae=>!Ae&&we(null),children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsxs(zs,{children:["Open your ",(de==null?void 0:de.kind)==="email"?"email app":(de==null?void 0:de.kind)==="text"?"messaging app":"phone app","?"]}),e.jsx(kr,{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(Nr,{children:[e.jsx(B,{variant:"ghost",className:"rounded-full",onClick:()=>we(null),children:"Cancel"}),e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Oe,children:"Continue"})]})]})}),e.jsxs(fa,{defaultValue:"overview",children:[e.jsx(xa,{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(ss,{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(ns,{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(be,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Next best relationship touch"}),fe[0]?e.jsx(qSe,{rec:fe[0],agentName:VC(Le),agentStage:Le.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(be,{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(j7,{label:"Goals",children:Le.goals||e.jsx(xG,{label:"their goals"})}),e.jsx(j7,{label:"Challenges",children:Le.challenges||e.jsx(xG,{label:"their challenges"})}),e.jsx(j7,{label:"Interests",children:Le.interests||e.jsx(xG,{label:"interests"})}),e.jsx(j7,{label:"Production context",children:Le.production_context||e.jsx(xG,{label:"production context"})}),e.jsx(j7,{label:"Primary pillar",children:Le.primary_pillar?e.jsx("span",{className:"capitalize",children:Le.primary_pillar}):e.jsx(xG,{label:"a pillar"})}),e.jsx(j7,{label:"Added to pipeline",children:new Date(Le.created_at).toLocaleDateString()})]})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Touches (90d)",value:De.touches90},{label:"Kits shared",value:De.shares.length},{label:"Kit opens",value:De.totalKitOpens},{label:"Events attended",value:De.attended}].map(Ae=>e.jsxs(be,{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(be,{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($Ut,{score:n.score})]})]}),fe.length>1&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500",children:"Other open recommendations"}),fe.slice(1).map(Ae=>e.jsx(qSe,{rec:Ae,agentName:VC(Le),showAgentLink:!1,compact:!0},Ae.id))]})]}),e.jsx(ns,{value:"timeline",className:"mt-5",children:e.jsxs(be,{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:kyt.map(Ae=>e.jsx("button",{onClick:()=>b(Ae.key),className:Et("rounded-full px-3 py-1.5 text-[12px] font-medium transition-colors",g===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(Rr,{className:"h-3.5 w-3.5 mr-1.5"})," Log something"]})]}),Ee.length?e.jsxs("ol",{className:"relative pl-5 sm:pl-6",children:[e.jsx("span",{"aria-hidden":!0,className:"absolute left-1.5 top-1 bottom-1 w-px bg-slate-200"}),Ee.map(Ae=>e.jsxs("li",{className:"relative pb-5",children:[e.jsx("span",{"aria-hidden":!0,className:Et("absolute -left-[15px] sm:-left-[18px] top-1.5 h-2.5 w-2.5 rounded-full ring-2 ring-white",UOn[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(ns,{value:"value",className:"mt-5 space-y-4",children:[i&&e.jsxs(be,{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(Yn,{to:"/attract/provide/kits",children:"Open Resource Kits"})})]}),a.length?a.map(Ae=>e.jsxs(be,{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(qe,{variant:"outline",className:Et("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,Ue])=>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:Ue}),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(be,{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(ns,{value:"events",className:"mt-5 space-y-3",children:De.attendees.length?De.attendees.map(Ae=>e.jsx(be,{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(Yn,{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(qe,{variant:"outline",className:"rounded-full capitalize",children:Ae.followup_status?`follow-up ${Ae.followup_status}`:Ae.status??"invited"})]})},Ae.id)):e.jsxs(be,{className:"p-8 rounded-2xl text-center",children:[e.jsx(qv,{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(Yn,{to:"/attract/events",children:"See your events"})})]})}),e.jsx(ns,{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)p.mutate(Ae.id),children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-1.5"})," Complete"]})]},Ae.id)}):e.jsxs(be,{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:()=>J(!0),children:"Create one"})]})}),e.jsxs(ns,{value:"notes",className:"mt-5 space-y-4",children:[e.jsxs(be,{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"})]}),Le.notes?e.jsx("div",{className:"text-[13.5px] text-slate-700 whitespace-pre-wrap",children:Le.notes}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No notes recorded yet."})]}),e.jsxs(be,{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(YYe,{agent:Le,open:C,onOpenChange:T,onDeleted:()=>t("/attract/relationships")}),Le.email&&e.jsx(cw,{open:je,onOpenChange:xe,contact:{id:Le.id,first_name:Le.preferred_name||Le.first_name,last_name:Le.last_name||"",email:Le.email},gmailEmail:y,sendSource:"attract",logTouchpoint:!1,onSendComplete:()=>{x.mutate({agent_id:Le.id,activity_type:"email",title:`Emailed ${VC(Le)}`})}})]})}const VOn=[{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 HOn(){const{intel:s,byId:t,isLoading:n,error:r,refetch:a}=A6(),{data:i=[],isLoading:l}=bee(),o=NTe();kTe();const[c,d]=j.useState(""),[u,h]=j.useState("all"),[m,p]=j.useState("open"),x=b=>{var k;const v=(k=t.get(b))==null?void 0:k.agent;return v?[v.first_name,v.last_name].filter(Boolean).join(" "):"Unknown agent"},y=j.useMemo(()=>{const b=Date.now();return i.filter(v=>m==="open"?v.status==="open"||v.status==="snoozed"&&v.snoozed_until&&+new Date(v.snoozed_until)<=b:m==="snoozed"?v.status==="snoozed":m==="done"?v.status==="completed":m==="dismissed"?v.status==="dismissed":!0).filter(v=>u==="all"||v.signal_group===u).filter(v=>{if(!c.trim())return!0;const k=c.toLowerCase();return x(v.agent_id).toLowerCase().includes(k)||v.title.toLowerCase().includes(k)||(v.reasons??[]).join(" ").toLowerCase().includes(k)}).sort((v,k)=>k.rank_score-v.rank_score)},[i,m,u,c,t]),g=j.useMemo(()=>{const b=i.filter(v=>v.status==="open");return{open:b.length,urgent:b.filter(v=>v.priority==="urgent").length,highIntent:b.filter(v=>v.signal_group==="high_intent").length,overdue:b.filter(v=>v.suggested_due_at&&+new Date(v.suggested_due_at)e.jsx(gn,{className:"h-28 w-full rounded-2xl"},b))}):r?e.jsxs(be,{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(Ki,{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(Ki,{className:Et("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:g.open},{label:"Urgent",value:g.urgent},{label:"High intent signals",value:g.highIntent},{label:"Past suggested date",value:g.overdue}].map(b=>e.jsxs(be,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:b.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:b.label})]},b.label))}),e.jsxs(be,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px]",children:[e.jsx(Fr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(ye,{value:c,onChange:b=>d(b.target.value),placeholder:"Search agents or reasons",className:"pl-9 rounded-full h-9","aria-label":"Search recommendations"})]}),e.jsxs(vs,{value:u,onValueChange:h,children:[e.jsxs(gs,{className:"w-[190px] h-9 rounded-full text-[13px]",children:[e.jsx(Nj,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(bs,{})]}),e.jsx(ys,{children:VOn.map(b=>e.jsx(Je,{value:b.key,children:b.label},b.key))})]}),e.jsxs(vs,{value:m,onValueChange:p,children:[e.jsx(gs,{className:"w-[150px] h-9 rounded-full text-[13px]",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"open",children:"Needs action"}),e.jsx(Je,{value:"snoozed",children:"Snoozed"}),e.jsx(Je,{value:"done",children:"Completed"}),e.jsx(Je,{value:"dismissed",children:"Dismissed"}),e.jsx(Je,{value:"all",children:"All"})]})]})]}),y.length?e.jsx("div",{className:"space-y-3",children:y.map(b=>{var v;return e.jsx(qSe,{rec:b,agentName:x(b.agent_id),agentStage:(v=t.get(b.agent_id))==null?void 0:v.agent.stage},b.id)})}):i.length?e.jsx(DRn,{label:"Nothing matches this view. Try switching the filter."}):e.jsxs(be,{className:"p-10 rounded-2xl text-center",children:[e.jsx(yn,{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(Yn,{to:"/attract/pipeline",children:"Open pipeline"})}),e.jsx(B,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(Yn,{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(b=>QUt(b.signal_group)))].join(", ")]})]})}const W8e=s=>[s.first_name,s.last_name].filter(Boolean).join(" ");function GOn(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 Cqt(s,t,n=new Date){const r=GOn(n),a=new Date(r.getTime()+6*864e5),i=new Date(n.getTime()-7*864e5),c=s.filter(L=>L.primary).slice().sort((L,I)=>I.primary.rank_score-L.primary.rank_score||L.score.score-I.score.score).slice(0,5).map((L,I)=>({agent_id:L.agent.id,agent_name:W8e(L.agent),rank:I+1,reason:L.primary.reasons.join(" · "),channel:L.primary.channel,draft_message:L.primary.draft_message,score:L.score.score,stage:L.agent.stage})),d=L=>s.map(I=>{const O=L(I);return O?{agent_id:I.agent.id,agent_name:W8e(I.agent),detail:O}:null}).filter(Boolean).slice(0,8),u=d(L=>L.signals.meetingRequests>0||L.signals.questions>0||L.signals.highIntentShares.some(I=>I.engagement_level==="high_intent")?`${L.signals.meetingRequests} meeting request(s), ${L.signals.questions} question(s), ${L.signals.totalKitOpens} kit open(s)`:null),h=d(L=>L.recommendations.some(I=>I.rec_key==="renewed_interest")?"Came back to a kit you shared after going quiet":null),m=d(L=>L.signals.overdueFollowUps.length?`${L.signals.overdueFollowUps.length} overdue follow-up(s) — oldest: ${L.signals.overdueFollowUps[0].title}`:null),p=d(L=>L.signals.daysSinceTouch!==null&&L.signals.daysSinceTouch>60?`${L.signals.daysSinceTouch} days since a real conversation`:null),x=t.shares.filter(L=>new Date(L.created_at)>=i),y={shares:x.length,opened:t.shares.filter(L=>L.first_opened_at&&new Date(L.first_opened_at)>=i).length,engaged:t.shares.filter(L=>L.engagement_level==="engaged").length,high_intent:t.shares.filter(L=>L.engagement_level==="high_intent").length,downloads:t.kitEvents.filter(L=>L.event_type==="file_download"&&new Date(L.created_at)>=i).length,questions:t.kitEvents.filter(L=>L.event_type==="question_submitted"&&new Date(L.created_at)>=i).length},g={invited:t.attendees.filter(L=>L.invited_at&&new Date(L.invited_at)>=i).length,registered:t.attendees.filter(L=>L.registered_at&&new Date(L.registered_at)>=i).length,attended:t.attendees.filter(L=>L.checked_in_at&&new Date(L.checked_in_at)>=i).length,no_shows:t.attendees.filter(L=>L.no_show_at&&new Date(L.no_show_at)>=i).length,follow_ups_pending:t.attendees.filter(L=>L.checked_in_at&&L.followup_status!=="done").length,upcoming:t.events.filter(L=>L.starts_at&&new Date(L.starts_at)>n&&L.status==="published").sort((L,I)=>+new Date(L.starts_at)-+new Date(I.starts_at)).slice(0,3).map(L=>({title:L.title,starts_at:L.starts_at??null}))},b=[...s.filter(L=>L.agent.next_follow_up_at&&new Date(L.agent.next_follow_up_at)>n&&Qx(n,L.agent.next_follow_up_at)<=7).slice(0,5).map(L=>({label:W8e(L.agent),detail:`Follow-up scheduled ${new Date(L.agent.next_follow_up_at).toLocaleDateString()}`})),...g.upcoming.map(L=>({label:L.title,detail:L.starts_at?`Event on ${new Date(L.starts_at).toLocaleDateString()}`:"Event scheduled"}))].slice(0,6),v=t.activities.filter(L=>new Date(L.created_at)>=i),k={produce:0,influence:0,provide:0,connect:0};for(const L of v)L.pillar&&k[L.pillar]!==void 0&&k[L.pillar]++;const C=Object.entries(k).map(([L,I])=>({pillar:L,count:I})),T=C.slice().sort((L,I)=>L.count-I.count)[0],M=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.`,P={advanced:t.stageChanges.filter(L=>new Date(L.created_at)>=i).length,follow_ups_completed:t.followUps.filter(L=>L.completed_at&&new Date(L.completed_at)>=i).length,conversations_logged:v.filter(L=>["touch_logged","call","text","email","dm","meeting"].includes(L.activity_type)).length,kits_shared:x.length};return{week_start:r.toISOString().slice(0,10),week_end:a.toISOString().slice(0,10),generated_at:n.toISOString(),conversations:c,high_intent:u,renewed:h,overdue:m,stale:p,kit_summary:y,event_summary:g,upcoming_opportunities:b,pillar_balance:C,recommended_focus:M,wins:P}}function Zyt(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 h3=U;function WOn(){const{user:s}=Ns(),t=as(),n=mt({queryKey:["attract-digest-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await h3.from("attract_digest_settings").select("*").eq("user_id",s.id).maybeSingle();if(i)throw i;return a??null}}),r=vt({mutationFn:async a=>{const{error:i}=await h3.from("attract_digest_settings").upsert({user_id:s.id,...a},{onConflict:"user_id"});if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digest-settings"]}),re.success("Digest settings saved")},onError:a=>re.error(a.message)});return{settings:n.data,isLoading:n.isLoading,save:r}}function KOn(){const{user:s}=Ns();return mt({queryKey:["attract-digests",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await h3.from("attract_digests").select("*").order("week_start",{ascending:!1}).limit(26);if(n)throw n;return t??[]}})}function YOn(s){const t=as(),n=mt({queryKey:["attract-digest-items",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await h3.from("attract_digest_items").select("*").eq("digest_id",s).order("rank");if(i)throw i;return a??[]}}),r=vt({mutationFn:async a=>{const{error:i}=await h3.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]}),re.success("Marked as done")}});return{items:n.data??[],isLoading:n.isLoading,markComplete:r}}function ZOn(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{const{data:r,error:a}=await h3.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 h3.from("attract_digest_items").delete().eq("digest_id",i).is("completed_at",null);const{data:l}=await h3.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 h3.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=>re.error(n.message)})}function XOn(){const s=as();return vt({mutationFn:async t=>{const{data:n,error:r}=await U.functions.invoke("attract-send-digest",{body:t});if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-digests"]}),t!=null&&t.ok?re.success("Digest email sent"):re.error((t==null?void 0:t.reason)||"Email delivery is not configured yet")},onError:t=>re.error(t.message??"Send failed")})}const QOn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function N7({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 $re({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(Yn,{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 JOn(){var M;const{user:s}=Ns(),{intel:t,dataset:n,isLoading:r}=A6(),{settings:a,save:i}=WOn(),{data:l=[]}=KOn(),o=ZOn(),c=XOn(),[d,u]=j.useState(),h=d??((M=l[0])==null?void 0:M.id),{items:m,markComplete:p}=YOn(h),[x,y]=j.useState(""),g=j.useMemo(()=>n?Cqt(t,n):null,[t,n]),b=l.find(P=>P.id===h),v=(b==null?void 0:b.payload)??g,k=x||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",C=()=>{g&&o.mutate(g,{onSuccess:P=>{u(P),re.success("This week's digest is ready")}})},T=P=>{if(!v)return;if(!k){re.error("Add an email address first");return}const L=I=>c.mutate({digestId:I,to:k,subject:`Your Weekly Attraction Digest — ${v.week_start}`,html:Zyt(v,window.location.origin),test:P});b?L(b.id):g&&o.mutate(g,{onSuccess:I=>{u(I),L(I)}})};return r||!v?e.jsxs("div",{className:"space-y-4",children:[e.jsx(gn,{className:"h-10 w-56"}),e.jsx(gn,{className:"h-72 w-full rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Relationship Intelligence"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900 mt-0.5",children:"Weekly Attraction Digest"}),e.jsxs("p",{className:"text-[13.5px] text-slate-500 mt-1",children:["Week of ",new Date(`${v.week_start}T12:00:00`).toLocaleDateString()," – ",new Date(`${v.week_end}T12:00:00`).toLocaleDateString(),b&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"capitalize",children:b.delivery_status.replace(/_/g," ")}),b.sent_at?` ${new Date(b.sent_at).toLocaleString()}`:""]})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:C,disabled:o.isPending,children:[e.jsx(Ki,{className:Et("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(Zyt(v,window.location.origin)),re.success("Digest HTML copied")},children:[e.jsx(ja,{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(Dr,{className:"h-3.5 w-3.5 mr-1.5"})," Email it to me"]})]})]}),e.jsxs(fa,{defaultValue:"digest",children:[e.jsx(xa,{className:"rounded-full bg-white border border-slate-200 p-1",children:[["digest","This week"],["history","History"],["settings","Delivery settings"]].map(([P,L])=>e.jsx(ss,{value:P,className:"rounded-full text-[13px] data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:L},P))}),e.jsxs(ns,{value:"digest",className:"mt-5 space-y-5",children:[e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[["Conversations logged",v.wins.conversations_logged],["Stage moves",v.wins.advanced],["Follow-ups completed",v.wins.follow_ups_completed],["Kits shared",v.wins.kits_shared]].map(([P,L])=>e.jsxs(be,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:L}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:P})]},P))}),e.jsxs(be,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Your five conversations this week"}),v.conversations.length?e.jsx("div",{className:"space-y-3",children:v.conversations.map(P=>{const L=m.find(O=>O.agent_id===P.agent_id),I=!!(L!=null&&L.completed_at);return e.jsxs("div",{className:Et("rounded-xl border border-slate-200 p-4",I&&"bg-emerald-50/60 border-emerald-200"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[14.5px] font-semibold text-slate-900",children:[P.rank,". ",e.jsx(Yn,{to:`/attract/agents/${P.agent_id}`,className:"hover:text-violet-700",children:P.agent_name})]}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:P.reason})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:P.channel}),e.jsxs(qe,{variant:"outline",className:"rounded-full",children:["Health ",P.score]})]})]}),P.draft_message&&e.jsx("div",{className:"mt-3 rounded-lg bg-slate-50 p-3 text-[13px] text-slate-700 whitespace-pre-wrap",children:P.draft_message}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(P.draft_message||""),re.success("Copied")},children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]}),L&&!I&&e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>p.mutate(L.id),children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark done"]}),I&&e.jsx("span",{className:"text-[12.5px] text-emerald-700 font-medium self-center",children:"Completed"}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsx(Yn,{to:`/attract/agents/${P.agent_id}`,children:"Open relationship"})})]})]},P.agent_id)})}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No conversations to recommend yet — Attract needs real signals first."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs(be,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(N7,{title:"High intent",children:e.jsx($re,{rows:v.high_intent,empty:"No high-intent signals this week."})}),e.jsx(N7,{title:"Renewed interest",children:e.jsx($re,{rows:v.renewed,empty:"Nobody re-engaged after going quiet."})})]}),e.jsxs(be,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(N7,{title:"Overdue commitments",children:e.jsx($re,{rows:v.overdue,empty:"Nothing overdue. Well kept."})}),e.jsx(N7,{title:"Going cold",children:e.jsx($re,{rows:v.stale,empty:"No relationships past 60 days of silence."})})]}),e.jsx(be,{className:"p-5 rounded-2xl",children:e.jsx(N7,{title:"Value shared",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[v.kit_summary.shares," kits shared · ",v.kit_summary.opened," opened"]}),e.jsxs("div",{children:[v.kit_summary.downloads," downloads · ",v.kit_summary.questions," questions asked"]}),e.jsxs("div",{children:[v.kit_summary.engaged," engaged · ",v.kit_summary.high_intent," high intent"]})]})})}),e.jsx(be,{className:"p-5 rounded-2xl",children:e.jsx(N7,{title:"Events",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[v.event_summary.invited," invited · ",v.event_summary.registered," registered"]}),e.jsxs("div",{children:[v.event_summary.attended," attended · ",v.event_summary.no_shows," no-shows"]}),e.jsxs("div",{children:[v.event_summary.follow_ups_pending," attendee follow-ups still pending"]}),v.event_summary.upcoming.map(P=>e.jsxs("div",{className:"text-slate-600 flex items-center gap-1.5",children:[e.jsx(Vc,{className:"h-3.5 w-3.5"})," ",P.title,P.starts_at?` — ${new Date(P.starts_at).toLocaleDateString()}`:""]},P.title))]})})})]}),e.jsxs(be,{className:"p-5 rounded-2xl bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-700",children:"Recommended focus"}),e.jsx("p",{className:"text-[14px] text-slate-800 mt-1.5",children:v.recommended_focus}),e.jsx("div",{className:"flex gap-2 mt-3 flex-wrap",children:v.pillar_balance.map(P=>e.jsxs(qe,{variant:"outline",className:"rounded-full capitalize bg-white/70",children:[P.pillar,": ",P.count]},P.pillar))})]})]}),e.jsx(ns,{value:"history",className:"mt-5 space-y-3",children:l.length?l.map(P=>e.jsxs(be,{className:Et("p-4 rounded-2xl flex items-center justify-between gap-3 flex-wrap",P.id===h&&"ring-1 ring-violet-300"),children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[14px] font-semibold text-slate-900",children:["Week of ",new Date(`${P.week_start}T12:00:00`).toLocaleDateString()]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[e.jsx("span",{className:"capitalize",children:P.delivery_status.replace(/_/g," ")}),P.sent_at&&` · sent ${new Date(P.sent_at).toLocaleString()}`,P.delivery_note&&` · ${P.delivery_note}`]})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u(P.id),children:"View"})]},P.id)):e.jsx(be,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"No digests generated yet."})}),e.jsx(ns,{value:"settings",className:"mt-5",children:e.jsxs(be,{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(Mn,{checked:!!(a!=null&&a.enabled),onCheckedChange:P=>i.mutate({enabled:P})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Day"}),e.jsxs(vs,{value:String((a==null?void 0:a.weekday)??1),onValueChange:P=>i.mutate({weekday:Number(P)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:QOn.map((P,L)=>e.jsx(Je,{value:String(L),children:P},P))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Hour (local)"}),e.jsxs(vs,{value:String((a==null?void 0:a.send_hour)??7),onValueChange:P=>i.mutate({send_hour:Number(P)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Array.from({length:24},(P,L)=>e.jsxs(Je,{value:String(L),children:[L,":00"]},L))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Send to"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:x||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",onChange:P=>y(P.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(on,{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 bM=U,eFn=[{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 tFn(){const{user:s}=Ns(),t=as(),{intel:n,dataset:r,isLoading:a,refetch:i}=A6(),l=NTe(),o=zUt(),[c,d]=j.useState(""),[u,h]=j.useState(!1),m=j.useMemo(()=>r?Cqt(n,r):null,[n,r]),p=j.useMemo(()=>{const g=c.toLowerCase().trim();return n.filter(b=>!g||`${b.agent.first_name} ${b.agent.last_name??""}`.toLowerCase().includes(g))},[n,c]),x=async()=>{if(!s)return;h(!0);const{data:g}=await bM.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0);if((g??[]).length){re.info("Demo agents already exist"),h(!1);return}const{data:b,error:v}=await bM.from("attract_agents").insert(eFn.map(C=>({...C,user_id:s.id,is_demo:!0,source:"demo_seed"}))).select("id, first_name");if(v){re.error(v.message),h(!1);return}const k=Date.now();await bM.from("attract_activities").insert((b??[]).map((C,T)=>({user_id:s.id,agent_id:C.id,activity_type:"touch_logged",pillar:"connect",title:`Demo conversation with ${C.first_name}`,created_at:new Date(k-(T+1)*14*864e5).toISOString()}))),await bM.from("attract_follow_ups").insert({user_id:s.id,agent_id:b[0].id,title:"Demo overdue commitment",touch_type:"call",priority:"high",due_at:new Date(k-6*864e5).toISOString()}),re.success("Demo relationships seeded"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()},y=async()=>{if(!s)return;h(!0);const{data:g}=await bM.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0),b=(g??[]).map(v=>v.id);if(!b.length){re.info("No demo data to clear"),h(!1);return}for(const v of["attract_recommendations","attract_agent_scores","attract_follow_ups","attract_activities"])await bM.from(v).delete().in("agent_id",b);await bM.from("attract_agents").delete().in("id",b),re.success("Demo data removed"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()};return a?e.jsx(gn,{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(Yn,{to:"/admin",children:[e.jsx(_a,{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(Ki,{className:"h-3.5 w-3.5 mr-1.5"})," Recompute & persist"]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:x,disabled:u,children:[e.jsx(TW,{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(Rn,{className:"h-3.5 w-3.5 mr-1.5"})," Clear demo data"]})]}),e.jsxs(fa,{defaultValue:"agents",children:[e.jsxs(xa,{className:"rounded-full",children:[e.jsx(ss,{value:"agents",className:"rounded-full",children:"Scores & signals"}),e.jsx(ss,{value:"digest",className:"rounded-full",children:"Digest payload"})]}),e.jsxs(ns,{value:"agents",className:"mt-4 space-y-3",children:[e.jsx(ye,{value:c,onChange:g=>d(g.target.value),placeholder:"Filter by name",className:"max-w-sm rounded-full"}),!p.length&&e.jsx(be,{className:"p-6 rounded-2xl text-[13.5px] text-muted-foreground",children:"No agents in your Attract pipeline."}),p.map(g=>e.jsxs(be,{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(Yn,{to:`/attract/agents/${g.agent.id}`,className:"text-[15px] font-semibold hover:text-violet-700",children:[g.agent.first_name,g.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("div",{className:"text-[12px] text-muted-foreground mt-0.5 capitalize",children:[g.agent.stage.replace(/_/g," ")," · ",g.agent.temperature??"no temperature"," · ",g.signals.daysSinceTouch??"—"," days since touch"]})]}),g.agent.is_demo&&e.jsx(qe,{variant:"outline",className:"rounded-full",children:"Demo"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4 mt-4",children:[e.jsx($Ut,{score:g.score}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground mb-1.5",children:["Recommendations (",g.recommendations.length,")"]}),g.recommendations.length?e.jsx("ul",{className:"space-y-2",children:g.recommendations.map(b=>e.jsxs("li",{className:"text-[12.5px]",children:[e.jsx("span",{className:"font-medium",children:b.title}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",b.signal_group," · rank ",b.rank_score," · ",b.priority]}),e.jsx("div",{className:"text-muted-foreground",children:b.reasons.join(" · ")})]},b.rec_key))}):e.jsx("div",{className:"text-[13px] text-muted-foreground",children:"None generated."})]})]}),e.jsxs("details",{className:"mt-3",children:[e.jsx("summary",{className:"text-[12px] cursor-pointer text-muted-foreground",children:"Raw signals"}),e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto mt-2 max-h-72",children:JSON.stringify({touches90:g.signals.touches90,kitShares:g.signals.shares.length,kitOpens:g.signals.totalKitOpens,questions:g.signals.questions,meetingRequests:g.signals.meetingRequests,overdueFollowUps:g.signals.overdueFollowUps.length,attended:g.signals.attended},null,2)})]})]},g.agent.id))]}),e.jsx(ns,{value:"digest",className:"mt-4",children:e.jsx(be,{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 sFn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),a=j.useMemo(()=>e$e.filter(l=>{const o=s.toLowerCase().trim();return n!=="all"&&l.status!==n?!1:!o||`${l.title} ${l.pillar} ${l.route??""}`.toLowerCase().includes(o)}),[s,n]),i=j.useMemo(()=>{const l={live:0,partial:0,placeholder:0,integration_required:0};return e$e.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(Yn,{to:"/admin",children:[e.jsx(_a,{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(be,{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:t$e[l]})]},l))}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(ye,{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(be,{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(qe,{variant:"outline",className:"rounded-full capitalize",children:l.pillar}),e.jsx(qe,{variant:"outline",className:`rounded-full ${sqt[l.status]}`,children:t$e[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(Yn,{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 _M=U,Xyt=["idea","researching","pitching","applied","tentative","confirmed","completed","declined","archived"],Qyt=["panel","keynote","mls_talk","podcast","webinar","mastermind","training","conference","other"],Jyt=["attract-speaking"];function Aqt(){const{user:s}=Ns(),t=as(),n=mt({queryKey:[...Jyt,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await _M.from("attract_speaking_opportunities").select("*").order("starts_at",{ascending:!0,nullsFirst:!1});if(h)throw h;return u??[]}}),r=()=>{t.invalidateQueries({queryKey:Jyt}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-activities"]})},a=vt({mutationFn:async u=>{const{data:h,error:m}=await _M.from("attract_speaking_opportunities").insert({...u,user_id:s.id}).select("*").single();if(m)throw m;return h},onSuccess:()=>{r(),re.success("Speaking opportunity saved")},onError:u=>re.error(u.message)}),i=vt({mutationFn:async({id:u,...h})=>{const{error:m}=await _M.from("attract_speaking_opportunities").update(h).eq("id",u);if(m)throw m},onSuccess:()=>{r(),re.success("Updated")},onError:u=>re.error(u.message)}),l=vt({mutationFn:async u=>{const{id:h,created_at:m,updated_at:p,user_id:x,...y}=u,{data:g,error:b}=await _M.from("attract_speaking_opportunities").insert({...y,title:`${u.title} (copy)`,status:"idea",user_id:s.id}).select("id").single();if(b)throw b;return g},onSuccess:()=>{r(),re.success("Duplicated")},onError:u=>re.error(u.message)}),o=vt({mutationFn:async u=>{const{error:h}=await _M.from("attract_speaking_opportunities").delete().eq("id",u);if(h)throw h},onSuccess:()=>{r(),re.success("Deleted")},onError:u=>re.error(u.message)}),c=vt({mutationFn:async({title:u,dueAt:h,notes:m,touchType:p="speaking"})=>{const{error:x}=await _M.from("attract_follow_ups").insert({user_id:s.id,title:u,due_at:h??null,notes:m??null,touch_type:p,priority:"medium"});if(x)throw x},onSuccess:()=>{r(),re.success("Added to Follow-Up Center")},onError:u=>re.error(u.message)}),d=vt({mutationFn:async({title:u,pillar:h="influence",activityType:m="speaking_outreach",agentId:p})=>{const{error:x}=await _M.from("attract_activities").insert({user_id:s.id,title:u,pillar:h,activity_type:m,agent_id:p??null});if(x)throw x},onSuccess:()=>{r(),re.success("Outreach logged")},onError:u=>re.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 l$e={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"},K8e={title:"",organization:"",event_type:"panel",status:"idea",timezone:"America/New_York",pillar:"influence",linked_agent_ids:[]};function nFn(){const{items:s,isLoading:t,create:n,update:r,duplicate:a,remove:i,addTask:l,logActivity:o}=Aqt(),{agents:c=[]}=x0(),{kits:d=[]}=Xq(),u=STe(),h=(u==null?void 0:u.events)??(u==null?void 0:u.data)??[],[m,p]=j.useState("month"),[x,y]=j.useState(new Date),[g,b]=j.useState("all"),[v,k]=j.useState("all"),[C,T]=j.useState("all"),[M,P]=j.useState(!1),[L,I]=j.useState(null),[O,$]=j.useState(null),q=j.useMemo(()=>s.filter(ie=>!(!M&&(ie.is_archived||ie.status==="archived")||g!=="all"&&ie.status!==g||v!=="all"&&ie.event_type!==v||C!=="all"&&!(ie.linked_agent_ids??[]).includes(C))),[s,g,v,C,M]),W=q.filter(ie=>ie.starts_at),G=q.filter(ie=>!ie.starts_at),K=new Date,ee=j.useMemo(()=>{const ie=W.filter(fe=>vb(Ep(fe.starts_at),K)&&["confirmed","tentative"].includes(fe.status)),de=q.filter(fe=>fe.submission_deadline&&vb(Ep(fe.submission_deadline),K)),we=q.filter(fe=>["pitching","applied","researching"].includes(fe.status)),je=q.filter(fe=>fe.status==="confirmed"),xe=q.filter(fe=>fe.follow_up_date&&fe.status==="completed");return{upcoming:ie,deadlines:de,pitches:we,confirmed:je,followUps:xe}},[q,W]),J=j.useMemo(()=>XDe(m==="week"?{start:xg(x),end:v$(x)}:{start:xg(Vu(x)),end:v$(Uv(x))}),[x,m]),le=ie=>W.filter(de=>pd(Ep(de.starts_at),ie)),ue=async()=>{var de;if(!((de=L==null?void 0:L.title)!=null&&de.trim())){re.error("Give the talk a title");return}const ie={...L};delete ie.created_at,delete ie.updated_at,delete ie.user_id,(ie.fee===""||ie.fee==null)&&(ie.fee=null),["starts_at","ends_at","submission_deadline","follow_up_date","linked_event_id","linked_kit_id"].forEach(we=>{ie[we]===""&&(ie[we]=null)}),L.id?await r.mutateAsync(ie):await n.mutateAsync(ie),I(null)},oe=ie=>{if(!ie.starts_at){re.error("Add a date first");return}const de=Se=>new Date(Se).toISOString().replace(/[-:]|\.\d{3}/g,""),we=ie.ends_at??new Date(new Date(ie.starts_at).getTime()+60*6e4).toISOString(),je=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp Attract//Speaking//EN","BEGIN:VEVENT",`UID:${ie.id}@levelup-attract`,`DTSTAMP:${de(new Date().toISOString())}`,`DTSTART:${de(ie.starts_at)}`,`DTEND:${de(we)}`,`SUMMARY:${(ie.title||"").replace(/\n/g," ")}`,`LOCATION:${(ie.location||ie.virtual_link||"").replace(/\n/g," ")}`,`DESCRIPTION:${[ie.organization,ie.topic].filter(Boolean).join(" — ").replace(/\n/g," ")}`,"END:VEVENT","END:VCALENDAR"].join(`\r `),xe=URL.createObjectURL(new Blob([je],{type:"text/calendar"})),fe=document.createElement("a");fe.href=xe,fe.download=`${ie.title.replace(/\W+/g,"-").toLowerCase()}.ics`,fe.click(),URL.revokeObjectURL(xe)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(gn,{className:"h-32 rounded-2xl"}),e.jsx(gn,{className:"h-96 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{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:()=>I({...K8e}),children:[e.jsx(Js,{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(gG,{label:"Upcoming talks",value:ee.upcoming.length,icon:Sj}),e.jsx(gG,{label:"Deadlines ahead",value:ee.deadlines.length,icon:Vr}),e.jsx(gG,{label:"Pitches in flight",value:ee.pitches.length,icon:Dr}),e.jsx(gG,{label:"Confirmed",value:ee.confirmed.length,icon:Rr}),e.jsx(gG,{label:"Post-event follow-ups",value:ee.followUps.length,icon:zp})]}),e.jsxs(be,{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(ie=>e.jsx("button",{onClick:()=>p(ie),className:`px-3 py-1.5 rounded-full text-[12.5px] font-medium capitalize ${m===ie?"bg-white shadow-sm text-slate-900":"text-slate-500"}`,children:ie},ie))}),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"?i3(x,-1):Ax(x,-1)),children:e.jsx(Cc,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-semibold min-w-[130px] text-center",children:Bs(x,m==="week"?"'Week of' MMM d":"MMMM yyyy")}),e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>y(m==="week"?i3(x,1):Ax(x,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(vs,{value:g,onValueChange:b,children:[e.jsx(gs,{className:"w-[140px] rounded-full h-9",children:e.jsx(bs,{placeholder:"Status"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All statuses"}),Xyt.map(ie=>e.jsx(Je,{value:ie,className:"capitalize",children:ie.replace(/_/g," ")},ie))]})]}),e.jsxs(vs,{value:v,onValueChange:k,children:[e.jsx(gs,{className:"w-[140px] rounded-full h-9",children:e.jsx(bs,{placeholder:"Type"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All types"}),Qyt.map(ie=>e.jsx(Je,{value:ie,className:"capitalize",children:ie.replace(/_/g," ")},ie))]})]}),e.jsxs(vs,{value:C,onValueChange:T,children:[e.jsx(gs,{className:"w-[160px] rounded-full h-9",children:e.jsx(bs,{placeholder:"Relationship"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All relationships"}),c.map(ie=>e.jsx(Je,{value:ie.id,children:[ie.first_name,ie.last_name].filter(Boolean).join(" ")},ie.id))]})]}),e.jsxs(B,{variant:M?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>P(ie=>!ie),children:[e.jsx(gm,{className:"h-3.5 w-3.5 mr-1.5"}),"Archived"]})]}),s.length===0?e.jsxs(be,{className:"p-10 rounded-2xl text-center",children:[e.jsx(Sj,{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:()=>I({...K8e}),children:[e.jsx(Js,{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(be,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"Nothing matches these filters."}),[...W,...G].map(ie=>e.jsx(rFn,{o:ie,onEdit:()=>I(ie),onComplete:()=>$(ie),onDuplicate:()=>a.mutate(ie),onDelete:()=>i.mutate(ie.id),onArchive:()=>r.mutate({id:ie.id,is_archived:!ie.is_archived,status:ie.is_archived?"idea":"archived"}),onIcs:()=>oe(ie),onPitchTask:()=>l.mutate({title:`Pitch: ${ie.title}${ie.organization?` (${ie.organization})`:""}`,dueAt:ie.submission_deadline?new Date(ie.submission_deadline).toISOString():null,notes:ie.notes??void 0}),onLogOutreach:()=>o.mutate({title:`Outreach for ${ie.title}`}),onConfirm:()=>r.mutate({id:ie.id,status:"confirmed"})},ie.id))]}):e.jsxs(be,{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(ie=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider font-semibold text-slate-500 text-center",children:ie},ie))}),e.jsx("div",{className:"grid grid-cols-7",children:J.map(ie=>{const de=le(ie);return e.jsxs("div",{className:`min-h-[92px] sm:min-h-[112px] border-b border-r p-1.5 ${GU(ie,x)||m==="week"?"bg-white":"bg-slate-50/60"}`,children:[e.jsx("button",{onClick:()=>I({...K8e,starts_at:new Date(ie.setHours(10,0,0,0)).toISOString()}),className:`text-[11.5px] font-semibold h-6 w-6 rounded-full grid place-items-center ${pd(ie,K)?"bg-violet-600 text-white":"text-slate-500 hover:bg-slate-100"}`,children:Bs(ie,"d")}),e.jsxs("div",{className:"mt-1 space-y-1",children:[de.slice(0,3).map(we=>e.jsx("button",{onClick:()=>I(we),className:`w-full text-left text-[11px] px-1.5 py-1 rounded-md border truncate ${l$e[we.status]??""}`,children:we.title},we.id)),de.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-400 pl-1",children:["+",de.length-3," more"]})]})]},ie.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(ie=>e.jsx("button",{onClick:()=>I(ie),className:`text-[12px] px-2.5 py-1 rounded-full border ${l$e[ie.status]??""}`,children:ie.title},ie.id))})]})]}),e.jsx(HO,{}),e.jsx(Fs,{open:!!L,onOpenChange:ie=>!ie&&I(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsx(zs,{children:L!=null&&L.id?"Edit speaking opportunity":"New speaking opportunity"})}),L&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(Dh,{label:"Title",className:"sm:col-span-2",children:e.jsx(ye,{value:L.title??"",onChange:ie=>I({...L,title:ie.target.value}),placeholder:"Panel: Winning listings in a shifting market"})}),e.jsx(Dh,{label:"Event / organization",children:e.jsx(ye,{value:L.organization??"",onChange:ie=>I({...L,organization:ie.target.value})})}),e.jsx(Dh,{label:"Event type",children:e.jsxs(vs,{value:L.event_type??"panel",onValueChange:ie=>I({...L,event_type:ie}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Qyt.map(ie=>e.jsx(Je,{value:ie,className:"capitalize",children:ie.replace(/_/g," ")},ie))})]})}),e.jsx(Dh,{label:"Contact name",children:e.jsx(ye,{value:L.contact_name??"",onChange:ie=>I({...L,contact_name:ie.target.value})})}),e.jsx(Dh,{label:"Contact email",children:e.jsx(ye,{type:"email",value:L.contact_email??"",onChange:ie=>I({...L,contact_email:ie.target.value})})}),e.jsx(Dh,{label:"Contact phone",children:e.jsx(ye,{value:L.contact_phone??"",onChange:ie=>I({...L,contact_phone:ie.target.value})})}),e.jsx(Dh,{label:"Audience",children:e.jsx(ye,{value:L.audience??"",onChange:ie=>I({...L,audience:ie.target.value}),placeholder:"120 local agents"})}),e.jsx(Dh,{label:"Location",children:e.jsx(ye,{value:L.location??"",onChange:ie=>I({...L,location:ie.target.value})})}),e.jsx(Dh,{label:"Virtual link",children:e.jsx(ye,{value:L.virtual_link??"",onChange:ie=>I({...L,virtual_link:ie.target.value})})}),e.jsx(Dh,{label:"Starts",children:e.jsx(ye,{type:"datetime-local",value:evt(L.starts_at),onChange:ie=>I({...L,starts_at:ie.target.value?new Date(ie.target.value).toISOString():null})})}),e.jsx(Dh,{label:"Ends",children:e.jsx(ye,{type:"datetime-local",value:evt(L.ends_at),onChange:ie=>I({...L,ends_at:ie.target.value?new Date(ie.target.value).toISOString():null})})}),e.jsx(Dh,{label:"Status",children:e.jsxs(vs,{value:L.status??"idea",onValueChange:ie=>I({...L,status:ie}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Xyt.map(ie=>e.jsx(Je,{value:ie,className:"capitalize",children:ie},ie))})]})}),e.jsx(Dh,{label:"Fee / honorarium",children:e.jsx(ye,{type:"number",value:L.fee??"",onChange:ie=>I({...L,fee:ie.target.value===""?null:Number(ie.target.value)})})}),e.jsx(Dh,{label:"Submission deadline",children:e.jsx(ye,{type:"date",value:L.submission_deadline??"",onChange:ie=>I({...L,submission_deadline:ie.target.value||null})})}),e.jsx(Dh,{label:"Follow-up date",children:e.jsx(ye,{type:"date",value:L.follow_up_date??"",onChange:ie=>I({...L,follow_up_date:ie.target.value||null})})}),e.jsx(Dh,{label:"Application URL",className:"sm:col-span-2",children:e.jsx(ye,{value:L.application_url??"",onChange:ie=>I({...L,application_url:ie.target.value})})}),e.jsx(Dh,{label:"Topic",className:"sm:col-span-2",children:e.jsx(ye,{value:L.topic??"",onChange:ie=>I({...L,topic:ie.target.value})})}),e.jsx(Dh,{label:"Linked Connect event",children:e.jsxs(vs,{value:L.linked_event_id??"none",onValueChange:ie=>I({...L,linked_event_id:ie==="none"?null:ie}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"None"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"None"}),h.map(ie=>e.jsx(Je,{value:ie.id,children:ie.title},ie.id))]})]})}),e.jsx(Dh,{label:"Linked Resource Kit",children:e.jsxs(vs,{value:L.linked_kit_id??"none",onValueChange:ie=>I({...L,linked_kit_id:ie==="none"?null:ie}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"None"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"None"}),d.map(ie=>e.jsx(Je,{value:ie.id,children:ie.title},ie.id))]})]})}),e.jsx(Dh,{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(ie=>{const de=(L.linked_agent_ids??[]).includes(ie.id);return e.jsx("button",{type:"button",onClick:()=>I({...L,linked_agent_ids:de?(L.linked_agent_ids??[]).filter(we=>we!==ie.id):[...L.linked_agent_ids??[],ie.id]}),className:`text-[12px] px-2.5 py-1 rounded-full border ${de?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-600"}`,children:[ie.first_name,ie.last_name].filter(Boolean).join(" ")},ie.id)})]})}),e.jsx(Dh,{label:"Travel notes",className:"sm:col-span-2",children:e.jsx(Ds,{rows:2,value:L.travel_notes??"",onChange:ie=>I({...L,travel_notes:ie.target.value})})}),e.jsx(Dh,{label:"Notes",className:"sm:col-span-2",children:e.jsx(Ds,{rows:3,value:L.notes??"",onChange:ie=>I({...L,notes:ie.target.value})})})]}),e.jsxs(Nr,{className:"gap-2",children:[e.jsx(B,{variant:"ghost",onClick:()=>I(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(aFn,{item:O,onClose:()=>$(null),onSave:async(ie,de)=>{await r.mutateAsync({id:O.id,status:"completed",outcome:ie}),de&&await l.mutateAsync({title:`Post-event follow-up: ${O.title}`,dueAt:new Date(Date.now()+2*864e5).toISOString(),notes:ie.next_actions}),await o.mutateAsync({title:`Spoke at ${O.title}`,activityType:"speaking_completed"}),$(null)}})]})}function evt(s){if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)}function Dh({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(se,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function gG({label:s,value:t,icon:n}){return e.jsxs(be,{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 rFn({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?Ky(Ep(u.submission_deadline),new Date):null;return e.jsx(be,{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(Vc,{className:"h-3.5 w-3.5"}),Bs(Ep(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(Vr,{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(Bn,{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(qe,{variant:"outline",className:`capitalize rounded-full ${l$e[u.status]??""}`,children:u.status}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",children:e.jsx(Hy,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[e.jsx(wa,{onClick:t,children:"Edit"}),e.jsxs(wa,{onClick:o,children:[e.jsx(zp,{className:"h-3.5 w-3.5 mr-2"}),"Add pitch task"]}),e.jsxs(wa,{onClick:c,children:[e.jsx(Dr,{className:"h-3.5 w-3.5 mr-2"}),"Log outreach"]}),e.jsxs(wa,{onClick:d,children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-2"}),"Mark confirmed"]}),e.jsxs(wa,{onClick:n,children:[e.jsx(Rr,{className:"h-3.5 w-3.5 mr-2"}),"Mark completed"]}),e.jsxs(wa,{onClick:l,children:[e.jsx(ii,{className:"h-3.5 w-3.5 mr-2"}),"Download .ics"]}),e.jsxs(wa,{onClick:r,children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(wa,{onClick:i,children:[e.jsx(gm,{className:"h-3.5 w-3.5 mr-2"}),u.is_archived?"Unarchive":"Archive"]}),e.jsxs(wa,{className:"text-destructive",onClick:a,children:[e.jsx(Rn,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]})]})})}function aFn({item:s,onClose:t,onSave:n}){const[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState("");return e.jsx(Fs,{open:!!s,onOpenChange:h=>!h&&t(),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx($s,{children:e.jsx(zs,{children:"Capture the outcome"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Dh,{label:"Attendance",children:e.jsx(ye,{value:r,onChange:h=>a(h.target.value),placeholder:"How many were in the room?"})}),e.jsx(Dh,{label:"Leads / relationships created",children:e.jsx(Ds,{rows:2,value:i,onChange:h=>l(h.target.value)})}),e.jsx(Dh,{label:"Content captured",children:e.jsx(Ds,{rows:2,value:o,onChange:h=>c(h.target.value),placeholder:"Photos, clips, quotes"})}),e.jsx(Dh,{label:"Next actions",children:e.jsx(Ds,{rows:2,value:d,onChange:h=>u(h.target.value)})})]}),e.jsxs(Nr,{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 S9=U,c$e=["attract-masterclasses"];function iFn(){const{user:s}=Ns(),t=as(),n=mt({queryKey:[...c$e,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await S9.from("attract_masterclasses").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=()=>t.invalidateQueries({queryKey:c$e}),a=vt({mutationFn:async o=>{const{data:c,error:d}=await S9.from("attract_masterclasses").insert({title:"Untitled masterclass",...o,user_id:s.id}).select("*").single();if(d)throw d;return c},onSuccess:()=>r(),onError:o=>re.error(o.message)}),i=vt({mutationFn:async o=>{const{id:c,created_at:d,updated_at:u,user_id:h,...m}=o,{data:p,error:x}=await S9.from("attract_masterclasses").insert({...m,title:`${o.title} (copy)`,status:"draft",user_id:s.id}).select("id").single();if(x)throw x;return p},onSuccess:()=>{r(),re.success("Duplicated")},onError:o=>re.error(o.message)}),l=vt({mutationFn:async o=>{const{error:c}=await S9.from("attract_masterclasses").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),re.success("Deleted")},onError:o=>re.error(o.message)});return{items:n.data??[],isLoading:n.isLoading,refetch:n.refetch,create:a,duplicate:i,remove:l}}function oFn(s){const t=as(),n=mt({queryKey:["attract-masterclass",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await S9.from("attract_masterclasses").select("*").eq("id",s).maybeSingle();if(i)throw i;return a}}),r=vt({mutationFn:async a=>{const{error:i}=await S9.from("attract_masterclasses").update(a).eq("id",s);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-masterclass",s]}),t.invalidateQueries({queryKey:c$e})},onError:a=>re.error(a.message)});return{masterclass:n.data??null,isLoading:n.isLoading,save:r}}const Om=(s,t)=>({id:crypto.randomUUID(),title:s,lessons:t.map(([n,r,a])=>({id:crypto.randomUUID(),title:n,minutes:r,talking_points:a}))}),tvt=[{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:[Om("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"]]),Om("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"]]),Om("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:[Om("Audit",[["Sorting your list into A/B/C",10,"Criteria that actually predict referrals"],["Fixing missing data",8,"Birthdays, anniversaries, spouse names"]]),Om("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"]]),Om("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:[Om("Before",[["Neighborhood invites",8,"Door knocking and digital invites"],["Setting the stage",7,"Materials that create conversations"]]),Om("During",[["The three questions",10,"How to qualify without interrogating"],["Capturing real contact info",8,"Sign-in that people actually complete"]]),Om("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:[Om("Positioning",[["Pick your lane",10,"Neighborhood, niche, or narrative"],["What to never post",6,"The credibility killers"]]),Om("Content system",[["The four content types",14,"Teach, prove, connect, invite"],["Batch filming",10,"One hour, ten pieces"]]),Om("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:[Om("Foundations",[["What AI is good and bad at",10,"Drafting vs deciding"],["Prompting basics",10,"Context, role, constraints"]]),Om("Workflows",[["Listing descriptions and marketing",12,"Brand voice inputs"],["Follow-up and email drafts",12,"Never auto-send"]]),Om("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:[Om("The builder landscape",[["How builder comp works",12,"Registration rules that protect you"],["Local builders worth knowing",8,"Relationship map"]]),Om("Representing the buyer",[["Contract differences",14,"What is negotiable"],["Inspections and walkthroughs",10,"Timeline checkpoints"]]),Om("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:[Om("Standards",[["What luxury clients notice",12,"Response time, discretion, detail"],["Your materials",10,"Photography, print, web"]]),Om("The listing experience",[["Pre-market strategy",12,"Whisper listings and staging"],["Private showings",8,"Choreography"]]),Om("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:[Om("Mindset",[["Why value beats pitching",10,"Relationship-first framing"],["Choosing your 20",8,"Fit criteria"]]),Om("The value plan",[["Resource kits that help",14,"What agents actually want"],["Events and masterminds",10,"Small rooms win"]]),Om("The conversation",[["When to talk business",10,"Earned invitation"],['Handling "I am happy where I am"',8,"Stay in relationship"]])]}];function lFn(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 cFn(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 dFn(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("",`${Ure(n)} SECTION: ${r.title}`),r.lessons.forEach(a=>{t.push(`${Ure(n)} ${a.title}${a.minutes?` (${a.minutes}m)`:""}${a.talking_points?` — ${a.talking_points}`:""}`),n+=a.minutes??5})}),t.push("",`${Ure(n)} Q&A`,`${Ure(n+7)} Close: next step + resource kit`),t.join(` `)}function Ure(s){const t=Math.floor(s/60),n=s%60;return`${t}:${String(n).padStart(2,"0")}`}function uFn(){const{items:s,isLoading:t,create:n,duplicate:r,remove:a}=iFn(),i=Hn(),[l,o]=j.useState(!1),c=s.filter(m=>!m.is_archived),d=s.filter(m=>m.is_archived),u=async()=>{const m=await n.mutateAsync({title:"Untitled masterclass"});i(`/attract/provide/masterclasses/${m.id}`)},h=async m=>{const p=tvt.find(y=>y.key===m),x=await n.mutateAsync(lFn(p));i(`/attract/provide/masterclasses/${x.id}`)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(gn,{className:"h-28 rounded-2xl"}),e.jsx(gn,{className:"h-64 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wh,{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(yn,{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(Js,{className:"h-4 w-4 mr-2"}),"New masterclass"]})]})}),(l||s.length===0)&&e.jsxs(be,{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:tvt.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(qe,{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(be,{className:"p-10 rounded-2xl text-center",children:[e.jsx(Uh,{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(be,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(qe,{variant:"outline",className:"capitalize rounded-full",children:m.status}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full h-7 w-7",children:e.jsx(Hy,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[e.jsx(wa,{onClick:()=>i(`/attract/provide/masterclasses/${m.id}`),children:"Open builder"}),e.jsxs(wa,{onClick:()=>r.mutate(m),children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(wa,{className:"text-destructive",onClick:()=>a.mutate(m.id),children:[e.jsx(Rn,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]}),e.jsxs(Yn,{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&&` · ${Bs(new Date(m.delivery_date),"MMM d")}`]})]},m.id))}),d.length>0&&e.jsxs(be,{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(gm,{className:"h-3.5 w-3.5"}),"Archived"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(m=>e.jsx(Yn,{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(HO,{})]})}const svt=U,hFn=["Strategy","Curriculum","Assets","Promotion","Delivery","Follow-up"];function mFn(){var W,G,K,ee,J,le,ue,oe,ie,de,we,je,xe;const{masterclassId:s}=$i(),t=Hn(),{user:n}=Ns(),{masterclass:r,isLoading:a,save:i}=oFn(s),l=GUt(),{create:o}=Xq(),[c,d]=j.useState(null),[u,h]=j.useState(0),[m,p]=j.useState(!1),[x,y]=j.useState("idle"),g=j.useRef(null),b=j.useRef(!1);j.useEffect(()=>{r&&!c&&d(r)},[r,c]);const v=fe=>{d(Se=>Se&&{...Se,...fe}),b.current=!0,y("saving"),clearTimeout(g.current),g.current=setTimeout(()=>k({...c??{},...fe}),900)},k=async fe=>{const{id:Se,user_id:Ee,created_at:Le,updated_at:De,...Be}=fe;await i.mutateAsync(Be),b.current=!1,y("saved"),setTimeout(()=>y(Ne=>Ne==="saved"?"idle":Ne),1800)},C=(c==null?void 0:c.curriculum)??[],T=fe=>v({curriculum:fe}),M=j.useMemo(()=>C.reduce((fe,Se)=>fe+Se.lessons.reduce((Ee,Le)=>Ee+(Le.minutes??0),0),0),[C]);if(a||!c)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(gn,{className:"h-24 rounded-2xl"}),e.jsx(gn,{className:"h-96 rounded-2xl"})]});const P=()=>{v({promotion:{...c.promotion,...cFn(c)}}),re.success("Draft copy generated — edit before you send anything")},L=()=>{v({delivery:{...c.delivery,run_of_show:dFn(c)}}),re.success("Run of show generated")},I=async()=>{const fe=await l.mutateAsync({title:c.title,description:c.promise??void 0,event_type:"masterclass",intended_audience:c.target_audience??void 0,related_pillar:c.pillar??"provide",starts_at:c.delivery_date??new Date(Date.now()+12096e5).toISOString(),format:c.format==="in_person"?"in_person":"virtual",agenda:C.flatMap(Se=>Se.lessons.map(Ee=>({item:`${Se.title}: ${Ee.title}`}))),learning_outcomes:c.desired_outcome?[c.desired_outcome]:[]});await i.mutateAsync({linked_event_id:fe.id,status:"scheduled"}),d(Se=>Se&&{...Se,linked_event_id:fe.id,status:"scheduled"}),re.success("Connect event created as a draft"),t(`/attract/events/${fe.id}/edit`)},O=async()=>{var Ee,Le,De,Be,Ne;const fe=await o.mutateAsync({title:`${c.title} — Resource Kit`,description:c.promise??void 0,audience:c.target_audience??void 0,pillar:c.pillar??"provide",intro_text:((Ee=c.assets)==null?void 0:Ee.workbook)??void 0,cta_label:((Le=c.assets)==null?void 0:Le.cta_label)??void 0,cta_url:((De=c.assets)==null?void 0:De.cta_url)??void 0}),Se=[...(((Be=c.assets)==null?void 0:Be.downloads)??[]).map((Ge,_e)=>({type:"link",title:Ge.title,url:Ge.url,sort_order:_e})),...(((Ne=c.assets)==null?void 0:Ne.videos)??[]).map((Ge,_e)=>({type:"video",title:Ge.title,url:Ge.url,sort_order:100+_e}))];Se.length&&await svt.from("attract_resource_kit_items").insert(Se.map(Ge=>({...Ge,kit_id:fe.id,user_id:n.id}))),await i.mutateAsync({linked_kit_id:fe.id}),d(Ge=>Ge&&{...Ge,linked_kit_id:fe.id}),re.success("Resource Kit created from your assets"),t(`/attract/provide/kits/${fe.id}/edit`)},$=async()=>{const fe=Date.now(),Se=[{title:`Send recap + resources: ${c.title}`,due_at:new Date(fe+1*864e5).toISOString()},{title:`Personal check-in with attendees: ${c.title}`,due_at:new Date(fe+3*864e5).toISOString()},{title:`Invite engaged attendees to a 1:1: ${c.title}`,due_at:new Date(fe+7*864e5).toISOString()}],{error:Ee}=await svt.from("attract_follow_ups").insert(Se.map(Le=>({...Le,user_id:n.id,touch_type:"masterclass",priority:"medium"})));if(Ee){re.error(Ee.message);return}re.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(Yn,{to:"/attract/provide/masterclasses",children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1.5"}),"All masterclasses"]})}),e.jsx(Wh,{eyebrow:"Pillar 03 · Provide",title:c.title||"Untitled masterclass",description:c.promise??"Build the promise, curriculum, assets, promotion, delivery and follow-up.",actions:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[12px] text-slate-500 inline-flex items-center gap-1.5",children:x==="saving"?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-3.5 w-3.5 animate-spin"}),"Saving…"]}):x==="saved"?e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-3.5 w-3.5 text-emerald-600"}),"Saved"]}):"All changes saved"}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>p(fe=>!fe),children:[e.jsx(ma,{className:"h-4 w-4 mr-2"}),m?"Edit":"Preview"]})]})}),e.jsx(be,{className:"p-2 rounded-2xl flex gap-1 overflow-x-auto",children:hFn.map((fe,Se)=>e.jsxs("button",{onClick:()=>{p(!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,". ",fe]},fe))}),m?e.jsx(fFn,{m:c}):e.jsxs(be,{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(rf,{label:"Title",className:"sm:col-span-2",children:e.jsx(ye,{value:c.title,onChange:fe=>v({title:fe.target.value})})}),e.jsx(rf,{label:"The promise",className:"sm:col-span-2",children:e.jsx(Ds,{rows:2,value:c.promise??"",onChange:fe=>v({promise:fe.target.value}),placeholder:"Walk out with…"})}),e.jsx(rf,{label:"Target audience",children:e.jsx(ye,{value:c.target_audience??"",onChange:fe=>v({target_audience:fe.target.value})})}),e.jsx(rf,{label:"Problem solved",children:e.jsx(ye,{value:c.problem_solved??"",onChange:fe=>v({problem_solved:fe.target.value})})}),e.jsx(rf,{label:"Desired outcome",className:"sm:col-span-2",children:e.jsx(ye,{value:c.desired_outcome??"",onChange:fe=>v({desired_outcome:fe.target.value})})}),e.jsx(rf,{label:"Pillar",children:e.jsxs(vs,{value:c.pillar??"provide",onValueChange:fe=>v({pillar:fe}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["produce","influence","provide","connect"].map(fe=>e.jsx(Je,{value:fe,className:"capitalize",children:fe},fe))})]})}),e.jsx(rf,{label:"Format",children:e.jsxs(vs,{value:c.format??"virtual",onValueChange:fe=>v({format:fe}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["virtual","in_person","hybrid"].map(fe=>e.jsx(Je,{value:fe,className:"capitalize",children:fe.replace("_"," ")},fe))})]})}),e.jsx(rf,{label:"Duration (minutes)",children:e.jsx(ye,{type:"number",value:c.duration_minutes??45,onChange:fe=>v({duration_minutes:Number(fe.target.value)})})}),e.jsx(rf,{label:"Delivery date",children:e.jsx(ye,{type:"datetime-local",value:pFn(c.delivery_date),onChange:fe=>v({delivery_date:fe.target.value?new Date(fe.target.value).toISOString():null})})}),e.jsx(rf,{label:"Status",children:e.jsxs(vs,{value:c.status,onValueChange:fe=>v({status:fe}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:["draft","ready","scheduled","delivered","archived"].map(fe=>e.jsx(Je,{value:fe,className:"capitalize",children:fe},fe))})]})})]}),u===1&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[C.length," sections · ",M," minutes planned"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>T([...C,{id:crypto.randomUUID(),title:"New section",lessons:[]}]),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1.5"}),"Add section"]})]}),C.length===0&&e.jsx("div",{className:"text-[13.5px] text-slate-500 border border-dashed rounded-xl p-8 text-center",children:"No sections yet. Add your first one."}),C.map((fe,Se)=>e.jsxs(be,{className:"p-4 rounded-xl bg-slate-50/60",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{value:fe.title,onChange:Ee=>T(C.map(Le=>Le.id===fe.id?{...Le,title:Ee.target.value}:Le)),className:"font-semibold"}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Se===0,onClick:()=>T(qre(C,Se,Se-1)),children:e.jsx(Qy,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Se===C.length-1,onClick:()=>T(qre(C,Se,Se+1)),children:e.jsx(Po,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>T(C.filter(Ee=>Ee.id!==fe.id)),children:e.jsx(Rn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[fe.lessons.map((Ee,Le)=>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(ye,{value:Ee.title,placeholder:"Lesson title",onChange:De=>q(fe.id,Ee.id,{title:De.target.value})}),e.jsx(ye,{type:"number",className:"w-20",value:Ee.minutes??"",placeholder:"min",onChange:De=>q(fe.id,Ee.id,{minutes:Number(De.target.value)})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Le===0,onClick:()=>T(C.map(De=>De.id===fe.id?{...De,lessons:qre(De.lessons,Le,Le-1)}:De)),children:e.jsx(Qy,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Le===fe.lessons.length-1,onClick:()=>T(C.map(De=>De.id===fe.id?{...De,lessons:qre(De.lessons,Le,Le+1)}:De)),children:e.jsx(Po,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>T(C.map(De=>De.id===fe.id?{...De,lessons:De.lessons.filter(Be=>Be.id!==Ee.id)}:De)),children:e.jsx(Rn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-2",children:[e.jsx(Ds,{rows:2,placeholder:"Talking points",value:Ee.talking_points??"",onChange:De=>q(fe.id,Ee.id,{talking_points:De.target.value})}),e.jsx(Ds,{rows:2,placeholder:"Exercise",value:Ee.exercise??"",onChange:De=>q(fe.id,Ee.id,{exercise:De.target.value})}),e.jsx(Ds,{rows:2,placeholder:"Example / story",value:Ee.example??"",onChange:De=>q(fe.id,Ee.id,{example:De.target.value})}),e.jsx(Ds,{rows:2,placeholder:"Speaker notes",value:Ee.speaker_notes??"",onChange:De=>q(fe.id,Ee.id,{speaker_notes:De.target.value})})]})]},Ee.id)),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>T(C.map(Ee=>Ee.id===fe.id?{...Ee,lessons:[...Ee.lessons,{id:crypto.randomUUID(),title:""}]}:Ee)),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1.5"}),"Add lesson"]})]})]},fe.id))]}),u===2&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(rf,{label:"Slide outline",children:e.jsx(Ds,{rows:5,value:((W=c.assets)==null?void 0:W.slide_outline)??"",onChange:fe=>v({assets:{...c.assets,slide_outline:fe.target.value}})})}),e.jsx(rf,{label:"Workbook / checklist outline",children:e.jsx(Ds,{rows:5,value:((G=c.assets)==null?void 0:G.workbook)??"",onChange:fe=>v({assets:{...c.assets,workbook:fe.target.value}})})}),e.jsx(nvt,{label:"Downloads",items:((K=c.assets)==null?void 0:K.downloads)??[],onChange:fe=>v({assets:{...c.assets,downloads:fe}})}),e.jsx(nvt,{label:"Videos",items:((ee=c.assets)==null?void 0:ee.videos)??[],onChange:fe=>v({assets:{...c.assets,videos:fe}})}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(rf,{label:"CTA label",children:e.jsx(ye,{value:((J=c.assets)==null?void 0:J.cta_label)??"",onChange:fe=>v({assets:{...c.assets,cta_label:fe.target.value}})})}),e.jsx(rf,{label:"CTA URL",children:e.jsx(ye,{value:((le=c.assets)==null?void 0:le.cta_url)??"",onChange:fe=>v({assets:{...c.assets,cta_url:fe.target.value}})})})]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:O,disabled:o.isPending,children:[e.jsx(XW,{className:"h-4 w-4 mr-2"}),"Create Resource Kit from these assets"]}),c.linked_kit_id&&e.jsx(qe,{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:P,children:[e.jsx(um,{className:"h-4 w-4 mr-2"}),"Generate draft copy"]})]}),[["registration_copy","Registration page copy"],["email_invite","Email invite"],["social_post","Social post"],["dm_invite","DM / text invite"],["reminder","Reminder message"],["follow_up","Follow-up message"]].map(([fe,Se])=>{var Ee;return e.jsx(rf,{label:Se,children:e.jsx(Ds,{rows:5,value:((Ee=c.promotion)==null?void 0:Ee[fe])??"",onChange:Le=>v({promotion:{...c.promotion,[fe]:Le.target.value}})})},fe)})]}),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:L,children:[e.jsx(um,{className:"h-4 w-4 mr-2"}),"Build run of show"]})}),e.jsx(rf,{label:"Run of show",children:e.jsx(Ds,{rows:12,className:"font-mono text-[12.5px]",value:((ue=c.delivery)==null?void 0:ue.run_of_show)??"",onChange:fe=>v({delivery:{...c.delivery,run_of_show:fe.target.value}})})}),e.jsx(rf,{label:"Check-in link",children:e.jsx(ye,{value:((oe=c.delivery)==null?void 0:oe.checkin_link)??"",onChange:fe=>v({delivery:{...c.delivery,checkin_link:fe.target.value}}),placeholder:"Paste the Connect event check-in URL"})}),e.jsx(rf,{label:"Event notes",children:e.jsx(Ds,{rows:4,value:((ie=c.delivery)==null?void 0:ie.event_notes)??"",onChange:fe=>v({delivery:{...c.delivery,event_notes:fe.target.value}})})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:I,disabled:l.isPending,children:[e.jsx(Wy,{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(Yn,{to:`/attract/events/${c.linked_event_id}`,children:"Open linked event"})})]})]}),u===5&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(rf,{label:"Attendee segmentation",children:e.jsx(Ds,{rows:3,value:((de=c.follow_up)==null?void 0:de.segments)??"",onChange:fe=>v({follow_up:{...c.follow_up,segments:fe.target.value}}),placeholder:"Attended + asked a question / attended / registered no-show"})}),e.jsx(rf,{label:"Resource kit sharing note",children:e.jsx(Ds,{rows:3,value:((we=c.follow_up)==null?void 0:we.kit_note)??"",onChange:fe=>v({follow_up:{...c.follow_up,kit_note:fe.target.value}})})}),e.jsx(rf,{label:"Suggested personal follow-ups",children:e.jsx(Ds,{rows:3,value:((je=c.follow_up)==null?void 0:je.personal_touches)??"",onChange:fe=>v({follow_up:{...c.follow_up,personal_touches:fe.target.value}})})}),e.jsx(rf,{label:"Conversion / relationship outcomes",children:e.jsx(Ds,{rows:3,value:((xe=c.follow_up)==null?void 0:xe.outcomes)??"",onChange:fe=>v({follow_up:{...c.follow_up,outcomes:fe.target.value}})})}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:$,children:[e.jsx(zp,{className:"h-4 w-4 mr-2"}),"Add 3 follow-ups to Follow-Up Center"]})]})]})]});function q(fe,Se,Ee){T(C.map(Le=>Le.id===fe?{...Le,lessons:Le.lessons.map(De=>De.id===Se?{...De,...Ee}:De)}:Le))}}function qre(s,t,n){const r=[...s],[a]=r.splice(t,1);return r.splice(n,0,a),r}function pFn(s){if(!s)return"";const t=new Date(s);return new Date(t.getTime()-t.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function rf({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(se,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function nvt({label:s,items:t,onChange:n}){return e.jsxs("div",{children:[e.jsx(se,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),e.jsxs("div",{className:"space-y-2",children:[t.map((r,a)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:r.title,placeholder:"Title",onChange:i=>n(t.map((l,o)=>o===a?{...l,title:i.target.value}:l))}),e.jsx(ye,{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(Rn,{className:"h-4 w-4"})})]},a)),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>n([...t,{title:"",url:""}]),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1.5"}),"Add ",s.toLowerCase().slice(0,-1)]})]})]})}function fFn({m:s}){var t,n,r;return e.jsxs("div",{className:"grid lg:grid-cols-2 gap-4",children:[e.jsxs(be,{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(be,{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(be,{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(be,{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 wA=U;function wee(s,t={}){const{orderBy:n="created_at",ascending:r=!1,titleField:a="title",duplicateOverrides:i={},label:l="Record"}=t,{user:o}=Ns(),c=as(),d=[s,o==null?void 0:o.id],u=mt({queryKey:d,enabled:!!o,queryFn:async()=>{const{data:b,error:v}=await wA.from(s).select("*").order(n,{ascending:r,nullsFirst:!1});if(v)throw v;return b??[]}}),h=()=>{c.invalidateQueries({queryKey:[s]}),c.invalidateQueries({queryKey:["attract-followups"]}),c.invalidateQueries({queryKey:["attract-activities"]})},m=vt({mutationFn:async b=>{const{data:v,error:k}=await wA.from(s).insert({...b,user_id:o.id}).select("*").single();if(k)throw k;return v},onSuccess:()=>{h(),re.success(`${l} saved`)},onError:b=>re.error(b.message)}),p=vt({mutationFn:async({id:b,...v})=>{const{error:k}=await wA.from(s).update(v).eq("id",b);if(k)throw k},onSuccess:()=>{h(),re.success("Updated")},onError:b=>re.error(b.message)}),x=vt({mutationFn:async b=>{const{id:v,created_at:k,updated_at:C,user_id:T,...M}=b,P={...M,...i,user_id:o.id};a&&P[a]&&(P[a]=`${P[a]} (copy)`);const{data:L,error:I}=await wA.from(s).insert(P).select("id").single();if(I)throw I;return L},onSuccess:()=>{h(),re.success("Duplicated")},onError:b=>re.error(b.message)}),y=vt({mutationFn:async({id:b,archived:v})=>{const{error:k}=await wA.from(s).update({is_archived:v}).eq("id",b);if(k)throw k},onSuccess:(b,v)=>{h(),re.success(v.archived?"Archived":"Restored")},onError:b=>re.error(b.message)}),g=vt({mutationFn:async b=>{const{error:v}=await wA.from(s).delete().eq("id",b);if(v)throw v},onSuccess:()=>{h(),re.success("Deleted")},onError:b=>re.error(b.message)});return{items:u.data??[],isLoading:u.isLoading,error:u.error,refetch:u.refetch,create:m,update:p,duplicate:x,archive:y,remove:g,userId:o==null?void 0:o.id}}function PTe(){const{user:s}=Ns(),t=as();return vt({mutationFn:async({title:n,dueAt:r,notes:a,touchType:i="task",agentId:l})=>{const{error:o}=await wA.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"]}),re.success("Added to Follow-Up Center & Today’s Plan")},onError:n=>re.error(n.message)})}function jee(){const{user:s}=Ns(),t=as();return vt({mutationFn:async({title:n,description:r,pillar:a="produce",activityType:i="tool_action",agentId:l,metadata:o})=>{const{error:c}=await wA.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=>re.error(n.message)})}const xFn=["annual","quarterly","monthly"],k7=[{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 S7(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 gFn(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 yFn(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 vFn(){const s=wee("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}=Nqt(),n=PTe(),r=jee(),a=j.useMemo(()=>{const i={};return s.items.forEach(l=>{i[l.id]={closings:t.filter(o=>yFn(o.closing_date,l)).length}}),i},[s.items,t]);return{...s,goals:s.items,autoProgress:a,quickTask:n,logActivity:r}}function bFn(s){const t=Number(s??0);return t?{monthly:t/12,weekly:t/52}:null}const _Fn=Array.from({length:12},(s,t)=>({value:t+1,label:new Date(2e3,t,1).toLocaleString("en-US",{month:"long"})}));function o4(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 wFn({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 rvt={period_type:"annual",year:new Date().getFullYear(),quarter:1,month:new Date().getMonth()+1,use_auto_progress:!0};function jFn(){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}=vFn(),[m,p]=j.useState(!1),[x,y]=j.useState(null),[g,b]=j.useState(null),[v,k]=j.useState(null),C=j.useMemo(()=>s.filter(L=>m?L.is_archived:!L.is_archived),[s,m]),T=(L,I)=>{var $;const O=Number(L[I.actual]??0);return L.use_auto_progress&&I.key==="closings"?Math.max(O,(($=d[L.id])==null?void 0:$.closings)??0):O},M=async()=>{var I;if(!x)return;const L={label:((I=x.label)==null?void 0:I.trim())||null,period_type:x.period_type??"annual",year:Number(x.year)||new Date().getFullYear(),quarter:x.period_type==="quarterly"?Number(x.quarter)||1:null,month:x.period_type==="monthly"?Number(x.month)||1:null,closings_target:x.closings_target??null,gci_target:x.gci_target??null,volume_target:x.volume_target??null,listings_target:x.listings_target??null,buyer_sides_target:x.buyer_sides_target??null,appointments_target:x.appointments_target??null,use_auto_progress:x.use_auto_progress??!0,notes:x.notes??null};x.id?await i.mutateAsync({id:x.id,...L}):await a.mutateAsync(L),y(null)},P=async()=>{if(!g)return;const L={};k7.forEach(I=>{L[I.actual]=Number(g[I.actual]??0)}),await i.mutateAsync({id:g.id,...L}),await h.mutateAsync({title:`Updated production progress — ${S7(g)}`,pillar:"produce",activityType:"goal_progress"}),b(null)};return e.jsxs("div",{children:[e.jsxs(Yn,{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(_a,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Wh,{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:()=>p(L=>!L),children:m?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y({...rvt}),children:[e.jsx(Js,{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(L=>e.jsx(gn,{className:"h-56 rounded-2xl"},L))}),!t&&n&&e.jsxs(be,{className:"p-8 rounded-2xl text-center",children:[e.jsx(po,{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(bm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&C.length===0&&e.jsxs(be,{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(uu,{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({...rvt}),children:[e.jsx(Js,{className:"h-4 w-4 mr-1.5"})," Create your first goal"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:C.map(L=>{const I=gFn(L),O=k7.find(J=>L[J.target])??k7[0],$=Number(L[O.target]??0),q=T(L,O),W=$?q/$:0,G=$*I,K=q>=G,ee=bFn($);return e.jsxs(be,{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:L.label||`${S7(L)} Goals`}),e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:L.period_type}),e.jsx(qe,{variant:"outline",className:"rounded-full",children:S7(L)})]}),L.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:L.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(L),children:e.jsx(Za,{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(ja,{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(gm,{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(L),children:e.jsx(Rn,{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(wFn,{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:O.label}),e.jsxs("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:[o4(q,O.format)," ",e.jsxs("span",{className:"text-slate-400 text-[15px]",children:["/ ",o4($,O.format)]})]}),e.jsxs("div",{className:`text-[12.5px] mt-0.5 font-medium ${K?"text-emerald-600":"text-amber-600"}`,children:[K?"Ahead of pace":"Behind pace"," · pace target ",o4(G,O.format)," (",Math.round(I*100),"% of period elapsed)"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 mt-4",children:k7.filter(J=>L[J.target]).map(J=>{const le=Number(L[J.target]),ue=T(L,J);return e.jsxs("div",{className:"rounded-xl bg-slate-50 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:J.label}),e.jsxs("div",{className:"text-[13.5px] font-semibold tabular-nums text-slate-900",children:[o4(ue,J.format)," / ",o4(le,J.format)]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-200 mt-1.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-violet-600",style:{width:`${Math.min(100,le?ue/le*100:0)}%`}})})]},J.key)})}),L.period_type==="annual"&&ee&&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:o4(ee.monthly,O.format)})," per month ·"," ",e.jsx("strong",{children:o4(ee.weekly,O.format)})," per week of ",O.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:()=>b({...L}),children:"Update progress"}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u.mutate({title:`Goal push: ${O.label} — ${o4(ee?ee.weekly:$,O.format)} this week`,dueAt:new Date().toISOString(),notes:`From ${S7(L)} production goal`,touchType:"goal"}),children:[e.jsx(zp,{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 ${S7(L)} goals`,pillar:"produce",activityType:"goal_win"}),children:[e.jsx(ll,{className:"h-3.5 w-3.5 mr-1.5"})," Log a win"]})]})]},L.id)})}),e.jsx(Fs,{open:!!x,onOpenChange:L=>!L&&y(null),children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:x!=null&&x.id?"Edit goal":"New production goal"}),e.jsx(kr,{children:"Only fill in the targets you actually track. Blank targets are hidden."})]}),x&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Label (optional)"}),e.jsx(ye,{value:x.label??"",onChange:L=>y({...x,label:L.target.value}),placeholder:"e.g. 2026 Big Rock"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Period"}),e.jsxs(vs,{value:x.period_type,onValueChange:L=>y({...x,period_type:L}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:xFn.map(L=>e.jsx(Je,{value:L,className:"capitalize",children:L},L))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Year"}),e.jsx(ye,{type:"number",value:x.year??"",onChange:L=>y({...x,year:Number(L.target.value)})})]}),x.period_type==="quarterly"&&e.jsxs("div",{children:[e.jsx(se,{children:"Quarter"}),e.jsxs(vs,{value:String(x.quarter??1),onValueChange:L=>y({...x,quarter:Number(L)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:[1,2,3,4].map(L=>e.jsxs(Je,{value:String(L),children:["Q",L]},L))})]})]}),x.period_type==="monthly"&&e.jsxs("div",{children:[e.jsx(se,{children:"Month"}),e.jsxs(vs,{value:String(x.month??1),onValueChange:L=>y({...x,month:Number(L)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:_Fn.map(L=>e.jsx(Je,{value:String(L.value),children:L.label},L.value))})]})]})]}),e.jsx("div",{className:"grid sm:grid-cols-3 gap-3",children:k7.map(L=>e.jsxs("div",{children:[e.jsxs(se,{children:[L.label," target"]}),e.jsx(ye,{type:"number",value:x[L.target]??"",onChange:I=>y({...x,[L.target]:I.target.value===""?null:Number(I.target.value)})})]},L.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(Mn,{checked:x.use_auto_progress??!0,onCheckedChange:L=>y({...x,use_auto_progress:L})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ds,{value:x.notes??"",onChange:L=>y({...x,notes:L.target.value}),rows:3})]})]}),e.jsxs(Nr,{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:M,disabled:a.isPending||i.isPending,children:"Save goal"})]})]})}),e.jsx(Fs,{open:!!g,onOpenChange:L=>!L&&b(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Update progress"}),e.jsxs(kr,{children:[g?S7(g):""," — enter your actuals to date."]})]}),g&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:k7.filter(L=>g[L.target]).map(L=>e.jsxs("div",{children:[e.jsx(se,{children:L.label}),e.jsx(ye,{type:"number",value:g[L.actual]??0,onChange:I=>b({...g,[L.actual]:Number(I.target.value)})})]},L.key))}),e.jsxs(Nr,{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:P,children:"Save progress"})]})]})}),e.jsx(Fs,{open:!!v,onOpenChange:L=>!L&&k(null),children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Delete this goal?"}),e.jsx(kr,{children:"This can't be undone. Archive it instead if you want to keep the history."})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>k(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(v.id),k(null)},children:"Delete"})]})]})})]})}const Y8e=[{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 NFn(){const s=wee("attract_awards",{orderBy:"awarded_on",ascending:!1,label:"Award",duplicateOverrides:{is_archived:!1}}),t=jee();return{...s,awards:s.items,logActivity:t}}const avt={category:"award",status:"active",is_public:!0};function ivt(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 kFn(){const{awards:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,logActivity:d}=NFn(),[u,h]=j.useState(!1),[m,p]=j.useState("all"),[x,y]=j.useState(""),[g,b]=j.useState(null),[v,k]=j.useState(null),C=j.useMemo(()=>s.filter(P=>{if(u!==!!P.is_archived||m!=="all"&&P.category!==m)return!1;const L=x.toLowerCase().trim();return!L||`${P.title} ${P.issuer??""} ${P.description??""}`.toLowerCase().includes(L)}),[s,u,m,x]),T=async()=>{var L;if(!((L=g==null?void 0:g.title)!=null&&L.trim())){re.error("Add a title");return}const P={title:g.title.trim(),issuer:g.issuer||null,awarded_on:g.awarded_on||null,category:g.category??"award",description:g.description||null,proof_url:g.proof_url||null,production_period:g.production_period||null,is_public:g.is_public??!0};g.id?await i.mutateAsync({id:g.id,...P}):(await a.mutateAsync(P),await d.mutateAsync({title:`Added recognition: ${P.title}`,pillar:"produce",activityType:"award_added"})),b(null)},M=P=>{var I;const L=[P.title,P.issuer&&`— ${P.issuer}`,P.awarded_on&&`(${ivt(P.awarded_on)})`].filter(Boolean).join(" ");(I=navigator.clipboard)==null||I.writeText(L),re.success("Proof point copied — paste it into Content Studio")};return e.jsxs("div",{children:[e.jsxs(Yn,{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(_a,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Wh,{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(P=>!P),children:u?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>b({...avt}),children:[e.jsx(Js,{className:"h-4 w-4 mr-1.5"})," Add Recognition"]})]})}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(ye,{value:x,onChange:P=>y(P.target.value),placeholder:"Search recognitions",className:"max-w-xs rounded-full"}),e.jsxs(vs,{value:m,onValueChange:p,children:[e.jsx(gs,{className:"w-[190px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All categories"}),Y8e.map(P=>e.jsx(Je,{value:P.value,children:P.label},P.value))]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(P=>e.jsx(gn,{className:"h-36 rounded-2xl"},P))}),!t&&n&&e.jsxs(be,{className:"p-8 rounded-2xl text-center",children:[e.jsx(po,{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(bm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&C.length===0&&e.jsxs(be,{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(cu,{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:()=>b({...avt}),children:[e.jsx(Js,{className:"h-4 w-4 mr-1.5"})," Add your first"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:C.map(P=>{var L;return e.jsxs(be,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15.5px] font-semibold text-slate-900",children:P.title}),e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:((L=Y8e.find(I=>I.value===P.category))==null?void 0:L.label)??P.category})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[P.issuer,ivt(P.awarded_on),P.production_period].filter(Boolean).join(" · ")}),P.description&&e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:P.description})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>b(P),children:e.jsx(Za,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(P),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:P.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:P.id,archived:!P.is_archived}),children:e.jsx(gm,{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(P),children:e.jsx(Rn,{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:()=>M(P),children:[e.jsx(Rc,{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(Yn,{to:"/attract/influence/content-studio",children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1.5"})," Write about it"]})}),P.proof_url&&e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:P.proof_url,target:"_blank",rel:"noreferrer",children:["Proof ",e.jsx(Tr,{className:"h-3 w-3 ml-1.5"})]})})]})]},P.id)})}),e.jsx(Fs,{open:!!g,onOpenChange:P=>!P&&b(null),children:e.jsxs(Os,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:g!=null&&g.id?"Edit recognition":"Add recognition"}),e.jsx(kr,{children:"Keep it factual — this feeds the proof points you use publicly."})]}),g&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(ye,{value:g.title??"",onChange:P=>b({...g,title:P.target.value}),placeholder:"e.g. Top 1% Producer"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Issued by"}),e.jsx(ye,{value:g.issuer??"",onChange:P=>b({...g,issuer:P.target.value}),placeholder:"Board, brokerage, publication"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Category"}),e.jsxs(vs,{value:g.category??"award",onValueChange:P=>b({...g,category:P}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Y8e.map(P=>e.jsx(Je,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Date awarded"}),e.jsx(ye,{type:"date",value:g.awarded_on??"",onChange:P=>b({...g,awarded_on:P.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Production period"}),e.jsx(ye,{value:g.production_period??"",onChange:P=>b({...g,production_period:P.target.value}),placeholder:"e.g. 2025"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Proof link"}),e.jsx(ye,{value:g.proof_url??"",onChange:P=>b({...g,proof_url:P.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{rows:3,value:g.description??"",onChange:P=>b({...g,description:P.target.value})})]})]}),e.jsxs(Nr,{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:T,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(Fs,{open:!!v,onOpenChange:P=>!P&&k(null),children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Delete this recognition?"}),e.jsx(kr,{children:"This can't be undone."})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>k(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(v.id),k(null)},children:"Delete"})]})]})})]})}const SFn=U,ovt=[{value:"pending",label:"Permission pending"},{value:"granted",label:"Permission granted"},{value:"anonymous_only",label:"Anonymous use only"},{value:"declined",label:"Permission declined"}],CFn=["buyer","seller","both","investor","referral_partner","agent","other"];function Vre(s){return s.status==="approved"&&(s.permission_status==="granted"||s.permission_status==="anonymous_only")}function AFn(){const s=wee("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=jee(),n=as(),r=vt({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 SFn.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"]}),re.success("Usage recorded")},onError:a=>re.error(a.message)});return{...s,testimonials:s.items,recordUse:r,logActivity:t}}const lvt={permission_status:"pending",status:"draft",rating:5,tags:[]};function TFn(){const{testimonials:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,recordUse:d,logActivity:u}=AFn(),[h,m]=j.useState(!1),[p,x]=j.useState("all"),[y,g]=j.useState(""),[b,v]=j.useState(null),[k,C]=j.useState(null),T=j.useMemo(()=>s.filter(I=>{if(h!==!!I.is_archived||p==="usable"&&!Vre(I)||p==="pending"&&I.permission_status!=="pending")return!1;const O=y.toLowerCase().trim();return!O||`${I.client_name} ${I.quote} ${(I.tags??[]).join(" ")}`.toLowerCase().includes(O)}),[s,h,p,y]),M=s.filter(I=>!I.is_archived&&Vre(I)).length,P=async()=>{var O,$;if(!((O=b==null?void 0:b.client_name)!=null&&O.trim())||!(($=b==null?void 0:b.quote)!=null&&$.trim())){re.error("Client name and quote are required");return}const I={client_name:b.client_name.trim(),quote:b.quote.trim(),relationship_type:b.relationship_type||null,transaction_type:b.transaction_type||null,rating:b.rating??null,received_on:b.received_on||null,source_url:b.source_url||null,permission_status:b.permission_status??"pending",market:b.market||null,status:b.status??"draft",tags:b.tags??[]};b.id?await i.mutateAsync({id:b.id,...I}):(await a.mutateAsync(I),await u.mutateAsync({title:`Captured a testimonial from ${I.client_name}`,pillar:"produce",activityType:"testimonial_added"})),v(null)},L=(I,O)=>{var $;if(!Vre(I)){re.error("Mark it approved with permission before using it publicly");return}($=navigator.clipboard)==null||$.writeText(`"${I.quote}" — ${I.permission_status==="anonymous_only"?"Client":I.client_name}`),d.mutate({item:I,kind:O})};return e.jsxs("div",{children:[e.jsxs(Yn,{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(_a,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Wh,{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(I=>!I),children:h?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v({...lvt}),children:[e.jsx(Js,{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(be,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(I=>!I.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"In library"})]}),e.jsxs(be,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:M}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Cleared for use"})]}),e.jsxs(be,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:s.filter(I=>!I.is_archived&&I.permission_status==="pending").length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Permission pending"})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(ye,{value:y,onChange:I=>g(I.target.value),placeholder:"Search quotes, clients, tags",className:"max-w-xs rounded-full"}),e.jsxs(vs,{value:p,onValueChange:I=>x(I),children:[e.jsx(gs,{className:"w-[200px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All testimonials"}),e.jsx(Je,{value:"usable",children:"Cleared for use"}),e.jsx(Je,{value:"pending",children:"Permission pending"})]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(I=>e.jsx(gn,{className:"h-40 rounded-2xl"},I))}),!t&&n&&e.jsxs(be,{className:"p-8 rounded-2xl text-center",children:[e.jsx(po,{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(bm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&T.length===0&&e.jsxs(be,{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(yN,{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:()=>v({...lvt}),children:[e.jsx(Js,{className:"h-4 w-4 mr-1.5"})," Add one"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:T.map(I=>{var O;return e.jsxs(be,{className:"p-5 rounded-2xl flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:I.client_name}),I.relationship_type&&e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:I.relationship_type.replace("_"," ")}),e.jsx(qe,{variant:"outline",className:`rounded-full ${Vre(I)?"bg-emerald-50 text-emerald-700 border-emerald-200":"bg-amber-50 text-amber-700 border-amber-200"}`,children:((O=ovt.find($=>$.value===I.permission_status))==null?void 0:O.label)??I.permission_status})]}),!!I.rating&&e.jsx("div",{className:"flex gap-0.5 mt-1.5",children:Array.from({length:5}).map(($,q)=>e.jsx(Wa,{className:`h-3.5 w-3.5 ${q<(I.rating??0)?"text-amber-500 fill-amber-500":"text-slate-200"}`},q))})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>v(I),children:e.jsx(Za,{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(ja,{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(gm,{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:()=>C(I),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("blockquote",{className:"mt-3 text-[13.5px] text-slate-700 border-l-2 border-violet-200 pl-3 italic",children:['"',I.quote,'"']}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-3",children:["Used ",I.use_count??0," ",I.use_count===1?"time":"times",I.last_used_at?` · last ${new Date(I.last_used_at).toLocaleDateString("en-US")}`:"",I.status==="approved"?"":" · draft"]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>L(I,"copied"),children:[e.jsx(ja,{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(Yn,{to:"/attract/influence/content-studio",children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1.5"})," Draft social proof"]})}),I.status!=="approved"&&e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full text-emerald-700",onClick:()=>i.mutate({id:I.id,status:"approved"}),children:[e.jsx(a0,{className:"h-3.5 w-3.5 mr-1.5"})," Mark approved"]})]})]},I.id)})}),e.jsx(Fs,{open:!!b,onOpenChange:I=>!I&&v(null),children:e.jsxs(Os,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:b!=null&&b.id?"Edit testimonial":"Add testimonial"}),e.jsx(kr,{children:"Use the client's own words. Only publish quotes where permission is granted."})]}),b&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Client name *"}),e.jsx(ye,{value:b.client_name??"",onChange:I=>v({...b,client_name:I.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Relationship"}),e.jsxs(vs,{value:b.relationship_type??"",onValueChange:I=>v({...b,relationship_type:I}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select"})}),e.jsx(ys,{children:CFn.map(I=>e.jsx(Je,{value:I,className:"capitalize",children:I.replace("_"," ")},I))})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Quote *"}),e.jsx(Ds,{rows:4,value:b.quote??"",onChange:I=>v({...b,quote:I.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Rating"}),e.jsxs(vs,{value:String(b.rating??5),onValueChange:I=>v({...b,rating:Number(I)}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:[5,4,3,2,1].map(I=>e.jsxs(Je,{value:String(I),children:[I," star",I>1?"s":""]},I))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Received on"}),e.jsx(ye,{type:"date",value:b.received_on??"",onChange:I=>v({...b,received_on:I.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Permission"}),e.jsxs(vs,{value:b.permission_status??"pending",onValueChange:I=>v({...b,permission_status:I}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:ovt.map(I=>e.jsx(Je,{value:I.value,children:I.label},I.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:b.status??"draft",onValueChange:I=>v({...b,status:I}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"draft",children:"Draft"}),e.jsx(Je,{value:"approved",children:"Approved"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Market / area"}),e.jsx(ye,{value:b.market??"",onChange:I=>v({...b,market:I.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Source link"}),e.jsx(ye,{value:b.source_url??"",onChange:I=>v({...b,source_url:I.target.value}),placeholder:"https://"})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>v(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(Fs,{open:!!k,onOpenChange:I=>!I&&C(null),children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Delete this testimonial?"}),e.jsx(kr,{children:"This can't be undone."})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>C(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(k.id),C(null)},children:"Delete"})]})]})})]})}const cvt=[{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"}],dvt=["idea","planned","drafted","scheduled","published","skipped"],EFn=["weekly","biweekly","monthly","quarterly","one_off"];function Tqt(){const s=wee("attract_market_presence",{orderBy:"planned_for",ascending:!0,label:"Commitment",duplicateOverrides:{status:"idea",published_url:null,results_notes:null,is_archived:!1}}),t=PTe(),n=jee();return{...s,commitments:s.items,quickTask:t,logActivity:n}}const uvt={content_type:"market_update",cadence:"monthly",status:"planned"};function MFn(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 LFn={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 PFn(){const{commitments:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,quickTask:d,logActivity:u}=Tqt(),[h,m]=j.useState(!1),[p,x]=j.useState("all"),[y,g]=j.useState(null),[b,v]=j.useState(null),k=j.useMemo(()=>s.filter(L=>h!==!!L.is_archived?!1:p==="all"||L.status===p),[s,h,p]),C=s.filter(L=>{if(L.status!=="published"||!L.planned_for)return!1;const[I,O,$]=L.planned_for.split(/[-/T]/).map(Number);return(Date.now()-new Date(I,O-1,$).getTime())/864e5<=30}).length,T=s.filter(L=>{if(L.is_archived||!L.planned_for||["published","skipped"].includes(L.status))return!1;const[I,O,$]=L.planned_for.split(/[-/T]/).map(Number);return new Date(I,O-1,$){var I;if(!((I=y==null?void 0:y.title)!=null&&I.trim())){re.error("Add a title");return}const L={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,...L}):await a.mutateAsync(L),g(null)},P=async L=>{await i.mutateAsync({id:L.id,status:"published"}),await u.mutateAsync({title:`Published market presence: ${L.title}`,pillar:"produce",activityType:"market_presence_published"})};return e.jsxs("div",{children:[e.jsxs(Yn,{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(_a,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Wh,{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(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:()=>g({...uvt}),children:[e.jsx(Js,{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(be,{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:"Active commitments"})]}),e.jsxs(be,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:C}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Published last 30 days"})]}),e.jsxs(be,{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(vs,{value:p,onValueChange:x,children:[e.jsx(gs,{className:"w-[190px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All statuses"}),dvt.map(L=>e.jsx(Je,{value:L,className:"capitalize",children:L},L))]})]})}),t&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(L=>e.jsx(gn,{className:"h-24 rounded-2xl"},L))}),!t&&n&&e.jsxs(be,{className:"p-8 rounded-2xl text-center",children:[e.jsx(po,{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(bm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&k.length===0&&e.jsxs(be,{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(iy,{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:()=>g({...uvt}),children:[e.jsx(Js,{className:"h-4 w-4 mr-1.5"})," Add a commitment"]})]}),e.jsx("div",{className:"space-y-2",children:k.map(L=>{var I;return e.jsxs(be,{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:L.title}),e.jsx(qe,{variant:"outline",className:"rounded-full",children:((I=cvt.find(O=>O.value===L.content_type))==null?void 0:I.label)??L.content_type}),e.jsx(qe,{variant:"outline",className:`rounded-full capitalize ${LFn[L.status]??""}`,children:L.status}),e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:L.cadence.replace("_"," ")})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[MFn(L.planned_for),L.channel,L.audience].filter(Boolean).join(" · ")}),L.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:L.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>g(L),children:e.jsx(Za,{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(ja,{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(gm,{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:()=>v(L),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[L.status!=="published"&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>P(L),children:[e.jsx(Rr,{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: ${L.title}`,dueAt:L.planned_for?`${L.planned_for}T09:00:00`:new Date().toISOString(),notes:L.notes,touchType:"content"}),children:[e.jsx(zp,{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(Yn,{to:"/attract/influence/content-studio",children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1.5"})," Draft it"]})})]})]},L.id)})}),e.jsx(Fs,{open:!!y,onOpenChange:L=>!L&&g(null),children:e.jsxs(Os,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:y!=null&&y.id?"Edit commitment":"New commitment"}),e.jsx(kr,{children:"Pick something you can genuinely sustain."})]}),y&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(ye,{value:y.title??"",onChange:L=>g({...y,title:L.target.value}),placeholder:"e.g. October market update video"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Type"}),e.jsxs(vs,{value:y.content_type??"market_update",onValueChange:L=>g({...y,content_type:L}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:cvt.map(L=>e.jsx(Je,{value:L.value,children:L.label},L.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Cadence"}),e.jsxs(vs,{value:y.cadence??"monthly",onValueChange:L=>g({...y,cadence:L}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:EFn.map(L=>e.jsx(Je,{value:L,className:"capitalize",children:L.replace("_"," ")},L))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Planned for"}),e.jsx(ye,{type:"date",value:y.planned_for??"",onChange:L=>g({...y,planned_for:L.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Status"}),e.jsxs(vs,{value:y.status??"planned",onValueChange:L=>g({...y,status:L}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:dvt.map(L=>e.jsx(Je,{value:L,className:"capitalize",children:L},L))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Channel"}),e.jsx(ye,{value:y.channel??"",onChange:L=>g({...y,channel:L.target.value}),placeholder:"Instagram, email, YouTube"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Audience"}),e.jsx(ye,{value:y.audience??"",onChange:L=>g({...y,audience:L.target.value}),placeholder:"Agents, sphere, neighborhood"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ds,{rows:3,value:y.notes??"",onChange:L=>g({...y,notes:L.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Published URL"}),e.jsx(ye,{value:y.published_url??"",onChange:L=>g({...y,published_url:L.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Results"}),e.jsx(ye,{value:y.results_notes??"",onChange:L=>g({...y,results_notes:L.target.value}),placeholder:"Reach, replies, leads"})]})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>g(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:M,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(Fs,{open:!!b,onOpenChange:L=>!L&&v(null),children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Delete this commitment?"}),e.jsx(kr,{children:"This can't be undone."})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>v(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(b.id),v(null)},children:"Delete"})]})]})})]})}function hvt(s){if(!s)return null;const[t]=s.split("T");return t||null}const Hre={draft:{label:"Content",icon:yn,cls:"bg-violet-50 text-violet-700 border-violet-200"},presence:{label:"Market presence",icon:iy,cls:"bg-blue-50 text-blue-700 border-blue-200"},speaking:{label:"Speaking",icon:Sj,cls:"bg-amber-50 text-amber-700 border-amber-200"}};function IFn(){const{drafts:s,isLoading:t,save:n}=kqt(),{commitments:r,isLoading:a}=Tqt(),i=Aqt(),l=PTe(),[o,c]=j.useState(()=>{const T=new Date;return new Date(T.getFullYear(),T.getMonth(),1)}),[d,u]=j.useState("all"),[h,m]=j.useState(null),p=j.useMemo(()=>(i.items??[]).filter(T=>!T.is_archived).map(T=>({id:T.id,kind:"speaking",title:T.title,date:hvt(T.starts_at),status:T.status,href:"/attract/influence/speaking"})),[i.items]),x=j.useMemo(()=>{const T=s.map(P=>({id:P.id,kind:"draft",title:P.topic||P.mode.replace(/_/g," "),date:hvt(P.planned_at??P.posted_at??null),status:P.status,href:"/attract/influence/content-studio"})),M=r.filter(P=>!P.is_archived).map(P=>({id:P.id,kind:"presence",title:P.title,date:P.planned_for,status:P.status,href:"/attract/produce/market-presence"}));return[...T,...M,...p].filter(P=>d==="all"||P.kind===d)},[s,r,p,d]),y=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}`,g=x.filter(T=>{var M;return(M=T.date)==null?void 0:M.startsWith(y)}),b=x.filter(T=>!T.date),v=j.useMemo(()=>{const T=new Date(o.getFullYear(),o.getMonth(),1),M=new Date(T);return M.setDate(T.getDate()-T.getDay()),Array.from({length:42},(P,L)=>{const I=new Date(M);I.setDate(M.getDate()+L);const O=`${I.getFullYear()}-${String(I.getMonth()+1).padStart(2,"0")}-${String(I.getDate()).padStart(2,"0")}`;return{date:I,key:O,inMonth:I.getMonth()===o.getMonth(),items:x.filter($=>$.date===O)}})},[o,x]),k=(()=>{const T=new Date;return`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`})(),C=t||a;return e.jsxs("div",{children:[e.jsxs(Yn,{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(_a,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(Wh,{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(Yn,{to:"/attract/influence/content-studio",children:[e.jsx(Js,{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(Cc,{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(qe,{variant:"outline",className:"rounded-full",children:[g.length," scheduled this month"]}),e.jsxs(vs,{value:d,onValueChange:T=>u(T),children:[e.jsx(gs,{className:"w-[180px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"all",children:"All types"}),e.jsx(Je,{value:"draft",children:"Content drafts"}),e.jsx(Je,{value:"presence",children:"Market presence"}),e.jsx(Je,{value:"speaking",children:"Speaking"})]})]})]})]}),C?e.jsx(gn,{className:"h-[560px] rounded-2xl"}):e.jsxs(be,{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:v.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(M=>{const P=Hre[M.kind];return e.jsx(Yn,{to:M.href,className:`block truncate rounded-md border px-1.5 py-0.5 text-[11px] ${P.cls}`,title:M.title,children:M.title},`${M.kind}-${M.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(be,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:["Unscheduled (",b.length,")"]}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Give these a date so they show on the calendar."}),b.length===0&&e.jsx("div",{className:"text-[13px] text-slate-500",children:"Everything has a date. Nice."}),e.jsx("div",{className:"space-y-2",children:b.slice(0,8).map(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:[Hre[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(Yn,{to:T.href,children:"Open"})})]},`${T.kind}-${T.id}`))})]}),e.jsxs(be,{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(Hre).map(T=>{const M=Hre[T],P=M.icon,L=g.filter(I=>I.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 ${M.cls}`,children:e.jsx(P,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 flex-1",children:M.label}),e.jsx("div",{className:"text-[16px] font-semibold tabular-nums text-slate-900",children:L})]},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(zp,{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(Yn,{to:"/attract/produce/market-presence",children:[e.jsx(Vc,{className:"h-3.5 w-3.5 mr-1.5"})," Manage market presence cadence"]})})]})]}),e.jsx(Fs,{open:!!h,onOpenChange:T=>!T&&m(null),children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Schedule draft"}),e.jsx(kr,{className:"capitalize",children:h==null?void 0:h.title})]}),h&&e.jsxs("div",{children:[e.jsx(se,{children:"Planned date"}),e.jsx(ye,{type:"date",value:h.date,onChange:T=>m({...h,date:T.target.value})})]}),e.jsxs(Nr,{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 mvt=[{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 RFn(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return{y:t,m:n,d:r}}function d$e(s,t=new Date){const{y:n,m:r,d:a}=RFn(s.milestone_on);if(!s.recurs_annually)return new Date(n,r-1,a);const i=new Date(t.getFullYear(),r-1,a),l=new Date(t.getFullYear(),t.getMonth(),t.getDate());return i{const l=[];return r.forEach(o=>{const c=[o.preferred_name||o.first_name,o.last_name].filter(Boolean).join(" ");[["birthday",o.birthday_on,`${c} — Birthday`],["work_anniversary",o.work_anniversary_on,`${c} — Work Anniversary`],["license_anniversary",o.license_anniversary_on,`${c} — License Anniversary`]].forEach(([d,u,h])=>{u&&l.push({id:`agent:${o.id}:${d}`,user_id:o.user_id,title:h,milestone_type:d,milestone_on:String(u).slice(0,10),recurs_annually:!0,linked_agent_ids:[o.id],notes:null,last_celebrated_at:null,is_archived:!1,created_at:o.created_at,updated_at:o.updated_at})})}),l},[r]),i=j.useMemo(()=>{const l=new Set(s.items.filter(c=>!c.is_archived).map(c=>{var d;return`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${((d=c.linked_agent_ids)==null?void 0:d[0])??""}`}));return[...s.items.filter(c=>!c.is_archived),...a.filter(c=>!l.has(`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${c.linked_agent_ids[0]}`))].map(c=>({item:c,next:d$e(c)})).map(c=>({...c,days:Eqt(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 pvt={milestone_type:"birthday",recurs_annually:!0,linked_agent_ids:[]};function OFn(s){return s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function FFn(){var O;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}=DFn(),m=x0(),p=(m==null?void 0:m.agents)??(m==null?void 0:m.items)??[],[x,y]=j.useState(!1),[g,b]=j.useState("90"),[v,k]=j.useState(null),[C,T]=j.useState(null),M=j.useMemo(()=>{if(x)return s.filter(q=>q.is_archived).map(q=>({item:q,next:d$e(q),days:Eqt(d$e(q))}));const $=g==="all"?1/0:Number(g);return t.filter(q=>q.days<=$)},[s,t,x,g]),P=$=>{const q=p.find(W=>W.id===$);return q?[q.preferred_name||q.first_name,q.last_name].filter(Boolean).join(" "):"Agent"},L=async()=>{var q;if(!((q=v==null?void 0:v.title)!=null&&q.trim())||!(v!=null&&v.milestone_on)){re.error("Title and date are required");return}const $={title:v.title.trim(),milestone_type:v.milestone_type??"birthday",milestone_on:v.milestone_on,recurs_annually:v.recurs_annually??!0,linked_agent_ids:v.linked_agent_ids??[],notes:v.notes||null};v.id?await l.mutateAsync({id:v.id,...$}):await i.mutateAsync($),k(null)},I=async $=>{var q;await l.mutateAsync({id:$.id,last_celebrated_at:new Date().toISOString()}),await h.mutateAsync({title:`Celebrated: ${$.title}`,pillar:"connect",activityType:"milestone_celebrated",agentId:((q=$.linked_agent_ids)==null?void 0:q[0])??null})};return e.jsxs("div",{children:[e.jsxs(Yn,{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(_a,{className:"h-3.5 w-3.5"})," Back to Connect"]}),e.jsx(Wh,{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:x?"Show upcoming":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>k({...pvt}),children:[e.jsx(Js,{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(be,{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(be,{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(be,{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"})]})]}),!x&&e.jsx("div",{className:"flex gap-2 flex-wrap mb-4",children:e.jsxs(vs,{value:g,onValueChange:$=>b($),children:[e.jsx(gs,{className:"w-[190px] rounded-full",children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"30",children:"Next 30 days"}),e.jsx(Je,{value:"90",children:"Next 90 days"}),e.jsx(Je,{value:"all",children:"All upcoming"})]})]})}),n&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map($=>e.jsx(gn,{className:"h-20 rounded-2xl"},$))}),!n&&r&&e.jsxs(be,{className:"p-8 rounded-2xl text-center",children:[e.jsx(po,{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(bm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!n&&!r&&M.length===0&&e.jsxs(be,{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(Wm,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:x?"Nothing archived":"No milestones in this window"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Add birthdays, license anniversaries, and production milestones for the agents you're building relationships with."}),!x&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>k({...pvt}),children:[e.jsx(Js,{className:"h-4 w-4 mr-1.5"})," Add a milestone"]})]}),e.jsx("div",{className:"space-y-2",children:M.map(({item:$,next:q,days:W})=>{var K,ee;const G=String($.id).startsWith("agent:");return e.jsxs(be,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-violet-50 text-violet-700 grid place-items-center flex-shrink-0",children:e.jsxs("div",{className:"text-center leading-none",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wider",children:q.toLocaleString("en-US",{month:"short"})}),e.jsx("div",{className:"text-[15px] font-semibold",children:q.getDate()})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:$.title}),e.jsx(qe,{variant:"outline",className:"rounded-full",children:((K=mvt.find(J=>J.value===$.milestone_type))==null?void 0:K.label)??$.milestone_type}),G&&e.jsx(qe,{variant:"outline",className:"rounded-full bg-violet-50 text-violet-700 border-violet-200",children:"From contact record"}),!x&&e.jsx(qe,{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(qe,{variant:"outline",className:"rounded-full",children:"Annual"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[OFn(q),(ee=$.linked_agent_ids)!=null&&ee.length?` · ${$.linked_agent_ids.map(P).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(Yn,{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(Za,{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(ja,{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(gm,{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(Rn,{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 J;return u.mutate({title:`Reach out: ${$.title}`,dueAt:q.toISOString(),notes:$.notes,touchType:"celebration",agentId:((J=$.linked_agent_ids)==null?void 0:J[0])??null})},children:[e.jsx(zp,{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:()=>I($),children:[e.jsx(bf,{className:"h-3.5 w-3.5 mr-1.5"})," Mark celebrated"]})]})]},$.id)})}),e.jsx(Fs,{open:!!v,onOpenChange:$=>!$&&k(null),children:e.jsxs(Os,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:v!=null&&v.id?"Edit milestone":"Add milestone"}),e.jsx(kr,{children:"Annual milestones roll forward automatically each year."})]}),v&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Title *"}),e.jsx(ye,{value:v.title??"",onChange:$=>k({...v,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(se,{children:"Type"}),e.jsxs(vs,{value:v.milestone_type??"birthday",onValueChange:$=>k({...v,milestone_type:$}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:mvt.map($=>e.jsx(Je,{value:$.value,children:$.label},$.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Date *"}),e.jsx(ye,{type:"date",value:v.milestone_on??"",onChange:$=>k({...v,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(Mn,{checked:v.recurs_annually??!0,onCheckedChange:$=>k({...v,recurs_annually:$})})]}),p.length>0&&e.jsxs("div",{children:[e.jsx(se,{children:"Link to agent"}),e.jsxs(vs,{value:((O=v.linked_agent_ids)==null?void 0:O[0])??"none",onValueChange:$=>k({...v,linked_agent_ids:$==="none"?[]:[$]}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Optional"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No agent"}),p.map($=>e.jsx(Je,{value:$.id,children:P($.id)},$.id))]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Notes"}),e.jsx(Ds,{rows:3,value:v.notes??"",onChange:$=>k({...v,notes:$.target.value}),placeholder:"Gift ideas, personal details, how you'll reach out"})]})]}),e.jsxs(Nr,{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:L,disabled:i.isPending||l.isPending,children:"Save"})]})]})}),e.jsx(Fs,{open:!!C,onOpenChange:$=>!$&&T(null),children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Delete this milestone?"}),e.jsx(kr,{children:"This can't be undone."})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>T(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{d.mutate(C.id),T(null)},children:"Delete"})]})]})})]})}function zFn(){var c;const{shareToken:s}=$i(),[t,n]=j.useState("loading"),[r,a]=j.useState(null),[i,l]=j.useState(!1);j.useEffect(()=>{(async()=>{if(!s){n("not_found");return}const{data:d,error:u}=await U.rpc("public_get_attract_kit",{_token:s});if(u){n("error");return}if(!d||d.status!=="ok"){n((d==null?void 0:d.status)??"not_found");return}a(d),n("ok"),U.rpc("public_log_attract_kit_event",{_token:s,_event_type:"page_view",_item_id:null,_metadata:{}})})()},[s]);const o=(d,u,h)=>{s&&U.rpc("public_log_attract_kit_event",{_token:s,_event_type:d,_item_id:u??null,_metadata:h??{}})};return t==="loading"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center text-slate-300",children:"Loading…"}):t!=="ok"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center px-6",children:e.jsxs(be,{className:"max-w-md w-full p-8 bg-white/5 border-white/10 text-slate-100 rounded-2xl text-center",children:[e.jsx(po,{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(yn,{className:"h-3.5 w-3.5"})," A LevelUp Attract kit"]}),e.jsx(Sqt,{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(be,{className:"mt-6 p-6 bg-white/5 border-white/10 text-slate-100 rounded-2xl",children:i?e.jsx(BFn,{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 BFn({token:s,onSent:t,onEvent:n}){const[r,a]=j.useState(""),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(!1),h=async()=>{if(o.trim().length<2)return re.error("Please add a short message");u(!0);const{data:m,error:p}=await U.rpc("public_submit_attract_kit_question",{_token:s,_name:r,_email:i,_message:o});if(u(!1),p||!(m!=null&&m.ok))return re.error("Could not send — please try again");re.success("Sent — thank you!"),t()};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[14px] font-semibold",children:"Send a private message"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsx(ye,{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(ye,{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(Ds,{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"),re.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 $Fn(){const{slug:s}=$i(),[t]=dc(),n=t.get("inv")||null,[r,a]=j.useState("loading"),[i,l]=j.useState(null),[o,c]=j.useState({name:"",email:"",phone:"",answers:{}}),[d,u]=j.useState(!1),[h,m]=j.useState(null);j.useEffect(()=>{s&&(async()=>{const{data:y,error:g}=await U.rpc("public_get_attract_event",{_slug:s});if(g||!y||y.error){a((y==null?void 0:y.error)||"not_found");return}l(y),a("ok"),n&&U.rpc("public_track_attract_invitation_view",{_token:n})})()},[s,n]);const p=async()=>{u(!0);const{data:y,error:g}=await U.rpc("public_register_attract_event",{_slug:s,_name:o.name,_email:o.email,_phone:o.phone||null,_answers:o.answers||{},_invitation_token:n});if(u(!1),g){alert("Something went wrong. Please try again.");return}const b=y;if(b!=null&&b.error){alert(b.error==="invalid_email"?"That email looks off.":b.error==="full"?"This event is full.":"Could not register.");return}m(b)},x=()=>{if(!i)return;const y=new Blob([YUt(i)],{type:"text/calendar"}),g=document.createElement("a");g.href=URL.createObjectURL(y),g.download=`${s}.ics`,g.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(be,{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(ra,{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:Bs(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(Zr,{className:"h-5 w-5 text-violet-600 mt-0.5"}):e.jsx(oi,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"Where"}),e.jsx("div",{className:"font-semibold text-slate-900",children:i.format==="virtual"?"Virtual — link sent after registration":i.location||"In person"}),i.address&&e.jsx("div",{className:"text-slate-500 text-[12px]",children:i.address})]})]}),i.capacity&&e.jsxs("div",{className:"flex items-start gap-3 md:col-span-2",children:[e.jsx(Bn,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"Room size"}),e.jsx("div",{className:"font-semibold text-slate-900",children:i.seats_left===0?"Waitlist only":`${i.seats_left} of ${i.capacity} seats left`})]})]})]}),i.description&&e.jsx("p",{className:"text-[15px] text-slate-700 leading-relaxed mt-5",children:i.description}),(i.learning_outcomes||[]).length>0&&e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"What you will receive"}),e.jsx("ul",{className:"space-y-1.5",children:i.learning_outcomes.map((y,g)=>e.jsxs("li",{className:"flex gap-2 text-[14px] text-slate-800",children:[e.jsx(da,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",y]},g))})]}),(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,g)=>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})]},g))})]})]}),h?e.jsxs(be,{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(da,{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:x,children:[e.jsx(ii,{className:"h-4 w-4 mr-2"})," Add to calendar"]})]}):e.jsxs(be,{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(yn,{className:"h-4 w-4 text-violet-600"})," Save your seat"]}),e.jsx("div",{className:"text-[13px] text-slate-500 mb-4",children:"The room is small on purpose."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Full name"}),e.jsx(ye,{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(se,{children:"Email"}),e.jsx(ye,{type:"email",value:o.email,onChange:y=>c({...o,email:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone (optional)"}),e.jsx(ye,{value:o.phone,onChange:y=>c({...o,phone:y.target.value})})]})]}),(i.registration_questions||[]).map(y=>e.jsxs("div",{children:[e.jsx(se,{children:y.label}),y.type==="long"?e.jsx(Ds,{rows:3,value:o.answers[y.key]||"",onChange:g=>c({...o,answers:{...o.answers,[y.key]:g.target.value}})}):e.jsx(ye,{value:o.answers[y.key]||"",onChange:g=>c({...o,answers:{...o.answers,[y.key]:g.target.value}})})]},y.key))]}),e.jsx(B,{disabled:d,className:"w-full mt-5 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 h-11",onClick:p,children:d?"Saving…":i.seats_left===0?"Join the waitlist":"Save my seat"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center mt-3",children:"Build relationships first. We will only email you about this event."})]})]})})}function UFn(){const{token:s}=$i(),[t]=dc(),n=t.get("a"),[r,a]=j.useState("loading"),[i,l]=j.useState("");return j.useEffect(()=>{if(!s||!n){a("error");return}(async()=>{const{data:o}=await U.rpc("public_check_in_attendee",{_check_in_token:s,_attendee_token:n}),c=o;c!=null&&c.ok?(l(c.name||""),a(c.already?"already":"ok")):a("error")})()},[s,n]),e.jsx("div",{className:"min-h-screen grid place-items-center bg-slate-50 px-4",children:e.jsxs(be,{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(da,{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 Gre=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function qFn(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 Mqt({cfg:s,onSubmitLead:t,onTrack:n,preview:r}){var P,L,I;const a=s.primary_color||"#0f1b3d",i=s.accent_color||"#c9a84c",l=s.sections||{},[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(!1),[p,x]=j.useState({first_name:"",last_name:"",email:"",phone:"",brokerage:"",message:""}),[y,g]=j.useState({first_name:"",email:""}),b=s.calculator||{},[v,k]=j.useState(15e4),C=j.useMemo(()=>{const O=Number(b.cap??16e3),$=Number(b.split??80)/100,q=Number(b.transaction_fee??250),W=Number(b.current_split??70)/100,G=Number(b.current_monthly_fees??150),K=Math.min(v*(1-$),O),ee=v-K-q*12,J=v*W-G*12;return{here:Math.max(ee,0),current:Math.max(J,0),diff:Math.max(ee-J,0),capped:K>=O}},[v,b]),T=async(O,$,q)=>{if(r||!t){u(O);return}m(!0);try{await t({first_name:$.first_name||"",last_name:$.last_name||"",email:$.email||"",phone:$.phone||"",brokerage:$.brokerage||"",message:$.message||"",source:O,metadata:q}),u(O)}catch(W){ba({title:"We couldn't send that",description:(W==null?void 0:W.message)||"Please try again in a moment.",variant:"destructive"})}finally{m(!1)}},M=O=>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:[O||s.cta_label||"Book a confidential 15-min call",e.jsx(Xa,{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:[M(),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(ra,{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((O,$)=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold md:text-3xl",style:{color:i},children:O.value}),e.jsx("div",{className:"mt-1 text-xs uppercase tracking-wider text-white/50",children:O.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:qFn(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(vh,{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((O,$)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 transition-colors hover:border-white/25",children:[e.jsx("div",{className:"mb-3 flex h-9 w-9 items-center justify-center rounded-lg",style:{backgroundColor:`${i}22`,color:i},children:e.jsx(da,{className:"h-4 w-4"})}),e.jsx("h3",{className:"mb-2 text-lg font-semibold",children:O.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:O.body}),O.proof&&e.jsx("p",{className:"mt-3 text-xs uppercase tracking-wider text-white/40",children:O.proof})]},$))})]})}),l.calculator!==!1&&b.enabled!==!1&&e.jsx("section",{className:"py-20 md:py-28",children:e.jsx("div",{className:"mx-auto max-w-4xl px-6",children:e.jsxs("div",{className:"rounded-3xl border border-white/10 bg-gradient-to-b from-white/[0.06] to-transparent p-8 md:p-12",children:[e.jsx("h2",{className:"mb-2 text-3xl font-bold tracking-tight md:text-4xl",children:b.title||"Run your own numbers"}),e.jsx("p",{className:"mb-8 text-white/60",children:"Move the slider to your gross commission income for the year."}),e.jsxs("div",{className:"mb-8",children:[e.jsxs("div",{className:"mb-3 flex items-baseline justify-between",children:[e.jsx(se,{className:"text-white/70",children:"Your annual GCI"}),e.jsx("span",{className:"text-2xl font-bold",style:{color:i},children:Gre(v)})]}),e.jsx("input",{type:"range",min:25e3,max:1e6,step:5e3,value:v,onChange:O=>k(Number(O.target.value)),onMouseUp:()=>n==null?void 0:n("calculator_run","calculator",{gci:v}),onTouchEnd:()=>n==null?void 0:n("calculator_run","calculator",{gci:v}),className:"w-full accent-white"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-2xl border border-white/10 p-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-white/45",children:"Where you are now"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-white/80",children:Gre(C.current)})]}),e.jsxs("div",{className:"rounded-2xl border p-5",style:{borderColor:i},children:[e.jsx("div",{className:"text-xs uppercase tracking-wider",style:{color:i},children:"With me"}),e.jsx("div",{className:"mt-2 text-2xl font-bold",children:Gre(C.here)}),C.capped&&e.jsx("div",{className:"mt-1 text-xs text-white/50",children:"You would cap this year."})]}),e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-white/45",children:"Difference"}),e.jsxs("div",{className:"mt-2 text-2xl font-bold",style:{color:i},children:["+",Gre(C.diff)]})]})]}),e.jsx("p",{className:"mt-6 text-xs leading-relaxed text-white/35",children:"Estimates only, based on the assumptions above. Your actual numbers depend on your production and agreements."}),e.jsx("div",{className:"mt-8",children:M("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((O,$)=>e.jsxs("div",{className:"flex gap-4 rounded-2xl border border-white/10 p-6",children:[e.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-sm font-bold",style:{backgroundColor:i,color:"#10131c"},children:$+1}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1.5 font-semibold",children:O.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:O.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((O,$)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(yN,{className:"mb-4 h-6 w-6",style:{color:i}}),e.jsxs("p",{className:"text-sm leading-relaxed text-white/75",children:['"',O.quote,'"']}),e.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[O.photo_url?e.jsx("img",{src:O.photo_url,alt:O.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:O.name}),O.role&&e.jsx("div",{className:"text-xs text-white/45",children:O.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(vO,{type:"single",collapsible:!0,className:"w-full",children:(s.faqs||[]).map((O,$)=>e.jsxs(l6,{value:`faq-${$}`,className:"border-white/10",children:[e.jsx(c6,{className:"text-left text-base font-medium text-white hover:no-underline",children:O.q}),e.jsx(d6,{className:"text-sm leading-relaxed text-white/65",children:O.a})]},$))})]})}),l.lead_magnet!==!1&&((P=s.lead_magnet)==null?void 0:P.enabled)!==!1&&((L=s.lead_magnet)==null?void 0:L.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(ii,{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:O=>{O.preventDefault(),T("lead_magnet",{first_name:y.first_name,email:y.email,message:`Requested: ${s.lead_magnet.title}`})},children:[e.jsx(ye,{required:!0,placeholder:"First name",value:y.first_name,onChange:O=>g($=>({...$,first_name:O.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(ye,{required:!0,type:"email",placeholder:"Email",value:y.email,onChange:O=>g($=>({...$,email:O.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(B,{type:"submit",disabled:h,className:"h-12 shrink-0 font-semibold",style:{backgroundColor:i,color:"#10131c"},children:s.lead_magnet.cta||"Send it"})]})]})})}),l.event!==!1&&((I=s.event_block)==null?void 0:I.title)&&e.jsx("section",{className:"pb-20",children:e.jsx("div",{className:"mx-auto max-w-3xl px-6",children:e.jsxs("div",{className:"flex flex-col items-start justify-between gap-5 rounded-2xl border p-6 md:flex-row md:items-center",style:{borderColor:`${i}55`},children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-xs uppercase tracking-widest",style:{color:i},children:"Coming up"}),e.jsx("div",{className:"text-lg font-semibold",children:s.event_block.title}),s.event_block.when&&e.jsx("div",{className:"text-sm text-white/55",children:s.event_block.when})]}),s.event_block.url&&e.jsx("a",{href:s.event_block.url,target:"_blank",rel:"noreferrer",onClick:()=>n==null?void 0:n("cta_click","event"),className:"rounded-full px-6 py-3 text-sm font-semibold",style:{backgroundColor:i,color:"#10131c"},children:"Save my seat"})]})})}),l.final_cta!==!1&&e.jsxs("section",{id:"connect",className:"relative overflow-hidden py-24",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(200deg, ${a}, #05070d)`}}),e.jsxs("div",{className:"relative z-10 mx-auto max-w-xl px-6",children:[e.jsxs("div",{className:"mb-8 text-center",children:[e.jsx("h2",{className:"mb-3 text-3xl font-bold tracking-tight md:text-4xl",children:"Let's have a confidential conversation"}),e.jsx("p",{className:"text-white/60",children:"No pitch, no pressure. You will get straight answers and your real numbers."})]}),d&&d!=="lead_magnet"?e.jsxs("div",{className:"rounded-3xl border border-white/15 bg-white/5 p-10 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full",style:{backgroundColor:i,color:"#10131c"},children:e.jsx(da,{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(ra,{className:"h-4 w-4"})," Pick a time"]})]}):e.jsxs("form",{onSubmit:O=>{O.preventDefault(),T("attraction_page",p,{gci:v})},className:"space-y-4 rounded-3xl border border-white/10 bg-white/[0.05] p-8 backdrop-blur",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"First name *"}),e.jsx(ye,{required:!0,value:p.first_name,onChange:O=>x($=>({...$,first_name:O.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Last name"}),e.jsx(ye,{value:p.last_name,onChange:O=>x($=>({...$,last_name:O.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Email *"}),e.jsx(ye,{required:!0,type:"email",value:p.email,onChange:O=>x($=>({...$,email:O.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Phone"}),e.jsx(ye,{value:p.phone,onChange:O=>x($=>({...$,phone:O.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"Current brokerage"}),e.jsx(ye,{value:p.brokerage,onChange:O=>x($=>({...$,brokerage:O.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-sm text-white/70",children:"What would you want to know?"}),e.jsx(Ds,{rows:3,value:p.message,onChange:O=>x($=>({...$,message:O.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(_f,{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(pa,{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(Xa,{className:"h-4 w-4"})]})})]})}const Wre=U;function VFn(){const{slug:s}=$i(),[t,n]=j.useState(null),[r,a]=j.useState("loading");j.useEffect(()=>{if(!s)return;let o=!1;return(async()=>{const{data:c,error:d}=await Wre.rpc("public_get_attract_landing_page",{_slug:s});if(!o){if(d||!c||c.error){a("missing");return}n(c),a("ready"),Wre.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&&Wre.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 Wre.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(ql,{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(Mqt,{cfg:t,onSubmitLead:l,onTrack:i})]})}const fvt={media_mode:"photo",show_property_snapshot:!0,show_discover:!0,show_testimonial:!0};function Lqt(s){const t=(s??"").trim();if(!t)return null;const n=t.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{6,})/);if(n)return{kind:"iframe",src:`https://www.youtube.com/embed/${n[1]}`};const r=t.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(r)return{kind:"iframe",src:`https://player.vimeo.com/video/${r[1]}`};const a=t.match(/loom\.com\/(?:share|embed)\/([\w-]+)/);return a?{kind:"iframe",src:`https://www.loom.com/embed/${a[1]}`}:/\.(mp4|webm|mov|m4v)(\?|$)/i.test(t)?{kind:"file",src:t}:{kind:"iframe",src:t}}const Kz=[{id:"fresh_perspective",name:"Fresh Perspective",tagline:"A new set of eyes",description:"Optimistic and forward-looking. Perfect for sellers who are frustrated but still motivated.",accent:"from-sky-500/20 to-sky-500/0",previewHeadline:"A Fresh Look At Your Home",previewBody:"Sometimes all a great home needs is a new perspective — and a plan built for today’s buyer."},{id:"second_chance",name:"Second Chance",tagline:"Empathy first",description:"Warm and human. Acknowledges the disappointment, then pivots to hope and a concrete plan.",accent:"from-amber-500/25 to-amber-500/0",previewHeadline:"Let’s Give Your Home A Second Chance It Deserves",previewBody:"Many great homes don’t sell the first time for reasons that can be fixed with the right strategy."},{id:"luxury_relaunch",name:"Luxury Relaunch",tagline:"Refined & understated",description:"Premium positioning language for higher price points and discerning sellers.",accent:"from-yellow-600/25 to-yellow-600/0",previewHeadline:"A Considered Relaunch For A Distinctive Home",previewBody:"Presentation, positioning and buyer curation — the three levers that move exceptional properties."},{id:"marketing_review",name:"Marketing Review",tagline:"Data forward",description:"Analytical and consultative. Leads with exposure gaps and a marketing scorecard.",accent:"from-emerald-500/22 to-emerald-500/0",previewHeadline:"Your Property Marketing Score",previewBody:"I reviewed your previous listing across six marketing dimensions. Here’s what I found."},{id:"neighborhood_expert",name:"Neighborhood Expert",tagline:"Hyper-local",description:"Leans on local buyer demand and comparable activity in the immediate area.",accent:"from-teal-500/22 to-teal-500/0",previewHeadline:"What’s Really Happening On Your Street",previewBody:"Buyer activity in your neighborhood tells a very different story than the headlines."},{id:"personal_introduction",name:"Personal Introduction",tagline:"Neighbor to neighbor",description:"Conversational and personal — feels like a handwritten note, not a marketing piece.",accent:"from-rose-500/22 to-rose-500/0",previewHeadline:"Hi — I’m Your Neighbor Who Happens To Sell Homes",previewBody:"I noticed your home came off the market and I wanted to reach out personally."},{id:"professional_review",name:"Professional Review",tagline:"Credible & structured",description:"Polished, businesslike and process-driven. Great for analytical sellers.",accent:"from-indigo-500/22 to-indigo-500/0",previewHeadline:"A Professional Review Of Your Previous Listing",previewBody:"A clear, structured assessment — and the exact process I would use to relaunch."}],Pqt=[{id:"professional",name:"Professional",note:"Clean structure, confident tone"},{id:"luxury",name:"Luxury",note:"Serif headlines, gold rules, generous space"},{id:"friendly",name:"Friendly",note:"Warm, conversational, approachable"},{id:"minimal",name:"Minimal",note:"Short, direct, nothing extra"},{id:"modern",name:"Modern",note:"Crisp sans type, bold accents"}],HFn=["New Lead","Attempting Contact","Conversation Started","Nurturing","Appointment Requested","Appointment Scheduled","Listing Presentation","Listing Signed","Long Term Follow Up","Lost"],GFn=[{value:"immediately",label:"As soon as possible"},{value:"1-3",label:"In the next 1–3 months"},{value:"3-6",label:"In 3–6 months"},{value:"6-12",label:"In 6–12 months"},{value:"just_curious",label:"Just curious for now"}],WFn=["Not enough showings","No offers","Marketing felt thin","Communication from my agent","Priced too high","Timing / market conditions","Something else"];function KFn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function YFn(s){const t=KFn(s)||"property",n=Math.random().toString(36).slice(2,7);return`${t}-${n}`}function VE(s){return s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`}const xvt="https://dashboard.relevelup.com";function u$e(){if(typeof window>"u")return xvt;const s=window.location.hostname;return s==="localhost"||s==="127.0.0.1"||s==="dashboard.relevelup.com"?window.location.origin:xvt}function Iqt(s){return`${u$e()}/revival/${s}`}const gvt=[Fr,ol,s0,uu,RR,yn];function yvt(){const s="revival_sid";let t=sessionStorage.getItem(s);return t||(t=Math.random().toString(36).slice(2)+Date.now().toString(36),sessionStorage.setItem(s,t)),t}async function Z8e(s){const{data:t,error:n}=await U.functions.invoke("listing-revival-public",{body:s});if(n)throw n;if(t!=null&&t.error)throw new Error(String(t.error));return t}function ZFn(){var I,O;const{slug:s=""}=$i(),[t]=dc(),[n,r]=j.useState(null),[a,i]=j.useState(!0),[l,o]=j.useState(!1),[c,d]=j.useState(!1),u=j.useRef(null),[h,m]=j.useState({first_name:"",last_name:"",email:"",phone:"",still_selling:"",timeline:"",frustration:"",preferred_contact:"email",comments:"",wants_plan:!0,honeypot:""}),p=($,q)=>m(W=>({...W,[$]:q}));j.useEffect(()=>{let $=!0;return(async()=>{try{const q=await Z8e({action:"get",slug:s});if(!$)return;r(q),await Z8e({action:"track",slug:s,event_type:t.get("src")==="qr"?"qr_scan":"page_view",session_id:yvt(),metadata:{referrer:document.referrer||null}})}catch{$&&r(null)}finally{$&&i(!1)}})(),()=>{$=!1}},[s,t]);const y=((n==null?void 0:n.campaign.content)??{}).landing,g=(n==null?void 0:n.campaign.landing_config)??{},b=(n==null?void 0:n.property)??((I=n==null?void 0:n.campaign)==null?void 0:I.property),v=n==null?void 0:n.agent,k=g.media_mode??"photo",C=Lqt(g.video_url),T=g.media_image_url||(b==null?void 0:b.photo_url)||null;j.useEffect(()=>{b!=null&&b.property_address&&(document.title=`Your Free Property Review — ${b.property_address}`)},[b==null?void 0:b.property_address]);const M=j.useMemo(()=>(y==null?void 0:y.discover)??[],[y]),P=async $=>{if($.preventDefault(),!(!h.first_name.trim()||!h.email.trim()&&!h.phone.trim())){o(!0);try{await Z8e({action:"submit",slug:s,session_id:yvt(),...h}),d(!0),window.scrollTo({top:0,behavior:"smooth"})}catch{o(!1)}}};if(a)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1]",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-[#0f2540]"})});if(!n)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1] px-6 text-center",children:e.jsxs("div",{children:[e.jsx(ia,{className:"h-8 w-8 mx-auto text-[#0f2540]"}),e.jsx("h1",{className:"revival-serif text-2xl mt-3 text-[#0f2540]",children:"This review is no longer available"}),e.jsx("p",{className:"text-[#4a5568] mt-1",children:"The link may have expired. Please reach out to your agent directly."})]})});const L=n.campaign.theme??"estate";return e.jsxs("div",{className:`revival-theme revival-theme-${L} min-h-screen`,children:[e.jsxs("header",{className:"revival-dark relative overflow-hidden",children:[b!=null&&b.photo_url?e.jsx("img",{src:b.photo_url,alt:b.property_address,className:"absolute inset-0 h-full w-full object-cover opacity-25"}):null,e.jsx("div",{className:"relative mx-auto max-w-5xl px-6 py-16 sm:py-24 text-center",children:e.jsxs(br.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},transition:{duration:.6},children:[e.jsx("div",{className:"revival-eyebrow text-accent",children:(y==null?void 0:y.eyebrow)??"A complimentary review"}),e.jsx("h1",{className:"revival-serif text-4xl sm:text-[54px] leading-[1.08] mt-3",children:(y==null?void 0:y.headline)??"Your Free Real Estate Relaunch Review"}),e.jsx("p",{className:"text-white/75 text-lg mt-4 max-w-2xl mx-auto",children:(y==null?void 0:y.subheadline)??"A personalized look at why your home didn’t sell — and exactly what to do next."}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-2 rounded-full bg-white/10 px-4 py-2 text-sm",children:[e.jsx(ia,{className:"h-4 w-4 text-accent"})," ",b==null?void 0:b.property_address]}),e.jsx("div",{className:"mt-8",children:e.jsx(B,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>{var $;return($=u.current)==null?void 0:$.scrollIntoView({behavior:"smooth"})},children:(y==null?void 0:y.cta)??"Get my free review"})})]})})]}),e.jsxs("main",{className:"mx-auto max-w-5xl px-6 py-14 space-y-14",children:[c?e.jsxs(br.div,{initial:{opacity:0,scale:.97},animate:{opacity:1,scale:1},className:"revival-tile p-10 text-center",children:[e.jsx(Rr,{className:"h-12 w-12 mx-auto text-accent"}),e.jsx("h2",{className:"revival-serif text-3xl mt-4",children:"Your review is on its way"}),e.jsxs("p",{className:"text-muted-foreground mt-2 max-w-lg mx-auto",children:[(v==null?void 0:v.name)??"Your agent"," has been notified and will personally prepare your Property Revival Plan. Watch your inbox — you’ll hear back shortly."]}),e.jsx(B,{className:"mt-6",asChild:!0,children:e.jsx("a",{href:`/revival/${s}/plan`,children:"View your Property Revival Plan"})})]}):null,e.jsxs("section",{className:`grid gap-8 items-center ${k==="none"?"":"lg:grid-cols-2"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"revival-eyebrow text-muted-foreground",children:["A word from ",(v==null?void 0:v.name)??"your agent"]}),e.jsx("p",{className:"mt-3 text-lg leading-relaxed",children:y==null?void 0:y.intro}),v?e.jsxs("div",{className:"mt-6 flex items-center gap-4",children:[v.avatar_url?e.jsx("img",{src:v.avatar_url,alt:v.name??"",className:"h-14 w-14 rounded-full object-cover"}):null,e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:v.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[v.title??"Real Estate Specialist",v.brokerage_name?` · ${v.brokerage_name}`:""]})]})]}):null]}),k==="video"&&C?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"revival-tile aspect-video overflow-hidden",children:C.kind==="file"?e.jsx("video",{src:C.src,controls:!0,playsInline:!0,className:"h-full w-full object-cover"}):e.jsx("iframe",{src:C.src,title:"Agent introduction",className:"h-full w-full",allowFullScreen:!0})}),g.video_caption?e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:g.video_caption}):null]}):k==="photo"&&T?e.jsx("div",{className:"revival-tile aspect-video overflow-hidden",children:e.jsx("img",{src:T,alt:(b==null?void 0:b.property_address)??"Property",className:"h-full w-full object-cover"})}):k!=="none"?e.jsx("div",{className:"revival-tile aspect-video grid place-items-center bg-muted/70",children:e.jsxs("div",{className:"text-center",children:[e.jsx(vh,{className:"h-12 w-12 mx-auto text-accent"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["A personal introduction from ",(v==null?void 0:v.name)??"your agent"]})]})}):null]}),b&&g.show_property_snapshot!==!1?e.jsxs("section",{className:"revival-tile overflow-hidden grid md:grid-cols-[1.1fr_1fr]",children:[b.photo_url?e.jsx("img",{src:b.photo_url,alt:b.property_address,className:"h-full w-full object-cover min-h-[220px]"}):e.jsx("div",{className:"revival-dark min-h-[220px]"}),e.jsxs("div",{className:"p-7",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Your property"}),e.jsx("h3",{className:"revival-serif text-2xl mt-1",children:b.property_address}),e.jsx("p",{className:"text-muted-foreground",children:[b.city,b.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Original"}),e.jsx("div",{className:"text-lg font-semibold",children:VE(b.original_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Final"}),e.jsx("div",{className:"text-lg font-semibold",children:VE(b.final_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Days listed"}),e.jsx("div",{className:"text-lg font-semibold",children:b.days_on_market??"—"})]})]})]})]}):null,M.length&&g.show_discover!==!1?e.jsxs("section",{children:[e.jsx("h2",{className:"revival-serif text-3xl text-center",children:"Inside your free review"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 mt-7",children:M.map(($,q)=>{const W=gvt[q%gvt.length];return e.jsxs(br.div,{initial:{opacity:0,y:18},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{delay:q*.06,duration:.45},className:"revival-tile p-6",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-accent/15 grid place-items-center",children:e.jsx(W,{className:"h-5 w-5 text-accent-foreground"})}),e.jsx("div",{className:"font-semibold mt-3",children:$.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:$.body})]},q)})})]}):null,(O=y==null?void 0:y.testimonial)!=null&&O.quote&&g.show_testimonial!==!1?e.jsxs("section",{className:"revival-dark rounded-3xl p-10 text-center",children:[e.jsxs("p",{className:"revival-serif text-2xl leading-relaxed max-w-3xl mx-auto",children:["“",y.testimonial.quote,"”"]}),e.jsx("p",{className:"text-accent text-sm mt-4 uppercase tracking-[0.2em]",children:y.testimonial.author})]}):null,e.jsxs("section",{ref:u,className:"revival-tile p-7 sm:p-10",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"No obligation, no pressure"}),e.jsx("h2",{className:"revival-serif text-3xl mt-1",children:"Request your free review"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Takes 60 seconds. Your information is never shared."})]}),e.jsxs("form",{onSubmit:P,className:"grid gap-4 sm:grid-cols-2 mt-7 max-w-2xl mx-auto",children:[e.jsx("input",{type:"text",tabIndex:-1,autoComplete:"off",className:"hidden",value:h.honeypot,onChange:$=>p("honeypot",$.target.value)}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"First name *"}),e.jsx(ye,{required:!0,value:h.first_name,onChange:$=>p("first_name",$.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Last name"}),e.jsx(ye,{value:h.last_name,onChange:$=>p("last_name",$.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{type:"email",value:h.email,onChange:$=>p("email",$.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:h.phone,onChange:$=>p("phone",$.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Are you still interested in selling?"}),e.jsxs(vs,{value:h.still_selling,onValueChange:$=>p("still_selling",$),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"yes",children:"Yes"}),e.jsx(Je,{value:"maybe",children:"Maybe — depends on the plan"}),e.jsx(Je,{value:"no",children:"Not right now"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Your timeline"}),e.jsxs(vs,{value:h.timeline,onValueChange:$=>p("timeline",$),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one"})}),e.jsx(ys,{children:GFn.map($=>e.jsx(Je,{value:$.value,children:$.label},$.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Biggest frustration last time"}),e.jsxs(vs,{value:h.frustration,onValueChange:$=>p("frustration",$),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select one"})}),e.jsx(ys,{children:WFn.map($=>e.jsx(Je,{value:$,children:$},$))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Preferred contact method"}),e.jsxs(vs,{value:h.preferred_contact,onValueChange:$=>p("preferred_contact",$),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"email",children:"Email"}),e.jsx(Je,{value:"phone",children:"Phone call"}),e.jsx(Je,{value:"text",children:"Text message"})]})]})]}),e.jsxs("div",{className:"sm:col-span-2 space-y-1.5",children:[e.jsx(se,{children:"Anything you'd like me to know?"}),e.jsx(Ds,{rows:3,value:h.comments,onChange:$=>p("comments",$.target.value)})]}),e.jsxs("label",{className:"sm:col-span-2 flex items-center gap-3 text-sm",children:[e.jsx(wi,{checked:h.wants_plan,onCheckedChange:$=>p("wants_plan",!!$)}),"Send me the full Property Revival Plan for my home"]}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx(B,{type:"submit",size:"lg",className:"w-full bg-accent text-accent-foreground hover:bg-accent/90",disabled:l,children:l?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending…"]}):(y==null?void 0:y.cta)??"Get my free review"})})]})]})]}),e.jsxs("footer",{className:"revival-dark py-10 text-center",children:[e.jsx("div",{className:"text-lg font-semibold",children:v==null?void 0:v.name}),e.jsx("div",{className:"text-accent text-sm",children:(v==null?void 0:v.title)??"Real Estate Specialist"}),e.jsx("div",{className:"text-white/60 text-sm mt-2",children:[v==null?void 0:v.phone,v==null?void 0:v.email].filter(Boolean).join(" · ")}),v!=null&&v.brokerage_name?e.jsx("div",{className:"text-white/40 text-xs mt-3",children:v.brokerage_name}):null]})]})}const h_="#0f2540",$k="#c9a227";function yG({children:s,className:t,footer:n,page:r}){return e.jsxs("div",{"data-revival-plan-page":"",className:Et("revival-plan-page relative mx-auto w-full max-w-[816px] bg-white text-[#1a2230]","aspect-[8.5/11] overflow-hidden flex flex-col shadow-[0_30px_70px_-40px_rgba(15,37,64,.6)]",t),children:[s,n!==void 0?e.jsxs("div",{className:"absolute bottom-0 inset-x-0 flex items-center justify-between px-10 pb-6 text-[10px] tracking-[0.22em] uppercase text-[#0f2540]/45",children:[e.jsx("span",{children:n}),r?e.jsx("span",{children:String(r).padStart(2,"0")}):null]}):null]})}function Kre({eyebrow:s,title:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:$k},children:s}),e.jsx("h2",{className:"revival-serif text-[30px] leading-tight mt-1",style:{color:h_},children:t}),e.jsx("div",{className:"mt-3 h-[3px] w-14 rounded-full",style:{background:$k}})]})}function XFn({label:s,value:t}){const n=Math.max(0,Math.min(5,Number(t)||0));return e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 px-4 py-3",children:[e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("span",{className:"text-[12.5px] font-semibold capitalize",style:{color:h_},children:s.replace(/_/g," ")}),e.jsxs("span",{className:"text-[12px] tabular-nums text-[#0f2540]/60",children:[n," ",e.jsx("span",{className:"text-[10px]",children:"/ 5"})]})]}),e.jsx("div",{className:"mt-2 flex gap-1",children:[1,2,3,4,5].map(r=>e.jsx("span",{className:"h-[6px] flex-1 rounded-full",style:{background:r<=n?$k:"rgba(15,37,64,.10)"}},r))})]})}function h$e({plan:s,property:t,agent:n,url:r,className:a}){var u,h,m;const i=t.property_address??"Your Property",l=[t.city,t.state].filter(Boolean).join(", "),o=Object.entries((s==null?void 0:s.scores)??{}),c=(s==null?void 0:s.strategy_weeks)??[],d=n.name?`${n.name} · Property Revival Plan`:"Property Revival Plan";return e.jsxs("div",{className:Et("space-y-8",a),children:[e.jsxs(yG,{children:[e.jsxs("div",{className:"relative h-[52%] overflow-hidden",style:{background:h_},children:[t.photo_url?e.jsx("img",{src:t.photo_url,alt:i,className:"absolute inset-0 h-full w-full object-cover opacity-55"}):null,e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(180deg, rgba(15,37,64,.35), ${h_})`}}),e.jsxs("div",{className:"relative h-full flex flex-col justify-end px-12 pb-9 text-white",children:[n.brokerage_name?e.jsx("div",{className:"text-[10.5px] tracking-[0.3em] uppercase text-white/70 font-bold",children:n.brokerage_name}):null,e.jsxs("div",{className:"text-[11px] tracking-[0.3em] uppercase font-bold mt-3",style:{color:$k},children:["Prepared exclusively for ",t.seller_name||"you"]}),e.jsx("h1",{className:"revival-serif text-[46px] leading-[1.05] mt-2",children:"Property Revival Plan"}),e.jsxs("p",{className:"text-white/80 mt-2 text-[15px]",children:[i,l?` · ${l}`:""]})]})]}),e.jsxs("div",{className:"flex-1 px-12 pt-8 flex flex-col",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[{k:"Original price",v:VE(t.original_price)},{k:"Final price",v:VE(t.final_price)},{k:"Days on market",v:t.days_on_market??"—"}].map(p=>e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 px-4 py-4 text-center",children:[e.jsx("div",{className:"text-[9.5px] tracking-[0.22em] uppercase text-[#0f2540]/50",children:p.k}),e.jsx("div",{className:"text-[20px] font-bold mt-1",style:{color:h_},children:p.v})]},p.k))}),s!=null&&s.intro?e.jsx("p",{className:"mt-7 text-[14.5px] leading-7 text-[#28313f]",children:s.intro}):null,e.jsxs("div",{className:"mt-auto mb-12 flex items-center gap-5 border-t border-[#0f2540]/10 pt-6",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:n.name??"",className:"h-[74px] w-[74px] rounded-full object-cover"}):null,e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[17px] font-bold",style:{color:h_},children:n.name}),e.jsxs("div",{className:"text-[12px] text-[#0f2540]/60",children:[n.title??"Real Estate Specialist",n.brokerage_name?` · ${n.brokerage_name}`:""]}),e.jsx("div",{className:"text-[12px] text-[#0f2540]/70 mt-1",children:[n.phone,n.email].filter(Boolean).join(" · ")})]}),r?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"rounded-lg border border-[#0f2540]/15 p-2 bg-white",children:e.jsx(PN,{value:r,size:64,level:"M",fgColor:h_})}),e.jsx("div",{className:"text-[8.5px] tracking-[0.18em] uppercase text-[#0f2540]/45 mt-1",children:"View online"})]}):null]})]})]}),o.length?e.jsx(yG,{footer:d,page:2,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Kre,{eyebrow:"Section One",title:"Marketing scorecard"}),e.jsx("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:"A review of how the previous listing performed across the six areas that most influence a sale. Each area is rated on a 1–5 scale, where 5 means the listing was doing everything today’s buyers respond to."}),e.jsx("div",{className:"mt-6 grid grid-cols-2 gap-3",children:o.map(([p,x])=>e.jsx(XFn,{label:p,value:Number(x)},p))}),(u=s==null?void 0:s.buyers_experienced)!=null&&u.length?e.jsxs("div",{className:"mt-8",children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:$k},children:"What buyers experienced"}),e.jsx("ul",{className:"mt-3 space-y-2",children:s.buyers_experienced.slice(0,5).map((p,x)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px] leading-6 text-[#28313f]",children:[e.jsx("span",{className:"mt-[7px] h-[6px] w-[6px] shrink-0 rounded-full",style:{background:$k}}),p]},x))})]}):null]})}):null,(h=s==null?void 0:s.differently)!=null&&h.length?e.jsx(yG,{footer:d,page:3,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Kre,{eyebrow:"Section Two",title:"What we would do differently"}),e.jsxs("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:["Every point below is part of the plan for ",i," — not a general list."]}),e.jsx("div",{className:"mt-6 grid grid-cols-2 gap-3",children:s.differently.slice(0,10).map((p,x)=>e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 px-4 py-3 flex gap-3",children:[e.jsx("span",{className:"h-[22px] w-[22px] shrink-0 rounded-full grid place-items-center text-[11px] font-bold text-white",style:{background:h_},children:x+1}),e.jsx("span",{className:"text-[13px] leading-6 text-[#28313f]",children:p})]},x))})]})}):null,c.length?e.jsx(yG,{footer:d,page:4,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Kre,{eyebrow:"Section Three",title:"Your relaunch strategy"}),e.jsxs("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:["A week-by-week plan for bringing ",i," back to market with momentum."]}),e.jsx("div",{className:"mt-6 space-y-3",children:c.slice(0,5).map((p,x)=>e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 p-5 flex gap-5",children:[e.jsx("div",{className:"h-11 w-11 shrink-0 rounded-xl grid place-items-center text-white font-bold",style:{background:h_},children:x+1}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] tracking-[0.26em] uppercase font-bold",style:{color:$k},children:p.week}),e.jsx("div",{className:"text-[16px] font-semibold mt-0.5",style:{color:h_},children:p.title}),e.jsx("p",{className:"text-[13px] leading-6 text-[#28313f] mt-1",children:p.body})]})]},x))})]})}):null,e.jsx(yG,{footer:d,page:5,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Kre,{eyebrow:"Section Four",title:"Your next steps"}),(m=s==null?void 0:s.questions)!=null&&m.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-5 text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:$k},children:"Questions to ask any agent"}),e.jsx("ol",{className:"mt-3 space-y-2",children:s.questions.slice(0,6).map((p,x)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px] leading-6 text-[#28313f]",children:[e.jsxs("span",{className:"text-[12px] font-bold tabular-nums",style:{color:h_},children:[x+1,"."]}),p]},x))})]}):null,e.jsxs("div",{className:"mt-8 rounded-2xl p-8 text-white",style:{background:h_},children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:$k},children:"An invitation"}),e.jsx("p",{className:"mt-3 text-[14.5px] leading-7 text-white/85",children:(s==null?void 0:s.invitation)??"Let’s walk through this plan together — no pressure, just helpful guidance."}),e.jsxs("div",{className:"mt-6 flex items-center gap-5",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:n.name??"",className:"h-[64px] w-[64px] rounded-full object-cover"}):null,e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[16px] font-bold",children:n.name}),e.jsx("div",{className:"text-[12px] text-white/60",children:n.title??"Real Estate Specialist"}),e.jsx("div",{className:"text-[12.5px] mt-1",style:{color:$k},children:[n.phone,n.email,n.website_url].filter(Boolean).join(" · ")})]}),r?e.jsx("div",{className:"rounded-lg bg-white p-2",children:e.jsx(PN,{value:r,size:60,level:"M",fgColor:h_})}):null]})]})]})})]})}const vG=[15,37,64],X8e=[201,162,39],vvt=[31,41,55],Yre=[107,114,128];async function QFn(s,t=8){return Qq.toDataURL(s,{margin:0,scale:t,color:{dark:"#0f2540",light:"#ffffff"}})}function JFn(s){return[s.title,s.brokerage_name,s.phone,s.email,s.website_url].filter(Boolean).map(String)}function sZe(s){return s.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase().slice(0,60)}async function e7n(s){const{campaign:t,agent:n,url:r,photoDataUrl:a}=s,i=t.property,l=new ho({unit:"pt",format:[648,432],orientation:"landscape"}),o=648,c=432;if(l.setFillColor(...vG),l.rect(0,0,o,c,"F"),a)try{l.addImage(a,"JPEG",0,0,o,c*.62)}catch{}l.setFillColor(...vG),l.rect(0,c*.6,o,c*.4,"F"),l.setFillColor(...X8e),l.rect(0,c*.6-4,o,4,"F"),l.setTextColor(...X8e),l.setFont("helvetica","bold"),l.setFontSize(9),l.text("LISTING REVIVAL",44,c*.6+34),l.setTextColor(255,255,255),l.setFont("times","normal"),l.setFontSize(28),l.text(l.splitTextToSize(s.headline??"Your home deserves a second chance.",o-88),44,c*.6+68),l.setFont("helvetica","normal"),l.setFontSize(11),l.setTextColor(220,224,232),l.text(l.splitTextToSize(s.subhead??`A complimentary marketing review for ${(i==null?void 0:i.property_address)??"your property"}.`,o-88),44,c*.6+118),l.addPage([648,432],"landscape"),l.setFillColor(255,255,255),l.rect(0,0,o,c,"F"),l.setFillColor(...vG),l.rect(0,0,10,c,"F");const d=44;l.setTextColor(...vG),l.setFont("times","normal"),l.setFontSize(19),l.text(n.name??"",d,54),l.setFont("helvetica","normal"),l.setFontSize(9),l.setTextColor(...Yre),l.text(JFn(n).join(" · "),d,72,{maxWidth:o/2+40}),l.setDrawColor(...X8e),l.setLineWidth(1),l.line(d,88,o/2+60,88),l.setTextColor(...vvt),l.setFont("times","normal"),l.setFontSize(11.5);const u=s.message??`I noticed ${(i==null?void 0:i.property_address)??"your home"} recently came off the market. I put together a private, no-obligation review of what buyers saw — and exactly what I would do differently to get it sold. Scan the code and it's yours in seconds.`;l.text(l.splitTextToSize(u,o/2+16),d,112);const h=await QFn(r);l.addImage(h,"PNG",d,c-150,108,108),l.setFont("helvetica","bold"),l.setFontSize(10),l.setTextColor(...vG),l.text("Scan for your free review",d+122,c-112),l.setFont("helvetica","normal"),l.setFontSize(8.5),l.setTextColor(...Yre),l.text(r,d+122,c-96,{maxWidth:220});const m=o/2+96;l.setDrawColor(210,214,220),l.setLineWidth(.7),l.rect(m,132,o-m-44,116),l.setFontSize(8),l.setTextColor(...Yre),l.text("MAILING ADDRESS",m+10,126),l.setFontSize(11),l.setTextColor(...vvt),[(i==null?void 0:i.seller_name)??"Current Resident",(i==null?void 0:i.mailing_address)??(i==null?void 0:i.property_address)??"",[(i==null?void 0:i.mailing_city)??(i==null?void 0:i.city),(i==null?void 0:i.mailing_state)??(i==null?void 0:i.state),(i==null?void 0:i.mailing_zip)??(i==null?void 0:i.zip)].filter(Boolean).join(", ")].filter(Boolean).forEach((x,y)=>l.text(String(x),m+14,162+y*18,{maxWidth:o-m-72})),l.setDrawColor(210,214,220),l.rect(o-118,40,74,62),l.setFontSize(7.5),l.setTextColor(...Yre),l.text("POSTAGE",o-96,74),l.save(`revival-postcard-${sZe((i==null?void 0:i.property_address)??t.name)}.pdf`)}async function Rqt(s){try{const n=await(await fetch(s,{mode:"cors"})).blob();return await new Promise(r=>{const a=new FileReader;a.onloadend=()=>r(String(a.result)),a.onerror=()=>r(null),a.readAsDataURL(n)})}catch{return null}}async function t7n(s,t){const{toPng:n}=await Mi(async()=>{const{toPng:d}=await Promise.resolve().then(()=>cMt);return{toPng:d}},void 0),r=Array.from(s.querySelectorAll("img")),a=r.map(d=>d.getAttribute("src")??"");await Promise.all(r.map(async(d,u)=>{const h=a[u];if(!h||h.startsWith("data:"))return;const m=await Rqt(h);m&&d.setAttribute("src",m)}));let i;try{i=await n(s,{pixelRatio:3,cacheBust:!0,backgroundColor:"#ffffff",width:s.offsetWidth,height:s.offsetHeight})}finally{r.forEach((d,u)=>{a[u]&&d.setAttribute("src",a[u])})}const l=new ho({unit:"pt",format:"letter",compress:!0}),o=l.internal.pageSize.getWidth(),c=l.internal.pageSize.getHeight();l.addImage(i,"PNG",0,0,o,c,void 0,"FAST"),l.save(`revival-letter-${sZe(t)}.pdf`)}async function Dqt(s,t){const{toPng:n}=await Mi(async()=>{const{toPng:d}=await Promise.resolve().then(()=>cMt);return{toPng:d}},void 0),r=Array.from(s.querySelectorAll("[data-revival-plan-page]"));if(!r.length)return;const a=Array.from(s.querySelectorAll("img")),i=a.map(d=>d.getAttribute("src")??"");await Promise.all(a.map(async(d,u)=>{const h=i[u];if(!h||h.startsWith("data:"))return;const m=await Rqt(h);m&&d.setAttribute("src",m)}));const l=new ho({unit:"pt",format:"letter",compress:!0}),o=l.internal.pageSize.getWidth(),c=l.internal.pageSize.getHeight();try{for(let d=0;d0&&l.addPage(),l.addImage(h,"PNG",0,0,o,c,void 0,"FAST")}}finally{a.forEach((d,u)=>{i[u]&&d.setAttribute("src",i[u])})}l.save(`revival-plan-${sZe(t)}.pdf`)}function bvt(){var m,p,x;const{slug:s=""}=$i(),[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(!1),o=j.useRef(null),c=((m=t==null?void 0:t.campaign)==null?void 0:m.property)??(t==null?void 0:t.property)??null,d=async()=>{if(o.current){l(!0);try{await Dqt(o.current,(c==null?void 0:c.property_address)??"plan")}finally{l(!1)}}};if(j.useEffect(()=>{let y=!0;return(async()=>{try{const{data:g,error:b}=await U.functions.invoke("listing-revival-public",{body:{action:"get",slug:s}});if(b)throw b;if(!y)return;n(g),await U.functions.invoke("listing-revival-public",{body:{action:"track",slug:s,event_type:"plan_view"}})}catch{y&&n(null)}finally{y&&a(!1)}})(),()=>{y=!1}},[s]),j.useEffect(()=>{c!=null&&c.property_address&&(document.title=`Property Revival Plan — ${c.property_address}`)},[c==null?void 0:c.property_address]),r)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1]",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-[#0f2540]"})});if(!t||!((x=(p=t.campaign)==null?void 0:p.content)!=null&&x.plan))return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1] px-6 text-center",children:e.jsxs("div",{children:[e.jsx(ia,{className:"h-8 w-8 mx-auto text-[#0f2540]"}),e.jsx("h1",{className:"revival-serif text-2xl mt-3 text-[#0f2540]",children:"This plan is no longer available"})]})});const{agent:u}=t,h=t.campaign.content.plan;return e.jsxs("div",{className:`revival-theme revival-theme-${t.campaign.theme??"estate"} min-h-screen bg-[#f7f5f1]`,children:[e.jsxs("div",{className:"mx-auto max-w-[900px] px-4 sm:px-6 py-8 sm:py-12",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-6",children:[e.jsxs("div",{className:"revival-eyebrow text-[#0f2540]/60",children:["Prepared for ",(c==null?void 0:c.property_address)??"your home"]}),e.jsxs("button",{onClick:d,disabled:i,className:"inline-flex items-center gap-2 rounded-full bg-[#0f2540] text-white px-5 py-2.5 text-sm font-semibold disabled:opacity-60",children:[i?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(ii,{className:"h-4 w-4"}),"Download PDF"]})]}),e.jsx("div",{ref:o,children:e.jsx(h$e,{plan:h,property:c??{property_address:"",city:null,state:null,photo_url:null,original_price:null,final_price:null,days_on_market:null},agent:u})}),u!=null&&u.phone||u!=null&&u.email?e.jsxs("div",{className:"mt-10 flex flex-wrap justify-center gap-3",children:[u.phone?e.jsxs("a",{href:`tel:${u.phone}`,className:"rounded-full bg-[#c9a227] text-[#0f2540] px-6 py-3 font-semibold",children:["Call ",u.phone]}):null,u.email?e.jsxs("a",{href:`mailto:${u.email}`,className:"rounded-full border border-[#0f2540]/25 text-[#0f2540] px-6 py-3 font-semibold",children:["Email ",u.name]}):null]}):null]}),e.jsxs("footer",{className:"py-10 text-center border-t border-border",children:[u!=null&&u.avatar_url?e.jsx("img",{src:u.avatar_url,alt:u.name??"",className:"h-16 w-16 rounded-full object-cover mx-auto"}):null,e.jsx("div",{className:"text-lg font-semibold mt-3",children:u==null?void 0:u.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(u==null?void 0:u.title)??"Real Estate Specialist"}),u!=null&&u.brokerage_name?e.jsx("div",{className:"text-xs text-muted-foreground mt-2",children:u.brokerage_name}):null]})]})}function s7n(){const{user:s}=Ns();return mt({queryKey:["revival-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_campaigns").select("*, property:listing_revival_properties(*)").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function n7n(s){return mt({queryKey:["revival-campaign",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_campaigns").select("*, property:listing_revival_properties(*)").eq("id",s).maybeSingle();if(n)throw n;return t??null}})}function r7n(){const{user:s}=Ns();return mt({queryKey:["revival-properties",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_properties").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function Oqt(){const{user:s}=Ns();return mt({queryKey:["revival-leads",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_leads").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function a7n(){const{user:s}=Ns();return mt({queryKey:["revival-tasks",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_tasks").select("*").order("due_date",{ascending:!0});if(n)throw n;return t??[]}})}function Fqt(){const{user:s}=Ns();return mt({queryKey:["revival-events",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("listing_revival_events").select("*").order("created_at",{ascending:!1}).limit(1e3);if(n)throw n;return t??[]}})}function nZe(){const s=as(),t=()=>{["revival-campaigns","revival-campaign","revival-properties","revival-leads","revival-tasks","revival-events"].forEach(o=>s.invalidateQueries({queryKey:[o]}))},n=vt({mutationFn:async o=>{const{data:c,error:d}=await U.functions.invoke("listing-revival-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(String(c.error));return c},onSuccess:t,onError:o=>re.error(o.message)}),r=vt({mutationFn:async o=>{const{error:c}=await U.from("listing_revival_campaigns").update(o.patch).eq("id",o.id);if(c)throw c},onSuccess:()=>{t(),re.success("Saved")},onError:o=>re.error(o.message)}),a=vt({mutationFn:async o=>{const{error:c}=await U.from("listing_revival_campaigns").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t(),re.success("Campaign deleted")},onError:o=>re.error(o.message)}),i=vt({mutationFn:async o=>{const{error:c}=await U.from("listing_revival_campaigns").update({status:o.archived?"archived":"active",published:!o.archived}).eq("id",o.id);if(c)throw c;return o},onSuccess:o=>{t(),re.success(o.archived?"Campaign archived":"Campaign restored")},onError:o=>re.error(o.message)}),l=vt({mutationFn:async o=>{const{error:c}=await U.from("listing_revival_tasks").update({completed_at:o.done?new Date().toISOString():null}).eq("id",o.id);if(c)throw c},onSuccess:t,onError:o=>re.error(o.message)});return{generate:n,saveCampaign:r,deleteCampaign:a,archiveCampaign:i,toggleTask:l,invalidate:t}}const i7n=[{id:"dashboard",label:"Dashboard",icon:vf},{id:"campaigns",label:"Campaigns",icon:yn},{id:"properties",label:"Properties",icon:ia},{id:"letters",label:"Letters",icon:on},{id:"landing",label:"Landing Pages",icon:Ql},{id:"plans",label:"Revival Plans",icon:$r},{id:"followup",label:"Follow Up",icon:r1},{id:"analytics",label:"Analytics",icon:ol},{id:"templates",label:"Templates",icon:q_},{id:"settings",label:"Settings",icon:tE}];function V1({label:s,value:t,icon:n,delay:r=0,hint:a}){return e.jsxs(br.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:r,duration:.45,ease:[.22,1,.36,1]},className:"revival-tile p-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("span",{className:"revival-eyebrow text-muted-foreground",children:s}),e.jsx(n,{className:"h-4 w-4 text-accent"})]}),e.jsx("div",{className:"mt-3 text-3xl font-bold tabular-nums tracking-tight",children:t}),a?e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:a}):null]})}function o7n(){const s=Hn(),[t,n]=j.useState("dashboard"),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(null),d=zCn(),u=s7n(),h=r7n(),m=Oqt(),p=a7n(),x=Fqt(),{toggleTask:y,archiveCampaign:g,deleteCampaign:b}=nZe(),v=u.data??[],k=m.data??[],C=x.data??[],T=p.data??[],M=j.useMemo(()=>{const G=K=>C.filter(ee=>ee.event_type===K).length;return{properties:(h.data??[]).length,campaigns:v.length,letters:v.filter(K=>{var ee;return(ee=K.content)==null?void 0:ee.letter}).length,qr:G("qr_scan"),visits:G("page_view"),planViews:G("plan_view"),leads:k.length,appointments:G("appointment"),won:k.filter(K=>K.stage==="listing_signed").length,hot:k.filter(K=>K.temperature==="hot").length}},[v,k,C,h.data]),P=j.useMemo(()=>{const G=[];for(let K=13;K>=0;K--){const ee=new Date(Date.now()-K*864e5),J=ee.toISOString().slice(0,10);G.push({day:Bs(ee,"MMM d"),visits:C.filter(le=>le.event_type==="page_view"&&le.created_at.startsWith(J)).length,scans:C.filter(le=>le.event_type==="qr_scan"&&le.created_at.startsWith(J)).length,leads:k.filter(le=>le.created_at.startsWith(J)).length})}return G},[C,k]),L=G=>G.status==="archived",I=v.filter(G=>{var ee,J;if(i?!L(G):L(G))return!1;const K=r.trim().toLowerCase();return K?`${G.name} ${((ee=G.property)==null?void 0:ee.property_address)??""} ${((J=G.property)==null?void 0:J.seller_name)??""}`.toLowerCase().includes(K):!0}),O=v.filter(L).length,$=G=>s(`/apps/listing-revival/campaigns/${G}`),q=G=>{navigator.clipboard.writeText(Iqt(G)),re.success("Landing page link copied")},W=G=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative max-w-sm flex-1 min-w-[200px]",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:r,onChange:K=>a(K.target.value),placeholder:"Search campaigns…",className:"pl-9"})]}),e.jsxs(B,{variant:i?"default":"outline",size:"sm",onClick:()=>l(K=>!K),children:[e.jsx(gm,{className:"h-3.5 w-3.5 mr-1.5"}),i?"Viewing archived":`Archived (${O})`]})]}),I.length===0?e.jsx("div",{className:"revival-tile p-10 text-center text-muted-foreground",children:i?"No archived campaigns.":G}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:I.map((K,ee)=>{var ie,de,we,je;const J=Kz.find(xe=>xe.id===K.style),le=k.filter(xe=>xe.campaign_id===K.id).length,ue=C.filter(xe=>xe.campaign_id===K.id&&xe.event_type==="page_view").length,oe=L(K);return e.jsxs(br.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:Math.min(ee*.04,.3),duration:.4},className:Et("revival-tile overflow-hidden",oe&&"opacity-80"),children:[e.jsxs("div",{className:"h-28 bg-muted relative",children:[(ie=K.property)!=null&&ie.photo_url?e.jsx("img",{src:K.property.photo_url,alt:K.property.property_address??"",className:"h-full w-full object-cover",loading:"lazy"}):e.jsx("div",{className:"h-full w-full revival-dark grid place-items-center",children:e.jsx(ia,{className:"h-7 w-7 text-accent"})}),e.jsx(qe,{className:"absolute top-3 left-3 bg-background/90 text-foreground border-0",children:(J==null?void 0:J.name)??K.style}),oe?e.jsx(qe,{className:"absolute top-3 right-3 bg-foreground/85 text-background border-0",children:"Archived"}):null]}),e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight",children:((de=K.property)==null?void 0:de.property_address)??K.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:((we=K.property)==null?void 0:we.seller_name)??"Homeowner"}),e.jsxs("div",{className:"mt-3 flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),ue]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),le]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3.5 w-3.5"}),((je=K.property)==null?void 0:je.days_on_market)??"—"," DOM"]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs(B,{size:"sm",className:"flex-1",onClick:()=>$(K.id),children:["Open ",e.jsx(Xa,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>q(K.slug),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:`/revival/${K.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{size:"sm",variant:"outline",children:e.jsx(W0,{className:"h-3.5 w-3.5"})})}),e.jsxs(xd,{align:"end",children:[e.jsx(wa,{onClick:()=>g.mutate({id:K.id,archived:!oe}),children:oe?e.jsxs(e.Fragment,{children:[e.jsx(zT,{className:"h-4 w-4 mr-2"})," Restore campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(gm,{className:"h-4 w-4 mr-2"})," Archive campaign"]})}),e.jsx(uy,{}),e.jsxs(wa,{className:"text-destructive focus:text-destructive",onClick:()=>{var xe;return c({id:K.id,name:((xe=K.property)==null?void 0:xe.property_address)??K.name})},children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"})," Delete permanently"]})]})]})]})]})]},K.id)})}),e.jsx(Nl,{open:!!o,onOpenChange:K=>!K&&c(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete this campaign?"}),e.jsxs(xl,{children:[o==null?void 0:o.name," — the letter, landing page, QR link, plan and follow-up tasks will be permanently removed. This can't be undone. Archive instead if you may need it later."]})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{o&&b.mutate(o.id),c(null)},children:"Delete permanently"})]})]})})]});return!d.isLoading&&!d.hasAccess?e.jsx(Vs,{title:"Listing Revival",children:e.jsx("div",{className:"revival-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)] grid place-items-center",children:e.jsxs("div",{className:"revival-tile p-10 text-center max-w-lg",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-2xl revival-dark grid place-items-center",children:e.jsx(yn,{className:"h-6 w-6 text-accent"})}),e.jsx("h2",{className:"revival-serif text-2xl mt-4",children:"Listing Revival is invite-only"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"This tool is currently being rolled out to select LevelUp members. Reach out to your coach to request early access."})]})})}):e.jsx(Vs,{title:"Listing Revival",children:e.jsxs("div",{className:"revival-theme relative -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(br.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},transition:{duration:.55,ease:[.22,1,.36,1]},className:"revival-dark rounded-3xl px-6 sm:px-10 py-9 relative overflow-hidden",children:[e.jsx("div",{className:"absolute -right-10 -top-16 h-56 w-56 rounded-full bg-accent/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"revival-eyebrow text-accent",children:"Listing Revival"}),e.jsx("h1",{className:"revival-serif text-3xl sm:text-[42px] leading-tight mt-2 max-w-2xl",children:"Turn Expired Listings Into Listing Appointments."}),e.jsx("p",{className:"text-white/70 mt-3 max-w-xl",children:"Import a property, choose a style, click once. Your letter, QR code, landing page, Property Revival Plan, emails, texts and follow-up tasks are built in under two minutes."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsxs(B,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>s("/apps/listing-revival/new"),children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," New Campaign"]}),e.jsx(B,{size:"lg",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>n("campaigns"),children:"View campaigns"})]})]})]}),e.jsxs(fa,{value:t,onValueChange:n,className:"mt-6",children:[e.jsx(xa,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:i7n.map(G=>e.jsxs(ss,{value:G.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm whitespace-nowrap",children:[e.jsx(G.icon,{className:"h-3.5 w-3.5 mr-1.5"}),G.label]},G.id))}),e.jsxs(ns,{value:"dashboard",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-5",children:[e.jsx(V1,{label:"Properties",value:M.properties,icon:ia,delay:0}),e.jsx(V1,{label:"Campaigns",value:M.campaigns,icon:yn,delay:.04}),e.jsx(V1,{label:"Letters",value:M.letters,icon:on,delay:.08}),e.jsx(V1,{label:"QR Scans",value:M.qr,icon:hg,delay:.12}),e.jsx(V1,{label:"Page Visits",value:M.visits,icon:Ql,delay:.16}),e.jsx(V1,{label:"Plans Viewed",value:M.planViews,icon:$r,delay:.2}),e.jsx(V1,{label:"Seller Leads",value:M.leads,icon:Bn,delay:.24}),e.jsx(V1,{label:"Appointments",value:M.appointments,icon:n1,delay:.28}),e.jsx(V1,{label:"Listings Won",value:M.won,icon:ll,delay:.32}),e.jsx(V1,{label:"Hot Leads",value:M.hot,icon:Fd,delay:.36,hint:"Score 75+"})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsxs("div",{className:"revival-tile p-5 lg:col-span-2",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Last 14 days"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Homeowner engagement"}),e.jsx("div",{className:"h-64 mt-4",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(fWe,{data:P,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"revVisits",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"revLeads",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--accent))",stopOpacity:.5}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--accent))",stopOpacity:0})]})]}),e.jsx(KD,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(p1,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(f1,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(ff,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(Nb,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#revVisits)",strokeWidth:2}),e.jsx(Nb,{type:"monotone",dataKey:"leads",stroke:"hsl(var(--accent))",fill:"url(#revLeads)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Recent activity"}),e.jsxs("div",{className:"mt-3 space-y-3 max-h-64 overflow-auto pr-1",children:[C.slice(0,20).map(G=>e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-accent mt-1.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium capitalize",children:G.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Bs(new Date(G.created_at),"MMM d, h:mm a")})]})]},G.id)),C.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity yet. Mail your first letter to start tracking."}):null]})]})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Upcoming follow ups"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[T.filter(G=>!G.completed_at).slice(0,6).map(G=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border px-4 py-3",children:[e.jsx(wi,{checked:!!G.completed_at,onCheckedChange:K=>y.mutate({id:G.id,done:!!K})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:G.title}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:G.detail})]}),e.jsx(qe,{variant:"outline",children:Bs(new Date(`${G.due_date}T12:00:00`),"MMM d")})]},G.id)),T.filter(G=>!G.completed_at).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing due. Create a campaign to generate your follow-up plan."}):null]})]})]}),e.jsx(ns,{value:"campaigns",className:"mt-6",children:W("No campaigns yet — click New Campaign to build your first one.")}),e.jsx(ns,{value:"properties",className:"mt-6",children:e.jsx("div",{className:"revival-tile overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/60 text-left",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Property"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Seller"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Original"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Final"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"DOM"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Expired"})]})}),e.jsxs("tbody",{children:[(h.data??[]).map(G=>e.jsxs("tr",{className:"border-t border-border",children:[e.jsx("td",{className:"px-4 py-3 font-medium",children:G.property_address}),e.jsx("td",{className:"px-4 py-3",children:G.seller_name??"—"}),e.jsx("td",{className:"px-4 py-3",children:VE(G.original_price)}),e.jsx("td",{className:"px-4 py-3",children:VE(G.final_price)}),e.jsx("td",{className:"px-4 py-3",children:G.days_on_market??"—"}),e.jsx("td",{className:"px-4 py-3",children:G.expiration_date??"—"})]},G.id)),(h.data??[]).length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-10 text-center text-muted-foreground",children:"No properties imported yet."})}):null]})]})})}),e.jsx(ns,{value:"letters",className:"mt-6",children:W("Letters appear here once you create a campaign.")}),e.jsx(ns,{value:"landing",className:"mt-6",children:W("Landing pages appear here once you create a campaign.")}),e.jsx(ns,{value:"plans",className:"mt-6",children:W("Property Revival Plans appear here once you create a campaign.")}),e.jsxs(ns,{value:"followup",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Open tasks"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[T.filter(G=>!G.completed_at).map(G=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border px-4 py-3",children:[e.jsx(wi,{checked:!1,onCheckedChange:()=>y.mutate({id:G.id,done:!0})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:G.title}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:G.detail})]}),e.jsx(qe,{variant:"outline",className:"capitalize",children:G.channel})]},G.id)),T.filter(G=>!G.completed_at).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"All caught up."}):null]})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Seller leads"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[k.map(G=>e.jsxs("div",{className:"rounded-xl border border-border px-4 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium",children:[G.first_name,G.last_name].filter(Boolean).join(" ")||"Homeowner"}),e.jsxs(qe,{className:Et("capitalize border-0",G.temperature==="hot"&&"bg-red-500/15 text-red-600",G.temperature==="warm"&&"bg-amber-500/15 text-amber-700",G.temperature==="nurture"&&"bg-sky-500/15 text-sky-700",G.temperature==="low"&&"bg-muted text-muted-foreground"),children:[G.temperature," · ",G.lead_score]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[G.timeline?`Timeline: ${G.timeline} · `:"",G.next_action]})]},G.id)),k.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No seller leads captured yet."}):null]})]})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Opportunity pipeline"}),e.jsx("div",{className:"mt-4 flex gap-2 overflow-x-auto no-scrollbar pb-1",children:HFn.map(G=>{const K=G.toLowerCase().replace(/ /g,"_"),ee=k.filter(J=>J.stage===K).length;return e.jsxs("div",{className:"min-w-[150px] rounded-xl border border-border p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:G}),e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:ee})]},G)})})]})]}),e.jsxs(ns,{value:"analytics",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-4",children:[e.jsx(V1,{label:"Lead capture %",value:`${M.visits?Math.round(M.leads/M.visits*100):0}%`,icon:Bn}),e.jsx(V1,{label:"Scan → visit",value:`${M.qr?Math.round(M.visits/M.qr*100):0}%`,icon:hg}),e.jsx(V1,{label:"Appointments",value:M.appointments,icon:n1}),e.jsx(V1,{label:"Conversion %",value:`${M.leads?Math.round(M.won/M.leads*100):0}%`,icon:ll})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Campaign performance"}),e.jsx("div",{className:"h-72 mt-4",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(CAe,{data:v.slice(0,10).map(G=>{var K;return{name:(((K=G.property)==null?void 0:K.property_address)??G.name).slice(0,18),visits:C.filter(ee=>ee.campaign_id===G.id&&ee.event_type==="page_view").length,leads:k.filter(ee=>ee.campaign_id===G.id).length}}),children:[e.jsx(KD,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(p1,{dataKey:"name",tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),e.jsx(f1,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(ff,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(Bj,{dataKey:"visits",fill:"hsl(var(--primary))",radius:[6,6,0,0]}),e.jsx(Bj,{dataKey:"leads",fill:"hsl(var(--accent))",radius:[6,6,0,0]})]})})})]})]}),e.jsxs(ns,{value:"templates",className:"mt-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Campaign styles"}),e.jsx("div",{className:"grid gap-3 mt-3 md:grid-cols-2 xl:grid-cols-3",children:Kz.map(G=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:Et("h-1.5 w-full rounded-full bg-gradient-to-r mb-4",G.accent)}),e.jsx("div",{className:"font-semibold",children:G.name}),e.jsx("div",{className:"text-xs uppercase tracking-wider text-accent-foreground/70",children:G.tagline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:G.description}),e.jsxs("p",{className:"revival-serif text-[15px] mt-3 leading-snug",children:["“",G.previewHeadline,"”"]})]},G.id))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Letter templates"}),e.jsx("div",{className:"grid gap-3 mt-3 sm:grid-cols-2 lg:grid-cols-5",children:Pqt.map(G=>e.jsxs("div",{className:"revival-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:G.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:G.note})]},G.id))})]})]}),e.jsx(ns,{value:"settings",className:"mt-6",children:e.jsxs("div",{className:"revival-tile p-6 space-y-4 max-w-2xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Branding"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Letters, landing pages and emails automatically pull your name, photo, phone, brokerage and website from your LevelUp profile."}),e.jsx(B,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>s("/profile"),children:"Edit my profile"})]}),e.jsxs("div",{className:"border-t border-border pt-4",children:[e.jsx("div",{className:"font-semibold",children:"Agent OS integration"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every seller submission creates or updates a contact, applies the ListingRevival, ExpiredSeller and LandingPageLead tags, opens an opportunity in your pipeline, logs the activity and creates your next follow-up task automatically."})]}),e.jsxs("div",{className:"border-t border-border pt-4",children:[e.jsx("div",{className:"font-semibold",children:"Availability"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Listing Revival is currently in private beta and visible to LevelUp admins only."})]})]})})]})]})})}const _vt=["Import the property","Choose the campaign style","Generate everything"];function l7n(){var v;const s=Hn(),{user:t}=Ns(),{generate:n,invalidate:r}=nZe(),[a,i]=j.useState(0),[l,o]=j.useState(!1),[c,d]=j.useState(Kz[0].id),[u,h]=j.useState("professional"),[m,p]=j.useState({property_address:"",city:"",state:"",zip:"",seller_name:"",seller_email:"",seller_phone:"",mailing_address:"",mailing_city:"",mailing_state:"",mailing_zip:"",original_price:"",final_price:"",days_on_market:"",expiration_date:"",mls_link:"",photo_url:"",agent_notes:""}),x=(k,C)=>p(T=>({...T,[k]:C})),y=a===0?m.property_address.trim().length>3:!0,g=async()=>{if(t){o(!0);try{const{data:k,error:C}=await U.from("listing_revival_properties").insert({owner_user_id:t.id,property_address:m.property_address.trim(),city:m.city||null,state:m.state||null,zip:m.zip||null,seller_name:m.seller_name||null,seller_email:m.seller_email||null,seller_phone:m.seller_phone||null,mailing_address:m.mailing_address||null,mailing_city:m.mailing_city||null,mailing_state:m.mailing_state||null,mailing_zip:m.mailing_zip||null,original_price:m.original_price?Number(m.original_price):null,final_price:m.final_price?Number(m.final_price):null,days_on_market:m.days_on_market?Number(m.days_on_market):null,expiration_date:m.expiration_date||null,mls_link:m.mls_link||null,photo_url:m.photo_url||null,agent_notes:m.agent_notes||null}).select().single();if(C)throw C;const{data:T,error:M}=await U.from("listing_revival_campaigns").insert({owner_user_id:t.id,property_id:k.id,name:m.property_address.trim(),slug:YFn(m.property_address),style:c,letter_template:u,status:"generating",published:!0}).select().single();if(M)throw M;await n.mutateAsync({campaignId:T.id}),r(),re.success("Campaign built — everything is ready."),s(`/apps/listing-revival/campaigns/${T.id}`)}catch(k){re.error(k instanceof Error?k.message:"Could not create the campaign")}finally{o(!1)}}},b=(k,C,T={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:C}),e.jsx(ye,{value:m[k],onChange:M=>x(k,M.target.value),...T})]});return e.jsx(Vs,{title:"New Revival Campaign",children:e.jsxs("div",{className:"revival-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>s("/apps/listing-revival"),children:[e.jsx(_a,{className:"h-4 w-4"})," Back to Listing Revival"]}),e.jsx("div",{className:"flex items-center gap-3 mb-6",children:_vt.map((k,C)=>e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:Et("h-9 w-9 rounded-full grid place-items-center text-sm font-bold shrink-0 transition-colors",Cx("photo_url",k??""),label:"Property photo",prefix:"revival-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Ds,{rows:6,value:m.agent_notes,onChange:k=>x("agent_notes",k.target.value),placeholder:"Anything you know: why it didn't sell, condition, seller's motivation, photos were poor, etc."})]})]})]}):null,a===1?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"revival-tile p-6",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Step two"}),e.jsx("h2",{className:"revival-serif text-2xl mt-1",children:"Pick the voice of the campaign"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"The style shapes the letter, the landing page and the whole email and text sequence."}),e.jsx("div",{className:"grid gap-3 mt-5 md:grid-cols-2 xl:grid-cols-3",children:Kz.map(k=>e.jsxs("button",{type:"button",onClick:()=>d(k.id),className:Et("text-left rounded-2xl border p-5 transition-all",c===k.id?"border-accent ring-2 ring-accent/40 bg-accent/[0.04]":"border-border hover:border-accent/50"),children:[e.jsx("div",{className:Et("h-1.5 w-full rounded-full bg-gradient-to-r mb-4",k.accent)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"font-semibold",children:k.name}),c===k.id?e.jsx(da,{className:"h-4 w-4 text-accent"}):null]}),e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:k.tagline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:k.description}),e.jsxs("div",{className:"mt-3 rounded-xl bg-muted/60 p-3",children:[e.jsx("p",{className:"revival-serif text-[14px] leading-snug",children:k.previewHeadline}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:k.previewBody})]})]},k.id))})]}),e.jsxs("div",{className:"revival-tile p-6",children:[e.jsx("div",{className:"font-semibold",children:"Letter design"}),e.jsx("div",{className:"grid gap-3 mt-3 sm:grid-cols-3 lg:grid-cols-5",children:Pqt.map(k=>e.jsxs("button",{type:"button",onClick:()=>h(k.id),className:Et("rounded-xl border p-4 text-left transition-all",u===k.id?"border-accent ring-2 ring-accent/40":"border-border hover:border-accent/50"),children:[e.jsx("div",{className:"font-medium",children:k.name}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:k.note})]},k.id))})]})]}):null,a===2?e.jsxs("div",{className:"revival-tile p-8 text-center max-w-2xl mx-auto",children:[e.jsx("div",{className:"mx-auto h-16 w-16 rounded-2xl revival-dark grid place-items-center",children:e.jsx(um,{className:"h-7 w-7 text-accent"})}),e.jsx("h2",{className:"revival-serif text-2xl mt-4",children:"Build the full campaign"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"One click creates the personalized letter with its QR code, the private landing page, the Property Revival Plan, a 7-email sequence, 5 texts, your call and video scripts, and a 30-day follow-up task plan."}),e.jsxs("div",{className:"mt-6 rounded-2xl border border-border p-5 text-left space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Property"}),e.jsx("span",{className:"font-medium",children:m.property_address||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Seller"}),e.jsx("span",{className:"font-medium",children:m.seller_name||"Homeowner"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Style"}),e.jsx("span",{className:"font-medium",children:(v=Kz.find(k=>k.id===c))==null?void 0:v.name})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Letter"}),e.jsx("span",{className:"font-medium capitalize",children:u})]})]}),e.jsx(B,{size:"lg",className:"mt-6 w-full bg-accent text-accent-foreground hover:bg-accent/90",disabled:l,onClick:g,children:l?e.jsxs(e.Fragment,{children:[e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"})," Building your campaign…"]}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{className:"h-4 w-4 mr-2"})," Generate campaign"]})})]}):null]},a)}),a<2?e.jsxs("div",{className:"flex justify-between mt-6",children:[e.jsx(B,{variant:"outline",disabled:a===0,onClick:()=>i(k=>k-1),children:"Back"}),e.jsxs(B,{disabled:!y,onClick:()=>i(k=>k+1),children:["Continue ",e.jsx(Xa,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"flex justify-start mt-6",children:e.jsx(B,{variant:"outline",disabled:l,onClick:()=>i(1),children:"Back"})})]})})}const wvt={professional:{head:"font-semibold tracking-tight",body:"",rule:"bg-[#0f2540]",size:15},luxury:{head:"revival-serif font-normal tracking-tight",body:"revival-serif",rule:"bg-[#c9a227]",size:15.5},friendly:{head:"font-semibold",body:"",rule:"bg-[#c9a227]",size:15},minimal:{head:"font-medium tracking-tight",body:"",rule:"bg-neutral-300",size:14.5},modern:{head:"font-bold tracking-tighter uppercase",body:"",rule:"bg-[#0f2540]",size:15}};function c7n(s){return s<=900?1:s<=1150?.94:s<=1400?.88:s<=1700?.82:s<=2100?.76:.7}function jvt({campaign:s,letter:t,agent:n,url:r,className:a}){var h,m;const i=wvt[s.letter_template]??wvt.professional,l=s.property,o=t.paragraphs??[],c=o.join(" ").length+(((h=t.closing)==null?void 0:h.length)??0)+(((m=t.greeting)==null?void 0:m.length)??0),d=c7n(c),u={fontSize:`${(i.size*d).toFixed(2)}px`,lineHeight:1.6};return e.jsxs("div",{id:"revival-letter-sheet",className:Et("mx-auto w-full max-w-[816px] bg-white text-[#1a2230] shadow-[0_30px_70px_-40px_rgba(15,37,64,.6)]","aspect-[8.5/11] overflow-hidden flex flex-col",a),children:[e.jsxs("div",{className:"flex items-stretch",children:[e.jsxs("div",{className:"flex-1 px-10 pt-9 pb-6",children:[n.brokerage_name?e.jsx("div",{className:"text-[11px] tracking-[0.28em] uppercase text-[#0f2540]/70 font-bold",children:n.brokerage_name}):null,e.jsx("div",{className:"text-2xl font-bold tracking-tight text-[#0f2540] mt-1",children:n.name??"Your Name"})]}),e.jsxs("div",{className:"w-[46%] bg-[#0f2540] text-white px-8 py-6 flex flex-col justify-center [clip-path:polygon(9%_0,100%_0,100%_100%,0_100%)]",children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.2em] uppercase text-white/70",children:"A personal review prepared"}),e.jsx("div",{className:"text-[12px] tracking-[0.2em] uppercase font-bold text-[#c9a227]",children:"exclusively for you"})]})]}),e.jsxs("div",{className:"grid grid-cols-[1.15fr_1fr] gap-8 px-10 flex-1 min-h-0 pb-2",children:[e.jsxs("div",{className:"min-h-0 flex flex-col",children:[e.jsx("h1",{className:Et("text-[#0f2540]",i.head),style:{fontSize:`${(30*Math.max(d,.82)).toFixed(1)}px`,lineHeight:1.12},children:t.greeting.replace(/,$/,"")}),e.jsx("div",{className:Et("mt-1 h-[3px] w-16 rounded-full",i.rule)}),e.jsxs("div",{className:Et("mt-4 text-[#28313f] flex flex-col",i.body),style:{...u,gap:`${(.7*d).toFixed(2)}em`},children:[o.map((p,x)=>e.jsx("p",{children:p},x)),t.closing?e.jsx("p",{className:"font-semibold text-[#0f2540]",children:t.closing}):null]}),e.jsxs("div",{className:"mt-auto pt-4",children:[e.jsx("div",{style:{fontSize:`${(13*d).toFixed(1)}px`},className:"text-[#28313f]",children:"Sincerely,"}),e.jsx("div",{className:"revival-serif italic text-[#0f2540] leading-tight mt-1",style:{fontSize:`${(26*d).toFixed(1)}px`},children:t.signature||n.name})]})]}),e.jsxs("div",{className:"min-h-0 space-y-4 pt-2",children:[l!=null&&l.photo_url?e.jsxs("div",{className:"overflow-hidden rounded-lg",children:[e.jsx("img",{src:l.photo_url,alt:l.property_address??"Property",className:"h-[190px] w-full object-cover",loading:"lazy"}),e.jsxs("div",{className:"bg-[#0f2540] text-white px-4 py-3 text-[11.5px] grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-white/60",children:"Property"}),e.jsx("div",{className:"font-semibold leading-tight",children:l.property_address})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-white/60",children:"Days on market"}),e.jsx("div",{className:"font-semibold",children:l.days_on_market??"—"})]})]})]}):null,e.jsxs("div",{className:"rounded-xl border border-[#c9a227]/45 p-4 text-center",children:[e.jsx("div",{className:"inline-block bg-[#c9a227] text-[#0f2540] text-[10px] font-extrabold tracking-[0.18em] uppercase px-3 py-1 rounded",children:"Scan to unlock"}),e.jsxs("div",{className:"revival-serif text-[19px] text-[#0f2540] leading-tight mt-2",children:["Your Private",e.jsx("br",{}),"Property Review"]}),e.jsx("div",{className:"flex justify-center my-3",children:e.jsx(PN,{value:r,size:116,level:"M",fgColor:"#0f2540"})}),e.jsx("div",{className:"text-[11px] text-[#28313f]",children:"Scan the QR code or visit"}),e.jsx("div",{className:"text-[11.5px] font-bold text-[#0f2540] break-all",children:r.replace(/^https?:\/\//,"")})]}),e.jsx("p",{className:"text-[11px] leading-5 text-[#4a5568] italic",children:t.ps})]})]}),e.jsxs("div",{className:"mt-4 bg-[#0f2540] text-white px-10 py-5 flex items-center gap-5",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:n.name??"Agent",className:"h-16 w-16 rounded-lg object-cover"}):null,e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-lg font-bold tracking-wide uppercase",children:n.name}),e.jsx("div",{className:"text-[#c9a227] text-[12.5px] font-semibold",children:n.title??"Real Estate Specialist"})]}),e.jsxs("div",{className:"text-[12px] space-y-0.5 text-right text-white/85",children:[n.phone?e.jsx("div",{children:n.phone}):null,n.email?e.jsx("div",{children:n.email}):null,n.website_url?e.jsx("div",{children:n.website_url.replace(/^https?:\/\//,"")}):null]})]})]})}function zqt({letter:s,saving:t,onSave:n,onCancel:r}){const[a,i]=j.useState(s);j.useEffect(()=>{i(s)},[s]);const l=(u,h)=>i(m=>({...m,[u]:h})),o=(u,h)=>i(m=>({...m,paragraphs:m.paragraphs.map((p,x)=>x===u?h:p)})),c=()=>i(u=>({...u,paragraphs:[...u.paragraphs,""]})),d=u=>i(h=>({...h,paragraphs:h.paragraphs.filter((m,p)=>p!==u)}));return e.jsxs("div",{className:"rounded-xl border border-border bg-card p-5 space-y-5 max-w-3xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold",children:"Edit letter"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your edits are saved to this campaign and used in the PDF."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",variant:"ghost",onClick:r,disabled:t,children:[e.jsx(dr,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel"]}),e.jsxs(B,{size:"sm",onClick:()=>n({...a,paragraphs:a.paragraphs.map(u=>u.trim()).filter(Boolean)}),disabled:t,children:[t?e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Jo,{className:"h-3.5 w-3.5 mr-1.5"}),"Save letter"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Greeting"}),e.jsx(ye,{value:a.greeting??"",onChange:u=>l("greeting",u.target.value),placeholder:"Dear Jane,"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{className:"text-xs",children:"Body paragraphs"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:c,children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1.5"})," Add paragraph"]})]}),a.paragraphs.map((u,h)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(Ds,{value:u,onChange:m=>o(h,m.target.value),rows:4,className:"flex-1"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>d(h),"aria-label":"Remove paragraph",children:e.jsx(Rn,{className:"h-4 w-4 text-muted-foreground"})})]},h))]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Closing line"}),e.jsx(ye,{value:a.closing??"",onChange:u=>l("closing",u.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"Signature"}),e.jsx(ye,{value:a.signature??"",onChange:u=>l("signature",u.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"text-xs",children:"P.S."}),e.jsx(Ds,{value:a.ps??"",onChange:u=>l("ps",u.target.value),rows:2})]})]})}function Nvt(s){if(!s)return null;const t=Math.floor(s/60),n=Math.round(s%60);return`${t}:${String(n).padStart(2,"0")}`}function d7n(s){return s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url}function u7n({video:s}){const[t,n]=j.useState(!1),r=d7n(s);return!r||t?e.jsx("div",{className:"h-full w-full grid place-items-center bg-gradient-to-br from-muted to-muted/40",children:e.jsx(vh,{className:"h-7 w-7 text-muted-foreground/70"})}):e.jsx("img",{src:r,alt:s.title??"Video thumbnail",loading:"lazy",onError:()=>n(!0),className:"h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.04]"})}const h7n=(()=>{if(typeof window>"u"||window.self===window.top)return!1;try{const s=document.featurePolicy;if(s!=null&&s.allowsFeature)return!(s.allowsFeature("camera")&&s.allowsFeature("microphone"))}catch{}return!0})();function m7n({open:s,onOpenChange:t,onSelect:n,propertyAddress:r}){const{user:a}=Ns(),[i,l]=j.useState("library"),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(""),[p,x]=j.useState("record"),[y,g]=j.useState(0),[b,v]=j.useState(0),k=hS(),C=j.useCallback(async()=>{if(a){u(!0);try{const{data:I,error:O}=await U.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(60);if(O)throw O;c(I??[])}catch{re.error("Could not load your video library")}finally{u(!1)}}},[a]);j.useEffect(()=>{s&&C()},[s,C]);const T=j.useMemo(()=>{const I=h.trim().toLowerCase();return I?o.filter(O=>`${O.title??""} ${O.recipient_name??""}`.toLowerCase().includes(I)):o},[o,h]),M=I=>{if(!I.playback_url){re.error("That video has no playable link yet");return}n(I.playback_url),t(!1)},P=I=>{!I&&(p==="uploading"||p==="processing")||(t(I),I||(x("record"),g(0),v(0)))},L=j.useCallback(async(I,O)=>{x("uploading");const $=r?`Listing Revival — ${r}`:"Listing Revival intro";try{const{videoId:q,libraryId:W}=await w6($),{uploadUrl:G,apiKey:K}=await j6(q),ee=new XMLHttpRequest;ee.upload.onprogress=de=>{de.lengthComputable&&g(de.loaded/de.total*100)},await new Promise((de,we)=>{ee.onload=()=>ee.status>=200&&ee.status<300?de():we(new Error("Upload failed")),ee.onerror=()=>we(new Error("Upload failed")),ee.open("PUT",G),ee.setRequestHeader("AccessKey",K),ee.send(I)}),x("processing");const J=`https://iframe.mediadelivery.net/embed/${W}/${q}`,le=Date.now(),ue=9e4;let oe=0;for(;oe<4;){if(await new Promise(we=>setTimeout(we,3e3)),Date.now()-le>ue){await k.mutateAsync({bunny_video_id:q,playback_url:`https://iframe.mediadelivery.net/play/${W}/${q}`,file_size_mb:I.size/(1024*1024),title:$,status:"processing",touch_type:"video"}),n(J),re.success("Video saved — still encoding, it will appear shortly."),x("done"),setTimeout(()=>P(!1),1200);return}const de=await $j(q);if(oe=de.status,v(de.encodeProgress||0),oe===5||oe===6)throw new Error("Video processing failed")}const ie=await $j(q);await k.mutateAsync({bunny_video_id:q,playback_url:ie.directPlayUrl||J,thumbnail_url:ie.thumbnailUrl,preview_url:ie.previewUrl||null,duration_seconds:ie.length||O,file_size_mb:(ie.storageSize||I.size)/(1024*1024),title:$,status:"ready",touch_type:"video"}),n(ie.directPlayUrl||J),re.success("Video recorded and added to your landing page!"),x("done"),setTimeout(()=>P(!1),1200)}catch(q){console.error("Revival recording upload error:",q),re.error("Failed to process video. Please try again."),x("record")}},[k,n,r]);return e.jsx(Fs,{open:s,onOpenChange:P,children:e.jsxs(Os,{className:"max-w-4xl max-h-[92vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsx(zs,{children:"Add a video to your landing page"}),e.jsx(kr,{children:"Pick one you already recorded, or record a brand new one right here without leaving Listing Revival."})]}),e.jsxs(fa,{value:i,onValueChange:l,children:[e.jsxs(xa,{className:"grid w-full grid-cols-2",children:[e.jsxs(ss,{value:"library",children:[e.jsx(wh,{className:"h-3.5 w-3.5 mr-1.5"})," My library"]}),e.jsxs(ss,{value:"record",children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1.5"})," Record new"]})]}),e.jsxs(ns,{value:"library",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:h,onChange:I=>m(I.target.value),placeholder:"Search your videos…",className:"pl-9"})]}),d?e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:Array.from({length:6}).map((I,O)=>e.jsx(gn,{className:"aspect-video rounded-xl"},O))}):T.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border p-10 text-center",children:[e.jsx(vh,{className:"h-8 w-8 mx-auto text-muted-foreground/60"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:o.length===0?"No finished videos yet — record one on the next tab.":"No videos match that search."}),e.jsxs(B,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>l("record"),children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1.5"})," Record a video now"]})]}):e.jsx("div",{className:"grid gap-3 sm:grid-cols-3 max-h-[55vh] overflow-y-auto pr-1",children:T.map(I=>e.jsxs("button",{type:"button",onClick:()=>M(I),className:"group text-left rounded-xl border border-border bg-card overflow-hidden transition hover:border-primary hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsxs("div",{className:"aspect-video bg-muted overflow-hidden relative",children:[e.jsx(u7n,{video:I}),Nvt(I.duration_seconds)?e.jsx("span",{className:"absolute bottom-1.5 right-1.5 rounded bg-foreground/80 px-1.5 py-0.5 text-[10px] font-medium text-background",children:Nvt(I.duration_seconds)}):null]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:I.title||I.recipient_name||"Untitled video"}),I.created_at?e.jsx("div",{className:"text-[11px] text-muted-foreground",children:Bs(new Date(I.created_at),"MMM d, yyyy")}):null]})]},I.id))})]}),e.jsxs(ns,{value:"record",className:"mt-4",children:[p==="record"?e.jsxs("div",{className:"space-y-3",children:[h7n?e.jsxs("div",{className:"rounded-xl border border-border bg-muted/40 p-3 flex flex-wrap items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground flex-1 min-w-[220px]",children:"This editor preview blocks camera access. Open the app in its own browser tab — recording works right here in the popup for your agents."}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>window.open(window.location.href,"_blank","noopener"),children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1.5"})," Open in new tab"]})]}):null,e.jsx(k6,{maxDurationSeconds:600,onRecordingComplete:L,onError:I=>re.error(I)})]}):null,p==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Wt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading your video…"}),e.jsx(qi,{value:y,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(y),"%"]})]}):null,p==="processing"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Wt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing your video…"}),e.jsx(qi,{value:b,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(b),"%"]})]}):null,p==="done"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(To,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video added to your landing page!"})]}):null]})]})]})})}const p7n=[{id:"photo",label:"Property photo",hint:"Shows the listing photo. Best if you have no video.",icon:ac},{id:"video",label:"Video",hint:"Record one here, pick from your library, or paste a link.",icon:Zr},{id:"none",label:"Nothing",hint:"Hide the media block entirely for a clean, text-only intro.",icon:n0}];function f7n({campaignId:s,content:t,landingConfig:n,propertyPhotoUrl:r,saving:a,onSave:i}){var T;const[l,o]=j.useState(t.landing),[c,d]=j.useState({...fvt,...n}),[u,h]=j.useState(!1),[m,p]=j.useState(!1);j.useEffect(()=>{o(t.landing)},[t.landing]),j.useEffect(()=>{d({...fvt,...n})},[n]);const x=(M,P)=>{o(L=>({...L??{},[M]:P})),h(!0)},y=(M,P)=>{d(L=>({...L,[M]:P})),h(!0)},g=(l==null?void 0:l.discover)??[],b=M=>x("discover",M),v=j.useMemo(()=>Lqt(c.video_url),[c.video_url]),k=c.media_image_url||r||null,C=()=>{i({content:{...t,landing:l},landing_config:c}),h(!1)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Landing page editor"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Everything here updates your public page instantly after saving."})]}),e.jsxs(B,{size:"sm",onClick:C,disabled:!u||a,children:[a?e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Jo,{className:"h-3.5 w-3.5 mr-1.5"}),"Save changes"]})]}),e.jsxs("div",{className:"revival-tile p-6 space-y-4",children:[e.jsx("div",{className:"font-semibold",children:"Headline & intro"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Eyebrow"}),e.jsx(ye,{value:(l==null?void 0:l.eyebrow)??"",onChange:M=>x("eyebrow",M.target.value),placeholder:"A complimentary review"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Button text"}),e.jsx(ye,{value:(l==null?void 0:l.cta)??"",onChange:M=>x("cta",M.target.value),placeholder:"Get my free review"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Headline"}),e.jsx(ye,{value:(l==null?void 0:l.headline)??"",onChange:M=>x("headline",M.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Subheadline"}),e.jsx(Ds,{rows:2,value:(l==null?void 0:l.subheadline)??"",onChange:M=>x("subheadline",M.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Personal intro paragraph"}),e.jsx(Ds,{rows:5,value:(l==null?void 0:l.intro)??"",onChange:M=>x("intro",M.target.value)})]})]}),e.jsxs("div",{className:"revival-tile p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Intro media"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No video? Choose the property photo and the page still looks complete."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:p7n.map(M=>{const P=(c.media_mode??"photo")===M.id;return e.jsxs("button",{type:"button",onClick:()=>y("media_mode",M.id),className:`text-left rounded-xl border p-4 transition ${P?"border-accent ring-1 ring-accent":"border-border hover:border-accent/50"}`,children:[e.jsx(M.icon,{className:`h-5 w-5 ${P?"text-accent":"text-muted-foreground"}`}),e.jsx("div",{className:"font-medium mt-2",children:M.label}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:M.hint})]},M.id)})}),(c.media_mode??"photo")==="video"?e.jsxs("div",{className:"space-y-3 rounded-xl border border-border p-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Video link"}),e.jsx(ye,{value:c.video_url??"",onChange:M=>y("video_url",M.target.value),placeholder:"Paste a YouTube, Vimeo, Loom or .mp4 link"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Or record a new video right here — it saves to your library automatically."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{type:"button",size:"sm",onClick:()=>p(!0),children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1.5"})," Record or choose a video"]}),c.video_url?e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>y("video_url",""),children:[e.jsx(Rn,{className:"h-3.5 w-3.5 mr-1.5"})," Remove video"]}):null]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Caption under the video"}),e.jsx(ye,{value:c.video_caption??"",onChange:M=>y("video_caption",M.target.value),placeholder:"A personal introduction"})]}),e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted grid place-items-center",children:(v==null?void 0:v.kind)==="file"?e.jsx("video",{src:v.src,controls:!0,className:"h-full w-full object-cover"}):v?e.jsx("iframe",{src:v.src,title:"Video preview",className:"h-full w-full",allowFullScreen:!0}):e.jsxs("div",{className:"text-center text-sm text-muted-foreground",children:[e.jsx(vh,{className:"h-8 w-8 mx-auto mb-1 opacity-60"})," Your video preview appears here"]})})]}):null,(c.media_mode??"photo")==="photo"?e.jsxs("div",{className:"space-y-3 rounded-xl border border-border p-4",children:[e.jsx(gee,{label:"Photo shown next to your intro",value:c.media_image_url??"",onChange:M=>y("media_image_url",M),prefix:"revival-landing",hint:"Leave empty to use the property photo from this campaign."}),k?e.jsx("img",{src:k,alt:"Landing media",className:"rounded-lg w-full max-h-64 object-cover"}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No property photo on this campaign yet — add one here or the media block will be hidden."})]}):null]}),e.jsxs("div",{className:"revival-tile p-6 space-y-4",children:[e.jsx("div",{className:"font-semibold",children:"Sections"}),[["show_property_snapshot","Property snapshot","Address, pricing history and days on market."],["show_discover","Inside your free review","The cards explaining what the seller receives."],["show_testimonial","Testimonial","The quote from a past client."]].map(([M,P,L])=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:P}),e.jsx("p",{className:"text-xs text-muted-foreground",children:L})]}),e.jsx(Mn,{checked:c[M]!==!1,onCheckedChange:I=>y(M,I)})]},M))]}),e.jsxs("div",{className:"revival-tile p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"font-semibold",children:"Review highlights"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>b([...g,{title:"",body:""}]),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1.5"})," Add card"]})]}),g.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No highlight cards yet."}):null,g.map((M,P)=>e.jsxs("div",{className:"rounded-xl border border-border p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"outline",children:P+1}),e.jsx(ye,{value:M.title,placeholder:"Card title",onChange:L=>b(g.map((I,O)=>O===P?{...I,title:L.target.value}:I))}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>b(g.filter((L,I)=>I!==P)),children:e.jsx(Rn,{className:"h-4 w-4"})})]}),e.jsx(Ds,{rows:2,value:M.body,placeholder:"What this card explains",onChange:L=>b(g.map((I,O)=>O===P?{...I,body:L.target.value}:I))})]},P))]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:C,disabled:!u||a,children:[a?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Save changes"]})}),e.jsx(m7n,{open:m,onOpenChange:p,propertyAddress:((T=t==null?void 0:t.landing)==null?void 0:T.headline)??null,onSelect:M=>{y("video_url",M),y("media_mode","video")}})]})}const Q8e={intro:"",scores:{},buyers_experienced:[],differently:[],strategy_weeks:[],questions:[],resources:[],invitation:""},x7n=s=>Math.min(5,Math.max(1,Math.round(s||1)));function g7n({plan:s,saving:t,onSave:n}){const[r,a]=j.useState({...Q8e,...s});j.useEffect(()=>{a({...Q8e,...s})},[s]);const i=(o,c)=>a(d=>({...d,[o]:c})),l=(o,c,d)=>e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:c}),e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>i(o,[...r[o]??[],""]),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d}),e.jsxs("div",{className:"space-y-2",children:[(r[o]??[]).map((u,h)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ds,{value:u,rows:2,onChange:m=>{const p=[...r[o]??[]];p[h]=m.target.value,i(o,p)}}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",onClick:()=>i(o,(r[o]??[]).filter((m,p)=>p!==h)),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]},h)),(r[o]??[]).length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Nothing yet."}):null]})]});return e.jsxs("div",{className:"revival-tile p-5 space-y-7",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-accent-foreground/70",children:"Edit plan"}),e.jsx("h3",{className:"revival-serif text-xl mt-1",children:"Make it yours"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Every word in the seller presentation can be rewritten here. Changes update the preview, the PDF and the live plan page."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>a({...Q8e,...s}),children:[e.jsx(bm,{className:"h-3.5 w-3.5 mr-1.5"})," Reset"]}),e.jsxs(B,{type:"button",size:"sm",disabled:t,className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>n(r),children:[t?e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Jo,{className:"h-3.5 w-3.5 mr-1.5"}),"Save plan"]})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"plan-intro",children:"Introduction"}),e.jsx(Ds,{id:"plan-intro",rows:4,value:r.intro,onChange:o=>i("intro",o.target.value)})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Marketing scorecard (1–5)"}),e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("scores",{...r.scores,[`Category ${Object.keys(r.scores??{}).length+1}`]:3}),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Add category"]})]}),e.jsx("div",{className:"space-y-2",children:Object.entries(r.scores??{}).map(([o,c],d)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{value:o,onChange:u=>{const h=Object.entries(r.scores??{});h[d]=[u.target.value,c],i("scores",Object.fromEntries(h))}}),e.jsx(ye,{type:"number",min:1,max:5,className:"w-20",value:c,onChange:u=>i("scores",{...r.scores,[o]:x7n(Number(u.target.value))})}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",onClick:()=>{const u={...r.scores??{}};delete u[o],i("scores",u)},children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]},`${o}-${d}`))})]}),l("buyers_experienced","What buyers experienced","Honest observations about the previous listing."),l("differently","What we will do differently","The concrete changes you are proposing."),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Relaunch timeline"}),e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("strategy_weeks",[...r.strategy_weeks??[],{week:`Week ${(r.strategy_weeks??[]).length+1}`,title:"",body:""}]),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Add week"]})]}),e.jsx("div",{className:"space-y-3",children:(r.strategy_weeks??[]).map((o,c)=>e.jsxs("div",{className:"rounded-xl border p-3 space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{className:"w-28",value:o.week,placeholder:"Week 1",onChange:d=>{const u=[...r.strategy_weeks??[]];u[c]={...o,week:d.target.value},i("strategy_weeks",u)}}),e.jsx(ye,{value:o.title,placeholder:"Title",onChange:d=>{const u=[...r.strategy_weeks??[]];u[c]={...o,title:d.target.value},i("strategy_weeks",u)}}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",onClick:()=>i("strategy_weeks",(r.strategy_weeks??[]).filter((d,u)=>u!==c)),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]}),e.jsx(Ds,{rows:2,value:o.body,placeholder:"What happens this week",onChange:d=>{const u=[...r.strategy_weeks??[]];u[c]={...o,body:d.target.value},i("strategy_weeks",u)}})]},c))})]}),l("questions","Questions for the seller","Prompts you want to discuss at the appointment."),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Resources"}),e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("resources",[...r.resources??[],{title:"",body:""}]),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Add resource"]})]}),e.jsx("div",{className:"space-y-3",children:(r.resources??[]).map((o,c)=>e.jsxs("div",{className:"rounded-xl border p-3 space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:o.title,placeholder:"Title",onChange:d=>{const u=[...r.resources??[]];u[c]={...o,title:d.target.value},i("resources",u)}}),e.jsx(B,{type:"button",size:"icon",variant:"ghost",onClick:()=>i("resources",(r.resources??[]).filter((d,u)=>u!==c)),children:e.jsx(Rn,{className:"h-4 w-4 text-destructive"})})]}),e.jsx(Ds,{rows:2,value:o.body,onChange:d=>{const u=[...r.resources??[]];u[c]={...o,body:d.target.value},i("resources",u)}})]},c))})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx(se,{htmlFor:"plan-invitation",children:"Closing invitation"}),e.jsx(Ds,{id:"plan-invitation",rows:3,value:r.invitation,onChange:o=>i("invitation",o.target.value)})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{type:"button",disabled:t,className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>n(r),children:[t?e.jsx(Wt,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-1.5"}),"Save plan"]})})]})}const y7n=[{key:"letter",label:"Letter",icon:on,blurb:"Personalized print-ready letter mailed to the homeowner."},{key:"qr_scan",label:"QR Scan",icon:hg,blurb:"Homeowner scans the unique code on the letter."},{key:"page_view",label:"Landing Page",icon:Ql,blurb:"Private property review page opens on their phone."},{key:"form_submit",label:"Lead Form",icon:r1,blurb:"They request the plan — Agent OS is updated instantly."},{key:"plan_view",label:"Revival Plan",icon:$r,blurb:"The full Property Revival Plan is delivered."},{key:"email",label:"Email Sequence",icon:Dr,blurb:"Seven branded emails nurture the conversation."},{key:"sms",label:"Text Sequence",icon:ro,blurb:"Five short texts keep momentum going."},{key:"appointment",label:"Appointment",icon:n1,blurb:"They book a complimentary strategy session."},{key:"listing",label:"Listing Signed",icon:cu,blurb:"The relaunch begins."}];function v7n({counts:s,onStep:t,activeStep:n}){return e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:y7n.map((r,a)=>{const i=r.icon,l=s[r.key]??0,o=l>0;return e.jsxs(br.button,{type:"button",onClick:()=>t==null?void 0:t(r.key),initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:a*.05,duration:.45,ease:[.22,1,.36,1]},className:Et("revival-tile text-left p-5 relative overflow-hidden group",n===r.key&&"ring-2 ring-accent"),children:[e.jsx("div",{className:"absolute right-4 top-4 text-[11px] font-bold tracking-widest text-muted-foreground",children:String(a+1).padStart(2,"0")}),e.jsx("div",{className:Et("h-11 w-11 rounded-xl grid place-items-center transition-colors",o?"bg-accent/20 text-accent-foreground":"bg-muted text-muted-foreground"),children:e.jsx(i,{className:"h-5 w-5"})}),e.jsx("div",{className:"mt-3 font-semibold",children:r.label}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:r.blurb}),e.jsxs("div",{className:"mt-3 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold tabular-nums",children:l}),e.jsx("span",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:o?"recorded":"waiting"})]}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-1 bg-gradient-to-r from-accent to-accent/0 origin-left transition-transform duration-500 scale-x-0 group-hover:scale-x-100"})]},r.key)})})}function b7n({open:s,onOpenChange:t,campaignId:n,email:r,ctaUrl:a,seller:i}){const{user:l}=Ns(),[o,c]=j.useState([]),[d,u]=j.useState(""),[h,m]=j.useState([]),[p,x]=j.useState(""),[y,g]=j.useState(""),[b,v]=j.useState("View your property review"),[k,C]=j.useState(""),[T,M]=j.useState(!1),[P,L]=j.useState(!1),I=j.useRef(null);j.useEffect(()=>{!s||!r||(c([]),u(""),m([]),x(r.subject||""),g(r.body||""),C(""))},[s,r==null?void 0:r.key,r==null?void 0:r.subject]),j.useEffect(()=>{if(!s||!r)return;const G=setTimeout(async()=>{M(!0);try{const{data:K,error:ee}=await U.functions.invoke("listing-revival-email",{body:{campaign_id:n,subject:p,body:y,preview_text:r.preview,cta_label:b,cta_url:a,preview_only:!0}});if(ee)throw ee;K!=null&&K.html&&C(K.html)}catch{}finally{M(!1)}},400);return()=>clearTimeout(G)},[s,n,p,y,b,a,r==null?void 0:r.key]),j.useEffect(()=>{I.current&&clearTimeout(I.current);const G=d.trim();if(!l||G.length<2||/\S+@\S+\.\S+/.test(G)){m([]);return}return I.current=setTimeout(async()=>{const K=`%${G}%`,ee=U,{data:J}=await ee.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",l.id).not("email","is",null).or(`first_name.ilike.${K},last_name.ilike.${K},email.ilike.${K}`).order("first_name",{ascending:!0}).limit(6);m(J||[])},200),()=>{I.current&&clearTimeout(I.current)}},[d,l==null?void 0:l.id]);const O=G=>{G.email&&(c(K=>K.some(ee=>ee.email.toLowerCase()===G.email.toLowerCase())?K:[...K,G]),u(""),m([]))},$=()=>{const G=d.trim();if(!/\S+@\S+\.\S+/.test(G)){re.error("Enter a valid email address");return}O({email:G})},q=j.useMemo(()=>!!r&&o.length>0&&p.trim().length>0&&!P,[r,o,p,P]),W=async()=>{if(r){L(!0);try{const{data:G,error:K}=await U.functions.invoke("listing-revival-email",{body:{campaign_id:n,subject:p,body:y,preview_text:r.preview,cta_label:b,cta_url:a,email_key:r.key,recipients:o}});if(K)throw K;if(!(G!=null&&G.success))throw new Error((G==null?void 0:G.error)||"Could not send the email");re.success(G.failed?`Sent to ${G.sent} · ${G.failed} failed`:`Email sent to ${G.sent} ${G.sent===1?"contact":"contacts"}`),t(!1)}catch(G){re.error((G==null?void 0:G.message)||"Could not send the email")}finally{L(!1)}}};return e.jsx(Fs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsxs($s,{children:[e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-4 w-4"})," Send this email"]}),e.jsx(kr,{children:"Pick contacts from your Agent OS database — they receive the fully branded HTML version."})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_1.1fr]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Recipients"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:d,onChange:G=>u(G.target.value),placeholder:"Search contacts or type an email",onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),$())}}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:$,children:e.jsx(Js,{className:"h-4 w-4"})})]}),h.length>0&&e.jsx("div",{className:"rounded-xl border divide-y overflow-hidden",children:h.map(G=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 hover:bg-muted/60 flex items-center gap-2",onClick:()=>O({email:G.email,first_name:G.first_name,last_name:G.last_name,contact_id:G.id}),children:[e.jsx(Eo,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:[G.first_name,G.last_name].filter(Boolean).join(" ")||G.email}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:G.email})]},G.id))}),(i==null?void 0:i.email)&&!o.some(G=>G.email.toLowerCase()===i.email.toLowerCase())&&e.jsxs(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>O({email:i.email,first_name:(i.name||"").split(" ")[0]}),children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1.5"})," Add seller (",i.email,")"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 pt-1",children:o.map(G=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[[G.first_name,G.last_name].filter(Boolean).join(" ")||G.email,e.jsx("button",{type:"button",onClick:()=>c(K=>K.filter(ee=>ee.email!==G.email)),children:e.jsx(dr,{className:"h-3 w-3"})})]},G.email))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Subject"}),e.jsx(ye,{value:p,onChange:G=>x(G.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Message"}),e.jsx(Ds,{rows:10,value:y,onChange:G=>g(G.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ",e.jsx("code",{children:"{{first_name}}"}),", ",e.jsx("code",{children:"{{address}}"})," or ",e.jsx("code",{children:"{{agent_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Button label"}),e.jsx(ye,{value:b,onChange:G=>v(G.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{className:"flex items-center gap-2",children:["Live preview ",T&&e.jsx(Wt,{className:"h-3 w-3 animate-spin"})]}),e.jsx("div",{className:"rounded-xl border overflow-hidden bg-muted/30 h-[520px]",children:k?e.jsx("iframe",{title:"Email preview",srcDoc:k,className:"w-full h-full border-0"}):e.jsx("div",{className:"h-full grid place-items-center text-sm text-muted-foreground",children:"Building preview…"})})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:W,disabled:!q,children:[P?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Dr,{className:"h-4 w-4 mr-2"}),"Send to ",o.length||0]})]})]})})}const _7n=[{id:"estate",name:"Estate Navy",description:"The signature look — deep navy, gold rules, serif headlines.",bg:"#0f2540",surface:"#ffffff",ink:"#1f2937",muted:"#6b7280",accent:"#c9a227",accentInk:"#0f2540",headingFont:'Georgia, "Times New Roman", serif',bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#0f2540","#c9a227","#ffffff"]},{id:"coastal",name:"Coastal",description:"Airy sea-glass blues and sand — perfect for beach markets.",bg:"#0d3b45",surface:"#fbfaf6",ink:"#12303a",muted:"#5c7a80",accent:"#4ea6a0",accentInk:"#04262b",headingFont:'"Iowan Old Style", Georgia, serif',bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#0d3b45","#4ea6a0","#fbfaf6"]},{id:"ranch",name:"Land & Ranch",description:"Earthy clay and saddle tones for land, farm and ranch.",bg:"#2f2a22",surface:"#fdfaf4",ink:"#2b2620",muted:"#7a6f60",accent:"#b4703a",accentInk:"#fff8ef",headingFont:"Georgia, serif",bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#2f2a22","#b4703a","#fdfaf4"]},{id:"modern",name:"Modern Mono",description:"Editorial black and white with a single sharp accent.",bg:"#111113",surface:"#ffffff",ink:"#111113",muted:"#6d6d73",accent:"#e0483c",accentInk:"#ffffff",headingFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#111113","#e0483c","#ffffff"]}],kvt="c0a11111-0000-4000-8000-000000000030";function w7n(){var le,ue,oe,ie,de,we,je,xe,fe,Se,Ee,Le,De,Be,Ne,Ge,_e,Oe,Ae,Xe,Ue,Ze,Qe,Ye,nt,rt,Fe,dt,Dt;const{id:s}=$i(),t=Hn(),{user:n}=Ns(),r=n7n(s),a=Fqt(),i=Oqt(),{generate:l,saveCampaign:o,deleteCampaign:c}=nZe(),[d,u]=j.useState(""),[h,m]=j.useState(null),[p,x]=j.useState(!1),[y,g]=j.useState(!1),[b,v]=j.useState(null),k=mt({queryKey:["revival-drip-campaigns",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:pt}=await U.from("drip_campaigns").select("id, name").eq("owner_user_id",n.id).order("name");return pt??[]}}),C=vt({mutationFn:async()=>{if(!n)throw new Error("Not signed in");const[{data:pt},{data:zt}]=await Promise.all([U.from("drip_campaigns").select("*").eq("id",kvt).maybeSingle(),U.from("drip_campaign_steps").select("*").eq("campaign_id",kvt).order("step_order")]);if(!pt)throw new Error("Starter campaign not found");const{data:Gt,error:qs}=await U.from("drip_campaigns").insert({owner_user_id:n.id,name:pt.name,description:pt.description,category:pt.category,icon:pt.icon,cover_color:pt.cover_color,goal:pt.goal,is_active:!0,is_starter:!1}).select("id, name").single();if(qs)throw qs;if(zt!=null&&zt.length){const{error:As}=await U.from("drip_campaign_steps").insert(zt.map(Bt=>({campaign_id:Gt.id,step_order:Bt.step_order,channel:Bt.channel,subject:Bt.subject,body:Bt.body,delay_type:Bt.delay_type,delay_days:Bt.delay_days,delay_hours:Bt.delay_hours,send_window_start:Bt.send_window_start,send_window_end:Bt.send_window_end})));if(As)throw As}return Gt},onSuccess:async pt=>{await k.refetch(),o.mutate({id:s,patch:{drip_campaign_id:pt.id}}),re.success("Expired Listing Revival drip installed and assigned")},onError:pt=>re.error(pt.message)}),T=(k.data??[]).some(pt=>{var zt;return(zt=pt.name)==null?void 0:zt.startsWith("Expired Listing Revival")}),M=mt({queryKey:["revival-agent-profile",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:pt}=await U.from("profiles").select("name, email, phone, avatar_url, brokerage_name, website_url, title").eq("id",n.id).maybeSingle();return pt}}),P=r.data,L=(P==null?void 0:P.content)??{},I=P?Iqt(P.slug):"",O={name:(le=M.data)==null?void 0:le.name,title:(ue=M.data)==null?void 0:ue.title,phone:(oe=M.data)==null?void 0:oe.phone,email:(ie=M.data)==null?void 0:ie.email,website_url:(de=M.data)==null?void 0:de.website_url,avatar_url:(we=M.data)==null?void 0:we.avatar_url,brokerage_name:(je=M.data)==null?void 0:je.brokerage_name},$=j.useRef(null),q=async()=>{var zt,Gt;const pt=(zt=$.current)==null?void 0:zt.firstElementChild;if(pt){m("letter");try{await t7n(pt,((Gt=P==null?void 0:P.property)==null?void 0:Gt.property_address)??(P==null?void 0:P.name)??"letter"),re.success("Letter PDF downloaded")}catch{re.error("Could not build the letter PDF")}finally{m(null)}}},W=j.useRef(null),G=async()=>{var zt;const pt=W.current;if(pt){m("plan");try{await Dqt(pt,((zt=P==null?void 0:P.property)==null?void 0:zt.property_address)??(P==null?void 0:P.name)??"plan"),re.success("Plan PDF downloaded")}catch{re.error("Could not build the plan PDF")}finally{m(null)}}},K=j.useMemo(()=>{var Gt,qs;const pt=(a.data??[]).filter(As=>As.campaign_id===s),zt={};return pt.forEach(As=>{zt[As.event_type]=(zt[As.event_type]??0)+1}),zt.letter=L.letter?1:0,zt.email=((Gt=L.emails)==null?void 0:Gt.length)??0,zt.sms=((qs=L.sms)==null?void 0:qs.length)??0,zt.form_submit=(i.data??[]).filter(As=>As.campaign_id===s).length,zt},[a.data,i.data,s,L]);if(r.isLoading)return e.jsx(Vs,{title:"Campaign",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin"})})});if(!P)return e.jsx(Vs,{title:"Campaign",children:e.jsx("div",{className:"py-24 text-center text-muted-foreground",children:"Campaign not found."})});const ee=Kz.find(pt=>pt.id===P.style),J=pt=>l.mutate({campaignId:P.id,section:pt,instruction:d||void 0});return e.jsxs(Vs,{title:P.name,children:[e.jsxs("div",{className:"revival-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>t("/apps/listing-revival"),children:[e.jsx(_a,{className:"h-4 w-4"})," Back to Listing Revival"]}),e.jsx(br.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{duration:.45},className:"revival-dark rounded-3xl overflow-hidden",children:e.jsxs("div",{className:"grid lg:grid-cols-[1.4fr_1fr]",children:[e.jsxs("div",{className:"p-7",children:[e.jsx("div",{className:"revival-eyebrow text-accent",children:(ee==null?void 0:ee.name)??P.style}),e.jsx("h1",{className:"revival-serif text-3xl mt-1",children:(xe=P.property)==null?void 0:xe.property_address}),e.jsxs("p",{className:"text-white/70 mt-1",children:[((fe=P.property)==null?void 0:fe.seller_name)??"Homeowner",(Se=P.property)!=null&&Se.city?` · ${P.property.city}, ${P.property.state??""}`:""]}),e.jsxs("div",{className:"mt-5 grid grid-cols-3 gap-4 max-w-md",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-white/50 text-xs uppercase tracking-wider",children:"Original"}),e.jsx("div",{className:"text-lg font-semibold",children:VE((Ee=P.property)==null?void 0:Ee.original_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-white/50 text-xs uppercase tracking-wider",children:"Final"}),e.jsx("div",{className:"text-lg font-semibold",children:VE((Le=P.property)==null?void 0:Le.final_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-white/50 text-xs uppercase tracking-wider",children:"Days on market"}),e.jsx("div",{className:"text-lg font-semibold",children:((De=P.property)==null?void 0:De.days_on_market)??"—"})]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-2",children:[e.jsx(B,{size:"sm",className:"bg-accent text-accent-foreground hover:bg-accent/90",asChild:!0,children:e.jsxs("a",{href:`/revival/${P.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1.5"})," View landing page"]})}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>{navigator.clipboard.writeText(I),re.success("Link copied")},children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-1.5"})," Copy link"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",disabled:l.isPending,onClick:()=>J(),children:[l.isPending?e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ki,{className:"h-3.5 w-3.5 mr-1.5"}),"Regenerate all"]})]})]}),e.jsxs("div",{className:"relative min-h-[220px]",children:[(Be=P.property)!=null&&Be.photo_url?e.jsx("img",{src:P.property.photo_url,alt:P.property.property_address??"",className:"absolute inset-0 h-full w-full object-cover"}):null,e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-[hsl(var(--revival-navy))] via-transparent to-transparent"})]})]})}),e.jsxs(fa,{defaultValue:"journey",className:"mt-6",children:[e.jsx(xa,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:["journey","letter","print","landing","plan","emails","texts","scripts","settings"].map(pt=>e.jsx(ss,{value:pt,className:"capitalize data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm",children:pt},pt))}),e.jsxs(ns,{value:"journey",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(rz,{className:"h-4 w-4"})," The homeowner's journey, tracked end to end."]}),e.jsx(v7n,{counts:K})]}),e.jsxs(ns,{value:"letter",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 items-center print:hidden",children:[e.jsxs(B,{size:"sm",disabled:!L.letter||h==="letter",onClick:q,children:[h==="letter"?e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(GR,{className:"h-3.5 w-3.5 mr-1.5"}),"Download print-ready PDF"]}),e.jsxs(B,{size:"sm",variant:"outline",disabled:!L.letter,onClick:()=>g(pt=>!pt),children:[e.jsx(Za,{className:"h-3.5 w-3.5 mr-1.5"})," ",y?"Close editor":"Edit letter"]}),e.jsxs(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("letter"),children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite letter"]}),e.jsx(ye,{value:d,onChange:pt=>u(pt.target.value),placeholder:"Optional instruction: e.g. shorter, warmer, mention the pool",className:"max-w-sm"})]}),y&&L.letter?e.jsx(zqt,{letter:L.letter,saving:o.isPending,onCancel:()=>g(!1),onSave:pt=>{o.mutate({id:s,patch:{content:{...L,letter:pt}}},{onSuccess:()=>g(!1)})}}):null,L.letter?e.jsx(jvt,{campaign:P,letter:L.letter,url:I,agent:O}):e.jsx("p",{className:"text-muted-foreground",children:"No letter generated yet."})]}),e.jsx(ns,{value:"print",className:"mt-6 space-y-4",children:e.jsxs("div",{className:"revival-tile p-6 space-y-5 max-w-2xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Print & mail"}),e.jsx("h3",{className:"revival-serif text-2xl mt-1",children:"Print-ready files"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Vector PDFs built at true print size with the QR code baked in — send them to your printer or mail house as-is."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-xl border border-border p-4",children:[e.jsx("div",{className:"font-semibold",children:"Personalized letter"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"8.5″ × 11″ · letterhead + signature block"}),e.jsxs(B,{size:"sm",className:"mt-3",disabled:!L.letter||h==="letter",onClick:q,children:[h==="letter"?e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(jj,{className:"h-3.5 w-3.5 mr-1.5"}),"Download letter PDF"]})]}),e.jsxs("div",{className:"rounded-xl border border-border p-4",children:[e.jsx("div",{className:"font-semibold",children:"Revival postcard"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"6″ × 9″ · front and back, mail-ready"}),e.jsxs(B,{size:"sm",className:"mt-3",disabled:h==="postcard",onClick:async()=>{var pt,zt,Gt,qs,As,Bt,At,Is,jt,Qs;m("postcard");try{await e7n({campaign:P,url:I,headline:(pt=L.landing)==null?void 0:pt.headline,subhead:(zt=L.landing)==null?void 0:zt.subheadline,message:(Gt=L.landing)==null?void 0:Gt.intro,photoDataUrl:((qs=P.property)==null?void 0:qs.photo_url)??null,agent:{name:(As=M.data)==null?void 0:As.name,title:(Bt=M.data)==null?void 0:Bt.title,phone:(At=M.data)==null?void 0:At.phone,email:(Is=M.data)==null?void 0:Is.email,website_url:(jt=M.data)==null?void 0:jt.website_url,brokerage_name:(Qs=M.data)==null?void 0:Qs.brokerage_name}}),re.success("Postcard PDF downloaded")}catch{re.error("Could not build the postcard PDF")}finally{m(null)}},children:[h==="postcard"?e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(jj,{className:"h-3.5 w-3.5 mr-1.5"}),"Download postcard PDF"]})]})]}),e.jsxs("div",{className:"rounded-xl bg-muted/50 p-4 text-sm text-muted-foreground",children:["Mailing address on file:"," ",e.jsxs("span",{className:"text-foreground font-medium",children:[((Ne=P.property)==null?void 0:Ne.mailing_address)??((Ge=P.property)==null?void 0:Ge.property_address)??"—",(_e=P.property)!=null&&_e.mailing_city?`, ${P.property.mailing_city} ${P.property.mailing_state??""} ${P.property.mailing_zip??""}`:""]})]})]})}),e.jsxs(ns,{value:"landing",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("landing"),children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite landing copy"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/revival/${P.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live page"]})})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[1fr_auto] items-start",children:[e.jsx(f7n,{campaignId:P.id,content:L,landingConfig:P.landing_config??{},propertyPhotoUrl:(Oe=P.property)==null?void 0:Oe.photo_url,saving:o.isPending,onSave:pt=>o.mutate({id:P.id,patch:pt})}),e.jsxs("div",{className:"revival-tile p-6 text-center h-fit",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Campaign QR"}),e.jsx("div",{className:"mt-3",children:e.jsx(PN,{value:I,size:168,level:"M"})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-3 max-w-[180px] break-all",children:I})]})]})]}),e.jsxs(ns,{value:"plan",className:"mt-6 space-y-4",children:[e.jsx("div",{className:"revival-tile p-5",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-accent-foreground/70",children:"Seller deliverable"}),e.jsx("h3",{className:"revival-serif text-xl mt-1",children:"The Property Revival Plan"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:"This is the branded presentation your seller receives after they opt in from the landing page or QR code. Preview it below, download it as a PDF to bring to the listing appointment, or share the live link."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("plan"),children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite plan"]}),e.jsxs(B,{size:"sm",variant:p?"secondary":"outline",onClick:()=>x(pt=>!pt),children:[e.jsx(Za,{className:"h-3.5 w-3.5 mr-1.5"})," ",p?"Done editing":"Edit plan"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/revival/${P.slug}/plan`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1.5"})," View live plan"]})}),e.jsxs(B,{size:"sm",className:"bg-accent text-accent-foreground hover:bg-accent/90",disabled:!L.plan||h==="plan",onClick:G,children:[h==="plan"?e.jsx(Wt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(jj,{className:"h-3.5 w-3.5 mr-1.5"}),"Download plan PDF"]})]})]})}),p&&L.plan?e.jsx(g7n,{plan:L.plan,saving:o.isPending,onSave:pt=>o.mutate({id:P.id,patch:{content:{...L,plan:pt}}},{onSuccess:()=>re.success("Plan updated")})}):null,L.plan?e.jsx("div",{className:"rounded-3xl bg-muted/40 p-4 sm:p-8",children:e.jsx(h$e,{plan:L.plan,property:{...P.property??{},seller_name:(Ae=P.property)==null?void 0:Ae.seller_name},agent:O,url:`${u$e()}/revival/${P.slug}/plan`})}):e.jsx("div",{className:"revival-tile p-10 text-center text-muted-foreground",children:"No plan generated yet — use “Rewrite plan”."})]}),e.jsxs(ns,{value:"emails",className:"mt-6 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("emails"),children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite emails"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Each email sends as a fully branded HTML email to contacts you choose."})]}),(L.emails??[]).map((pt,zt)=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-semibold",children:pt.subject}),e.jsx(qe,{variant:"outline",children:pt.key})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:pt.preview}),e.jsx("p",{className:"mt-3 text-sm whitespace-pre-wrap leading-relaxed",children:pt.body}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1",children:[e.jsxs(B,{size:"sm",onClick:()=>v(pt),children:[e.jsx(on,{className:"h-3.5 w-3.5 mr-1.5"})," Preview & send"]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(`${pt.subject} ${pt.body}`),re.success("Email copied")},children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]})]})]},zt))]}),e.jsxs(ns,{value:"texts",className:"mt-6 space-y-3",children:[e.jsxs(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("sms"),children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite texts"]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:(L.sms??[]).map((pt,zt)=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx(qe,{variant:"outline",children:pt.key}),e.jsx("p",{className:"mt-2 text-sm leading-relaxed",children:pt.body}),e.jsxs(B,{size:"sm",variant:"ghost",className:"mt-2",onClick:()=>{navigator.clipboard.writeText(pt.body),re.success("Text copied")},children:[e.jsx(ja,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]})]},zt))})]}),e.jsxs(ns,{value:"scripts",className:"mt-6 space-y-3",children:[e.jsxs(B,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>J("scripts"),children:[e.jsx(yn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite scripts"]}),[["Phone script",(Xe=L.scripts)==null?void 0:Xe.phone],["Voicemail",(Ue=L.scripts)==null?void 0:Ue.voicemail],["Video script",(Ze=L.scripts)==null?void 0:Ze.video],["Door knock",(Qe=L.scripts)==null?void 0:Qe.door_knock]].map(([pt,zt])=>zt?e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"font-semibold",children:pt}),e.jsx("p",{className:"mt-2 text-sm whitespace-pre-wrap leading-relaxed",children:zt})]},pt):null),(((Ye=L.scripts)==null?void 0:Ye.objections)??[]).length?e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"font-semibold",children:"Objection handlers"}),e.jsx("div",{className:"mt-3 space-y-3",children:(((nt=L.scripts)==null?void 0:nt.objections)??[]).map((pt,zt)=>e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-medium",children:["“",pt.objection,"”"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:pt.response})]},zt))})]}):null]}),e.jsx(ns,{value:"settings",className:"mt-6",children:e.jsxs("div",{className:"revival-tile p-6 space-y-5 max-w-xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{className:"font-semibold",children:"Landing page live"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn off to take the public page offline."})]}),e.jsx(Mn,{checked:P.published,onCheckedChange:pt=>o.mutate({id:P.id,patch:{published:pt}})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"font-semibold",children:"Campaign name"}),e.jsx(ye,{defaultValue:P.name,onBlur:pt=>pt.target.value!==P.name&&o.mutate({id:P.id,patch:{name:pt.target.value}})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{className:"font-semibold",children:"Landing page theme"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Changes the look of the public page instantly."}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:_7n.map(pt=>e.jsxs("button",{type:"button",onClick:()=>o.mutate({id:P.id,patch:{theme:pt.id}}),className:`text-left rounded-xl border p-3 transition-all ${(P.theme??"estate")===pt.id?"border-accent ring-2 ring-accent/40":"border-border hover:border-accent/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[pt.swatch.map(zt=>e.jsx("span",{className:"h-4 w-4 rounded-full border border-black/10",style:{background:zt}},zt)),e.jsx("span",{className:"font-medium ml-1",children:pt.name})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:pt.description})]},pt.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border pt-4",children:[e.jsxs("div",{children:[e.jsxs(se,{className:"font-semibold flex items-center gap-1.5",children:[e.jsx(f3,{className:"h-4 w-4"})," Alert me on engagement"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Email me the first time this homeowner scans or visits."})]}),e.jsx(Mn,{checked:!!P.alert_on_engagement,onCheckedChange:pt=>o.mutate({id:P.id,patch:{alert_on_engagement:pt}})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(se,{className:"font-semibold flex items-center gap-1.5",children:[e.jsx(on,{className:"h-4 w-4"})," Auto-enroll new leads in a drip"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sellers who submit the form get added to this campaign automatically."}),e.jsxs(vs,{value:P.drip_campaign_id??"none",onValueChange:pt=>o.mutate({id:P.id,patch:{drip_campaign_id:pt==="none"?null:pt}}),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"No drip campaign"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"No drip campaign"}),(k.data??[]).map(pt=>e.jsx(Je,{value:pt.id,children:pt.name},pt.id))]})]}),!T&&e.jsxs("div",{className:"mt-3 rounded-xl border border-amber-500/30 bg-amber-500/5 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Recommended: Expired Listing Revival (8 emails, 45 days)"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"A luxury-styled nurture written for homeowners whose listing expired — confirmation, why homes expire, the 5-part relaunch plan, pricing truth, presentation, a case study, and two graceful closes."}),e.jsx(B,{size:"sm",className:"mt-3",disabled:C.isPending,onClick:()=>C.mutate(),children:C.isPending?"Installing…":"Install & assign to this campaign"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"font-semibold",children:"Internal notes"}),e.jsx(Ds,{rows:4,defaultValue:((rt=P.branding)==null?void 0:rt.notes)??"",onBlur:pt=>o.mutate({id:P.id,patch:{branding:{...P.branding,notes:pt.target.value}}})})]}),e.jsx("div",{className:"border-t border-border pt-4",children:e.jsxs(B,{variant:"destructive",size:"sm",onClick:async()=>{await Bi("Delete this campaign? The landing page will stop working.")&&c.mutate(P.id,{onSuccess:()=>t("/apps/listing-revival")})},children:[e.jsx(Rn,{className:"h-3.5 w-3.5 mr-1.5"})," Delete campaign"]})})]})})]}),L.letter?e.jsx("div",{ref:$,"aria-hidden":!0,className:"pointer-events-none fixed left-[-10000px] top-0 w-[816px]",children:e.jsx(jvt,{campaign:P,letter:L.letter,url:I,agent:O,className:"shadow-none"})}):null,L.plan?e.jsx("div",{ref:W,"aria-hidden":!0,className:"pointer-events-none fixed left-[-10000px] top-0 w-[816px]",children:e.jsx(h$e,{plan:L.plan,property:{...P.property??{},seller_name:(Fe=P.property)==null?void 0:Fe.seller_name},agent:O,url:`${u$e()}/revival/${P.slug}/plan`})}):null]}),e.jsx(b7n,{open:!!b,onOpenChange:pt=>!pt&&v(null),campaignId:P.id,email:b,ctaUrl:I,seller:{name:(dt=P.property)==null?void 0:dt.seller_name,email:(Dt=P.property)==null?void 0:Dt.seller_email}})]})}function Bqt(){const{user:s}=Ns();return mt({queryKey:["fsbo-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_campaigns").select("*, property:fsbo_properties(*)").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function j7n(s){return mt({queryKey:["fsbo-campaign",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_campaigns").select("*, property:fsbo_properties(*)").eq("id",s).maybeSingle();if(n)throw n;return t??null}})}function $qt(){const{user:s}=Ns();return mt({queryKey:["fsbo-properties",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_properties").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function rZe(){const{user:s}=Ns();return mt({queryKey:["fsbo-leads",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_leads").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function N7n(){const{user:s}=Ns();return mt({queryKey:["fsbo-tasks",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_tasks").select("*").order("due_date",{ascending:!0});if(n)throw n;return t??[]}})}function aZe(){const{user:s}=Ns();return mt({queryKey:["fsbo-events",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await U.from("fsbo_events").select("*").order("created_at",{ascending:!1}).limit(1e3);if(n)throw n;return t??[]}})}function iZe(){const s=as(),t=()=>{["fsbo-campaigns","fsbo-campaign","fsbo-properties","fsbo-leads","fsbo-tasks","fsbo-events"].forEach(o=>s.invalidateQueries({queryKey:[o]}))},n=vt({mutationFn:async o=>{const{data:c,error:d}=await U.functions.invoke("fsbo-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(String(c.error));return c},onSuccess:t,onError:o=>re.error(o.message)}),r=vt({mutationFn:async o=>{const{error:c}=await U.from("fsbo_campaigns").update(o.patch).eq("id",o.id);if(c)throw c},onSuccess:()=>{t(),re.success("Saved")},onError:o=>re.error(o.message)}),a=vt({mutationFn:async o=>{const{error:c}=await U.from("fsbo_campaigns").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t(),re.success("Campaign deleted")},onError:o=>re.error(o.message)}),i=vt({mutationFn:async o=>{const{error:c}=await U.from("fsbo_campaigns").update({status:o.archived?"archived":"draft",published:!o.archived}).eq("id",o.id);if(c)throw c;return o},onSuccess:o=>{t(),re.success(o.archived?"Campaign archived":"Campaign restored")},onError:o=>re.error(o.message)}),l=vt({mutationFn:async o=>{const{error:c}=await U.from("fsbo_tasks").update({completed_at:o.done?new Date().toISOString():null}).eq("id",o.id);if(c)throw c},onSuccess:t,onError:o=>re.error(o.message)});return{generate:n,saveCampaign:r,deleteCampaign:a,archiveCampaign:i,toggleTask:l,invalidate:t}}function k7n(s){const t=(s??"").trim();if(!t)return null;const n=t.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{6,})/);if(n)return{kind:"iframe",src:`https://www.youtube.com/embed/${n[1]}`};const r=t.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(r)return{kind:"iframe",src:`https://player.vimeo.com/video/${r[1]}`};const a=t.match(/loom\.com\/(?:share|embed)\/([\w-]+)/);return a?{kind:"iframe",src:`https://www.loom.com/embed/${a[1]}`}:/\.(mp4|webm|mov|m4v)(\?|$)/i.test(t)?{kind:"file",src:t}:{kind:"iframe",src:t}}const WSe=[{id:"market_expert",name:"Market Expert",tagline:"Data, not pressure",description:"Consultative and informed. Shows the seller what the market is actually doing without pushing them toward an agent.",accent:"from-teal-500/20 to-teal-500/0",previewHeadline:"What the Market Is Really Telling You",previewBody:"A clear look at buyer activity, pricing, and the places FSBO sellers most often miss."},{id:"friendly_neighbor",name:"Friendly Neighbor",tagline:"Helpful advice first",description:"Warm and personal — feels like a neighbor who knows the street and wants the best outcome.",accent:"from-amber-500/20 to-amber-500/0",previewHeadline:"A Friendly Note From the Neighborhood",previewBody:"I saw your home is for sale by owner and I wanted to share a guide that might help."},{id:"professional_review",name:"Professional Review",tagline:"Structured & credible",description:"Polished and businesslike. A clear assessment of the FSBO process with a proven next-step plan.",accent:"from-indigo-500/20 to-indigo-500/0",previewHeadline:"A Professional FSBO Review",previewBody:"An honest, structured look at the advantages, risks, and what a pro would watch."},{id:"equity_advocate",name:"Equity Advocate",tagline:"Maximize net proceeds",description:"Focuses on the money. Helps the seller understand hidden costs and the math behind selling alone.",accent:"from-emerald-500/20 to-emerald-500/0",previewHeadline:"The True Math of Selling On Your Own",previewBody:"Commission isn't the only number that matters. Here's what to count before you decide."},{id:"second_opinion",name:"Second Opinion",tagline:"No pressure perspective",description:"Respectful and non-defensive. Offers a free second opinion for a smart seller who may simply want a fresh set of eyes.",accent:"from-sky-500/20 to-sky-500/0",previewHeadline:"Would a Second Opinion Help?",previewBody:"You know your home best. I just want to offer a free, no-obligation perspective if it's useful."}],Uqt=[{id:"professional",name:"Professional",note:"Polished and businesslike"},{id:"friendly",name:"Friendly",note:"Warm and conversational"},{id:"consultative",name:"Consultative",note:"Curious and patient"},{id:"minimal",name:"Minimal",note:"Short and direct"},{id:"modern",name:"Modern",note:"Crisp and confident"}],S7n=[{value:"single_family",label:"Single Family"},{value:"condo",label:"Condo"},{value:"townhouse",label:"Townhouse"},{value:"multi_family",label:"Multi-Family"},{value:"land",label:"Land"},{value:"luxury",label:"Luxury"},{value:"commercial",label:"Commercial"},{value:"other",label:"Other"}],C7n=[{value:"immediately",label:"As soon as possible"},{value:"0-30",label:"In the next 30 days"},{value:"1-3",label:"In the next 1–3 months"},{value:"3-6",label:"In 3–6 months"},{value:"6-12",label:"In 6–12 months"},{value:"just_curious",label:"Just curious for now"}],A7n=["Need to sell quickly","Want to maximize net proceeds","Testing the market","Already bought another home","Relocating","Downsizing / Upsizing","Estate sale","Other"],T7n=[{value:"email",label:"Email"},{value:"phone",label:"Phone"},{value:"text",label:"Text"}];function m$e(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function E7n(s){const t=m$e(s)||"property",n=Math.random().toString(36).slice(2,7);return`${t}-${n}`}function qqt(s){return s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`}function M7n(){return typeof window>"u"?"":window.location.origin}function Vqt(s){return`${M7n()}/fsbo/${s}`}const Svt="fsbo_breakthrough";function L7n(){const{user:s,loading:t,isAdmin:n}=Ns(),{data:r}=mt({queryKey:["feature-entitlement",Svt,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await U.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",Svt).maybeSingle();if(i)throw i;return{tier:(a==null?void 0:a.tier)??null}}});return{hasAccess:!0,tier:n?"admin":(r==null?void 0:r.tier)??null,isLoading:t}}const P7n=[{id:"dashboard",label:"Dashboard",icon:vf},{id:"campaigns",label:"Campaigns",icon:yn},{id:"properties",label:"Properties",icon:ia},{id:"letters",label:"Letters",icon:on},{id:"landing",label:"Landing Pages",icon:Ql},{id:"guides",label:"Seller Guides",icon:$r},{id:"followup",label:"Follow Up",icon:r1},{id:"analytics",label:"Analytics",icon:ol},{id:"templates",label:"Templates",icon:q_},{id:"settings",label:"Settings",icon:tE}];function Ak({label:s,value:t,icon:n,delay:r=0,hint:a}){return e.jsxs(br.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:r,duration:.45,ease:[.22,1,.36,1]},className:"fsbo-tile p-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("span",{className:"fsbo-eyebrow text-muted-foreground",children:s}),e.jsx(n,{className:"h-4 w-4 text-accent"})]}),e.jsx("div",{className:"mt-3 text-3xl font-bold tabular-nums tracking-tight",children:t}),a?e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:a}):null]})}function I7n(){const s=Hn(),[t,n]=j.useState("dashboard"),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(null),d=L7n(),u=Bqt(),h=$qt(),m=rZe(),p=N7n(),x=aZe(),{toggleTask:y,archiveCampaign:g,deleteCampaign:b}=iZe(),v=u.data??[],k=m.data??[],C=x.data??[],T=p.data??[],M=j.useMemo(()=>{const G=K=>C.filter(ee=>ee.event_type===K).length;return{properties:(h.data??[]).length,campaigns:v.length,letters:v.filter(K=>{var ee;return(ee=K.content)==null?void 0:ee.letter}).length,qr:G("qr_scan"),visits:G("page_view"),guideViews:G("guide_view"),leads:k.length,appointments:G("appointment"),listed:k.filter(K=>K.temperature==="hot").length,hot:k.filter(K=>K.temperature==="hot").length}},[v,k,C,h.data]),P=j.useMemo(()=>{const G=[];for(let K=13;K>=0;K--){const ee=new Date(Date.now()-K*864e5),J=ee.toISOString().slice(0,10);G.push({day:Bs(ee,"MMM d"),visits:C.filter(le=>le.event_type==="page_view"&&le.created_at.startsWith(J)).length,scans:C.filter(le=>le.event_type==="qr_scan"&&le.created_at.startsWith(J)).length,leads:k.filter(le=>le.created_at.startsWith(J)).length})}return G},[C,k]),L=G=>G.status==="archived",I=v.filter(G=>{var ee,J;if(i?!L(G):L(G))return!1;const K=r.trim().toLowerCase();return K?`${G.name} ${((ee=G.property)==null?void 0:ee.property_address)??""} ${((J=G.property)==null?void 0:J.seller_name)??""}`.toLowerCase().includes(K):!0}),O=v.filter(L).length,$=G=>s(`/apps/fsbo-breakthrough/campaigns/${G}`),q=G=>{navigator.clipboard.writeText(Vqt(G)),re.success("Landing page link copied")},W=G=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative max-w-sm flex-1 min-w-[200px]",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:r,onChange:K=>a(K.target.value),placeholder:"Search campaigns…",className:"pl-9"})]}),e.jsxs(B,{variant:i?"default":"outline",size:"sm",onClick:()=>l(K=>!K),children:[e.jsx(gm,{className:"h-3.5 w-3.5 mr-1.5"}),i?"Viewing archived":`Archived (${O})`]})]}),I.length===0?e.jsx("div",{className:"fsbo-tile p-10 text-center text-muted-foreground",children:i?"No archived campaigns.":G}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:I.map((K,ee)=>{var ie,de,we,je;const J=WSe.find(xe=>xe.id===K.style),le=k.filter(xe=>xe.campaign_id===K.id).length,ue=C.filter(xe=>xe.campaign_id===K.id&&xe.event_type==="page_view").length,oe=L(K);return e.jsxs(br.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:Math.min(ee*.04,.3),duration:.4},className:Et("fsbo-tile overflow-hidden",oe&&"opacity-80"),children:[e.jsxs("div",{className:"h-28 bg-muted relative",children:[(ie=K.property)!=null&&ie.photo_url?e.jsx("img",{src:K.property.photo_url,alt:K.property.property_address??"",className:"h-full w-full object-cover",loading:"lazy"}):e.jsx("div",{className:"h-full w-full fsbo-dark grid place-items-center",children:e.jsx(ia,{className:"h-7 w-7 text-accent"})}),e.jsx(qe,{className:"absolute top-3 left-3 bg-background/90 text-foreground border-0",children:(J==null?void 0:J.name)??K.style}),oe?e.jsx(qe,{className:"absolute top-3 right-3 bg-foreground/85 text-background border-0",children:"Archived"}):null]}),e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight",children:((de=K.property)==null?void 0:de.property_address)??K.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:((we=K.property)==null?void 0:we.seller_name)??"Homeowner"}),e.jsxs("div",{className:"mt-3 flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ql,{className:"h-3.5 w-3.5"}),ue]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3.5 w-3.5"}),le]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3.5 w-3.5"}),((je=K.property)==null?void 0:je.property_type)??"—"]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs(B,{size:"sm",className:"flex-1",onClick:()=>$(K.id),children:["Open ",e.jsx(Xa,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>q(K.slug),children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:`/fsbo/${K.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{size:"sm",variant:"outline",children:e.jsx(W0,{className:"h-3.5 w-3.5"})})}),e.jsxs(xd,{align:"end",children:[e.jsx(wa,{onClick:()=>g.mutate({id:K.id,archived:!oe}),children:oe?e.jsxs(e.Fragment,{children:[e.jsx(zT,{className:"h-4 w-4 mr-2"})," Restore campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(gm,{className:"h-4 w-4 mr-2"})," Archive campaign"]})}),e.jsx(uy,{}),e.jsxs(wa,{className:"text-destructive focus:text-destructive",onClick:()=>{var xe;return c({id:K.id,name:((xe=K.property)==null?void 0:xe.property_address)??K.name})},children:[e.jsx(Rn,{className:"h-4 w-4 mr-2"})," Delete permanently"]})]})]})]})]})]},K.id)})}),e.jsx(Nl,{open:!!o,onOpenChange:K=>!K&&c(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete this campaign?"}),e.jsxs(xl,{children:[o==null?void 0:o.name," — the letter, landing page, QR link, seller guide and follow-up tasks will be permanently removed. This can't be undone. Archive instead if you may need it later."]})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{o&&b.mutate(o.id),c(null)},children:"Delete permanently"})]})]})})]});return!d.isLoading&&!d.hasAccess?e.jsx(Vs,{title:"By-Owner Breakthrough",children:e.jsx("div",{className:"fsbo-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)] grid place-items-center",children:e.jsxs("div",{className:"fsbo-tile p-10 text-center max-w-lg",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-2xl fsbo-dark grid place-items-center",children:e.jsx(yn,{className:"h-6 w-6 text-accent"})}),e.jsx("h2",{className:"fsbo-serif text-2xl mt-4",children:"By-Owner Breakthrough is invite-only"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"This tool is currently being rolled out to select LevelUp members. Reach out to your coach to request early access."})]})})}):e.jsx(Vs,{title:"By-Owner Breakthrough",children:e.jsxs("div",{className:"fsbo-theme relative -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(br.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},transition:{duration:.55,ease:[.22,1,.36,1]},className:"fsbo-dark rounded-3xl px-6 sm:px-10 py-9 relative overflow-hidden",children:[e.jsx("div",{className:"absolute -right-10 -top-16 h-56 w-56 rounded-full bg-accent/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"fsbo-eyebrow text-accent",children:"By-Owner Breakthrough"}),e.jsx("h1",{className:"fsbo-serif text-3xl sm:text-[42px] leading-tight mt-2 max-w-2xl",children:"Turn FSBOs Into Listing Appointments."}),e.jsx("p",{className:"text-white/70 mt-3 max-w-xl",children:"Add a for-sale-by-owner property, choose a voice, and generate a complete campaign: letter, QR code, landing page, seller guide, scripts, and follow-up tasks."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsxs(B,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>s("/apps/fsbo-breakthrough/new"),children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," New Campaign"]}),e.jsx(B,{size:"lg",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>n("campaigns"),children:"View campaigns"})]})]})]}),e.jsxs(fa,{value:t,onValueChange:n,className:"mt-6",children:[e.jsx(xa,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:P7n.map(G=>e.jsxs(ss,{value:G.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm whitespace-nowrap",children:[e.jsx(G.icon,{className:"h-3.5 w-3.5 mr-1.5"}),G.label]},G.id))}),e.jsxs(ns,{value:"dashboard",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-5",children:[e.jsx(Ak,{label:"Properties",value:M.properties,icon:ia,delay:0}),e.jsx(Ak,{label:"Campaigns",value:M.campaigns,icon:yn,delay:.04}),e.jsx(Ak,{label:"Letters",value:M.letters,icon:on,delay:.08}),e.jsx(Ak,{label:"QR Scans",value:M.qr,icon:hg,delay:.12}),e.jsx(Ak,{label:"Page Visits",value:M.visits,icon:Ql,delay:.16}),e.jsx(Ak,{label:"Guide Views",value:M.guideViews,icon:$r,delay:.2}),e.jsx(Ak,{label:"Seller Leads",value:M.leads,icon:Bn,delay:.24}),e.jsx(Ak,{label:"Appointments",value:M.appointments,icon:n1,delay:.28}),e.jsx(Ak,{label:"Hot Leads",value:M.hot,icon:Fd,delay:.32,hint:"Score 75+"}),e.jsx(Ak,{label:"Listings Won",value:M.listed,icon:ll,delay:.36})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsxs("div",{className:"fsbo-tile p-5 lg:col-span-2",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Last 14 days"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Homeowner engagement"}),e.jsx("div",{className:"h-64 mt-4",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(fWe,{data:P,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"fsboVisits",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"fsboLeads",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--accent))",stopOpacity:.5}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--accent))",stopOpacity:0})]})]}),e.jsx(KD,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(p1,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(f1,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(ff,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(Nb,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#fsboVisits)",strokeWidth:2}),e.jsx(Nb,{type:"monotone",dataKey:"leads",stroke:"hsl(var(--accent))",fill:"url(#fsboLeads)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Next up"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Your tasks"}),e.jsxs("div",{className:"mt-4 space-y-2",children:[T.filter(G=>!G.completed_at).slice(0,5).map(G=>e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/40",children:[e.jsx(wi,{checked:!!G.completed_at,onCheckedChange:K=>y.mutate({id:G.id,done:!!K})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium",children:G.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:G.detail}),G.due_date?e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Due ",G.due_date]}):null]})]},G.id)),!T.filter(G=>!G.completed_at).length&&e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:"No open tasks — create a campaign to get started."})]})]})]})]}),e.jsx(ns,{value:"campaigns",className:"mt-6",children:W("No campaigns yet. Start with a new FSBO property.")}),e.jsx(ns,{value:"properties",className:"mt-6",children:e.jsx("div",{className:"space-y-3",children:(h.data??[]).length===0?e.jsx("div",{className:"fsbo-tile p-10 text-center text-muted-foreground",children:"No FSBO properties added yet."}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:(h.data??[]).map(G=>e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:G.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[G.city,G.city&&G.state?", ":"",G.state]}),e.jsx("div",{className:"mt-2 text-sm",children:G.seller_name||"—"}),e.jsxs("div",{className:"mt-1 text-sm text-muted-foreground",children:["Est. value ",qqt(G.estimated_value)]})]},G.id))})})}),e.jsx(ns,{value:"followup",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold",children:"All follow-up tasks"}),e.jsx("div",{className:"mt-4 space-y-2",children:T.map(G=>e.jsxs("div",{className:Et("flex items-start gap-3 p-3 rounded-lg",G.completed_at?"bg-muted/30":"bg-muted/40"),children:[e.jsx(wi,{checked:!!G.completed_at,onCheckedChange:K=>y.mutate({id:G.id,done:!!K})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:Et("text-sm font-medium",G.completed_at&&"line-through text-muted-foreground"),children:G.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:G.detail}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 capitalize",children:[G.channel," · ",G.due_date??"No due date"]})]})]},G.id))})]})}),e.jsx(ns,{value:"analytics",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Recent events"}),e.jsx("div",{className:"mt-4 space-y-2",children:C.slice(0,50).map(G=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/40",children:[e.jsx("div",{className:"text-sm capitalize",children:G.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Bs(new Date(G.created_at),"MMM d, h:mm a")})]},G.id))})]})}),e.jsx(ns,{value:"letters",className:"mt-6",children:W("Generate letter content by creating a campaign first.")}),e.jsx(ns,{value:"landing",className:"mt-6",children:W("Generate landing pages by creating a campaign first.")}),e.jsx(ns,{value:"guides",className:"mt-6",children:W("Generate seller guides by creating a campaign first.")}),e.jsx(ns,{value:"templates",className:"mt-6",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:Uqt.map(G=>e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:G.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:G.note})]},G.id))})}),e.jsx(ns,{value:"settings",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5 max-w-xl",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Campaign style, tone, and landing page settings are managed inside each campaign."})]})})]})]})})}const Cvt=["Add the property","Choose the campaign voice","Generate everything"];function R7n(){const s=Hn(),{user:t}=Ns(),{generate:n,invalidate:r}=iZe(),[a,i]=j.useState(0),[l,o]=j.useState(!1),[c,d]=j.useState(WSe[0].id),[u,h]=j.useState("professional"),[m,p]=j.useState({property_address:"",city:"",state:"",zip:"",property_type:"single_family",estimated_value:"",seller_name:"",seller_email:"",seller_phone:"",notes:"",photo_url:""}),x=(v,k)=>p(C=>({...C,[v]:k})),y=a===0?m.property_address.trim().length>3:!0,g=async()=>{if(t){o(!0);try{const{data:v,error:k}=await U.from("fsbo_properties").insert({owner_user_id:t.id,property_address:m.property_address.trim(),city:m.city||null,state:m.state||null,zip:m.zip||null,property_type:m.property_type||"single_family",estimated_value:m.estimated_value?Number(m.estimated_value):null,seller_name:m.seller_name||null,seller_email:m.seller_email||null,seller_phone:m.seller_phone||null,notes:m.notes||null,photo_url:m.photo_url||null}).select().single();if(k)throw k;const{data:C,error:T}=await U.from("fsbo_campaigns").insert({owner_user_id:t.id,property_id:v.id,name:m.property_address.trim(),slug:E7n(m.property_address),style:c,tone:u,status:"generating",published:!0}).select().single();if(T)throw T;await n.mutateAsync({campaignId:C.id}),r(),re.success("Campaign built — everything is ready."),s(`/apps/fsbo-breakthrough/campaigns/${C.id}`)}catch(v){re.error(v instanceof Error?v.message:"Could not create the campaign")}finally{o(!1)}}},b=(v,k,C={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:k}),e.jsx(ye,{value:m[v],onChange:T=>x(v,T.target.value),...C})]});return e.jsx(Vs,{title:"New FSBO Campaign",children:e.jsxs("div",{className:"fsbo-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>s("/apps/fsbo-breakthrough"),children:[e.jsx(_a,{className:"h-4 w-4"})," Back to By-Owner Breakthrough"]}),e.jsx("div",{className:"flex items-center gap-3 mb-6",children:Cvt.map((v,k)=>e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:Et("h-9 w-9 rounded-full grid place-items-center text-sm font-bold shrink-0 transition-colors",kx("property_type",v.target.value),children:S7n.map(v=>e.jsx("option",{value:v.value,children:v.label},v.value))})]}),b("seller_name","Seller name"),b("seller_email","Seller email",{type:"email"}),b("seller_phone","Seller phone")]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Property photo"}),e.jsx(gee,{value:m.photo_url,onChange:v=>x("photo_url",v??""),label:"Property photo",prefix:"fsbo-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Ds,{rows:6,value:m.notes,onChange:v=>x("notes",v.target.value),placeholder:"Anything you know: asking price, why they're selling solo, motivation, photos, etc."})]})]})]}):null,a===1?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"fsbo-tile p-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Step two"}),e.jsx("h2",{className:"fsbo-serif text-2xl mt-1",children:"Pick the voice of the campaign"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"The style shapes the letter, the landing page and the whole follow-up sequence."}),e.jsx("div",{className:"grid gap-3 mt-5 md:grid-cols-2 xl:grid-cols-3",children:WSe.map(v=>e.jsxs("button",{onClick:()=>d(v.id),className:Et("text-left p-5 rounded-xl border transition-all relative overflow-hidden",c===v.id?"border-primary bg-primary/5":"border-border bg-card hover:border-primary/30"),children:[e.jsx("div",{className:Et("absolute inset-x-0 top-0 h-1 bg-gradient-to-r",v.accent)}),e.jsx("div",{className:"font-semibold",children:v.name}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:v.tagline}),e.jsx("div",{className:"text-sm text-muted-foreground mt-2",children:v.description}),e.jsx("div",{className:"mt-3 text-xs text-primary font-medium",children:v.previewHeadline}),e.jsx("div",{className:"text-xs text-muted-foreground",children:v.previewBody})]},v.id))})]}),e.jsxs("div",{className:"fsbo-tile p-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Letter tone"}),e.jsx("div",{className:"grid gap-3 mt-3 sm:grid-cols-2 lg:grid-cols-5",children:Uqt.map(v=>e.jsxs("button",{onClick:()=>h(v.id),className:Et("p-4 rounded-xl border text-left transition-all",u===v.id?"border-primary bg-primary/5":"border-border bg-card hover:border-primary/30"),children:[e.jsx("div",{className:"font-medium",children:v.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:v.note})]},v.id))})]})]}):null,a===2?e.jsxs("div",{className:"fsbo-tile p-10 text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-primary/10 grid place-items-center mb-4",children:e.jsx(um,{className:"h-6 w-6 text-primary"})}),e.jsx("h2",{className:"fsbo-serif text-2xl",children:"Ready to build your campaign"}),e.jsxs("p",{className:"text-muted-foreground mt-2 max-w-md mx-auto",children:["We'll generate the letter, landing page, seller guide, follow-up scripts, and task sequence for",e.jsxs("span",{className:"font-semibold text-foreground",children:[" ",m.property_address||"this property"]}),"."]}),e.jsx("div",{className:"mt-6 flex justify-center",children:e.jsxs(B,{size:"lg",onClick:g,disabled:l,children:[l?e.jsx(Wt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yn,{className:"h-4 w-4 mr-2"}),"Generate campaign"]})})]}):null]},a)}),e.jsxs("div",{className:"flex justify-between mt-6",children:[e.jsxs(B,{variant:"outline",disabled:a===0,onClick:()=>i(v=>v-1),children:[e.jsx(_a,{className:"h-4 w-4 mr-1"})," Back"]}),a<2&&e.jsxs(B,{disabled:!y,onClick:()=>i(v=>v+1),children:["Next ",e.jsx(Xa,{className:"h-4 w-4 ml-1"})]})]})]})})}function D7n(){var ue,oe,ie,de,we,je,xe,fe,Se,Ee,Le,De,Be,Ne,Ge;const{id:s}=$i(),t=Hn(),{user:n}=Ns(),r=j7n(s),a=aZe(),i=rZe(),{generate:l,saveCampaign:o,deleteCampaign:c}=iZe(),[d,u]=j.useState(""),[h,m]=j.useState(!1),[p,x]=j.useState("letter"),[y,g]=j.useState(!1),b=r.data,v=(b==null?void 0:b.content)??{},k=b?Vqt(b.slug):"",C=mt({queryKey:["fsbo-agent-profile",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:_e}=await U.from("profiles").select("name, email, phone, avatar_url, brokerage_name, website_url, title").eq("id",n.id).maybeSingle();return _e}}),T={name:(ue=C.data)==null?void 0:ue.name,title:(oe=C.data)==null?void 0:oe.title,phone:(ie=C.data)==null?void 0:ie.phone,email:(de=C.data)==null?void 0:de.email,website_url:(we=C.data)==null?void 0:we.website_url,avatar_url:(je=C.data)==null?void 0:je.avatar_url,brokerage_name:(xe=C.data)==null?void 0:xe.brokerage_name},M=j.useRef(null),P=j.useRef(null),L=j.useMemo(()=>{var Ae,Xe;const _e=(a.data??[]).filter(Ue=>Ue.campaign_id===s),Oe={};return _e.forEach(Ue=>{Oe[Ue.event_type]=(Oe[Ue.event_type]??0)+1}),Oe.letter=v.letter?1:0,Oe.email=((Ae=v.emails)==null?void 0:Ae.length)??0,Oe.sms=((Xe=v.sms)==null?void 0:Xe.length)??0,Oe.form_submit=(i.data??[]).filter(Ue=>Ue.campaign_id===s).length,Oe},[a.data,i.data,s,v]),I=async()=>{var _e;if(M.current){m(!0);try{const Oe=await L$(M.current,{pixelRatio:2}),Ae=document.createElement("a");Ae.href=Oe;const Xe=m$e(((_e=b==null?void 0:b.property)==null?void 0:_e.property_address)??"letter");Ae.download=`${Xe||"letter"}.png`,Ae.click(),re.success("Letter image downloaded")}catch{re.error("Could not download letter")}finally{m(!1)}}},O=async()=>{var _e;if(P.current){m(!0);try{const Oe=await L$(P.current,{pixelRatio:2}),Ae=document.createElement("a");Ae.href=Oe;const Xe=m$e(((_e=b==null?void 0:b.property)==null?void 0:_e.property_address)??"guide");Ae.download=`${Xe||"guide"}-guide.png`,Ae.click(),re.success("Guide image downloaded")}catch{re.error("Could not download guide")}finally{m(!1)}}},$=_e=>{s&&(l.mutate({campaignId:s,section:_e,instruction:d}),u(""))};if(r.isLoading)return e.jsx(Vs,{title:"Campaign",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin"})})});if(!b)return e.jsx(Vs,{title:"Campaign",children:e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"Campaign not found."})});const q=WSe.find(_e=>_e.id===b.style),W=v.letter,G=v.landing,K=v.guide,ee=v.emails??[],J=v.sms??[],le=v.scripts;return e.jsx(Vs,{title:"FSBO Campaign",children:e.jsxs("div",{className:"fsbo-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>t("/apps/fsbo-breakthrough"),children:[e.jsx(_a,{className:"h-4 w-4"})," Back to By-Owner Breakthrough"]}),e.jsxs("div",{className:"fsbo-dark rounded-2xl p-6 sm:p-8 relative overflow-hidden",children:[e.jsx("div",{className:"absolute -right-10 -top-16 h-56 w-56 rounded-full bg-accent/20 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col lg:flex-row lg:items-center justify-between gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"fsbo-eyebrow text-accent",children:[(q==null?void 0:q.name)??b.style," · ",b.status]}),e.jsx("h1",{className:"fsbo-serif text-2xl sm:text-3xl mt-1",children:((fe=b.property)==null?void 0:fe.property_address)??b.name}),e.jsxs("p",{className:"text-white/70 mt-1",children:[((Se=b.property)==null?void 0:Se.seller_name)||"Homeowner"," · ",(Ee=b.property)==null?void 0:Ee.city,(Le=b.property)!=null&&Le.city&&((De=b.property)!=null&&De.state)?", ":"",(Be=b.property)==null?void 0:Be.state,(Ne=b.property)!=null&&Ne.estimated_value?` · Est. ${qqt(b.property.estimated_value)}`:""]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",asChild:!0,children:e.jsxs("a",{href:k,target:"_blank",rel:"noreferrer",children:[e.jsx(Ql,{className:"h-4 w-4 mr-1"})," Preview"]})}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>{navigator.clipboard.writeText(k),re.success("Copied")},children:[e.jsx(ja,{className:"h-4 w-4 mr-1"})," Copy link"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>$(),children:[e.jsx(Ki,{className:"h-4 w-4 mr-1"})," Regenerate"]}),e.jsx(B,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20 hover:text-destructive",onClick:()=>c.mutate(b.id),children:e.jsx(Rn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"Page visits"}),e.jsx("div",{className:"text-xl font-bold",children:L.page_view??0})]}),e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"QR scans"}),e.jsx("div",{className:"text-xl font-bold",children:L.qr_scan??0})]}),e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"Leads"}),e.jsx("div",{className:"text-xl font-bold",children:L.form_submit??0})]}),e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"Guide views"}),e.jsx("div",{className:"text-xl font-bold",children:L.guide_view??0})]})]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsx(ye,{placeholder:"Tell AI what to change (e.g., 'make it shorter', 'focus on luxury buyers')...",value:d,onChange:_e=>u(_e.target.value),className:"max-w-xl"}),e.jsx(B,{variant:"outline",onClick:()=>$(),disabled:l.isPending,children:l.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):e.jsx(yn,{className:"h-4 w-4"})})]}),e.jsxs(fa,{value:p,onValueChange:x,className:"mt-6",children:[e.jsx(xa,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:[{id:"letter",label:"Letter",icon:on},{id:"landing",label:"Landing Page",icon:Ql},{id:"guide",label:"Seller Guide",icon:$r},{id:"scripts",label:"Scripts & Drip",icon:ro},{id:"leads",label:"Leads",icon:pa}].map(_e=>e.jsxs(ss,{value:_e.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm whitespace-nowrap",children:[e.jsx(_e.icon,{className:"h-3.5 w-3.5 mr-1.5"})," ",_e.label]},_e.id))}),e.jsxs(ns,{value:"letter",className:"mt-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Mail-ready letter"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>g(_e=>!_e),disabled:!W,children:[e.jsx(Za,{className:"h-4 w-4 mr-1"})," ",y?"Close editor":"Edit letter"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:I,disabled:h,children:[e.jsx(jj,{className:"h-4 w-4 mr-1"})," Download image"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>window.print(),children:[e.jsx(GR,{className:"h-4 w-4 mr-1"})," Print"]})]})]}),y&&W?e.jsx("div",{className:"mb-6 print:hidden",children:e.jsx(zqt,{letter:W,saving:o.isPending,onCancel:()=>g(!1),onSave:_e=>{o.mutate({id:s,patch:{content:{...v,letter:_e}}},{onSuccess:()=>g(!1)})}})}):null,e.jsx("div",{className:"fsbo-tile p-6 max-w-3xl mx-auto",children:e.jsxs("div",{ref:M,className:"bg-white text-foreground p-8 sm:p-12 rounded-lg shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{children:[T.name?e.jsx("div",{className:"font-bold text-lg",children:T.name}):null,T.title?e.jsx("div",{className:"text-sm text-gray-600",children:T.title}):null,T.brokerage_name?e.jsx("div",{className:"text-sm text-gray-600",children:T.brokerage_name}):null]}),T.avatar_url?e.jsx("img",{src:T.avatar_url,alt:T.name??"",className:"h-16 w-16 rounded-full object-cover"}):null]}),W?e.jsxs("div",{className:"space-y-4 text-[15px] leading-relaxed",children:[e.jsx("div",{children:W.greeting}),W.paragraphs.map((_e,Oe)=>e.jsx("p",{children:_e},Oe)),e.jsx("div",{children:W.closing}),e.jsx("div",{className:"font-semibold",children:W.signature}),e.jsx("div",{className:"text-sm text-gray-600 italic mt-4",children:W.ps})]}):e.jsx("div",{className:"text-muted-foreground",children:"Letter content not generated yet."}),e.jsxs("div",{className:"mt-8 pt-6 border-t flex items-center gap-4",children:[e.jsx("div",{className:"h-24 w-24 shrink-0",children:e.jsx(PN,{value:k,size:96})}),e.jsxs("div",{className:"text-sm text-gray-600",children:[e.jsx("div",{className:"font-semibold",children:"Scan for your free guide"}),e.jsx("div",{children:k})]})]})]})})]}),e.jsxs(ns,{value:"landing",className:"mt-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Landing page copy"}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:k,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-4 w-4 mr-1"})," Live preview"]})})]}),e.jsx("div",{className:"fsbo-tile p-6 max-w-3xl mx-auto space-y-4",children:G?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-primary",children:G.eyebrow}),e.jsx("h2",{className:"text-3xl font-bold",children:G.headline}),e.jsx("p",{className:"text-lg text-muted-foreground",children:G.subheadline}),e.jsx("p",{className:"text-foreground",children:G.intro}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 mt-4",children:G.discover.map((_e,Oe)=>e.jsxs("div",{className:"bg-muted/40 p-4 rounded-lg",children:[e.jsx("div",{className:"font-semibold",children:_e.title}),e.jsx("div",{className:"text-sm text-muted-foreground",children:_e.body})]},Oe))}),e.jsxs("div",{className:"mt-4 p-4 bg-primary/5 border-l-4 border-primary rounded-r-lg",children:[e.jsxs("div",{className:"italic",children:['"',G.testimonial.quote,'"']}),e.jsxs("div",{className:"text-sm font-semibold mt-2",children:["— ",G.testimonial.author]})]}),e.jsx("div",{className:"mt-4",children:e.jsx(B,{size:"lg",children:G.cta})})]}):e.jsx("div",{className:"text-muted-foreground",children:"Landing page content not generated yet."})})]}),e.jsxs(ns,{value:"guide",className:"mt-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Seller guide"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:O,disabled:h,children:[e.jsx(jj,{className:"h-4 w-4 mr-1"})," Download image"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`${k}/guide`,target:"_blank",rel:"noreferrer",children:[e.jsx(Tr,{className:"h-4 w-4 mr-1"})," Public view"]})})]})]}),e.jsx("div",{ref:P,className:"fsbo-tile p-8 max-w-4xl mx-auto space-y-6 bg-white text-foreground",children:K?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-center pb-6 border-b",children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-primary",children:"By-Owner Breakthrough"}),e.jsx("h2",{className:"text-3xl font-bold mt-2",children:"FSBO Seller Guide"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:(Ge=b.property)==null?void 0:Ge.property_address})]}),e.jsx("p",{className:"text-lg leading-relaxed",children:K.intro}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"FSBO Reality Checklist"}),e.jsx("ul",{className:"space-y-2",children:K.checklist.map((_e,Oe)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"}),e.jsx("span",{children:_e})]},Oe))})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"Common Pitfalls"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:K.pitfalls.map((_e,Oe)=>e.jsxs("div",{className:"bg-muted/30 p-4 rounded-lg",children:[e.jsx("div",{className:"font-semibold",children:_e.title}),e.jsx("div",{className:"text-sm text-muted-foreground",children:_e.body})]},Oe))})]}),e.jsxs("div",{className:"grid gap-6 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"Your Advantages"}),e.jsx("ul",{className:"space-y-2",children:K.seller_advantages.map((_e,Oe)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"+"}),e.jsx("span",{children:_e})]},Oe))})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"What an Agent Brings"}),e.jsx("ul",{className:"space-y-2",children:K.agent_value.map((_e,Oe)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"→"}),e.jsx("span",{children:_e})]},Oe))})]})]}),e.jsxs("div",{className:"bg-primary/10 p-6 rounded-xl text-center",children:[e.jsx("h3",{className:"text-xl font-semibold mb-2",children:K.cta}),e.jsx("p",{className:"text-muted-foreground mb-4",children:K.cta_body}),e.jsx(B,{size:"lg",children:"Request a Free Consultation"})]})]}):e.jsx("div",{className:"text-muted-foreground",children:"Guide content not generated yet."})})]}),e.jsx(ns,{value:"scripts",className:"mt-6",children:e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"Agent scripts"}),le?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Zre,{label:"Phone",text:le.phone}),e.jsx(Zre,{label:"Voicemail",text:le.voicemail}),e.jsx(Zre,{label:"Video",text:le.video}),e.jsx(Zre,{label:"Door knock",text:le.door_knock}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold mb-2",children:"Objection responses"}),e.jsx("div",{className:"space-y-2",children:le.objections.map((_e,Oe)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:['"',_e.objection,'"']}),e.jsx("div",{className:"text-sm mt-1",children:_e.response})]},Oe))})]})]}):e.jsx("div",{className:"text-muted-foreground",children:"Scripts not generated yet."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"Email sequence"}),e.jsxs("div",{className:"space-y-2",children:[ee.map((_e,Oe)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Day ",Oe*4+1]}),e.jsx("div",{className:"font-medium",children:_e.subject}),e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:_e.preview})]},_e.key)),!ee.length&&e.jsx("div",{className:"text-muted-foreground",children:"No emails generated yet."})]})]}),e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"SMS sequence"}),e.jsxs("div",{className:"space-y-2",children:[J.map((_e,Oe)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Step ",Oe+1]}),e.jsx("div",{className:"text-sm",children:_e.body})]},_e.key)),!J.length&&e.jsx("div",{className:"text-muted-foreground",children:"No SMS messages generated yet."})]})]})]})]})}),e.jsx(ns,{value:"leads",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"Seller leads"}),e.jsx("div",{className:"space-y-3",children:(i.data??[]).filter(_e=>_e.campaign_id===s).length===0?e.jsx("div",{className:"text-muted-foreground",children:"No leads yet. Share the landing page to start collecting them."}):(i.data??[]).filter(_e=>_e.campaign_id===s).map(_e=>e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg bg-muted/40",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium",children:[_e.first_name," ",_e.last_name]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[_e.email," · ",_e.phone]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:["Timeline: ",_e.timeline??"—"," · Motivation: ",_e.motivation??"—"]}),e.jsx("div",{className:"text-sm mt-1",children:_e.message})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs(qe,{className:Et(_e.temperature==="hot"?"bg-red-500/15 text-red-600":"bg-amber-500/15 text-amber-600"),children:[_e.temperature," · ",_e.lead_score]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:Bs(new Date(_e.created_at),"MMM d")})]})]},_e.id))})]})})]})]})})}function Zre({label:s,text:t}){return e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-sm font-semibold",children:s}),e.jsx(B,{size:"sm",variant:"ghost",className:"h-6 px-2",onClick:()=>{navigator.clipboard.writeText(t),re.success("Copied")},children:e.jsx(ja,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:t})]})}const O7n="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/fsbo-public",Avt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";async function b8(s){try{const t=await fetch(O7n,{method:"POST",headers:{"Content-Type":"application/json",apikey:Avt,Authorization:`Bearer ${Avt}`},body:JSON.stringify(s)});return t.ok?await t.json():null}catch{return null}}function F7n(){const{slug:s}=$i(),[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState({first_name:"",last_name:"",email:"",phone:"",timeline:"",motivation:"",preferred_contact:"email",message:""});j.useEffect(()=>{s&&(a(!0),b8({action:"get",slug:s}).then(k=>{k!=null&&k.campaign&&n(k),a(!1)}))},[s]),j.useEffect(()=>{if(!s)return;const k=sessionStorage.getItem(`fsbo-${s}`)||crypto.randomUUID();sessionStorage.setItem(`fsbo-${s}`,k),b8({action:"track",slug:s,event_type:"page_view",session_id:k})},[s]);const h=async k=>{if(k.preventDefault(),!s)return;c(!0);const C=sessionStorage.getItem(`fsbo-${s}`)||void 0,T=await b8({action:"submit",slug:s,...d,session_id:C,wants_guide:!0});c(!1),T?l(!0):alert("Could not submit. Please try again.")};if(r)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-stone-50",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-primary"})});if(!t)return e.jsx("div",{className:"min-h-screen grid place-items-center text-muted-foreground",children:"Landing page not found."});const m=t.campaign,p=m.content??{},x=p.landing,y=t.agent,g=m.property??{},b=p.landing_config??{media_mode:"photo",show_property_snapshot:!0,show_discover:!0,show_testimonial:!0},v=b.video_url?k7n(b.video_url):null;return e.jsxs("div",{className:"min-h-screen bg-stone-50 text-stone-900",children:[e.jsxs(ql,{children:[e.jsxs("title",{children:[(x==null?void 0:x.headline)||"Selling On Your Own?"," — ",(y==null?void 0:y.name)||"LevelUp"]}),e.jsx("meta",{name:"description",content:(x==null?void 0:x.subheadline)||"Free FSBO seller guide from a local agent."})]}),e.jsx("div",{className:"bg-gradient-to-br from-[#4a6741] to-[#2d5a3d] text-white",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 py-12 lg:py-20",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-10 items-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-[#f4d06f] font-semibold",children:(x==null?void 0:x.eyebrow)||"Free FSBO Seller Guide"}),e.jsx("h1",{className:"text-3xl sm:text-5xl font-bold mt-4 leading-tight",children:(x==null?void 0:x.headline)||"Selling On Your Own? Here's What You Should Know."}),e.jsx("p",{className:"text-lg text-white/80 mt-4",children:(x==null?void 0:x.subheadline)||`A complimentary guide for ${g.property_address||"your home"} created by a local agent.`}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsxs("a",{href:"#form",className:"inline-flex items-center gap-2 bg-[#f4d06f] text-[#0f4c5c] px-5 py-3 rounded-lg font-semibold hover:bg-[#f4d06f]/90",children:[(x==null?void 0:x.cta)||"Send Me the Free Guide"," ",e.jsx(Xa,{className:"h-4 w-4"})]}),e.jsx("a",{href:`/fsbo/${s}/guide`,className:"inline-flex items-center gap-2 bg-white/10 text-white px-5 py-3 rounded-lg font-semibold hover:bg-white/20",children:"Read the guide"})]})]}),e.jsx("div",{className:"rounded-2xl overflow-hidden shadow-2xl bg-white/10 ring-1 ring-white/15",children:(v==null?void 0:v.kind)==="iframe"?e.jsx("iframe",{src:v.src,className:"w-full aspect-video block border-0",scrolling:"no",allowFullScreen:!0,title:"Property media"}):(v==null?void 0:v.kind)==="file"?e.jsx("video",{src:v.src,className:"w-full aspect-video object-cover block",controls:!0}):typeof g.photo_url=="string"&&g.photo_url?e.jsx("img",{src:g.photo_url,alt:String(g.property_address||"Property photo"),loading:"eager",className:"w-full aspect-[4/3] object-cover object-center block"}):e.jsx("div",{className:"aspect-[4/3] grid place-items-center text-white/60",children:e.jsx(ia,{className:"h-12 w-12"})})})]})})}),b.show_property_snapshot!==!1&&e.jsx("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-8",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-lg p-5 flex flex-wrap gap-6 justify-center items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oi,{className:"h-4 w-4 text-[#4a6741]"})," ",e.jsx("span",{className:"font-semibold",children:g.property_address})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4 text-[#4a6741]"})," ",e.jsx("span",{className:"capitalize",children:String(g.property_type||"").replace("_"," ")})]}),g.estimated_value?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"font-semibold",children:["Est. $",Number(g.estimated_value).toLocaleString()]})}):null]})}),e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 py-16",children:e.jsxs("div",{className:"grid lg:grid-cols-5 gap-12",children:[e.jsxs("div",{className:"lg:col-span-3 space-y-6",children:[e.jsx("div",{className:"text-lg leading-relaxed text-stone-700",children:x==null?void 0:x.intro}),b.show_discover!==!1&&(x==null?void 0:x.discover)&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-4 mt-6",children:x.discover.map((k,C)=>e.jsxs("div",{className:"bg-white p-5 rounded-xl shadow-sm border border-stone-100",children:[e.jsx("div",{className:"font-semibold text-[#4a6741] mb-1",children:k.title}),e.jsx("div",{className:"text-sm text-stone-600",children:k.body})]},C))}),b.show_testimonial!==!1&&(x==null?void 0:x.testimonial)&&e.jsxs("div",{className:"mt-8 bg-[#4a6741]/10 p-6 rounded-2xl border-l-4 border-[#4a6741]",children:[e.jsx("div",{className:"flex gap-1 text-[#f4d06f] mb-2",children:[...Array(5)].map((k,C)=>e.jsx(Wa,{className:"h-4 w-4 fill-current"},C))}),e.jsxs("div",{className:"italic text-lg text-stone-800",children:['"',x.testimonial.quote,'"']}),e.jsxs("div",{className:"font-semibold text-sm mt-3",children:["— ",x.testimonial.author]})]})]}),e.jsx("div",{id:"form",className:"lg:col-span-2",children:e.jsx("div",{className:"bg-white rounded-2xl shadow-lg p-6 sm:p-8 sticky top-6",children:i?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-green-100 grid place-items-center mb-4",children:e.jsx(Rr,{className:"h-7 w-7 text-green-600"})}),e.jsx("h3",{className:"text-xl font-bold",children:"Your guide is on the way!"}),e.jsxs("p",{className:"text-stone-600 mt-2",children:["Check your email for the guide. ",(y==null?void 0:y.name)||"The agent"," will follow up soon."]}),e.jsx("a",{href:`/fsbo/${s}/guide`,className:"inline-block mt-4 text-[#4a6741] font-semibold underline",children:"Read it now"})]}):e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx("h3",{className:"text-xl font-bold",children:(x==null?void 0:x.form_subhead)||"Get your free guide"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"First"}),e.jsx(ye,{value:d.first_name,onChange:k=>u(C=>({...C,first_name:k.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Last"}),e.jsx(ye,{value:d.last_name,onChange:k=>u(C=>({...C,last_name:k.target.value})),required:!0})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Email"}),e.jsx(ye,{type:"email",value:d.email,onChange:k=>u(C=>({...C,email:k.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Phone"}),e.jsx(ye,{type:"tel",value:d.phone,onChange:k=>u(C=>({...C,phone:k.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Timeline"}),e.jsxs("select",{className:"w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",value:d.timeline,onChange:k=>u(C=>({...C,timeline:k.target.value})),children:[e.jsx("option",{value:"",children:"Select…"}),C7n.map(k=>e.jsx("option",{value:k.value,children:k.label},k.value))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Preferred contact"}),e.jsx("select",{className:"w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",value:d.preferred_contact,onChange:k=>u(C=>({...C,preferred_contact:k.target.value})),children:T7n.map(k=>e.jsx("option",{value:k.value,children:k.label},k.value))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"What prompted you to sell on your own?"}),e.jsxs("select",{className:"w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",value:d.motivation,onChange:k=>u(C=>({...C,motivation:k.target.value})),children:[e.jsx("option",{value:"",children:"Select…"}),A7n.map(k=>e.jsx("option",{value:k,children:k},k))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Message (optional)"}),e.jsx(Ds,{rows:3,value:d.message,onChange:k=>u(C=>({...C,message:k.target.value}))})]}),e.jsxs(B,{type:"submit",className:"w-full",size:"lg",disabled:o,children:[o?e.jsx(Wt,{className:"h-4 w-4 animate-spin mr-2"}):null,(x==null?void 0:x.cta)||"Send Me the Free Guide"]}),e.jsxs("p",{className:"text-xs text-stone-500 text-center",children:["No spam. Unsubscribe anytime. Your info helps ",(y==null?void 0:y.name)||"the agent"," tailor the guide."]})]})})})]})}),e.jsx("div",{className:"bg-white border-t border-stone-100",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 py-12",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center gap-6",children:[y!=null&&y.avatar_url?e.jsx("img",{src:y.avatar_url,alt:y.name||"",className:"h-24 w-24 rounded-full object-cover shadow-md"}):null,e.jsxs("div",{className:"text-center sm:text-left",children:[e.jsx("div",{className:"text-xl font-bold",children:y==null?void 0:y.name}),e.jsxs("div",{className:"text-stone-600",children:[y==null?void 0:y.title,y!=null&&y.title&&(y!=null&&y.brokerage)?" · ":"",y==null?void 0:y.brokerage]}),e.jsxs("div",{className:"flex flex-wrap justify-center sm:justify-start gap-2 mt-3",children:[y!=null&&y.phone?e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`tel:${y.phone}`,children:[e.jsx(pa,{className:"h-4 w-4 mr-1"})," Call"]})}):null,y!=null&&y.email?e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${y.email}`,children:[e.jsx(on,{className:"h-4 w-4 mr-1"})," Email"]})}):null,y!=null&&y.website_url?e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:y.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(ro,{className:"h-4 w-4 mr-1"})," Website"]})}):null]})]})]})})})]})}function z7n(){const{slug:s}=$i(),[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[o,c]=j.useState(!1),[d,u]=j.useState(!1);j.useEffect(()=>{s&&(a(!0),b8({action:"get",slug:s}).then(b=>{b!=null&&b.campaign&&n(b),a(!1)}))},[s]),j.useEffect(()=>{s&&b8({action:"track",slug:s,event_type:"guide_view"})},[s]);const h=async b=>{if(b.preventDefault(),!s||o)return;c(!0);const v=await b8({action:"submit",slug:s,...i,message:`Requested a free consultation from the guide page.${i.message?` — ${i.message}`:""}`,preferred_contact:"either",wants_guide:!1});c(!1),v?(u(!0),b8({action:"track",slug:s,event_type:"consultation_request"})):alert("Could not send your request. Please try again.")};if(r)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-stone-50",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin text-primary"})});if(!t)return e.jsx("div",{className:"min-h-screen grid place-items-center text-muted-foreground",children:"Guide not found."});const m=t.campaign,x=(m.content??{}).guide,y=t.agent,g=m.property??{};return e.jsxs("div",{className:"min-h-screen bg-stone-50 text-stone-900",children:[e.jsxs(ql,{children:[e.jsxs("title",{children:["FSBO Seller Guide — ",(g==null?void 0:g.property_address)||"Your home"]}),e.jsx("meta",{name:"description",content:"Free guide for selling your home by owner."})]}),e.jsx("div",{className:"bg-gradient-to-br from-[#4a6741] to-[#2d5a3d] text-white",children:e.jsx("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 py-6",children:e.jsxs(Yn,{to:`/fsbo/${s}`,className:"inline-flex items-center gap-1 text-sm text-white/80 hover:text-white",children:[e.jsx(_a,{className:"h-4 w-4"})," Back to landing page"]})})}),e.jsx("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 py-12",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg p-8 sm:p-12",children:[e.jsxs("div",{className:"text-center pb-8 border-b border-stone-100",children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-[#4a6741] font-semibold",children:"By-Owner Breakthrough"}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold mt-2 text-stone-900",children:"FSBO Seller Guide"}),e.jsx("p",{className:"text-stone-600 mt-2 text-lg",children:g==null?void 0:g.property_address})]}),x?e.jsxs("div",{className:"space-y-10 mt-8",children:[e.jsx("p",{className:"text-lg leading-relaxed text-stone-700",children:x.intro}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"FSBO Reality Checklist"}),e.jsx("ul",{className:"space-y-3",children:x.checklist.map((b,v)=>e.jsxs("li",{className:"flex items-start gap-3 p-3 bg-stone-50 rounded-lg",children:[e.jsx("span",{className:"text-[#4a6741] font-bold text-lg",children:"✓"}),e.jsx("span",{className:"text-stone-700",children:b})]},v))})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"Common Pitfalls"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:x.pitfalls.map((b,v)=>e.jsxs("div",{className:"bg-stone-50 p-5 rounded-xl",children:[e.jsx("div",{className:"font-semibold text-stone-900 mb-1",children:b.title}),e.jsx("div",{className:"text-sm text-stone-600",children:b.body})]},v))})]}),e.jsxs("div",{className:"grid gap-8 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"Your Advantages"}),e.jsx("ul",{className:"space-y-3",children:x.seller_advantages.map((b,v)=>e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-[#4a6741] font-bold",children:"+"}),e.jsx("span",{className:"text-stone-700",children:b})]},v))})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"What an Agent Brings"}),e.jsx("ul",{className:"space-y-3",children:x.agent_value.map((b,v)=>e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-[#4a6741] font-bold",children:"→"}),e.jsx("span",{className:"text-stone-700",children:b})]},v))})]})]}),e.jsxs("div",{id:"consult",className:"bg-[#4a6741]/10 p-8 rounded-2xl",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-bold mb-3 text-stone-900",children:x.cta}),e.jsx("p",{className:"text-stone-600 mb-6 max-w-lg mx-auto",children:x.cta_body})]}),d?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-green-100 grid place-items-center mb-3",children:e.jsx(Rr,{className:"h-7 w-7 text-green-600"})}),e.jsx("div",{className:"font-semibold text-lg",children:"Request received"}),e.jsxs("p",{className:"text-stone-600 mt-1",children:[(y==null?void 0:y.name)||"Your agent"," will reach out shortly with an objective look at your home."]})]}):e.jsxs("form",{onSubmit:h,className:"max-w-xl mx-auto space-y-3 bg-white rounded-xl p-6 shadow-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"First"}),e.jsx(ye,{value:i.first_name,onChange:b=>l(v=>({...v,first_name:b.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Last"}),e.jsx(ye,{value:i.last_name,onChange:b=>l(v=>({...v,last_name:b.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Email"}),e.jsx(ye,{type:"email",value:i.email,onChange:b=>l(v=>({...v,email:b.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Phone"}),e.jsx(ye,{type:"tel",value:i.phone,onChange:b=>l(v=>({...v,phone:b.target.value}))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(se,{className:"text-xs",children:"Best time / anything I should know (optional)"}),e.jsx(Ds,{rows:3,value:i.message,onChange:b=>l(v=>({...v,message:b.target.value}))})]}),e.jsxs(B,{type:"submit",size:"lg",className:"w-full",disabled:o,children:[o?e.jsx(Wt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Request a Free Consultation"]}),e.jsx("p",{className:"text-xs text-stone-500 text-center",children:"No obligation. No pressure — just clear facts about your home's market."})]})]})]}):e.jsx("div",{className:"text-stone-500 text-center py-12",children:"Guide content not available yet."}),e.jsxs("div",{className:"mt-12 pt-8 border-t border-stone-100 flex flex-col sm:flex-row items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[y!=null&&y.avatar_url?e.jsx("img",{src:y.avatar_url,alt:y.name??"",className:"h-16 w-16 rounded-full object-cover"}):null,e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-lg",children:y==null?void 0:y.name}),e.jsxs("div",{className:"text-sm text-stone-600",children:[y==null?void 0:y.title,y!=null&&y.title&&(y!=null&&y.brokerage)?" · ":"",y==null?void 0:y.brokerage]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[y!=null&&y.phone?e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`tel:${y.phone}`,children:[e.jsx(pa,{className:"h-4 w-4 mr-1"})," Call"]})}):null,y!=null&&y.email?e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${y.email}`,children:[e.jsx(on,{className:"h-4 w-4 mr-1"})," Email"]})}):null]})]})]})})]})}function B7n(){const s=Bqt(),t=$qt(),n=rZe(),r=aZe(),a=as(),[i,l]=j.useState(""),o=vt({mutationFn:async()=>{const{data:h,error:m}=await U.from("profiles").select("id");if(m)throw m;const p=new Date().toISOString(),x=(h??[]).map(g=>({user_id:g.id,feature_key:"fsbo_breakthrough",enabled:!0,tier:"beta",expires_at:null,created_at:p,updated_at:p})),{error:y}=await U.from("feature_entitlements").upsert(x,{onConflict:"user_id,feature_key"});if(y)throw y},onSuccess:()=>{re.success("Enabled for all members"),a.invalidateQueries({queryKey:["fsbo-breakthrough-access"]})},onError:h=>re.error(h.message)}),c=j.useMemo(()=>{const h=m=>(r.data??[]).filter(p=>p.event_type===m).length;return{properties:(t.data??[]).length,campaigns:(s.data??[]).length,letters:(s.data??[]).filter(m=>{var p;return(p=m.content)==null?void 0:p.letter}).length,qr:h("qr_scan"),visits:h("page_view"),guideViews:h("guide_view"),leads:(n.data??[]).length,appointments:h("appointment")}},[s.data,r.data,n.data,t.data]),d=j.useMemo(()=>{const h=[];for(let m=13;m>=0;m--){const p=new Date(Date.now()-m*864e5),x=p.toISOString().slice(0,10);h.push({day:Bs(p,"MMM d"),visits:(r.data??[]).filter(y=>y.event_type==="page_view"&&y.created_at.startsWith(x)).length,scans:(r.data??[]).filter(y=>y.event_type==="qr_scan"&&y.created_at.startsWith(x)).length,leads:(n.data??[]).filter(y=>y.created_at.startsWith(x)).length})}return h},[r.data,n.data]),u=(s.data??[]).filter(h=>{var m;return`${h.name} ${((m=h.property)==null?void 0:m.property_address)??""}`.toLowerCase().includes(i.trim().toLowerCase())});return s.isLoading||t.isLoading||n.isLoading||r.isLoading?e.jsx(Vs,{title:"By-Owner Breakthrough Admin",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Wt,{className:"h-6 w-6 animate-spin"})})}):e.jsx(Vs,{title:"By-Owner Breakthrough Admin",children:e.jsxs("div",{className:"fsbo-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Admin"}),e.jsx("h1",{className:"fsbo-serif text-2xl",children:"By-Owner Breakthrough"})]}),e.jsxs(B,{onClick:()=>o.mutate(),disabled:o.isPending,children:[o.isPending?e.jsx(Wt,{className:"h-4 w-4 animate-spin mr-2"}):null," Enable all members"]})]}),e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-4 mb-6",children:[e.jsx(HC,{label:"Properties",value:c.properties,icon:ia}),e.jsx(HC,{label:"Campaigns",value:c.campaigns,icon:on}),e.jsx(HC,{label:"Page visits",value:c.visits,icon:Ql}),e.jsx(HC,{label:"QR scans",value:c.qr,icon:hg}),e.jsx(HC,{label:"Guide views",value:c.guideViews,icon:$r}),e.jsx(HC,{label:"Leads",value:c.leads,icon:Bn}),e.jsx(HC,{label:"Appointments",value:c.appointments,icon:Bn}),e.jsx(HC,{label:"Letters",value:c.letters,icon:on})]}),e.jsxs("div",{className:"fsbo-tile p-5 mb-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Last 14 days"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Network-wide engagement"}),e.jsx("div",{className:"h-64 mt-4",children:e.jsx(jb,{width:"100%",height:"100%",children:e.jsxs(fWe,{data:d,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"fsboAdminVisits",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"fsboAdminLeads",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--accent))",stopOpacity:.5}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--accent))",stopOpacity:0})]})]}),e.jsx(KD,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(p1,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(f1,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(ff,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(Nb,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#fsboAdminVisits)",strokeWidth:2}),e.jsx(Nb,{type:"monotone",dataKey:"scans",stackId:"1",stroke:"hsl(var(--accent))",fill:"url(#fsboAdminLeads)",strokeWidth:2}),e.jsx(Nb,{type:"monotone",dataKey:"leads",stackId:"1",stroke:"#5b8a5c",fill:"#5b8a5c",fillOpacity:.15,strokeWidth:2})]})})})]}),e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"text-lg font-semibold",children:"All campaigns"}),e.jsxs("div",{className:"relative w-64",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{className:"pl-9",placeholder:"Search campaigns…",value:i,onChange:h=>l(h.target.value)})]})]}),e.jsxs("div",{className:"space-y-3",children:[u.map(h=>{var x,y,g,b,v,k;const m=(n.data??[]).filter(C=>C.campaign_id===h.id).length,p=(r.data??[]).filter(C=>C.campaign_id===h.id&&C.event_type==="page_view").length;return e.jsxs("a",{href:`/apps/fsbo-breakthrough/campaigns/${h.id}`,className:"flex items-center justify-between p-4 rounded-xl bg-muted/40 hover:bg-muted/60 transition-colors",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:((x=h.property)==null?void 0:x.property_address)??h.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((y=h.property)==null?void 0:y.seller_name)||"Homeowner"," · ",(g=h.property)==null?void 0:g.city,(b=h.property)!=null&&b.city&&((v=h.property)!=null&&v.state)?", ":"",(k=h.property)==null?void 0:k.state]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(qe,{variant:"secondary",children:[e.jsx(Ql,{className:"h-3 w-3 mr-1"}),p]}),e.jsxs(qe,{variant:"secondary",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),m]}),e.jsx(Xa,{className:"h-4 w-4 text-muted-foreground"})]})]},h.id)}),u.length===0&&e.jsx("div",{className:"text-muted-foreground text-center py-8",children:"No campaigns match."})]})]})]})})}function HC({label:s,value:t,icon:n}){return e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("span",{className:"fsbo-eyebrow text-muted-foreground",children:s}),e.jsx(n,{className:"h-4 w-4 text-accent"})]}),e.jsx("div",{className:"mt-2 text-2xl font-bold",children:t})]})}const Hqt={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},Tvt={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"},$7n=[{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."}],U7n=[{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."}],q7n=[{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."}],V7n="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.",H7n={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:""},G7n={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 W7n(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:$7n,sponsor_cards:q7n,faqs:U7n,lead_magnet:H7n,calculator:G7n,sections:Hqt,disclaimer:V7n,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 Gqt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}const bG=U;function K7n(){const{user:s}=Ns(),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 bG.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 bG.from("attract_landing_events").select("event_type, section_key, created_at").eq("page_id",r.id).order("created_at",{ascending:!1}).limit(1e3);if(d)throw d;const u=c||[],h=u.filter(x=>x.event_type==="view").length,m=u.filter(x=>x.event_type==="cta_click").length,p=u.filter(x=>x.event_type==="calculator_run").length;return{views:h,ctas:m,calcs:p,conversion:h?Math.round(m/h*100):0}}}),l=vt({mutationFn:async c=>{const d=Gqt(c||"my-attraction-page")||"attraction-page";let u=d;for(let x=0;x<5;x++){const{data:y}=await bG.from("attract_landing_pages").select("id").eq("slug",u).maybeSingle();if(!y)break;u=`${d}-${Math.random().toString(36).slice(2,6)}`}const h=W7n(c||"Your Name"),{data:m,error:p}=await bG.from("attract_landing_pages").insert({...h,user_id:s.id,slug:u}).select("*").single();if(p)throw p;return m},onSuccess:()=>{t.invalidateQueries({queryKey:n}),re.success("Attraction page created")},onError:c=>re.error(c.message||"Could not create the page")}),o=vt({mutationFn:async c=>{const{error:d}=await bG.from("attract_landing_pages").update(c).eq("id",r.id);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:n}),re.success("Saved")},onError:c=>{var d;return re.error((d=c.message)!=null&&d.includes("duplicate")?"That web address is already taken":c.message||"Could not save")}});return{page:r,isLoading:a,analytics:i,createPage:l,savePage:o}}function Y7n(){var g,b,v,k,C,T,M,P,L,I,O,$;const{user:s}=Ns(),{page:t,isLoading:n,analytics:r,createPage:a,savePage:i}=K7n(),[l,o]=j.useState(null),[c,d]=j.useState(!1);j.useEffect(()=>{t&&o({...t})},[t]);const u=j.useMemo(()=>l!=null&&l.slug?`${window.location.origin}/join/${l.slug}`:"",[l==null?void 0:l.slug]),h=q=>o(W=>({...W,...q})),m=(q,W)=>h({[q]:W}),p=(q,W,G)=>m(q,l[q].map((K,ee)=>ee===W?{...K,...G}:K)),x=()=>{const{id:q,user_id:W,created_at:G,updated_at:K,...ee}=l;i.mutate({...ee,slug:Gqt(ee.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(yn,{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 q;return a.mutate(((q=s==null?void 0:s.user_metadata)==null?void 0:q.full_name)||"My Attraction Page")},disabled:a.isPending,children:a.isPending?"Creating…":"Create my page"})]});if(!l)return null;if(c)return e.jsxs("div",{children:[e.jsxs("div",{className:"sticky top-0 z-50 flex items-center justify-between border-b bg-background px-4 py-3",children:[e.jsx("span",{className:"text-sm font-medium",children:"Preview"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>d(!1),children:"Back to editor"})]}),e.jsx(Mqt,{cfg:l,preview:!0})]});const y={...Hqt,...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(ma,{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:x,disabled:i.isPending,children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})]})]}),e.jsx("div",{className:"mb-6 grid gap-3 sm:grid-cols-4",children:[{label:"Page views",value:(r==null?void 0:r.views)??0},{label:"CTA clicks",value:(r==null?void 0:r.ctas)??0},{label:"Calculator runs",value:(r==null?void 0:r.calcs)??0},{label:"Click rate",value:`${(r==null?void 0:r.conversion)??0}%`}].map(q=>e.jsx(be,{children:e.jsxs(Re,{className:"p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:q.label}),e.jsx("div",{className:"mt-1 text-2xl font-bold",children:q.value})]})},q.label))}),e.jsxs(fa,{defaultValue:"content",children:[e.jsxs(xa,{className:"mb-6 flex-wrap",children:[e.jsx(ss,{value:"content",children:"Content"}),e.jsx(ss,{value:"proof",children:"Proof & FAQ"}),e.jsx(ss,{value:"calculator",children:"Calculator"}),e.jsx(ss,{value:"sections",children:"Sections"}),e.jsx(ss,{value:"publish",children:"Publish"})]}),e.jsxs(ns,{value:"content",className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Hero"})}),e.jsxs(Re,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Ph,{label:"Your name",value:l.agent_name,onChange:q=>h({agent_name:q})}),e.jsx(Ph,{label:"Title / brokerage",value:l.agent_title,onChange:q=>h({agent_title:q})}),e.jsx(Ph,{label:"Eyebrow line",value:l.eyebrow,onChange:q=>h({eyebrow:q}),className:"md:col-span-2"}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(se,{children:"Headline"}),e.jsx(Ds,{rows:2,value:l.headline||"",onChange:q=>h({headline:q.target.value})})]}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(se,{children:"Subheadline"}),e.jsx(Ds,{rows:3,value:l.subheadline||"",onChange:q=>h({subheadline:q.target.value})})]}),e.jsx(Ph,{label:"Button text",value:l.cta_label,onChange:q=>h({cta_label:q})}),e.jsx(Ph,{label:"Scheduling link (Calendly etc.)",value:l.calendar_url,onChange:q=>h({calendar_url:q})}),e.jsx(Ph,{label:"Headshot URL",value:l.headshot_url,onChange:q=>h({headshot_url:q})}),e.jsx(Ph,{label:"Hero background image URL",value:l.hero_image_url,onChange:q=>h({hero_image_url:q})}),e.jsx(Ph,{label:"Logo URL",value:l.logo_url,onChange:q=>h({logo_url:q})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Ph,{label:"Primary color",type:"color",value:l.primary_color,onChange:q=>h({primary_color:q})}),e.jsx(Ph,{label:"Accent color",type:"color",value:l.accent_color,onChange:q=>h({accent_color:q})})]}),e.jsx(Ph,{label:"Phone",value:l.phone,onChange:q=>h({phone:q})}),e.jsx(Ph,{label:"Email",value:l.email,onChange:q=>h({email:q})})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Credibility strip"})}),e.jsxs(Re,{className:"space-y-3",children:[(l.credibility||[]).map((q,W)=>e.jsxs(_G,{onRemove:()=>m("credibility",l.credibility.filter((G,K)=>K!==W)),children:[e.jsx(ye,{placeholder:"Value (e.g. $42M)",value:q.value||"",onChange:G=>p("credibility",W,{value:G.target.value})}),e.jsx(ye,{placeholder:"Label (e.g. Closed volume)",value:q.label||"",onChange:G=>p("credibility",W,{label:G.target.value})})]},W)),e.jsx(wG,{onClick:()=>m("credibility",[...l.credibility||[],{value:"",label:""}]),label:"Add stat"})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Your story"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsx(Ph,{label:"Section title",value:l.story_title,onChange:q=>h({story_title:q})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Story"}),e.jsx(Ds,{rows:6,value:l.story_body||"",onChange:q=>h({story_body:q.target.value})})]}),e.jsx(Ph,{label:"Story video URL (YouTube, Vimeo, Loom, MP4)",value:l.story_video_url,onChange:q=>h({story_video_url:q})})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Value stack"})}),e.jsxs(Re,{className:"space-y-4",children:[(l.value_cards||[]).map((q,W)=>e.jsxs(_G,{vertical:!0,onRemove:()=>m("value_cards",l.value_cards.filter((G,K)=>K!==W)),children:[e.jsx(ye,{placeholder:"Title",value:q.title||"",onChange:G=>p("value_cards",W,{title:G.target.value})}),e.jsx(Ds,{rows:2,placeholder:"Description",value:q.body||"",onChange:G=>p("value_cards",W,{body:G.target.value})}),e.jsx(ye,{placeholder:"Proof point (optional)",value:q.proof||"",onChange:G=>p("value_cards",W,{proof:G.target.value})})]},W)),e.jsx(wG,{onClick:()=>m("value_cards",[...l.value_cards||[],{title:"",body:""}]),label:"Add value card"})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"What you get from me"})}),e.jsxs(Re,{className:"space-y-4",children:[(l.sponsor_cards||[]).map((q,W)=>e.jsxs(_G,{vertical:!0,onRemove:()=>m("sponsor_cards",l.sponsor_cards.filter((G,K)=>K!==W)),children:[e.jsx(ye,{placeholder:"Title",value:q.title||"",onChange:G=>p("sponsor_cards",W,{title:G.target.value})}),e.jsx(Ds,{rows:2,placeholder:"Description",value:q.body||"",onChange:G=>p("sponsor_cards",W,{body:G.target.value})})]},W)),e.jsx(wG,{onClick:()=>m("sponsor_cards",[...l.sponsor_cards||[],{title:"",body:""}]),label:"Add commitment"})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Free download & upcoming event"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsx(Ph,{label:"Download title",value:(g=l.lead_magnet)==null?void 0:g.title,onChange:q=>h({lead_magnet:{...l.lead_magnet,title:q}})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Download description"}),e.jsx(Ds,{rows:2,value:((b=l.lead_magnet)==null?void 0:b.body)||"",onChange:q=>h({lead_magnet:{...l.lead_magnet,body:q.target.value}})})]}),e.jsx(Ph,{label:"File URL",value:(v=l.lead_magnet)==null?void 0:v.file_url,onChange:q=>h({lead_magnet:{...l.lead_magnet,file_url:q}})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ph,{label:"Event title",value:(k=l.event_block)==null?void 0:k.title,onChange:q=>h({event_block:{...l.event_block,title:q}})}),e.jsx(Ph,{label:"When",value:(C=l.event_block)==null?void 0:C.when,onChange:q=>h({event_block:{...l.event_block,when:q}})}),e.jsx(Ph,{label:"Registration link",value:(T=l.event_block)==null?void 0:T.url,onChange:q=>h({event_block:{...l.event_block,url:q}})})]})]})]})]}),e.jsxs(ns,{value:"proof",className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Testimonials"})}),e.jsxs(Re,{className:"space-y-4",children:[(l.testimonials||[]).map((q,W)=>e.jsxs(_G,{vertical:!0,onRemove:()=>m("testimonials",l.testimonials.filter((G,K)=>K!==W)),children:[e.jsx(Ds,{rows:3,placeholder:"Quote",value:q.quote||"",onChange:G=>p("testimonials",W,{quote:G.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(ye,{placeholder:"Name",value:q.name||"",onChange:G=>p("testimonials",W,{name:G.target.value})}),e.jsx(ye,{placeholder:"Role / market",value:q.role||"",onChange:G=>p("testimonials",W,{role:G.target.value})}),e.jsx(ye,{placeholder:"Photo URL",value:q.photo_url||"",onChange:G=>p("testimonials",W,{photo_url:G.target.value})})]})]},W)),e.jsx(wG,{onClick:()=>m("testimonials",[...l.testimonials||[],{quote:"",name:""}]),label:"Add testimonial"})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Objection-handling FAQ"})}),e.jsxs(Re,{className:"space-y-4",children:[(l.faqs||[]).map((q,W)=>e.jsxs(_G,{vertical:!0,onRemove:()=>m("faqs",l.faqs.filter((G,K)=>K!==W)),children:[e.jsx(ye,{placeholder:"Question",value:q.q||"",onChange:G=>p("faqs",W,{q:G.target.value})}),e.jsx(Ds,{rows:3,placeholder:"Answer",value:q.a||"",onChange:G=>p("faqs",W,{a:G.target.value})})]},W)),e.jsx(wG,{onClick:()=>m("faqs",[...l.faqs||[],{q:"",a:""}]),label:"Add question"})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Income disclaimer"})}),e.jsx(Re,{children:e.jsx(Ds,{rows:4,value:l.disclaimer||"",onChange:q=>h({disclaimer:q.target.value})})})]})]}),e.jsx(ns,{value:"calculator",children:e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Earnings calculator"})}),e.jsxs(Re,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Ph,{label:"Section title",value:(M=l.calculator)==null?void 0:M.title,onChange:q=>h({calculator:{...l.calculator,title:q}}),className:"md:col-span-2"}),e.jsx(Ph,{label:"Cap ($)",type:"number",value:(P=l.calculator)==null?void 0:P.cap,onChange:q=>h({calculator:{...l.calculator,cap:Number(q)}})}),e.jsx(Ph,{label:"Your split (%)",type:"number",value:(L=l.calculator)==null?void 0:L.split,onChange:q=>h({calculator:{...l.calculator,split:Number(q)}})}),e.jsx(Ph,{label:"Per-transaction fee ($)",type:"number",value:(I=l.calculator)==null?void 0:I.transaction_fee,onChange:q=>h({calculator:{...l.calculator,transaction_fee:Number(q)}})}),e.jsx(Ph,{label:"Typical competitor split (%)",type:"number",value:(O=l.calculator)==null?void 0:O.current_split,onChange:q=>h({calculator:{...l.calculator,current_split:Number(q)}})}),e.jsx(Ph,{label:"Typical competitor monthly fees ($)",type:"number",value:($=l.calculator)==null?void 0:$.current_monthly_fees,onChange:q=>h({calculator:{...l.calculator,current_monthly_fees:Number(q)}})}),e.jsx("p",{className:"text-xs text-muted-foreground md:col-span-2",children:"The calculator shows estimates only and always displays your disclaimer at the bottom of the page."})]})]})}),e.jsx(ns,{value:"sections",children:e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Show or hide sections"})}),e.jsx(Re,{className:"divide-y",children:Object.keys(Tvt).map(q=>e.jsxs("div",{className:"flex items-center justify-between py-3",children:[e.jsx("span",{className:"text-sm",children:Tvt[q]}),e.jsx(Mn,{checked:y[q]!==!1,onCheckedChange:W=>h({sections:{...y,[q]:W}})})]},q))})]})}),e.jsxs(ns,{value:"publish",className:"space-y-6",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Publishing"})}),e.jsxs(Re,{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(Mn,{checked:!!l.is_published,onCheckedChange:q=>h({is_published:q})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Hide from search engines"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Recommended — keep this page for direct outreach only."})]}),e.jsx(Mn,{checked:!!l.noindex,onCheckedChange:q=>h({noindex:q})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Web address"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:l.slug||"",onChange:q=>h({slug:q.target.value})}),e.jsx(B,{variant:"outline",onClick:()=>{navigator.clipboard.writeText(u),re.success("Link copied")},children:e.jsx(ja,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u})]}),e.jsx(Ph,{label:"Search title",value:l.seo_title,onChange:q=>h({seo_title:q})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Search description"}),e.jsx(Ds,{rows:2,value:l.seo_description||"",onChange:q=>h({seo_description:q.target.value})})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"flex items-center gap-2 text-base",children:[e.jsx(ol,{className:"h-4 w-4"})," Where leads go"]})}),e.jsx(Re,{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:x,disabled:i.isPending,children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})})]})}function Ph({label:s,value:t,onChange:n,type:r="text",className:a}){return e.jsxs("div",{className:`space-y-1.5 ${a||""}`,children:[e.jsx(se,{children:s}),e.jsx(ye,{type:r,value:t??"",onChange:i=>n(i.target.value)})]})}function _G({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(Rn,{className:"h-4 w-4"})})]})}function wG({onClick:s,label:t}){return e.jsxs(B,{variant:"outline",size:"sm",onClick:s,children:[e.jsx(Js,{className:"mr-2 h-4 w-4"})," ",t]})}function Z7n(s){const{user:t}=Ns(),n=as(),r=mt({queryKey:["admin-attract-list",s,t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{let o=U.from("profiles").select("id, email, full_name").order("full_name",{ascending:!0}).limit(100);if(s.trim()){const m=`%${s.trim()}%`;o=o.or(`email.ilike.${m},full_name.ilike.${m}`)}const{data:c,error:d}=await o;if(d)throw d;const u=(c??[]).map(m=>m.id);let h={};if(u.length){const{data:m,error:p}=await U.from("feature_entitlements").select("user_id, enabled, tier, enabled_at, expires_at, notes, enabled_by").eq("feature_key","levelup_attract").in("user_id",u);if(p)throw p;(m??[]).forEach(x=>{h[x.user_id]=x})}return(c??[]).map(m=>{var p,x,y,g,b,v;return{user_id:m.id,email:m.email,full_name:m.full_name,enabled:!!((p=h[m.id])!=null&&p.enabled),tier:((x=h[m.id])==null?void 0:x.tier)??null,enabled_at:((y=h[m.id])==null?void 0:y.enabled_at)??null,expires_at:((g=h[m.id])==null?void 0:g.expires_at)??null,notes:((b=h[m.id])==null?void 0:b.notes)??null,enabled_by:((v=h[m.id])==null?void 0:v.enabled_by)??null}})}}),a=mt({queryKey:["admin-attract-audit",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:o,error:c}=await U.from("feature_entitlement_audit").select("*").eq("feature_key","levelup_attract").order("created_at",{ascending:!1}).limit(50);if(c)throw c;return o??[]}}),i=vt({mutationFn:async({target_user_id:o,tier:c,expires_at:d,notes:u})=>{const h={user_id:o,feature_key:"levelup_attract",enabled:!0,tier:c??"beta",enabled_by:t.id,enabled_at:new Date().toISOString(),expires_at:d??null,notes:u??null},{error:m}=await U.from("feature_entitlements").upsert(h,{onConflict:"user_id,feature_key"});if(m)throw m;await U.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"grant",tier:h.tier,expires_at:h.expires_at,notes:h.notes,performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),re.success("Access granted")},onError:o=>re.error(o.message)}),l=vt({mutationFn:async o=>{const{error:c}=await U.from("feature_entitlements").update({enabled:!1}).eq("user_id",o).eq("feature_key","levelup_attract");if(c)throw c;await U.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"revoke",performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),re.success("Access revoked")},onError:o=>re.error(o.message)});return{list:r,audit:a,grant:i,revoke:l}}function X7n(){const[s,t]=j.useState(""),{list:n,audit:r,grant:a,revoke:i}=Z7n(s),[l,o]=j.useState(null),[c,d]=j.useState(null),[u,h]=j.useState("beta"),[m,p]=j.useState(""),[x,y]=j.useState(""),g=v=>{d(v),h(v.tier??"beta"),p(v.expires_at?v.expires_at.slice(0,10):""),y(v.notes??"")},b=async()=>{c&&(await a.mutateAsync({target_user_id:c.user_id,tier:u,expires_at:m?new Date(m).toISOString():null,notes:x||void 0}),d(null))};return e.jsxs("div",{className:"p-6",children:[e.jsx(oh,{title:"LevelUp Attract — Access Management",description:"Grant or revoke access to LevelUp Attract for individual members. Every change is audited."}),e.jsx(be,{className:"p-4 rounded-2xl mb-4",children:e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{value:s,onChange:v=>t(v.target.value),placeholder:"Search by name or email...",className:"pl-9"})]})}),e.jsxs(be,{className:"rounded-2xl overflow-hidden mb-8",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 text-[11px] uppercase tracking-widest text-slate-500 font-semibold border-b",children:[e.jsx("div",{children:"Member"}),e.jsx("div",{children:"Access"}),e.jsx("div",{children:"Enabled"}),e.jsx("div",{children:"Actions"})]}),n.isLoading&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"Loading members…"}),!n.isLoading&&(n.data??[]).length===0&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"No members match."}),(n.data??[]).map(v=>e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 items-center border-b last:border-0 hover:bg-slate-50",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:v.full_name||v.email||v.user_id}),e.jsx("div",{className:"text-[11.5px] text-slate-500 truncate",children:v.email})]}),e.jsx("div",{children:v.enabled?e.jsxs(qe,{className:"bg-emerald-100 text-emerald-800 border-0 gap-1",children:[e.jsx(yn,{className:"h-3 w-3"})," ",v.tier??"enabled"]}):e.jsx(qe,{variant:"outline",className:"text-slate-500",children:"Not enabled"})}),e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:v.enabled_at?Bs(new Date(v.enabled_at),"MMM d, yyyy"):"—"}),e.jsx("div",{className:"flex gap-1.5",children:v.enabled?e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>g(v),children:"Edit"}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>o({user:v,action:"revoke"}),children:"Revoke"})]}):e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>g(v),children:[e.jsx(a0,{className:"h-3.5 w-3.5 mr-1"})," Enable"]})})]},v.user_id))]}),e.jsxs(be,{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(GT,{className:"h-3.5 w-3.5"})," Recent audit history"]}),r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}),(r.data??[]).length===0&&!r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"No changes yet."}),e.jsx("div",{className:"space-y-1.5",children:(r.data??[]).map(v=>e.jsxs("div",{className:"text-[12.5px] text-slate-700 flex items-center gap-2",children:[e.jsx(qe,{variant:"outline",className:"text-[10.5px] capitalize",children:v.action}),e.jsx("span",{className:"font-mono text-[11px] text-slate-500",children:v.target_user_id.slice(0,8)}),v.tier&&e.jsxs("span",{className:"text-slate-500",children:["· ",v.tier]}),v.notes&&e.jsxs("span",{className:"text-slate-500",children:["· ",v.notes]}),e.jsx("span",{className:"text-slate-400 ml-auto",children:Bs(new Date(v.created_at),"MMM d h:mm a")})]},v.id))})]}),e.jsx(Fs,{open:!!c,onOpenChange:v=>!v&&d(null),children:e.jsxs(Os,{children:[e.jsxs($s,{children:[e.jsxs(zs,{children:[c!=null&&c.enabled?"Update":"Enable"," Attract access"]}),e.jsx(kr,{children:(c==null?void 0:c.full_name)||(c==null?void 0:c.email)})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Tier"}),e.jsxs(vs,{value:u,onValueChange:h,children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"beta",children:"Beta"}),e.jsx(Je,{value:"standard",children:"Standard"}),e.jsx(Je,{value:"pro",children:"Pro"}),e.jsx(Je,{value:"founder",children:"Founder"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Expires (optional)"}),e.jsx(ye,{type:"date",value:m,onChange:v=>p(v.target.value)})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Internal notes (optional)"}),e.jsx(Ds,{rows:2,value:x,onChange:v=>y(v.target.value)})]})]}),e.jsxs(Nr,{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:b,disabled:a.isPending,children:c!=null&&c.enabled?"Save changes":"Enable access"})]})]})}),e.jsx(Nl,{open:!!l,onOpenChange:v=>!v&&o(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Revoke Attract access?"}),e.jsxs(xl,{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(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsxs(cl,{className:"bg-rose-600 hover:bg-rose-700",onClick:async()=>{l&&await i.mutateAsync(l.user.user_id),o(null)},children:[e.jsx(Rd,{className:"h-4 w-4 mr-1.5"})," Revoke access"]})]})]})})]})}const Q7n=({team:s,onSelect:t})=>{const{data:n}=mt({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:r}=await U.from("team_members").select("user_id, role").eq("team_id",s.id),a=(r==null?void 0:r.length)||0,i=r==null?void 0:r.find(o=>o.role==="team_leader");let l=null;if(i){const{data:o}=await U.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(be,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:t,children:[e.jsx(Ft,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Ut,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(fr,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(qe,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(Bn,{className:"h-3 w-3 mr-1"}),(n==null?void 0:n.count)??"…"]})]})}),e.jsxs(Re,{className:"space-y-3",children:[(n==null?void 0:n.leaderProfile)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ra,{className:"h-6 w-6",children:[e.jsx(Fi,{src:n.leaderProfile.avatar_url||""}),e.jsx(Da,{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(sy,{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(_f,{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(qe,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(qe,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(qe,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},J7n=()=>{const{user:s,isAdmin:t,isBrokerageManager:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i}=Ns(),l=i||(a.length>0?a[0].id:r),o=t?void 0:l||void 0,{teams:c,isLoading:d,createTeam:u,updateTeam:h,deleteTeam:m,addMember:p,removeMember:x,updateMemberRole:y}=SO(o),[g,b]=j.useState(!1),[v,k]=j.useState(null),{data:C}=mt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:P,error:L}=await U.from("brokerages").select("id, name").order("name");if(L)throw L;return P||[]},enabled:t}),{data:T}=mt({queryKey:["brokerage-agents-for-teams",l],queryFn:async()=>{const{data:P,error:L}=await U.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",l).order("name");if(L)throw L;return P||[]},enabled:!!l}),M=async P=>{const L=P.brokerage_id||l||null,I=await u.mutateAsync({name:P.name,brokerage_id:L,description:P.description});if(P.leaderId&&P.leaderId!=="none"&&await p.mutateAsync({team_id:I.id,user_id:P.leaderId,role:"team_leader"}),P.memberIds)for(const O of P.memberIds)await p.mutateAsync({team_id:I.id,user_id:O,role:"team_member"});b(!1)};return!n&&!t?e.jsx(Vs,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Bn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Access Denied"}),e.jsx("p",{className:"text-muted-foreground",children:"You need brokerage manager access to manage teams."})]})}):e.jsx(Vs,{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:()=>b(!0),children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(BMt,{open:g,onOpenChange:b,onCreateTeam:M,isCreating:u.isPending,brokerageAgents:T||[],isAdmin:t,allBrokerages:C,activeBrokerageId:l}),d&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(P=>e.jsx(be,{children:e.jsxs(Re,{className:"p-6",children:[e.jsx(gn,{className:"h-5 w-32 mb-3"}),e.jsx(gn,{className:"h-4 w-48 mb-4"}),e.jsx(gn,{className:"h-8 w-full"})]})},P))}),!d&&c.length===0&&!v&&e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Bn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create your first team to organize agents and share resources."}),e.jsxs(B,{onClick:()=>b(!0),children:[e.jsx(Js,{className:"mr-2 h-4 w-4"}),"Create Your First Team"]})]})}),!d&&c.length>0&&!v&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c.map(P=>e.jsx(Q7n,{team:P,onSelect:()=>k(P)},P.id))}),v&&e.jsx(zMt,{team:v,brokerageAgents:T||[],onBack:()=>k(null),onUpdate:P=>h.mutateAsync({id:v.id,...P}).then(L=>k(L)),onAddMember:(P,L)=>p.mutateAsync({team_id:v.id,user_id:P,role:L}),onRemoveMember:P=>x.mutateAsync({team_id:v.id,member_id:P}),onUpdateRole:(P,L)=>y.mutateAsync({team_id:v.id,member_id:P,role:L}),onDeleteTeam:()=>m.mutate(v.id),isUpdating:h.isPending,isAddingMember:p.isPending})]})})},e9n=()=>{const{data:s,isLoading:t}=Hj(),{useTeamMembers:n}=SO(),{data:r=[],isLoading:a}=n((s==null?void 0:s.teamId)||"");if(t)return e.jsx(Vs,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(gn,{className:"h-8 w-48"}),e.jsx(gn,{className:"h-40 w-full"})]})});if(!s)return e.jsx(Vs,{title:"My Team",description:"Your team",children:e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Bn,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Team Yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't been assigned to a team. Ask your brokerage manager to add you."})]})})});const i=s.team;return e.jsx(Vs,{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(qe,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(sy,{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(fa,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(xa,{className:"flex-wrap",children:[e.jsx(ss,{value:"members",children:"Members"}),i.contact_visibility!=="private"&&e.jsxs(ss,{value:"contacts",children:[e.jsx(DR,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),i.lead_pond_enabled&&e.jsxs(ss,{value:"lead-pond",children:[e.jsx(mN,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),i.shared_assets_enabled&&e.jsxs(ss,{value:"shared-assets",children:[e.jsx(ny,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]})]}),e.jsx(ns,{value:"members",className:"space-y-2",children:a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(l=>e.jsx(gn,{className:"h-16 w-full"},l))}):r.map(l=>{var o,c,d,u;return e.jsx(be,{children:e.jsxs(Re,{className:"flex items-center gap-3 p-4",children:[e.jsxs(Ra,{className:"h-10 w-10",children:[e.jsx(Fi,{src:((o=l.profile)==null?void 0:o.avatar_url)||""}),e.jsx(Da,{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(qe,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(sy,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(qe,{variant:"secondary",className:"ml-auto",children:"Member"})]})},l.id)})}),i.contact_visibility!=="private"&&e.jsx(ns,{value:"contacts",className:"space-y-4",children:e.jsx(QHe,{})}),i.lead_pond_enabled&&e.jsx(ns,{value:"lead-pond",className:"space-y-4",children:e.jsx(JHe,{teamId:s.teamId})}),i.shared_assets_enabled&&e.jsx(ns,{value:"shared-assets",className:"space-y-4",children:e.jsx(FMt,{teamId:s.teamId})})]})]})})},Evt={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function t9n({types:s,onSave:t,onDelete:n}){const[r,a]=j.useState(null),[i,l]=j.useState(!1),o=()=>{a({name:"",description:"",duration_minutes:30,color:"#3B82F6",icon:"Calendar",is_active:!0,qualification_enabled:!1,is_coaching_only:!1}),l(!0)},c=u=>{a({...u}),l(!0)},d=()=>{r!=null&&r.name&&(t(r),l(!1),a(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(be,{children:[e.jsxs(Ft,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Ut,{children:"Booking Types"}),e.jsx(fr,{children:"The meeting types prospects can book with you"})]}),e.jsxs(B,{onClick:o,size:"sm",children:[e.jsx(Js,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(Re,{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:Evt[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(qe,{variant:"secondary",className:"text-xs",children:"Inactive"}),u.is_coaching_only&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"Coaching only"}),u.qualification_enabled&&e.jsxs(qe,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(KW,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Vr,{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(Za,{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(Rn,{className:"h-4 w-4"})})]})]},u.id))})})]}),e.jsx(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsxs(zs,{children:[r!=null&&r.id?"Edit":"New"," Booking Type"]})}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Name"}),e.jsx(ye,{value:r.name||"",onChange:u=>a({...r,name:u.target.value}),placeholder:"e.g. Listing Consultation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{value:r.description||"",onChange:u=>a({...r,description:u.target.value}),placeholder:"Brief description for prospects",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Duration (minutes)"}),e.jsx(ye,{type:"number",min:15,max:180,step:15,value:r.duration_minutes||30,onChange:u=>a({...r,duration_minutes:parseInt(u.target.value)||30})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:r.color||"#3B82F6",onChange:u=>a({...r,color:u.target.value}),className:"h-10 w-10 rounded border cursor-pointer"}),e.jsx(ye,{value:r.color||"#3B82F6",onChange:u=>a({...r,color:u.target.value}),className:"flex-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Max bookings per day"}),e.jsx(ye,{type:"number",min:0,max:50,value:r.max_per_day??"",onChange:u=>a({...r,max_per_day:u.target.value===""?null:parseInt(u.target.value)||0}),placeholder:"Unlimited"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for unlimited. Once this many are booked on a day, the day closes."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(Evt).map(([u,h])=>e.jsx("button",{onClick:()=>a({...r,icon:u}),className:`w-10 h-10 rounded-lg text-lg flex items-center justify-center border transition-colors ${r.icon===u?"border-primary bg-primary/10":"hover:bg-muted"}`,children:h},u))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Meeting Link Override (optional)"}),e.jsx(ye,{value:r.meeting_link_override||"",onChange:u=>a({...r,meeting_link_override:u.target.value||null}),placeholder:"Use a different link for this type"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(Mn,{checked:r.qualification_enabled||!1,onCheckedChange:u=>a({...r,qualification_enabled:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Coaching sessions only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hidden from your public booking page — only your coaching agents can book it"})]}),e.jsx(Mn,{checked:r.is_coaching_only||!1,onCheckedChange:u=>a({...r,is_coaching_only:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Active"}),e.jsx(Mn,{checked:r.is_active??!0,onCheckedChange:u=>a({...r,is_active:u})})]})]}),e.jsxs(Nr,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:d,children:"Save"})]})]})})]})}const s9n={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 n9n({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(Eo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(qe,{className:`text-xs ${s9n[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(Vc,{className:"h-3.5 w-3.5"}),Bs(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vr,{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(on,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pa,{className:"h-3 w-3"}),i.guest_phone]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1",children:[i.booking_type&&e.jsx(qe,{variant:"outline",className:"text-xs",children:i.booking_type.name}),i.google_sync_status==="synced"&&e.jsxs(qe,{variant:"outline",className:"text-xs gap-1 text-emerald-700 border-emerald-300 dark:text-emerald-400",children:[e.jsx(n1,{className:"h-3 w-3"})," On Google Calendar"]}),i.google_sync_status==="failed"&&e.jsxs(qe,{variant:"outline",className:"text-xs gap-1 text-amber-700 border-amber-300 dark:text-amber-400",children:[e.jsx(D9,{className:"h-3 w-3"})," Not synced to Google"]})]}),i.guest_message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 italic",children:['"',i.guest_message,'"']})]}),l&&i.status==="confirmed"&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx(Rd,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Upcoming Bookings"}),e.jsxs(fr,{children:[n.length," upcoming appointment",n.length!==1?"s":""]})]}),e.jsx(Re,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Past & Cancelled"})}),e.jsx(Re,{children:e.jsx("div",{className:"space-y-3",children:r.slice(0,20).map(i=>a(i))})})]})]})}function r9n(){const{settings:s,bookingTypes:t,availability:n,blockedDates:r,bookings:a,isLoading:i,initializeSettings:l,updateSettings:o,upsertBookingType:c,deleteBookingType:d,upsertAvailability:u,deleteAvailability:h,addBlockedDate:m,removeBlockedDate:p,cancelBooking:x}=OCt(),[y,g]=j.useState("");j.useState(15),y||s!=null&&s.meeting_link;const b=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(Vs,{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(Vs,{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(Vc,{className:"h-6 w-6 text-primary"}),"LevelUp Scheduler"]}),e.jsx("p",{className:"text-muted-foreground",children:"Manage your booking types, availability, and appointments"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[b&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(b),re.success("Booking link copied!")},children:[e.jsx(ja,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:b,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(Mn,{id:"scheduler-active",checked:s.is_active,onCheckedChange:v=>o.mutate({is_active:v})})]})]})]}),e.jsxs(fa,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"types",children:"Booking Types"}),e.jsx(ss,{value:"availability",children:"Availability"}),e.jsx(ss,{value:"settings",children:"Settings"}),e.jsxs(ss,{value:"bookings",children:["Bookings",a.filter(v=>v.status==="confirmed").length>0&&e.jsx(qe,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(v=>v.status==="confirmed").length})]})]}),e.jsx(ns,{value:"types",children:e.jsx(t9n,{types:t,onSave:v=>c.mutate(v),onDelete:v=>d.mutate(v)})}),e.jsx(ns,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(FCt,{slots:n,onSave:v=>u.mutate(v),onDelete:v=>h.mutate(v)}),e.jsx(zCt,{blockedDates:r,onAdd:v=>m.mutate(v),onRemove:v=>p.mutate(v)})]})}),e.jsxs(ns,{value:"settings",className:"space-y-6",children:[e.jsx(BCt,{scope:"agent"}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsxs(Ut,{className:"flex items-center gap-2",children:[e.jsx(tE,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(fr,{children:"Configure your booking page defaults"})]}),e.jsxs(Re,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{b&&(navigator.clipboard.writeText(b),re.success("Copied!"))},children:e.jsx(ja,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(se,{htmlFor:"meeting-link",children:[e.jsx(Rc,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(ye,{id:"meeting-link",placeholder:"https://zoom.us/j/your-personal-link",defaultValue:s.meeting_link||"",onBlur:v=>o.mutate({meeting_link:v.target.value||null})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Zoom personal link, Google Meet, or phone number"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"number",min:0,max:60,defaultValue:s.buffer_minutes,onBlur:v=>o.mutate({buffer_minutes:parseInt(v.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"number",min:0,max:72,defaultValue:s.min_notice_hours,onBlur:v=>o.mutate({min_notice_hours:parseInt(v.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(se,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"number",min:1,max:90,defaultValue:s.max_advance_days,onBlur:v=>o.mutate({max_advance_days:parseInt(v.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(se,{className:"text-sm font-semibold",children:"Guest Reminders"}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Email reminders"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sends 24 hours and 1 hour before the meeting, with reschedule and cancel links."})]}),e.jsx(Mn,{checked:s.reminders_enabled!==!1,onCheckedChange:v=>o.mutate({reminders_enabled:v})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Text message reminders"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Texts guests who left a phone number. Standard opt-out language is included."})]}),e.jsx(Mn,{checked:!!s.sms_reminders_enabled,onCheckedChange:v=>o.mutate({sms_reminders_enabled:v})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsx(se,{className:"text-sm font-semibold",children:"Embed on your website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this snippet anywhere on your site to show your booking page inline."}),e.jsx("pre",{className:"text-[11px] bg-muted rounded-lg p-3 overflow-x-auto whitespace-pre-wrap",children:``}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(``),re.success("Embed code copied")},children:[e.jsx(ja,{className:"h-4 w-4 mr-1.5"})," Copy embed code"]})]})]})]})]}),e.jsx(ns,{value:"bookings",children:e.jsx(n9n,{bookings:a,onCancel:v=>x.mutate({id:v})})})]})]})}):e.jsx(Vs,{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(Vc,{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(be,{children:e.jsxs(Re,{className:"pt-6 space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[{icon:"🏠",title:"Listing Consultation",desc:"60 min"},{icon:"🔍",title:"Buyer Consultation",desc:"45 min"},{icon:"💰",title:"Home Valuation",desc:"30 min"},{icon:"☕",title:"General Meeting",desc:"30 min"}].map(v=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx("span",{className:"text-2xl",children:v.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:v.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v.desc})]})]},v.title))}),e.jsx(Xl,{}),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(yn,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}function Xre(s){const[t,n]=String(s).split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`}function a9n(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return Bs(new Date(t,n-1,r),"EEEE, MMMM d, yyyy")}function i9n(){var ue;const{token:s}=$i(),[t]=dc(),[n,r]=j.useState(null),[a,i]=j.useState(!0),[l,o]=j.useState(null),[c,d]=j.useState("details"),[u,h]=j.useState(!1),[m,p]=j.useState(""),[x,y]=j.useState(null),[g,b]=j.useState(new Date),[v,k]=j.useState({}),[C,T]=j.useState(!1),[M,P]=j.useState(null),[L,I]=j.useState(null),O=async oe=>{var we,je;const{data:ie,error:de}=await U.functions.invoke("agent-booking",{body:oe});if(de){let xe=de.message;try{const fe=await((je=(we=de.context)==null?void 0:we.json)==null?void 0:je.call(we));fe!=null&&fe.error&&(xe=fe.error)}catch{}throw new Error(xe)}if(ie!=null&&ie.error)throw new Error(ie.error);return ie};j.useEffect(()=>{s&&(async()=>{try{const oe=await O({action:"manage_get",manage_token:s});r(oe),t.get("cancel")==="1"&&d("cancel")}catch(oe){o(oe.message)}finally{i(!1)}})()},[s]),j.useEffect(()=>{if(c!=="reschedule"||!(n!=null&&n.booking_type))return;let oe=!1;return(async()=>{T(!0);try{const ie=new Date(g.getFullYear(),g.getMonth(),1),de=xm(new Date),we=vb(de,ie)?de:ie,je=new Date(g.getFullYear(),g.getMonth()+1,0),xe=Math.max(1,Math.round((je.getTime()-we.getTime())/864e5)+1),fe=await O({action:"availability",slug:n.slug,booking_type_id:n.booking_type.id,start:Bs(we,"yyyy-MM-dd"),days:Math.min(xe,90),ignore_booking_id:n.booking.id});oe||k((fe==null?void 0:fe.availability)||{})}catch(ie){oe||re.error(ie.message)}finally{oe||T(!1)}})(),()=>{oe=!0}},[c,g,(ue=n==null?void 0:n.booking_type)==null?void 0:ue.id]);const $=j.useMemo(()=>{const oe=g.getFullYear(),ie=g.getMonth(),de=new Date(oe,ie,1),we=new Date(oe,ie+1,0),je=[];for(let xe=0;xe{h(!0);try{await O({action:"manage_cancel",manage_token:s,reason:m}),y("cancelled"),d("done")}catch(oe){re.error(oe.message)}finally{h(!1)}},G=async()=>{if(!(!M||!L)){h(!0);try{await O({action:"manage_reschedule",manage_token:s,date:Bs(M,"yyyy-MM-dd"),time:L}),y("rescheduled"),d("done")}catch(oe){re.error(oe.message)}finally{h(!1)}}};if(a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx(Wt,{className:"h-8 w-8 animate-spin text-[#406E71]"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading your booking…"})]})});if(l||!n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center px-4",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg p-8 max-w-sm text-center space-y-3",children:[e.jsx(Rd,{className:"h-10 w-10 text-slate-300 mx-auto"}),e.jsx("h1",{className:"text-lg font-bold text-slate-800",children:"Booking not found"}),e.jsx("p",{className:"text-sm text-slate-500",children:l||"This management link is no longer valid."})]})});const{booking:K,booking_type:ee,agent:J}=n,le=K.status==="cancelled";return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] py-10 px-4",children:e.jsxs("div",{className:"max-w-lg mx-auto",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-[#406E71] to-[#2a4c64] px-8 py-7 text-center",children:[e.jsx("h1",{className:"text-xl font-bold text-white",children:c==="done"?x==="cancelled"?"Booking cancelled":"Booking rescheduled":"Manage your booking"}),e.jsxs("p",{className:"text-white/80 text-sm mt-1",children:[(ee==null?void 0:ee.name)||"Meeting",J!=null&&J.name?` with ${J.name}`:""]})]}),e.jsxs("div",{className:"p-7 space-y-6",children:[c!=="reschedule"&&e.jsxs("div",{className:"rounded-xl border border-slate-100 bg-slate-50 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-800 font-semibold",children:[e.jsx(Vc,{className:"h-4 w-4 text-[#406E71]"}),a9n(K.booking_date)]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-600",children:[e.jsx(Vr,{className:"h-4 w-4 text-[#406E71]"}),Xre(String(K.start_time).slice(0,5))," –"," ",Xre(String(K.end_time).slice(0,5)),e.jsxs("span",{className:"text-xs text-slate-400",children:["(",n.timezone.replace(/_/g," "),")"]})]}),le&&e.jsx("p",{className:"text-xs font-semibold text-red-600 pt-1",children:"This booking is cancelled."})]}),c==="details"&&!le&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[n.allow_reschedule&&e.jsx(B,{className:"h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold",onClick:()=>d("reschedule"),children:"Reschedule"}),n.allow_cancel&&e.jsx(B,{variant:"outline",className:"h-12 rounded-xl border-red-200 text-red-600 hover:bg-red-50 font-semibold",onClick:()=>d("cancel"),children:"Cancel booking"})]}),c==="cancel"&&!le&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-slate-600",children:["Let ",(J==null?void 0:J.name)||"your host"," know why you can't make it (optional)."]}),e.jsx(Ds,{value:m,onChange:oe=>p(oe.target.value),placeholder:"Something came up…",className:"rounded-xl",rows:3}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(B,{variant:"ghost",className:"flex-1 h-11 rounded-xl",onClick:()=>d("details"),disabled:u,children:"Keep booking"}),e.jsx(B,{className:"flex-1 h-11 rounded-xl bg-red-600 hover:bg-red-700 text-white font-semibold",onClick:W,disabled:u,children:u?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):"Cancel booking"})]})]}),c==="reschedule"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("button",{onClick:()=>d("details"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800",children:[e.jsx(_a,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{className:"p-2 rounded-lg hover:bg-slate-100",onClick:()=>b(new Date(g.getFullYear(),g.getMonth()-1,1)),children:e.jsx(Cc,{className:"h-4 w-4 text-slate-500"})}),e.jsx("span",{className:"text-sm font-semibold text-slate-800",children:Bs(g,"MMMM yyyy")}),e.jsx("button",{className:"p-2 rounded-lg hover:bg-slate-100",onClick:()=>b(new Date(g.getFullYear(),g.getMonth()+1,1)),children:e.jsx(Qa,{className:"h-4 w-4 text-slate-500"})})]}),e.jsxs("div",{className:"grid grid-cols-7 gap-1 text-center",children:[["S","M","T","W","T","F","S"].map((oe,ie)=>e.jsx("div",{className:"text-[11px] font-semibold text-slate-400 py-1",children:oe},ie)),$.map((oe,ie)=>{if(!oe)return e.jsx("div",{},`p${ie}`);const de=Bs(oe,"yyyy-MM-dd"),we=(v[de]||[]).length>0&&!W_(oe,xm(new Date)),je=M&&pd(oe,M);return e.jsx("button",{disabled:!we,onClick:()=>{P(oe),I(null)},className:`aspect-square rounded-lg text-sm font-medium transition-colors ${je?"bg-[#406E71] text-white":we?"bg-[#406E71]/10 text-[#406E71] hover:bg-[#406E71]/20":"text-slate-300"}`,children:oe.getDate()},de)})]}),C&&e.jsxs("p",{className:"text-center text-xs text-slate-400 flex items-center justify-center gap-2",children:[e.jsx(Wt,{className:"h-3.5 w-3.5 animate-spin"})," Checking availability…"]}),M&&e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-48 overflow-y-auto",children:q.length===0?e.jsx("p",{className:"col-span-full text-center text-sm text-slate-400 py-4",children:"No open times on this day"}):q.map(oe=>e.jsx("button",{onClick:()=>I(oe),className:`px-3 py-2.5 rounded-xl text-sm font-medium ${L===oe?"bg-[#406E71] text-white":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10"}`,children:Xre(oe)},oe))}),e.jsx(B,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold",disabled:!M||!L||u,onClick:G,children:u?e.jsx(Wt,{className:"h-4 w-4 animate-spin"}):"Confirm new time"}),e.jsxs("p",{className:"text-center text-[11px] text-slate-400",children:["Times shown in ",n.timezone.replace(/_/g," ")]})]}),c==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[x==="cancelled"?e.jsx(Rd,{className:"h-12 w-12 text-red-500 mx-auto"}):e.jsx(Rr,{className:"h-12 w-12 text-emerald-500 mx-auto"}),e.jsx("p",{className:"text-sm text-slate-600",children:x==="cancelled"?`Your meeting has been cancelled and ${(J==null?void 0:J.name)||"your host"} has been notified.`:`Your meeting is now on ${M?Bs(M,"EEEE, MMMM d"):""} at ${L?Xre(L):""}. A confirmation is on its way.`})]})]})]}),e.jsx("p",{className:"text-center text-[11px] text-slate-400 mt-6",children:"Powered by LevelUp Scheduler"})]})})}const Mvt=[{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 o9n(){const{user:s}=Ns(),t=ei(),{toast:n}=pi(),r=Hn(),a=as(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState({title:"",description:"",page_type:"lead_capture"}),{data:p=[],isLoading:x}=mt({queryKey:["landing-pages",t],queryFn:async()=>{const{data:v,error:k}=await U.from("landing_pages").select("*").eq("user_id",t).is("deleted_at",null).order("created_at",{ascending:!1});if(k)throw k;return v},enabled:!!t}),y=vt({mutationFn:async()=>{const v=h.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:k}=await U.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),C=h.page_type==="just_listed"||h.page_type==="just_sold",{data:T,error:M}=await U.from("landing_pages").insert({user_id:t,title:h.title,description:h.description||null,page_type:h.page_type,slug:v,hero_headline:C?h.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":h.page_type==="lead_magnet"?"📥 Free Download":h.title,agent_name:(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:C?h.page_type.replace("just_",""):null}).select().single();if(M)throw M;const P=l9n(h.page_type);if(P.length>0){const{error:L}=await U.from("landing_page_fields").insert(P.map((I,O)=>({...I,page_id:T.id,sort_order:O})));if(L)throw L}return T},onSuccess:v=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),m({title:"",description:"",page_type:"lead_capture"}),n({title:"Landing page created!"}),r(`/mission-control/landing-pages/${v.id}`)},onError:v=>n({title:"Error",description:v.message,variant:"destructive"})}),g=vt({mutationFn:async v=>{const{error:k}=await U.from("landing_pages").update({deleted_at:new Date().toISOString(),is_published:!1}).eq("id",v);if(k)throw k},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),n({title:"Landing page deleted"})}}),b=v=>`https://pages.relevelup.com/${v}`;return e.jsxs(Vs,{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(ic,{className:"h-4 w-4 mr-2"})," Defaults"]}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(Js,{className:"h-4 w-4 mr-2"})," New Page"]})]})]}),x?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):p.length===0?e.jsx(be,{children:e.jsxs(Re,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx($r,{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(Js,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:p.map(v=>{var k;return e.jsx(be,{className:"hover:shadow-md transition-shadow",children:e.jsx(Re,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>r(`/mission-control/landing-pages/${v.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold truncate",children:v.title}),e.jsx(qe,{variant:v.is_published?"default":"secondary",className:"text-[10px]",children:v.is_published?"Published":"Draft"}),e.jsx(qe,{variant:"outline",className:"text-[10px]",children:((k=Mvt.find(C=>C.id===v.page_type))==null?void 0:k.label)||v.page_type})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:v.description}),e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ma,{className:"h-3 w-3"})," ",v.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($r,{className:"h-3 w-3"})," ",v.submission_count," submissions"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[v.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>u(b(v.slug)),children:e.jsx(hg,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(b(v.slug)),n({title:"Link copied!"})},children:e.jsx(ja,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:b(v.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(Tr,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(kd,{children:[e.jsx(Sd,{asChild:!0,children:e.jsx(B,{size:"sm",variant:"ghost",children:e.jsx(W0,{className:"h-4 w-4"})})}),e.jsxs(xd,{align:"end",children:[e.jsxs(wa,{onClick:()=>r(`/mission-control/landing-pages/${v.id}`),children:[e.jsx(Za,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(wa,{onClick:()=>c(v.id),className:"text-destructive",children:[e.jsx(Rn,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},v.id)})})]}),e.jsx(Fs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsx($s,{children:e.jsx(zs,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Page Title"}),e.jsx(ye,{value:h.title,onChange:v=>m(k=>({...k,title:v.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description (optional)"}),e.jsx(Ds,{value:h.description,onChange:v=>m(k=>({...k,description:v.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Page Template"}),e.jsxs(vs,{value:h.page_type,onValueChange:v=>m(k=>({...k,page_type:v})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:Mvt.map(v=>e.jsx(Je,{value:v.id,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:v.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:v.description})]})},v.id))})]})]})]}),e.jsxs(Nr,{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(Nl,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(hl,{children:[e.jsxs(ml,{children:[e.jsx(fl,{children:"Delete Landing Page?"}),e.jsx(xl,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(pl,{children:[e.jsx(gl,{children:"Cancel"}),e.jsx(cl,{onClick:()=>o&&g.mutate(o),children:"Delete"})]})]})}),e.jsx(Fs,{open:!!d,onOpenChange:()=>u(null),children:e.jsxs(Os,{className:"max-w-sm",children:[e.jsx($s,{children:e.jsx(zs,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(PN,{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(ja,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function l9n(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 c9n(s,t){return t?`${(s/t*100).toFixed(1)}%`:"0%"}function d9n({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 U.from("landing_page_events").select("event_type, session_id, utm_source, utm_medium, utm_campaign, referrer, device, created_at").eq("page_id",s).gte("created_at",l).order("created_at",{ascending:!1}).limit(1e3);if(c)throw c;return o||[]}}),{data:r=[]}=mt({queryKey:["landing-page-submissions-analytics",s],queryFn:async()=>{const{data:l}=await U.from("landing_page_submissions").select("id, created_at").eq("page_id",s);return l||[]}}),a=j.useMemo(()=>{const l=t.filter(x=>x.event_type==="view"),o=t.filter(x=>x.event_type==="click"),c=new Set(l.map(x=>x.session_id).filter(Boolean)),d=new Map,u=new Map,h=new Map;for(const x of l){const y=x.utm_source||"Direct / unknown";if(d.set(y,(d.get(y)||0)+1),x.referrer)try{const b=new URL(x.referrer).hostname.replace(/^www\./,"");u.set(b,(u.get(b)||0)+1)}catch{}const g=x.device||"unknown";h.set(g,(h.get(g)||0)+1)}const m=[];for(let x=13;x>=0;x--){const y=new Date;y.setHours(0,0,0,0),y.setDate(y.getDate()-x);const g=new Date(y);g.setDate(y.getDate()+1);const b=y.toLocaleDateString("en-US",{month:"numeric",day:"numeric"}),v=l.filter(C=>{const T=new Date(C.created_at);return T>=y&&T{const T=new Date(C.created_at);return T>=y&&Tx.views));return{views:l.length,sessions:c.size,clicks:o.length,submissions:r.length,conversion:c9n(r.length,c.size||l.length),sourceCounts:[...d.entries()].sort((x,y)=>y[1]-x[1]).slice(0,6),referrerCounts:[...u.entries()].sort((x,y)=>y[1]-x[1]).slice(0,6),deviceCounts:[...h.entries()].sort((x,y)=>y[1]-x[1]),days:m,maxBar:p}},[t,r]);if(n)return e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((l,o)=>e.jsx(gn,{className:"h-24"},o))});const i=[{label:"Views (30d)",value:a.views,icon:ma},{label:"Unique visitors",value:a.sessions,icon:Bn},{label:"Submissions",value:a.submissions,icon:Dr},{label:"Conversion rate",value:a.conversion,icon:kl}];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(be,{children:e.jsxs(Re,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Last 14 days"})}),e.jsxs(Re,{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(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(lu,{className:"h-4 w-4"})," Top sources"]})}),e.jsx(Re,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Top referrers"})}),e.jsx(Re,{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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Devices"})}),e.jsx(Re,{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 u9n=[{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 h9n=0;const Lvt=()=>`f_${Date.now()}_${++h9n}`;function m9n({field:s,index:t,updateField:n,removeField:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=RCe({id:s.clientId}),u={transform:RE.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(be,{ref:l,style:u,children:e.jsx(Re,{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(Fp,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Field Type"}),e.jsxs(vs,{value:s.field_type,onValueChange:h=>n(t,{field_type:h}),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsx(ys,{children:u9n.map(h=>e.jsx(Je,{value:h.value,children:h.label},h.value))})]})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Label"}),e.jsx(ye,{value:s.label,onChange:h=>n(t,{label:h.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Placeholder"}),e.jsx(ye,{value:s.placeholder||"",onChange:h=>n(t,{placeholder:h.target.value}),placeholder:"Optional hint text"})]})]}),(s.field_type==="select"||s.field_type==="multiselect")&&e.jsxs("div",{children:[e.jsx(se,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(ye,{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(Mn,{checked:s.is_required,onCheckedChange:h=>n(t,{is_required:h})}),e.jsx(se,{className:"text-xs",children:"Required"})]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>r(t),children:e.jsx(Rn,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function p9n(){const{pageId:s}=$i(),t=Hn(),{user:n}=Ns(),r=ei(),{toast:a}=pi(),i=as(),[l,o]=j.useState(null),[c,d]=j.useState(!1),{data:u,isLoading:h}=mt({queryKey:["landing-page",s],queryFn:async()=>{const{data:oe,error:ie}=await U.from("landing_pages").select("*").eq("id",s).single();if(ie)throw ie;return oe},enabled:!!s}),{data:m=[],isLoading:p}=mt({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:oe,error:ie}=await U.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(ie)throw ie;return oe},enabled:!!s}),{data:x=[]}=mt({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:oe,error:ie}=await U.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(ie)throw ie;return oe},enabled:!!s}),{data:y=[]}=mt({queryKey:["my-listings-for-pages",r],queryFn:async()=>{const{data:oe,error:ie}=await U.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, description, status").eq("agent_id",r).order("created_at",{ascending:!1});if(ie)throw ie;return oe},enabled:!!n&&((u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold")}),{data:g=[]}=mt({queryKey:["drips-for-landing",r],queryFn:async()=>{const{data:oe}=await U.from("drip_campaigns").select("id, name").eq("owner_user_id",r).eq("is_active",!0).order("name");return oe||[]},enabled:!!r}),{data:b}=mt({queryKey:["agent-landing-defaults",r],queryFn:async()=>{const{data:oe}=await U.from("agent_landing_page_defaults").select("*").eq("user_id",r).maybeSingle();return oe},enabled:!!r}),[v,k]=j.useState({title:"",hero_headline:"",hero_subtext:"",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",agent_name:"",agent_phone:"",agent_email:"",agent_photo_url:null,success_message:"Thank you! We'll be in touch soon.",is_published:!1,description:"",lead_magnet_file_url:null,lead_magnet_file_name:null,lead_magnet_external_url:null,listing_id:null,property_address:"",property_price:"",property_beds:"",property_baths:"",property_sqft:"",property_description:"",property_photos:[],property_status:"just_listed",theme_style:"premium",eyebrow:"",headline_accent:"",heading_font:"playfair",trust_pills:["No obligation","100% free","60 seconds or less"],settings_redirect_url:"",settings_auto_responder_subject:"",settings_auto_responder_body:"",settings_drip_campaign_id:null,settings_disable_auto_responder:!1,settings_disable_drip:!1,settings_event_starts_at:"",settings_event_location_name:"",settings_event_address:""}),[C,T]=j.useState([]);j.useEffect(()=>{var oe,ie,de,we,je,xe,fe,Se,Ee;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:((oe=u.settings)==null?void 0:oe.redirect_url)||"",settings_auto_responder_subject:((ie=u.settings)==null?void 0:ie.auto_responder_subject)||"",settings_auto_responder_body:((de=u.settings)==null?void 0:de.auto_responder_body)||"",settings_drip_campaign_id:((we=u.settings)==null?void 0:we.drip_campaign_id)||null,settings_disable_auto_responder:!!((je=u.settings)!=null&&je.disable_auto_responder),settings_disable_drip:!!((xe=u.settings)!=null&&xe.disable_drip),settings_event_starts_at:((fe=u.settings)==null?void 0:fe.event_starts_at)||"",settings_event_location_name:((Se=u.settings)==null?void 0:Se.event_location_name)||"",settings_event_address:((Ee=u.settings)==null?void 0:Ee.event_address)||""})},[u]),j.useEffect(()=>{m.length>0&&T(m.map(oe=>({id:oe.id,clientId:oe.id||Lvt(),field_type:oe.field_type,label:oe.label,placeholder:oe.placeholder,is_required:oe.is_required,options:typeof oe.options=="string"?oe.options:oe.options?JSON.stringify(oe.options):null,sort_order:oe.sort_order})))},[m]);const M=vt({mutationFn:async()=>{const{error:oe}=await U.from("landing_pages").update({title:v.title,hero_headline:v.hero_headline,hero_subtext:v.hero_subtext||null,hero_image_url:v.hero_image_url,logo_url:v.logo_url,primary_color:v.primary_color,accent_color:v.accent_color,agent_name:v.agent_name||null,agent_phone:v.agent_phone||null,agent_email:v.agent_email||null,agent_photo_url:v.agent_photo_url,success_message:v.success_message,is_published:v.is_published,description:v.description||null,lead_magnet_file_url:v.lead_magnet_file_url,lead_magnet_file_name:v.lead_magnet_file_name,lead_magnet_external_url:v.lead_magnet_external_url,listing_id:v.listing_id,property_address:v.property_address||null,property_price:v.property_price||null,property_beds:v.property_beds||null,property_baths:v.property_baths||null,property_sqft:v.property_sqft||null,property_description:v.property_description||null,property_photos:v.property_photos,property_status:v.property_status,theme_style:v.theme_style,eyebrow:v.eyebrow||null,headline_accent:v.headline_accent||null,heading_font:v.heading_font,trust_pills:v.trust_pills,settings:{...(u==null?void 0:u.settings)||{},redirect_url:v.settings_redirect_url||null,auto_responder_subject:v.settings_auto_responder_subject||null,auto_responder_body:v.settings_auto_responder_body||null,drip_campaign_id:v.settings_drip_campaign_id||null,disable_auto_responder:!!v.settings_disable_auto_responder,disable_drip:!!v.settings_disable_drip,event_starts_at:v.settings_event_starts_at||null,event_location_name:v.settings_event_location_name||null,event_address:v.settings_event_address||null},updated_at:new Date().toISOString()}).eq("id",s);if(oe)throw oe;if(await U.from("landing_page_fields").delete().eq("page_id",s),C.length>0){const{error:ie}=await U.from("landing_page_fields").insert(C.map((de,we)=>({page_id:s,field_type:de.field_type,label:de.label,placeholder:de.placeholder||null,is_required:de.is_required,options:de.options?JSON.parse(de.options):null,sort_order:we})));if(ie)throw ie}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:oe=>a({title:"Error",description:oe.message,variant:"destructive"})}),P=async(oe,ie)=>{const de=oe.name.split(".").pop(),we=`landing-pages/${n.id}/${ie}-${Date.now()}.${de}`,{error:je}=await U.storage.from("recruit-landing").upload(we,oe);if(je)throw je;const{data:{publicUrl:xe}}=U.storage.from("recruit-landing").getPublicUrl(we);return xe},L=async(oe,ie)=>{var we;const de=(we=oe.target.files)==null?void 0:we[0];if(de){o(ie);try{const je=await P(de,ie);k(xe=>({...xe,[ie]:je})),a({title:"Image uploaded!"})}catch(je){a({title:"Upload failed",description:je.message,variant:"destructive"})}finally{o(null)}}},I=async oe=>{var de;const ie=(de=oe.target.files)==null?void 0:de[0];if(ie){o("lead_magnet");try{const we=await P(ie,"lead-magnet");k(je=>({...je,lead_magnet_file_url:we,lead_magnet_file_name:ie.name})),a({title:"File uploaded!"})}catch(we){a({title:"Upload failed",description:we.message,variant:"destructive"})}finally{o(null)}}},O=async oe=>{const ie=oe.target.files;if(!(!ie||ie.length===0)){o("property_photos");try{const de=[];for(const we of Array.from(ie)){const je=await P(we,"property-photo");de.push(je)}k(we=>({...we,property_photos:[...we.property_photos,...de]})),a({title:`${de.length} photo(s) uploaded!`})}catch(de){a({title:"Upload failed",description:de.message,variant:"destructive"})}finally{o(null)}}},$=async oe=>{const ie=y.find(we=>we.id===oe);if(!ie)return;const{data:de}=await U.from("listing_photos").select("photo_url").eq("listing_id",oe).order("sort_order");k(we=>({...we,listing_id:oe,property_address:ie.property_address||`${ie.city}, ${ie.state}`,property_price:ie.price?`$${ie.price.toLocaleString()}`:"",property_beds:ie.bedrooms?String(ie.bedrooms):"",property_baths:ie.bathrooms?String(ie.bathrooms):"",property_sqft:ie.square_footage?ie.square_footage.toLocaleString():"",property_description:ie.description||"",property_photos:(de==null?void 0:de.map(je=>je.photo_url))||we.property_photos})),a({title:"Listing data imported!"})},q=()=>{T(oe=>[...oe,{clientId:Lvt(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:oe.length}])},W=(oe,ie)=>{T(de=>de.map((we,je)=>je===oe?{...we,...ie}:we))},G=oe=>{T(ie=>ie.filter((de,we)=>we!==oe))},K=SCe(I$(uq,{activationConstraint:{distance:6}}),I$(TCe,{coordinateGetter:cLt})),ee=oe=>{const{active:ie,over:de}=oe;!de||ie.id===de.id||T(we=>{const je=we.findIndex(fe=>fe.clientId===ie.id),xe=we.findIndex(fe=>fe.clientId===de.id);return je<0||xe<0?we:PCe(we,je,xe).map((fe,Se)=>({...fe,sort_order:Se}))})},J=u?`https://pages.relevelup.com/${u.slug}`:"",le=(u==null?void 0:u.page_type)==="lead_magnet",ue=(u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold";return h||p?e.jsx(Vs,{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(Vs,{title:v.title||"Edit Page",children:[e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/landing-pages"),children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold",children:v.title||"Untitled Page"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(qe,{variant:v.is_published?"default":"secondary",className:"text-[10px]",children:v.is_published?"Published":"Draft"}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ma,{className:"h-3 w-3"})," ",u.view_count," views"]}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Bn,{className:"h-3 w-3"})," ",x.length," submissions"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[v.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(hg,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(J),a({title:"Link copied!"})},children:[e.jsx(ja,{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:J,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Tr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(B,{onClick:()=>M.mutate(),disabled:M.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),M.isPending?"Saving...":"Save"]})]})]}),e.jsxs(fa,{defaultValue:"design",children:[e.jsxs(xa,{children:[e.jsx(ss,{value:"design",children:"Design"}),le&&e.jsx(ss,{value:"lead_magnet",children:"Lead Magnet"}),ue&&e.jsx(ss,{value:"property",children:"Property Details"}),e.jsxs(ss,{value:"fields",children:["Form Fields (",C.length,")"]}),e.jsxs(ss,{value:"submissions",children:["Submissions (",x.length,")"]}),e.jsx(ss,{value:"automation",children:"Automation"}),e.jsx(ss,{value:"analytics",children:"Analytics"}),e.jsx(ss,{value:"settings",children:"Settings"})]}),e.jsxs(ns,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Page Details"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Page Title (internal)"}),e.jsx(ye,{value:v.title,onChange:oe=>k(ie=>({...ie,title:oe.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description (internal)"}),e.jsx(ye,{value:v.description,onChange:oe=>k(ie=>({...ie,description:oe.target.value}))})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Theme Style"}),e.jsxs(vs,{value:v.theme_style,onValueChange:oe=>k(ie=>({...ie,theme_style:oe})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(Je,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Headline Font"}),e.jsxs(vs,{value:v.heading_font,onValueChange:oe=>k(ie=>({...ie,heading_font:oe})),children:[e.jsx(gs,{children:e.jsx(bs,{})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(Je,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(Je,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(Je,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(ye,{value:v.trust_pills.join(", "),onChange:oe=>k(ie=>({...ie,trust_pills:oe.target.value.split(",").map(de=>de.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(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Hero Section"})}),e.jsxs(Re,{className:"space-y-4",children:[v.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(se,{children:"Eyebrow (small label above headline)"}),e.jsx(ye,{value:v.eyebrow,onChange:oe=>k(ie=>({...ie,eyebrow:oe.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Headline"}),e.jsx(ye,{value:v.hero_headline,onChange:oe=>k(ie=>({...ie,hero_headline:oe.target.value})),placeholder:"What Is Your Home"})]}),v.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(se,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(ye,{value:v.headline_accent,onChange:oe=>k(ie=>({...ie,headline_accent:oe.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Subtext"}),e.jsx(Ds,{value:v.hero_subtext,onChange:oe=>k(ie=>({...ie,hero_subtext:oe.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(se,{children:["Background Image ",v.theme_style==="premium"&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(dusk/cinematic recommended)"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[v.hero_image_url&&e.jsx("img",{src:v.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(Ja,{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:oe=>L(oe,"hero_image_url")})]}),v.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>k(oe=>({...oe,hero_image_url:null})),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Branding"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[v.logo_url&&e.jsx("img",{src:v.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(Ja,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:oe=>L(oe,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[v.agent_photo_url&&e.jsx("img",{src:v.agent_photo_url,alt:"Agent",className:"h-10 w-10 rounded-full object-cover"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(Ja,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:oe=>L(oe,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:v.primary_color,onChange:oe=>k(ie=>({...ie,primary_color:oe.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:v.primary_color,onChange:oe=>k(ie=>({...ie,primary_color:oe.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:v.accent_color,onChange:oe=>k(ie=>({...ie,accent_color:oe.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:v.accent_color,onChange:oe=>k(ie=>({...ie,accent_color:oe.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(Re,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Name"}),e.jsx(ye,{value:v.agent_name,onChange:oe=>k(ie=>({...ie,agent_name:oe.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Phone"}),e.jsx(ye,{value:v.agent_phone,onChange:oe=>k(ie=>({...ie,agent_phone:oe.target.value}))})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Email"}),e.jsx(ye,{value:v.agent_email,onChange:oe=>k(ie=>({...ie,agent_email:oe.target.value}))})]})]})})]})]}),le&&e.jsx(ns,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(ii,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a file or provide an external URL. Visitors will receive the download link after submitting the form."}),e.jsxs("div",{children:[e.jsx(se,{children:"Upload File (PDF, guide, checklist, etc.)"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[v.lead_magnet_file_name&&e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(ii,{className:"h-3 w-3"})," ",v.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(Ja,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:I})]}),v.lead_magnet_file_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>k(oe=>({...oe,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(Rn,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("div",{className:"flex-1 border-t"}),e.jsx("span",{children:"OR"}),e.jsx("div",{className:"flex-1 border-t"})]}),e.jsxs("div",{children:[e.jsxs(se,{className:"flex items-center gap-1",children:[e.jsx(Rc,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(ye,{value:v.lead_magnet_external_url||"",onChange:oe=>k(ie=>({...ie,lead_magnet_external_url:oe.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(ns,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsxs(Ut,{className:"text-base flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pull property details and photos directly from one of your listings, or enter them manually below."}),e.jsxs(vs,{value:v.listing_id||"",onValueChange:oe=>$(oe),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Select a listing to import..."})}),e.jsx(ys,{children:y.map(oe=>{var ie;return e.jsxs(Je,{value:oe.id,children:[oe.property_address||`${oe.city}, ${oe.state}`," — $",(ie=oe.price)==null?void 0:ie.toLocaleString()]},oe.id)})})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Property Information"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Property Address"}),e.jsx(ye,{value:v.property_address,onChange:oe=>k(ie=>({...ie,property_address:oe.target.value})),placeholder:"123 Main St, City, State"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Price"}),e.jsx(ye,{value:v.property_price,onChange:oe=>k(ie=>({...ie,property_price:oe.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Beds"}),e.jsx(ye,{value:v.property_beds,onChange:oe=>k(ie=>({...ie,property_beds:oe.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Baths"}),e.jsx(ye,{value:v.property_baths,onChange:oe=>k(ie=>({...ie,property_baths:oe.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Sq Ft"}),e.jsx(ye,{value:v.property_sqft,onChange:oe=>k(ie=>({...ie,property_sqft:oe.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Description"}),e.jsx(Ds,{value:v.property_description,onChange:oe=>k(ie=>({...ie,property_description:oe.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Property Photos"})}),e.jsxs(Re,{className:"space-y-4",children:[v.property_photos.length>0&&e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:v.property_photos.map((oe,ie)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:oe,alt:`Property ${ie+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(de=>({...de,property_photos:de.property_photos.filter((we,je)=>je!==ie)})),children:e.jsx(Rn,{className:"h-3 w-3"})})]},ie))}),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(Ja,{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:O})]})]})]})]}),e.jsxs(ns,{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:q,children:[e.jsx(Js,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),C.length===0?e.jsx(be,{children:e.jsx(Re,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx(LCe,{sensors:K,collisionDetection:CCe,onDragEnd:ee,children:e.jsx(ICe,{items:C.map(oe=>oe.clientId),strategy:xzs,children:e.jsx("div",{className:"space-y-3",children:C.map((oe,ie)=>e.jsx(m9n,{field:oe,index:ie,updateField:W,removeField:G},oe.clientId))})})})]}),e.jsx(ns,{value:"submissions",className:"mt-4",children:x.length===0?e.jsx(be,{children:e.jsx(Re,{className:"py-12 text-center text-muted-foreground",children:"No submissions yet. Share your page to start collecting leads!"})}):e.jsx("div",{className:"space-y-3",children:x.map(oe=>e.jsx(be,{children:e.jsx(Re,{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:oe.contact_name||"Anonymous"}),oe.synced_to_crm&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[oe.contact_email&&e.jsx("span",{className:"mr-3",children:oe.contact_email}),oe.contact_phone&&e.jsx("span",{children:oe.contact_phone})]}),oe.answers&&typeof oe.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(oe.answers).map(([ie,de])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[ie,":"]})," ",e.jsx("span",{children:String(de)})]},ie))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(oe.created_at).toLocaleDateString()})]})})},oe.id))})}),e.jsxs(ns,{value:"automation",className:"space-y-4 mt-4",children:[(u==null?void 0:u.page_type)==="event_registration"&&e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{className:"text-base",children:"Event details"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown to visitors as a live countdown with add-to-calendar buttons."})]}),e.jsxs(Re,{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 md:col-span-2",children:[e.jsx(se,{children:"Starts at"}),e.jsx(ye,{type:"datetime-local",value:v.settings_event_starts_at,onChange:oe=>k(ie=>({...ie,settings_event_starts_at:oe.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Venue / location name"}),e.jsx(ye,{placeholder:"e.g. The Grand Hotel",value:v.settings_event_location_name,onChange:oe=>k(ie=>({...ie,settings_event_location_name:oe.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(se,{children:"Address (for map link)"}),e.jsx(ye,{placeholder:"123 Main St, City, ST",value:v.settings_event_address,onChange:oe=>k(ie=>({...ie,settings_event_address:oe.target.value}))})]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{className:"text-base",children:"Instant auto-reply to lead"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent the moment someone submits this page. Leave blank to use your",b!=null&&b.default_auto_responder_body?" account default":" built-in template",". Merge fields: ",e.jsx("code",{children:"{{client_first_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{page_title}}"}),", ",e.jsx("code",{children:"{{calendar_link}}"}),"."]})]}),e.jsxs(Re,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Send auto-reply for this page"}),e.jsx(Mn,{checked:!v.settings_disable_auto_responder,onCheckedChange:oe=>k(ie=>({...ie,settings_disable_auto_responder:!oe}))})]}),!v.settings_disable_auto_responder&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(se,{children:"Subject (override)"}),e.jsx(ye,{value:v.settings_auto_responder_subject,onChange:oe=>k(ie=>({...ie,settings_auto_responder_subject:oe.target.value})),placeholder:(b==null?void 0:b.default_auto_responder_subject)||"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Body (override)"}),e.jsx(Ds,{rows:8,value:v.settings_auto_responder_body,onChange:oe=>k(ie=>({...ie,settings_auto_responder_body:oe.target.value})),placeholder:(b==null?void 0:b.default_auto_responder_body)||`Hi {{client_first_name}}, Thanks for reaching out…`})]})]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{className:"text-base",children:"Smart Drip enrollment"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatically enroll every new lead into a drip campaign.",(b==null?void 0:b.default_drip_campaign_id)&&" Account default applies if no override is selected."]})]}),e.jsxs(Re,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(se,{children:"Enroll new leads in a drip"}),e.jsx(Mn,{checked:!v.settings_disable_drip,onCheckedChange:oe=>k(ie=>({...ie,settings_disable_drip:!oe}))})]}),!v.settings_disable_drip&&e.jsxs("div",{children:[e.jsx(se,{children:"Drip override for this page"}),e.jsxs("select",{className:"mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm",value:v.settings_drip_campaign_id||"",onChange:oe=>k(ie=>({...ie,settings_drip_campaign_id:oe.target.value||null})),children:[e.jsx("option",{value:"",children:"— Use account default —"}),g.map(oe=>e.jsx("option",{value:oe.id,children:oe.name},oe.id))]})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Redirect after submit"})}),e.jsxs(Re,{children:[e.jsx(ye,{value:v.settings_redirect_url,onChange:oe=>k(ie=>({...ie,settings_redirect_url:oe.target.value})),placeholder:(b==null?void 0:b.default_redirect_url)||"https://your-site.com/thank-you (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Leave blank to keep the inline Thank-You message."})]})]})]}),e.jsx(ns,{value:"analytics",className:"space-y-4 mt-4",children:e.jsx(d9n,{pageId:s})}),e.jsxs(ns,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Publishing"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(Mn,{checked:v.is_published,onCheckedChange:oe=>k(ie=>({...ie,is_published:oe}))})]}),v.is_published&&e.jsxs("div",{className:"p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Public URL:"}),e.jsx("code",{className:"text-xs ml-2 break-all",children:J})]})]})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{className:"text-base",children:"Thank You Message"})}),e.jsx(Re,{children:e.jsx(Ds,{value:v.success_message,onChange:oe=>k(ie=>({...ie,success_message:oe.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(Fs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"max-w-sm",children:[e.jsx($s,{children:e.jsx(zs,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(PN,{value:J,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:J})]})]})})]}):e.jsx(Vs,{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 f9n={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},x9n=`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 g9n(){const s=ei(),{toast:t}=pi(),n=Hn(),r=as(),[a,i]=j.useState(f9n),{data:l}=mt({queryKey:["landing-page-defaults",s],queryFn:async()=>{const{data:d}=await U.from("agent_landing_page_defaults").select("*").eq("user_id",s).maybeSingle();return d||null},enabled:!!s}),{data:o=[]}=mt({queryKey:["drip-campaigns-mine",s],queryFn:async()=>{const{data:d}=await U.from("drip_campaigns").select("id, name").eq("owner_user_id",s).eq("is_active",!0).order("name");return d||[]},enabled:!!s});j.useEffect(()=>{l&&i({default_auto_responder_subject:l.default_auto_responder_subject??"",default_auto_responder_body:l.default_auto_responder_body??"",default_drip_campaign_id:l.default_drip_campaign_id??null,default_redirect_url:l.default_redirect_url??"",default_calendar_link:l.default_calendar_link??"",text_agent_on_lead:!!l.text_agent_on_lead,agent_sms_phone:l.agent_sms_phone??"",use_brand_kit:l.use_brand_kit??!0})},[l]);const c=vt({mutationFn:async()=>{const{error:d}=await U.from("agent_landing_page_defaults").upsert({user_id:s,...a},{onConflict:"user_id"});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["landing-page-defaults"]}),t({title:"Defaults saved"})},onError:d=>t({title:"Save failed",description:d.message,variant:"destructive"})});return e.jsx(Vs,{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(_a,{className:"h-4 w-4 mr-1"})," Back to pages"]}),e.jsxs(B,{onClick:()=>c.mutate(),disabled:c.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"})," ",c.isPending?"Saving…":"Save Defaults"]})]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Page Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"These run on every landing page automatically. Any page can override them in its own settings."})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Instant auto-reply to the lead"}),e.jsxs(fr,{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(Re,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Subject"}),e.jsx(ye,{value:a.default_auto_responder_subject||"",onChange:d=>i(u=>({...u,default_auto_responder_subject:d.target.value})),placeholder:"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Message body"}),e.jsx(Ds,{rows:10,value:a.default_auto_responder_body||"",onChange:d=>i(u=>({...u,default_auto_responder_body:d.target.value})),placeholder:x9n}),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(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Default Smart Drip"}),e.jsx(fr,{children:"Every new lead drops into this drip unless a page overrides it."})]}),e.jsx(Re,{children:e.jsxs(vs,{value:a.default_drip_campaign_id||"none",onValueChange:d=>i(u=>({...u,default_drip_campaign_id:d==="none"?null:d})),children:[e.jsx(gs,{children:e.jsx(bs,{placeholder:"Pick a drip…"})}),e.jsxs(ys,{children:[e.jsx(Je,{value:"none",children:"— No default drip —"}),o.map(d=>e.jsx(Je,{value:d.id,children:d.name},d.id))]})]})})]}),e.jsxs(be,{children:[e.jsx(Ft,{children:e.jsx(Ut,{children:"Defaults for every page"})}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(se,{children:"Default booking / calendar link"}),e.jsx(ye,{value:a.default_calendar_link||"",onChange:d=>i(u=>({...u,default_calendar_link:d.target.value})),placeholder:"https://calendly.com/your-name/intro"})]}),e.jsxs("div",{children:[e.jsx(se,{children:"Default redirect after submit (optional)"}),e.jsx(ye,{value:a.default_redirect_url||"",onChange:d=>i(u=>({...u,default_redirect_url:d.target.value})),placeholder:"https://your-site.com/thanks"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(se,{className:"text-base",children:"Use my brand kit colors"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"New pages pick up your brand colors/logo automatically."})]}),e.jsx(Mn,{checked:a.use_brand_kit,onCheckedChange:d=>i(u=>({...u,use_brand_kit:d}))})]})]})]}),e.jsxs(be,{children:[e.jsxs(Ft,{children:[e.jsx(Ut,{children:"Text me when a lead submits"}),e.jsx(fr,{children:"Get an SMS the second a lead hits your inbox. Coming soon — requires SMS sender setup."})]}),e.jsxs(Re,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(se,{className:"text-base",children:"SMS me new leads"}),e.jsx(Mn,{checked:a.text_agent_on_lead,onCheckedChange:d=>i(u=>({...u,text_agent_on_lead:d}))})]}),a.text_agent_on_lead&&e.jsxs("div",{children:[e.jsx(se,{children:"Phone number for alerts"}),e.jsx(ye,{type:"tel",value:a.agent_sms_phone||"",onChange:d=>i(u=>({...u,agent_sms_phone:d.target.value})),placeholder:"(555) 123-4567"})]})]})]})]})})}function y9n(){return mt({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await U.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function ITe(){const{user:s}=Ns();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 U.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(n)throw n;return t||[]},enabled:!!(s!=null&&s.id)})}function RTe(){const{user:s}=Ns(),t=as();return vt({mutationFn:async({app_slug:n,enabled:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await U.from("agent_website_app_installs").upsert({user_id:s.id,app_slug:n,enabled:r},{onConflict:"user_id,app_slug"});if(a)throw a},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["agent-website-app-installs"]}),re.success(r.enabled?"App installed":"App turned off")},onError:n=>re.error(n.message||"Failed to update app")})}const v9n={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"}},b9n={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 _9n(){const s=Hn(),{data:t=[],isLoading:n}=y9n(),{data:r=[]}=ITe(),{hasLeadSite:a,siteUrl:i,isLoading:l}=h0(),o=RTe(),[c,d]=j.useState(!1),u=m=>{var p;return((p=r.find(x=>x.app_slug===m))==null?void 0:p.enabled)??!1},h=m=>r.some(p=>p.app_slug===m);return e.jsxs(Vs,{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(jf,{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(yn,{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(vh,{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(be,{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(Ql,{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(qe,{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(be,{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(j4,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 2 — Your existing website"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Already have a site (Wix, Squarespace, WordPress, custom)? Paste a one-line snippet and the widget appears anywhere."}),e.jsx("p",{className:"text-[11px] text-indigo-700 mt-2 font-medium",children:'Open any app below → "Install on my website" tab to copy your code.'})]})]})})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading apps..."}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(m=>{const p=T4e[m.icon||"Sparkles"]||yn,x=u(m.slug),y=h(m.slug),g=m.status==="coming_soon",b=v9n[m.slug]||b9n;return e.jsxs(be,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${b.ring} hover:ring-2 transition-all hover:shadow-xl ${g?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${b.gradient}`}),e.jsxs("div",{className:"p-5 flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:`w-14 h-14 rounded-2xl ${b.iconBg} ${b.iconText} flex items-center justify-center shadow-md group-hover:scale-105 transition-transform`,children:e.jsx(p,{className:"w-7 h-7"})}),g?e.jsx(qe,{variant:"secondary",children:"Coming soon"}):x?e.jsxs(qe,{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(qe,{variant:"outline",children:"Paused"}):e.jsx(qe,{className:b.chip+" hover:"+b.chip,children:"New"})]}),e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("h3",{className:"font-bold text-lg",children:m.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:m.description})]}),!g&&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(Mn,{checked:x,onCheckedChange:v=>o.mutate({app_slug:m.slug,enabled:v})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:x?"On":"Off"})]}),e.jsxs(B,{size:"sm",className:`bg-gradient-to-r ${b.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${m.slug}`),children:[e.jsx(ic,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(Xa,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},m.id)})})]}),e.jsx(Fs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx($s,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx(zs,{children:"How to use Website Apps"})}),c&&e.jsx("video",{src:"/website-apps-tutorial.mp4",controls:!0,autoPlay:!0,playsInline:!0,className:"w-full h-auto bg-black"})]})})]})}const J8e={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 w9n(){const{user:s}=Ns();return mt({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return J8e;const{data:t,error:n}=await U.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t?{...J8e,...t}:J8e},enabled:!!(s!=null&&s.id)})}function j9n(){const{user:s}=Ns(),t=as();return vt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:r}=await U.from("video_greeter_configs").upsert({user_id:s.id,...n},{onConflict:"user_id"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),re.success("Saved")},onError:n=>re.error(n.message||"Failed to save")})}function N9n({label:s,value:t,onChange:n,thumbnailUrl:r,placeholder:a="https://...",hint:i}){const l=j.useRef(null),[o,c]=j.useState(!1),d=async u=>{var m;const h=(m=u.target.files)==null?void 0:m[0];if(h){if(!h.type.startsWith("video/")){re.error("Please select a video file");return}if(h.size>50*1024*1024){re.error("Video must be under 50MB");return}c(!0);try{const p=h.name.split(".").pop()||"mp4",x=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${p}`,{error:y}=await U.storage.from("agent-uploads").upload(x,h,{upsert:!0});if(y)throw y;const{data:{publicUrl:g}}=U.storage.from("agent-uploads").getPublicUrl(x);n(g),re.success("Video uploaded!")}catch(p){re.error(p.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(se,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{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(Wt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Ja,{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}):N9(t)?e.jsx(XBe,{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(dr,{className:"h-3 w-3"})})]})})()]})}const k9n=[{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 S9n({onVideoReady:s}){const[t,n]=j.useState(!1),[r,a]=j.useState("script"),[i,l]=j.useState(""),[o,c]=j.useState(!0),[d,u]=j.useState(!1),[h,m]=j.useState(0),[p,x]=j.useState(0),y=hS(),g=()=>{a("script"),l(""),m(0),x(0),c(!0)},b=k=>{!k&&(r==="uploading"||r==="processing")||(n(k),k||g())},v=j.useCallback(async(k,C)=>{a("uploading");try{const T="Video Greeter",{videoId:M,libraryId:P}=await w6(T),{uploadUrl:L,apiKey:I}=await j6(M),O=new XMLHttpRequest;O.upload.onprogress=ue=>{ue.lengthComputable&&m(ue.loaded/ue.total*100)},await new Promise((ue,oe)=>{O.onload=()=>O.status>=200&&O.status<300?ue():oe(new Error("Upload failed")),O.onerror=()=>oe(new Error("Upload failed")),O.open("PUT",L),O.setRequestHeader("AccessKey",I),O.send(k)}),a("processing");let $=0;const q=Date.now(),W=9e4,G=`https://iframe.mediadelivery.net/embed/${P}/${M}`,K=`https://iframe.mediadelivery.net/play/${P}/${M}`;for(;$<4;){if(await new Promise(oe=>setTimeout(oe,3e3)),Date.now()-q>W){const oe=k.size/1048576,ie=await y.mutateAsync({bunny_video_id:M,playback_url:K,file_size_mb:oe,title:T,status:"processing",touch_type:"video"});s({videoId:(ie==null?void 0:ie.id)||M,playbackUrl:G,thumbnailUrl:null}),re.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{n(!1),g()},1500);return}const ue=await $j(M);if($=ue.status,x(ue.encodeProgress||0),$===5||$===6)throw new Error("Video processing failed")}const ee=await $j(M),J=(ee.storageSize||k.size)/(1024*1024),le=await y.mutateAsync({bunny_video_id:M,playback_url:ee.directPlayUrl||G,thumbnail_url:ee.thumbnailUrl,preview_url:ee.previewUrl||null,duration_seconds:ee.length||C,file_size_mb:J,title:T,status:"ready",touch_type:"video"});s({videoId:(le==null?void 0:le.id)||M,playbackUrl:ee.directPlayUrl||G,thumbnailUrl:ee.thumbnailUrl||null}),re.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{n(!1),g()},1500)}catch(T){console.error(T),re.error("Failed to process video. Please try again."),a("record")}},[y,s]);return e.jsxs(Fs,{open:t,onOpenChange:b,children:[e.jsx(Io,{asChild:!0,children:e.jsxs(B,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(Zr,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(Os,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx($s,{children:e.jsxs(zs,{className:"flex items-center gap-2",children:[e.jsx(yn,{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:k9n.map(k=>e.jsxs(be,{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(qe,{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(Ds,{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($r,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),r==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(k6,{maxDurationSeconds:60,onRecordingComplete:v,onRecordingStateChange:u,onError:k=>re.error(k),teleprompterContent:o&&i?e.jsx(eYe,{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($r,{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(Wt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(qi,{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(Wt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(qi,{value:p,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(p),"%"]})]}),r==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(To,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function C9n(){var C;const s=Hn(),{user:t}=Ns(),{leadSite:n}=h0(),{data:r}=w9n(),a=j9n(),{data:i=[]}=ITe(),l=RTe(),[o,c]=j.useState(null),[d,u]=j.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(j.useEffect(()=>{r&&!o&&c(r)},[r,o]),j.useEffect(()=>{t!=null&&t.id&&U.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:T})=>{const M=T||[];u({impressions:M.filter(P=>P.event_type==="impression").length,expands:M.filter(P=>P.event_type==="expand").length,ctaClicks:M.filter(P=>P.event_type==="cta_click").length,leads:M.filter(P=>P.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(Vs,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const h=((C=i.find(T=>T.app_slug==="video_greeter"))==null?void 0:C.enabled)??!1,m=T=>c({...o,...T}),p=T=>m({ctas:T}),x=()=>p([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),y=T=>p((o.ctas||[]).filter(M=>M.id!==T)),g=(T,M)=>p((o.ctas||[]).map(P=>P.id===T?{...P,...M}:P)),b=()=>a.mutate(o),v=(n==null?void 0:n.subdomain_slug)||(t==null?void 0:t.id)||"",k=`